fenilsonani / menu-browser / Sources/ PreferencesView.swift

import SwiftUI
import ServiceManagement

// MARK: - Preferences State

class PreferencesState: ObservableObject {
    @Published var shortcut: GlobalShortcut {
        didSet { shortcut.save(to: defaults) }
    }
    @Published var isRecording = false
    @Published var browsers: [BrowserInfo] = []

    /// Non-nil when the current shortcut couldn't be claimed (usually another app owns it).
    @Published var shortcutError: String?

    private let defaults: UserDefaults

    var recentBrowserIDs: [String] {
        didSet { defaults.set(recentBrowserIDs, forKey: "recentBrowserIDs") }
    }

    var shortcutDisplay: String { shortcut.displayString }

    var onShortcutChanged: (() -> Void)?
    private var localMonitor: Any?

    init(defaults: UserDefaults = .standard) {
        self.defaults = defaults
        self.recentBrowserIDs = defaults.stringArray(forKey: "recentBrowserIDs") ?? []
        self.shortcut = GlobalShortcut.load(from: defaults)
    }

    func pushRecent(browserID: String) {
        recentBrowserIDs.removeAll { $0.equalsIgnoringCase(browserID) }
        recentBrowserIDs.insert(browserID, at: 0)
        if recentBrowserIDs.count > 3 { recentBrowserIDs = Array(recentBrowserIDs.prefix(3)) }
    }

    // MARK: - Shortcut

    func startRecording() {
        isRecording = true
        localMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
            guard let self else { return event }
            if event.keyCode == 0x35 { self.stopRecording(); return nil }
            let mods = event.modifierFlags.intersection([.command, .shift, .option, .control])
            guard !mods.isEmpty else { return event }
            self.shortcut = GlobalShortcut(keyCode: event.keyCode, modifiers: mods)
            self.stopRecording()
            self.onShortcutChanged?()
            return nil
        }
    }

    func stopRecording() {
        if let monitor = localMonitor { NSEvent.removeMonitor(monitor); localMonitor = nil }
        isRecording = false
    }

    // MARK: - Browser Ordering

    func refreshBrowsers(using manager: BrowserManager) {
        browsers = applyOrder(to: manager.installedBrowsers())
    }

    func orderedBrowsers(from all: [BrowserInfo]) -> [BrowserInfo] { applyOrder(to: all) }

    private func applyOrder(to all: [BrowserInfo]) -> [BrowserInfo] {
        let storedIDs = UserDefaults.standard.stringArray(forKey: "browserOrder") ?? []
        var ordered: [BrowserInfo] = []
        for id in storedIDs {
            if let b = all.first(where: { $0.bundleIdentifier.equalsIgnoringCase(id) }) {
                ordered.append(b)
            }
        }
        for b in all where !ordered.contains(where: { $0.bundleIdentifier.equalsIgnoringCase(b.bundleIdentifier) }) {
            ordered.append(b)
        }
        return ordered
    }

    private func saveOrder() {
        UserDefaults.standard.set(browsers.map { $0.bundleIdentifier }, forKey: "browserOrder")
    }

    func moveBrowsers(from source: IndexSet, to destination: Int) {
        browsers.move(fromOffsets: source, toOffset: destination)
        saveOrder()
    }

}

// MARK: - Preferences View

struct PreferencesView: View {
    @ObservedObject var state: PreferencesState
    @ObservedObject var ruleManager: URLRuleManager
    let browserManager: BrowserManager

    @State private var selection: Tab = .browsers

    enum Tab: Hashable { case browsers, rules, about }

    var body: some View {
        TabView(selection: $selection) {
            BrowsersTab(state: state)
                .tabItem { Label("Browsers", systemImage: "square.grid.2x2.fill") }
                .tag(Tab.browsers)

            RulesTab(state: state, ruleManager: ruleManager, browserManager: browserManager)
                .tabItem { Label("Rules", systemImage: "arrow.triangle.branch") }
                .tag(Tab.rules)

            AboutTab()
                .tabItem { Label("About", systemImage: "info.circle.fill") }
                .tag(Tab.about)
        }
        .frame(minWidth: 680, idealWidth: 720, minHeight: 560, idealHeight: 600)
    }
}

// MARK: - Browsers Tab

private struct BrowsersTab: View {
    @ObservedObject var state: PreferencesState

    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            TabHeader(
                title: "Installed Browsers",
                subtitle: "Drag to reorder. The first nine browsers get ⌘1–⌘9 shortcuts in the menu."
            )
            .padding(.bottom, 16)

            if state.browsers.isEmpty {
                emptyState
            } else {
                browserList
            }
        }
        .padding(28)
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
    }

    private var emptyState: some View {
        VStack(spacing: 10) {
            Image(systemName: "magnifyingglass")
                .font(.system(size: 32, weight: .light))
                .foregroundStyle(.tertiary)
            Text("No browsers detected")
                .font(.headline)
            Text("Install a browser from your Applications folder, then reopen this window.")
                .font(.subheadline)
                .foregroundStyle(.secondary)
                .multilineTextAlignment(.center)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }

    private var browserList: some View {
        List {
            ForEach(Array(state.browsers.enumerated()), id: \.1.id) { index, browser in
                HStack(spacing: 12) {
                    Image(nsImage: browser.icon)
                        .resizable()
                        .frame(width: 26, height: 26)

                    Text(browser.name)
                        .font(.system(size: 14, weight: .medium))
                        .lineLimit(1)

                    Spacer()

                    if index < 9 {
                        Text("\u{2318}\(index + 1)")
                            .font(.system(.callout, design: .monospaced).weight(.medium))
                            .foregroundStyle(.secondary)
                            .padding(.horizontal, 8)
                            .padding(.vertical, 2)
                            .background(
                                RoundedRectangle(cornerRadius: 5)
                                    .fill(Color(nsColor: .quaternaryLabelColor).opacity(0.4))
                            )
                    }

                    Image(systemName: "line.3.horizontal")
                        .foregroundStyle(.tertiary)
                        .font(.system(size: 12, weight: .semibold))
                }
                .padding(.vertical, 6)
            }
            .onMove { state.moveBrowsers(from: $0, to: $1) }
        }
        .listStyle(.inset)
        .scrollContentBackground(.hidden)
        .cardSurface()
    }
}

// MARK: - Rules Tab

private struct RulesTab: View {
    @ObservedObject var state: PreferencesState
    @ObservedObject var ruleManager: URLRuleManager
    let browserManager: BrowserManager

    @State private var isDefaultBrowser = false
    @State private var isSettingDefault = false
    @State private var defaultBrowserError: String?
    @State private var showingAddSheet = false
    @State private var launchAtLogin = SMAppService.mainApp.status == .enabled

    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 20) {
                rulesHeader

                rulesCard

                defaultsCard

                generalCard
            }
            .padding(28)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
        .onAppear { isDefaultBrowser = browserManager.isSystemDefaultBrowser }
        .onChange(of: launchAtLogin) { _, newValue in toggleLaunchAtLogin(newValue) }
        .sheet(isPresented: $showingAddSheet) {
            AddRuleSheet(
                browsers: state.browsers,
                browserManager: browserManager,
                onCancel: { showingAddSheet = false },
                onSubmit: { pattern, browserID, profile in
                    ruleManager.addRule(pattern: pattern, browserBundleID: browserID, profileDirectory: profile)
                    showingAddSheet = false
                }
            )
        }
    }

    private func setAsDefaultBrowser() {
        isSettingDefault = true
        defaultBrowserError = nil
        browserManager.promoteSelfToSystemDefault { result in
            isSettingDefault = false
            switch result {
            case .success:
                isDefaultBrowser = true
            case .failed(let reason):
                isDefaultBrowser = false
                defaultBrowserError = reason
            }
        }
    }

    private func toggleLaunchAtLogin(_ enabled: Bool) {
        do {
            if enabled { try SMAppService.mainApp.register() }
            else { try SMAppService.mainApp.unregister() }
        } catch {
            launchAtLogin = SMAppService.mainApp.status == .enabled
        }
    }

    private var rulesHeader: some View {
        HStack(alignment: .top) {
            TabHeader(
                title: "URL Routing Rules",
                subtitle: "Route specific domains or paths to a chosen browser. Longest pattern wins."
            )
            Spacer()
            Button {
                showingAddSheet = true
            } label: {
                Label("Add Rule", systemImage: "plus")
            }
            .controlSize(.regular)
            .disabled(state.browsers.isEmpty)
        }
    }

    private var rulesCard: some View {
        VStack(spacing: 0) {
            if ruleManager.rules.isEmpty {
                emptyRulesState
            } else {
                ForEach(Array(ruleManager.rules.enumerated()), id: \.1.id) { index, rule in
                    RuleRow(
                        rule: rule,
                        browser: state.browsers.first { $0.bundleIdentifier.equalsIgnoringCase(rule.browserBundleID) },
                        hitCount: ruleManager.hitCount(for: rule),
                        onToggle: {
                            withAnimation(.easeInOut(duration: 0.15)) { ruleManager.toggleRule(id: rule.id) }
                        },
                        onDelete: { ruleManager.deleteRule(id: rule.id) }
                    )
                    if index < ruleManager.rules.count - 1 {
                        Divider().padding(.leading, 16)
                    }
                }
            }
        }
        .cardSurface()
    }

    private var emptyRulesState: some View {
        VStack(spacing: 6) {
            Image(systemName: "arrow.triangle.branch")
                .font(.system(size: 22, weight: .light))
                .foregroundStyle(.tertiary)
            Text("No rules yet")
                .font(.subheadline).fontWeight(.medium)
            Text("Click Add Rule to route a domain like github.com to a specific browser.")
                .font(.caption)
                .foregroundStyle(.secondary)
                .multilineTextAlignment(.center)
        }
        .frame(maxWidth: .infinity)
        .padding(.vertical, 28)
    }

    private var defaultsCard: some View {
        VStack(alignment: .leading, spacing: 8) {
            SectionLabel("Defaults")

            VStack(spacing: 0) {
                SettingsRow(
                    title: "Default Browser",
                    subtitle: "Where links open when no rule matches."
                ) {
                    Picker("", selection: Binding(
                        get: { ruleManager.fallbackBrowserID ?? state.browsers.first?.bundleIdentifier ?? "" },
                        set: { ruleManager.fallbackBrowserID = $0.isEmpty ? nil : $0 }
                    )) {
                        ForEach(state.browsers) { b in Text(b.name).tag(b.bundleIdentifier) }
                    }
                    .labelsHidden()
                    .frame(width: 180)
                }

                Divider().padding(.horizontal, 16)

                SettingsRow(
                    title: "macOS Routing",
                    subtitle: defaultBrowserError ?? "macOS sends every link to MenuBrowser first.",
                    subtitleIsWarning: defaultBrowserError != nil
                ) {
                    if isDefaultBrowser {
                        Label("Active", systemImage: "checkmark.circle.fill")
                            .foregroundStyle(.green)
                            .font(.system(size: 13, weight: .medium))
                    } else if isSettingDefault {
                        ProgressView().controlSize(.small)
                    } else {
                        Button("Enable", action: setAsDefaultBrowser)
                    }
                }
            }
            .cardSurface()
        }
    }

    private var generalCard: some View {
        VStack(alignment: .leading, spacing: 8) {
            SectionLabel("General")

            VStack(spacing: 0) {
                SettingsRow(
                    title: "Open Quick Menu",
                    subtitle: state.shortcutError ?? "Global hotkey to open the browser menu.",
                    subtitleIsWarning: state.shortcutError != nil
                ) {
                    Button(state.isRecording ? "Press shortcut\u{2026}" : state.shortcutDisplay) {
                        if state.isRecording { state.stopRecording() } else { state.startRecording() }
                    }
                    .font(.system(.body, design: .monospaced).weight(.medium))
                }

                Divider().padding(.horizontal, 16)

                SettingsRow(
                    title: "Launch at Login",
                    subtitle: "Start MenuBrowser automatically when you log in."
                ) {
                    Toggle("", isOn: $launchAtLogin).toggleStyle(.switch).labelsHidden()
                }
            }
            .cardSurface()
        }
    }
}

private struct RuleRow: View {
    let rule: URLRule
    let browser: BrowserInfo?
    let hitCount: Int
    let onToggle: () -> Void
    let onDelete: () -> Void

    var body: some View {
        HStack(spacing: 12) {
            Button(action: onToggle) {
                Image(systemName: rule.enabled ? "checkmark.circle.fill" : "circle")
                    .font(.system(size: 16))
                    .foregroundStyle(rule.enabled ? Color.accentColor : Color.secondary)
            }
            .buttonStyle(.plain)

            Text(rule.pattern)
                .font(.system(.body, design: .monospaced))
                .lineLimit(1)
                .foregroundStyle(rule.enabled ? .primary : .secondary)

            Image(systemName: "arrow.right")
                .font(.caption)
                .foregroundStyle(.tertiary)

            HStack(spacing: 6) {
                if let icon = browser?.icon {
                    Image(nsImage: icon).resizable().frame(width: 16, height: 16)
                }
                Text(browser?.name ?? rule.browserBundleID)
                    .lineLimit(1)
                    .foregroundStyle(.secondary)
            }

            if let profile = rule.profileDirectory {
                Text(profile)
                    .font(.system(.caption2, design: .monospaced))
                    .padding(.horizontal, 6)
                    .padding(.vertical, 2)
                    .background(
                        RoundedRectangle(cornerRadius: 4)
                            .fill(Color(nsColor: .quaternaryLabelColor).opacity(0.4))
                    )
            }

            Spacer()

            if hitCount > 0 {
                Text("\(hitCount) match\(hitCount == 1 ? "" : "es")")
                    .font(.system(.caption, design: .monospaced))
                    .foregroundStyle(.tertiary)
            }

            Button(action: onDelete) {
                Image(systemName: "xmark.circle.fill")
                    .foregroundStyle(.secondary)
                    .font(.system(size: 14))
            }
            .buttonStyle(.plain)
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
        .opacity(rule.enabled ? 1 : 0.55)
    }
}

private struct AddRuleSheet: View {
    let browsers: [BrowserInfo]
    let browserManager: BrowserManager
    let onCancel: () -> Void
    let onSubmit: (String, String, String?) -> Void

    @State private var pattern = ""
    @State private var browserID = ""
    @State private var profile = ""
    // Resolved when the browser selection changes rather than computed in `body`:
    // profile lookup reads and JSON-parses the browser's on-disk `Local State`.
    @State private var availableProfiles: [BrowserProfile] = []

    var body: some View {
        VStack(alignment: .leading, spacing: 20) {
            Text("Add URL Rule")
                .font(.system(size: 15, weight: .semibold))

            Form {
                TextField("Pattern", text: $pattern, prompt: Text("github.com  or  github.com/my-org"))
                    .textFieldStyle(.roundedBorder)
                    .font(.system(.body, design: .monospaced))

                Picker("Open in", selection: $browserID) {
                    Text("Select a browser\u{2026}").tag("")
                    ForEach(browsers) { b in Text(b.name).tag(b.bundleIdentifier) }
                }
                .onChange(of: browserID) { _, newID in
                    profile = ""
                    availableProfiles = browsers
                        .first { $0.bundleIdentifier == newID }
                        .map { browserManager.profiles(for: $0) } ?? []
                }

                if !availableProfiles.isEmpty {
                    Picker("Profile", selection: $profile) {
                        Text("Default").tag("")
                        ForEach(availableProfiles) { p in Text(p.name).tag(p.directory) }
                    }
                }
            }
            .formStyle(.grouped)

            HStack {
                Spacer()
                Button("Cancel", action: onCancel)
                    .keyboardShortcut(.cancelAction)
                Button("Add Rule") {
                    onSubmit(
                        pattern.trimmingCharacters(in: .whitespaces),
                        browserID,
                        profile.isEmpty ? nil : profile
                    )
                }
                .keyboardShortcut(.defaultAction)
                .disabled(pattern.trimmingCharacters(in: .whitespaces).isEmpty || browserID.isEmpty)
            }
        }
        .padding(24)
        .frame(width: 440)
    }
}

// MARK: - About Tab

private struct AboutTab: View {
    private var version: String {
        Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "1.0"
    }

    var body: some View {
        VStack(spacing: 20) {
            Spacer(minLength: 0)

            if let icon = NSImage(named: "AppIcon") {
                Image(nsImage: icon)
                    .resizable()
                    .interpolation(.high)
                    .frame(width: 112, height: 112)
            }

            VStack(spacing: 4) {
                Text("MenuBrowser")
                    .font(.system(size: 28, weight: .semibold))
                Text("Version \(version)")
                    .font(.system(size: 13))
                    .foregroundStyle(.secondary)
            }

            Text("A fast, keyboard-first browser router for macOS.")
                .font(.system(size: 13))
                .foregroundStyle(.secondary)

            HStack(spacing: 12) {
                Button {
                    openURL("https://github.com/fenilsonani/menu-browser")
                } label: {
                    Label("GitHub", systemImage: "arrow.up.right.square")
                }
                Button {
                    openURL("https://github.com/fenilsonani/menu-browser/issues/new")
                } label: {
                    Label("Report an Issue", systemImage: "ladybug")
                }
            }
            .controlSize(.regular)

            Spacer(minLength: 0)

            Text("Made by Fenil Sonani")
                .font(.caption)
                .foregroundStyle(.tertiary)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .padding(28)
    }

    private func openURL(_ urlString: String) {
        if let url = URL(string: urlString) {
            NSWorkspace.shared.open(url)
        }
    }
}

// MARK: - Shared

private struct TabHeader: View {
    let title: String
    let subtitle: String

    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            Text(title)
                .font(.system(size: 15, weight: .semibold))
            Text(subtitle)
                .font(.subheadline)
                .foregroundStyle(.secondary)
        }
    }
}

/// Small uppercase-weight label introducing a group of settings rows.
private struct SectionLabel: View {
    let title: String

    init(_ title: String) { self.title = title }

    var body: some View {
        Text(title)
            .font(.system(size: 11, weight: .semibold))
            .foregroundStyle(.secondary)
            .tracking(0.5)
    }
}

/// One "title + explanation on the left, control on the right" row inside a settings card.
private struct SettingsRow<Control: View>: View {
    let title: String
    let subtitle: String
    /// Draws the subtitle as an error instead of secondary explanatory text.
    var subtitleIsWarning: Bool = false
    @ViewBuilder let control: () -> Control

    var body: some View {
        HStack {
            VStack(alignment: .leading, spacing: 2) {
                Text(title)
                Text(subtitle)
                    .font(.caption)
                    .foregroundStyle(subtitleIsWarning ? AnyShapeStyle(Color.red) : AnyShapeStyle(.secondary))
                    .fixedSize(horizontal: false, vertical: true)
            }
            Spacer()
            control()
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }
}

private extension View {
    /// The rounded, hairline-bordered surface shared by every settings card.
    func cardSurface(cornerRadius: CGFloat = 10) -> some View {
        background(
            RoundedRectangle(cornerRadius: cornerRadius)
                .fill(Color(nsColor: .controlBackgroundColor))
        )
        .overlay(
            RoundedRectangle(cornerRadius: cornerRadius)
                .strokeBorder(Color(nsColor: .separatorColor), lineWidth: 0.5)
        )
    }
}