import SwiftUI
import UIKit

/// Settings → Tools → "Connect route-explorer". Walks the user through
/// the Safari-bookmarklet flow that mints a route-explorer `/api/token`
/// in Safari (where Cloudflare Turnstile passes silently because Safari
/// holds the `com.apple.developer.web-browser` entitlement and is
/// eligible for Apple Private Access Tokens), captures it, and hands it
/// back to this app via the `flights://routeexplorer-token` URL scheme.
///
/// One-time setup steps shown to the user:
///   1. Copy the bookmarklet JS (single button).
///   2. In Safari, navigate to https://route-explorer.com/ — open the
///      bookmarks editor (book icon → Edit) → tap "Add Bookmark" with
///      a recognizable name, then edit the bookmark's URL and paste the
///      JS over the http URL.
///   3. Anytime later: open route-explorer.com in Safari, tap the
///      bookmarklet → app comes to the foreground with a fresh token.
///
/// Daily-use steps (after setup):
///   • Tap "Open route-explorer.com" to launch Safari at the right URL.
///   • Tap the saved bookmarklet in Safari.
///   • Return to the app — token state at the top of this screen now
///     shows the new expiry.
struct RouteExplorerSetupView: View {
    @StateObject private var store = RouteExplorerTokenStore.shared
    @State private var didCopy: Bool = false
    @State private var nowTick: Date = .init()
    @State private var browserURL: URL?
    private let tickTimer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        List {
            browserSection
            statusSection
            actionsSection
            instructionsSection
            bookmarkletSection
            advancedSection
        }
        .listStyle(.insetGrouped)
        .navigationTitle("Connect route-explorer")
        .navigationBarTitleDisplayMode(.inline)
        .onReceive(tickTimer) { now in
            nowTick = now
        }
        .fullScreenCover(item: $browserURL) { url in
            NavigationStack {
                RouteExplorerBrowserView(url: url)
                    .ignoresSafeArea()
                    .toolbar {
                        ToolbarItem(placement: .cancellationAction) {
                            Button("Done") { browserURL = nil }
                        }
                    }
            }
        }
    }

    // MARK: - In-app browser

    /// Primary action: open route-explorer.com inside the app using
    /// SFSafariViewController. This bypasses the bookmarklet entirely
    /// — the user just searches in the embedded browser.
    private var browserSection: some View {
        Section {
            Button {
                browserURL = URL(string: "https://route-explorer.com/")
            } label: {
                Label("Open route-explorer in-app", systemImage: "globe")
                    .font(.body.weight(.semibold))
            }
        } header: {
            Text("Search")
        } footer: {
            Text("Opens route-explorer.com inside an embedded Safari browser. Multi-stop search, where-can-I-go, every feature — works because Safari (not WKWebView) passes Cloudflare Turnstile.")
        }
    }

    // MARK: - Status

    private var statusSection: some View {
        Section {
            HStack {
                Image(systemName: store.isValid ? "checkmark.seal.fill" : "exclamationmark.triangle.fill")
                    .foregroundStyle(store.isValid ? .green : .orange)
                VStack(alignment: .leading, spacing: 2) {
                    Text(store.isValid ? "Token active" : "No valid token").font(.subheadline.weight(.semibold))
                    if store.isValid {
                        Text("Expires in \(Self.formatRemaining(store.timeRemaining))")
                            .font(.caption).foregroundStyle(.secondary)
                    } else {
                        Text("Run the bookmarklet in Safari to refresh.")
                            .font(.caption).foregroundStyle(.secondary)
                    }
                }
            }
        } header: {
            Text("Token state")
        }
    }

    // MARK: - Actions

    private var actionsSection: some View {
        Section {
            Button {
                if let url = URL(string: "https://route-explorer.com/") {
                    UIApplication.shared.open(url)
                }
            } label: {
                Label("Open route-explorer.com in Safari", systemImage: "safari")
            }
            Button {
                copyBookmarklet()
            } label: {
                Label(didCopy ? "Copied!" : "Copy bookmarklet to clipboard",
                      systemImage: didCopy ? "doc.on.doc.fill" : "doc.on.doc")
            }
            if store.isValid {
                Button(role: .destructive) {
                    store.clear()
                } label: {
                    Label("Clear stored token", systemImage: "trash")
                }
            }
        }
    }

    // MARK: - Instructions

    private var instructionsSection: some View {
        Section {
            stepRow(num: 1, text: "Tap **Copy bookmarklet to clipboard** above.")
            stepRow(num: 2, text: "Tap **Open route-explorer.com in Safari**.")
            stepRow(num: 3, text: "In Safari, tap the share button → **Add Bookmark**. Save it as e.g. \"Flights Token\".")
            stepRow(num: 4, text: "Tap the bookmarks icon (book) → Edit → tap the new bookmark → replace its URL with the clipboard contents → Save.")
            stepRow(num: 5, text: "Each refresh: open route-explorer.com in Safari → tap **Bookmarks → Flights Token**. The app will pop up with a fresh token.")
        } header: {
            Text("One-time setup")
        } footer: {
            Text("Tokens expire every ~30 minutes. Re-run the bookmarklet from step 5 anytime to refresh.")
        }
    }

    private var bookmarkletSection: some View {
        Section {
            ScrollView(.horizontal, showsIndicators: false) {
                Text(bookmarkletJS)
                    .font(.caption.monospaced())
                    .padding(.vertical, 4)
            }
        } header: {
            Text("Bookmarklet JS")
        } footer: {
            Text("Reads route-explorer's /api/token (Safari has the Turnstile clearance cookie already), then redirects to flights:// with the token attached.")
        }
    }

    private var advancedSection: some View {
        Section {
            Button("Test the URL scheme") {
                testURLScheme()
            }
            .disabled(!store.isValid)
            if let token = store.token {
                HStack {
                    Text("Token").foregroundStyle(.secondary)
                    Spacer()
                    Text(String(token.prefix(12)) + "…")
                        .font(.caption.monospaced())
                }
            }
            if let cookie = store.capturedCookieHeader, !cookie.isEmpty {
                Text("Captured cookies: \(cookie.prefix(80))…")
                    .font(.caption.monospaced())
                    .foregroundStyle(.secondary)
            }
        } header: {
            Text("Advanced")
        }
    }

    // MARK: - Helpers

    private func stepRow(num: Int, text: String) -> some View {
        HStack(alignment: .top, spacing: 12) {
            Text("\(num)")
                .font(.footnote.weight(.bold).monospacedDigit())
                .frame(width: 22, height: 22)
                .background(Color.accentColor.opacity(0.15), in: Circle())
                .foregroundStyle(.tint)
            Text(.init(text))
                .font(.footnote)
            Spacer()
        }
    }

    private func copyBookmarklet() {
        UIPasteboard.general.string = bookmarkletJS
        didCopy = true
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) { didCopy = false }
    }

    private func testURLScheme() {
        // Simulate Safari's redirect to verify the handler chain is alive.
        let url = URL(string:
            "flights://routeexplorer-token?token=TEST_TOKEN_FROM_DIAGNOSTIC&exp=\(Int(Date().timeIntervalSince1970 + 60))"
        )!
        UIApplication.shared.open(url)
    }

    private static func formatRemaining(_ seconds: TimeInterval) -> String {
        let total = Int(seconds)
        let m = total / 60
        let s = total % 60
        if m > 0 { return "\(m)m \(s)s" }
        return "\(s)s"
    }

    /// Bookmarklet JS. Single-line `javascript:` URL the user pastes
    /// into a Safari bookmark. Reads the token from the route-explorer
    /// API (Safari has clearance), grabs any visible cookies, then
    /// jumps back into our app via the custom URL scheme.
    private var bookmarkletJS: String {
        """
        javascript:(function(){fetch('/api/token',{credentials:'include'}).then(function(r){return r.json();}).then(function(t){var c=encodeURIComponent(document.cookie||'');var tok=encodeURIComponent(t.token||'');var exp=Math.floor(Date.now()/1000)+1800;window.location='flights://routeexplorer-token?token='+tok+'&exp='+exp+'&cookie='+c;}).catch(function(e){alert('route-explorer token fetch failed: '+e);});})();
        """
    }
}
