import SwiftUI

/// "How does this work?" — surfaces every data source the app uses so
/// the user can judge what's live, what's curated, what's stale, and
/// what's hand-typed. Replaces a generic "About" screen with a
/// provenance-first layout: each card cites the actual source and pulls
/// the freshness date from the data file's `_meta` block when one exists.
///
/// Anything user-facing that doesn't have a clean cite-able source
/// (TSA baselines, the cascade-via-rotation fallback card) is labelled
/// honestly here so users know what they're looking at.
struct SettingsView: View {

    @State private var btsMeta: BTSMetadata?
    @State private var appVersion: String = "—"
    @State private var appBuild: String = "—"

    var body: some View {
        NavigationStack {
            List {
                introSection
                toolsSection
                liveSection
                curatedSection
                historicalSection
                personalSection
                aboutSection
            }
            .listStyle(.insetGrouped)
            .scrollContentBackground(.hidden)
            .background(FlightTheme.background.ignoresSafeArea())
            .navigationTitle("Settings")
            .navigationBarTitleDisplayMode(.large)
            .task {
                await loadMetadata()
                loadAppVersion()
            }
        }
    }

    // MARK: - Tools

    /// Section that hosts the nonrev-reference tools that used to live
    /// in their own tabs. Pulled under Settings so the tab bar stays
    /// focused on the three working surfaces (Search, Live, History).
    private var toolsSection: some View {
        Section {
            NavigationLink {
                HubLoadsView()
            } label: {
                toolRow(icon: "chart.bar.xaxis",
                        title: "Hub load heatmap",
                        subtitle: "BTS-derived load tightness per hub")
            }
            NavigationLink {
                RouteExplorerSetupView()
            } label: {
                toolRow(icon: "key.horizontal.fill",
                        title: "Connect route-explorer",
                        subtitle: "Bookmarklet token refresh — restores Search")
            }
            NavigationLink {
                TurnstileDebugView()
            } label: {
                toolRow(icon: "shield.lefthalf.filled",
                        title: "Turnstile diagnostics",
                        subtitle: "Live WKWebView gate — cookies, probe, console")
            }
            NavigationLink {
                DiagnosticsView()
            } label: {
                toolRow(icon: "doc.text.magnifyingglass",
                        title: "Diagnostics logs",
                        subtitle: "Full trace — share via AirDrop / email")
            }
        } header: {
            sectionHeader("Tools")
        }
    }

    private func toolRow(icon: String, title: String, subtitle: String) -> some View {
        HStack(spacing: 12) {
            Image(systemName: icon)
                .foregroundStyle(FlightTheme.accent)
                .frame(width: 28)
            VStack(alignment: .leading, spacing: 2) {
                Text(title)
                    .font(.footnote.weight(.semibold))
                    .foregroundStyle(FlightTheme.textPrimary)
                Text(subtitle)
                    .font(.caption2)
                    .foregroundStyle(FlightTheme.textSecondary)
            }
        }
    }

    // MARK: - Sections

    private var introSection: some View {
        Section {
            VStack(alignment: .leading, spacing: 8) {
                Text("Three kinds of data")
                    .font(.subheadline.weight(.semibold))
                    .foregroundStyle(FlightTheme.textPrimary)
                Text("**Live** — fetched fresh whenever you tap or refresh.\n**Reference** — curated tables shipped in the app; updated on app releases.\n**Yours** — flight history you log, stored on-device and synced to your iCloud.")
                    .font(.footnote)
                    .foregroundStyle(FlightTheme.textSecondary)
            }
            .padding(.vertical, 4)
        }
    }

    // MARK: Live data

    private var liveSection: some View {
        Section {
            sourceRow(
                icon: "antenna.radiowaves.left.and.right",
                title: "Live aircraft positions",
                source: "Flightradar24 (primary) + OpenSky Network (fallback)",
                detail: "Refreshes every 15 seconds while the Live tab is open, plus immediately when you bring the app back to the foreground. ADS-B feeds carry a 5–15 minute delay by design — what you see is the most recent fix each network has published.",
                links: [
                    ("Flightradar24", URL(string: "https://www.flightradar24.com/")!),
                    ("OpenSky", URL(string: "https://opensky-network.org/")!),
                ],
                isLive: true
            )
            sourceRow(
                icon: "cloud.sun",
                title: "Weather forecast",
                source: "Open-Meteo",
                detail: "Free, key-less public weather API. We fetch a 3-day hourly forecast for the departure and arrival airports and sample the hour closest to the flight's scheduled time. Risk band combines precipitation probability, weather code (thunderstorms), wind, and visibility.",
                links: [("Open-Meteo", URL(string: "https://open-meteo.com/")!)],
                isLive: true
            )
            sourceRow(
                icon: "camera",
                title: "Aircraft photos",
                source: "planespotters.net",
                detail: "Per-tail-number photos when the registration is known. The site is contributor-maintained — most recent photo per airframe is what surfaces, which is why special liveries appear naturally (photographers chase them first).",
                links: [("planespotters.net", URL(string: "https://www.planespotters.net/")!)],
                isLive: true
            )
            sourceRow(
                icon: "magnifyingglass",
                title: "Flight schedules (sister-flight finder)",
                source: "FlightConnections",
                detail: "When you open the Live detail sheet, the \"Other options today\" list queries FlightConnections for every flight on the route that day. The Search tab originally used route-explorer.com but their backend now requires a Cloudflare browser-verification step that we can't pass from a native app, so connection finding is currently out of reach without a backend proxy.",
                links: [("FlightConnections", URL(string: "https://www.flightconnections.com/")!)],
                isLive: true
            )
        } header: {
            sectionHeader("Live data")
        } footer: {
            Text("Live data is fetched fresh and isn't cached past the moment it was used.")
                .font(.caption2)
                .foregroundStyle(FlightTheme.textTertiary)
        }
    }

    // MARK: Curated / bundled reference data

    private var curatedSection: some View {
        Section {
            sourceRow(
                icon: "airplane",
                title: "Aircraft seat counts",
                source: "Each carrier's published fleet page",
                detail: "Per-carrier per-aircraft-type seat counts (e.g. AA's 737-800 vs WN's 737-800 — different cabin layouts, different totals). Powers the equipment-swap card. Citation URL per entry.",
                links: [],
                isLive: false
            )
            sourceRow(
                icon: "globe.americas",
                title: "Airport + airline database",
                source: "OpenFlights-derived bundle",
                detail: "~4,500 airports (IATA, name, lat/lng) and 1,000+ airlines (IATA, ICAO, name) ship inside the app. Used everywhere — autocomplete, map, timezone resolution, route lookups.",
                links: [("OpenFlights", URL(string: "https://openflights.org/")!)],
                isLive: false
            )
        } header: {
            sectionHeader("Reference data (curated, shipped with the app)")
        } footer: {
            Text("Curated data only updates when you install a new build of the app. Every entry has a `_meta` block in the bundled JSON tracking when it was last verified.")
                .font(.caption2)
                .foregroundStyle(FlightTheme.textTertiary)
        }
    }

    // MARK: Historical / statistical data

    private var historicalSection: some View {
        Section {
            sourceRow(
                icon: "chart.line.uptrend.xyaxis",
                title: "Load factor + on-time history",
                source: btsSourceLabel,
                detail: btsDetailString,
                links: btsMeta?.sourceURLs.compactMap { URL(string: $0) }.map { ($0.host ?? "source", $0) } ?? [],
                isLive: false
            )
            sourceRow(
                icon: "chart.bar.xaxis",
                title: "Hub load heatmap",
                source: "Derived from BTS bundle (above)",
                detail: "Per-airport aggregated load factor, weighted by route volume. Tap the chart icon on the Jumpseats tab to browse all hubs sorted tightest-first.",
                links: [],
                isLive: false
            )
        } header: {
            sectionHeader("Historical data")
        } footer: {
            Text("BTS publishes data about 2–3 months behind real-time. A new app update is needed to ship a newer sample period.")
                .font(.caption2)
                .foregroundStyle(FlightTheme.textTertiary)
        }
    }

    // MARK: Personal data

    private var personalSection: some View {
        Section {
            sourceRow(
                icon: "book.closed",
                title: "Your flight history",
                source: "Local SwiftData + iCloud (private DB)",
                detail: "Every flight you log lives on this device and syncs to your iCloud account. We don't run a server, we don't have analytics, and we never see your data. Logging in on a second device pulls everything from CloudKit automatically.",
                links: [],
                isLive: false
            )
            sourceRow(
                icon: "figure.stand.line.dotted.figure.stand",
                title: "Standby outcomes",
                source: "You",
                detail: "When you tap a flight in History and pick \"Standby — Made\" or \"Standby — Bumped\", we record it alongside the flight. The Standby Stats card on History and the per-route success rate are computed entirely from your own log.",
                links: [],
                isLive: false
            )
            sourceRow(
                icon: "exclamationmark.triangle",
                title: "Save failures",
                source: "DataIntegrityMonitor (in-app)",
                detail: "If a SwiftData save throws (rare — disk full, CloudKit conflict), a red banner appears at the top of the screen telling you which operation failed. Dismissing the banner doesn't retry the save — it just hides the warning. Best practice: take a screenshot of any failed edit, restart the app, and re-enter it.",
                links: [],
                isLive: false
            )
        } header: {
            sectionHeader("Your data")
        } footer: {
            Text("No analytics, no telemetry, no third-party servers in the flight-history loop. The only network calls are to the public sources listed above.")
                .font(.caption2)
                .foregroundStyle(FlightTheme.textTertiary)
        }
    }

    // MARK: About

    private var aboutSection: some View {
        Section {
            HStack {
                Image(systemName: "info.circle")
                    .foregroundStyle(FlightTheme.accent)
                    .frame(width: 28)
                Text("Version")
                    .font(.footnote)
                Spacer()
                Text("\(appVersion) (\(appBuild))")
                    .font(.footnote.monospaced())
                    .foregroundStyle(FlightTheme.textSecondary)
            }
            HStack {
                Image(systemName: "exclamationmark.bubble")
                    .foregroundStyle(FlightTheme.accent)
                    .frame(width: 28)
                Text("Reporting issues")
                    .font(.footnote)
                Spacer()
                Text("Save the failed screen and reach out directly")
                    .font(.caption)
                    .foregroundStyle(FlightTheme.textSecondary)
                    .multilineTextAlignment(.trailing)
            }
        } header: {
            sectionHeader("About")
        }
    }

    // MARK: - Row builders

    @ViewBuilder
    private func sourceRow(
        icon: String,
        title: String,
        source: String,
        detail: String,
        links: [(String, URL)],
        isLive: Bool,
        warning: String? = nil
    ) -> some View {
        DisclosureGroup {
            VStack(alignment: .leading, spacing: 10) {
                Text(detail)
                    .font(.footnote)
                    .foregroundStyle(FlightTheme.textSecondary)
                    .fixedSize(horizontal: false, vertical: true)

                if let warning {
                    HStack(alignment: .top, spacing: 6) {
                        Image(systemName: "exclamationmark.triangle.fill")
                            .font(.caption2)
                            .foregroundStyle(FlightTheme.cancelled)
                        Text(warning)
                            .font(.caption2.weight(.semibold))
                            .foregroundStyle(FlightTheme.cancelled)
                    }
                    .padding(.top, 2)
                }

                if !links.isEmpty {
                    VStack(alignment: .leading, spacing: 4) {
                        Text("SOURCES")
                            .font(.caption2.weight(.heavy))
                            .tracking(0.6)
                            .foregroundStyle(FlightTheme.textTertiary)
                        ForEach(links, id: \.1) { name, url in
                            Link(destination: url) {
                                HStack(spacing: 6) {
                                    Image(systemName: "arrow.up.right.square")
                                        .font(.caption2)
                                    Text(name)
                                        .font(.caption.weight(.medium))
                                }
                                .foregroundStyle(FlightTheme.accent)
                            }
                        }
                    }
                    .padding(.top, 4)
                }
            }
            .padding(.top, 4)
        } label: {
            HStack(spacing: 12) {
                Image(systemName: icon)
                    .foregroundStyle(FlightTheme.accent)
                    .frame(width: 28)
                VStack(alignment: .leading, spacing: 2) {
                    Text(title)
                        .font(.footnote.weight(.semibold))
                        .foregroundStyle(FlightTheme.textPrimary)
                    Text(source)
                        .font(.caption2)
                        .foregroundStyle(FlightTheme.textSecondary)
                        .lineLimit(2)
                }
                Spacer(minLength: 4)
                liveTag(isLive: isLive)
            }
        }
    }

    private func liveTag(isLive: Bool) -> some View {
        Text(isLive ? "LIVE" : "REF")
            .font(.caption2.weight(.heavy))
            .tracking(0.6)
            .foregroundStyle(.white)
            .padding(.horizontal, 6)
            .padding(.vertical, 2)
            .background(isLive ? FlightTheme.onTime : FlightTheme.textTertiary)
            .clipShape(Capsule())
    }

    private func sectionHeader(_ text: String) -> some View {
        Text(text)
            .font(.footnote.weight(.bold))
            .tracking(0.5)
            .foregroundStyle(FlightTheme.textSecondary)
    }

    // MARK: - Dynamic content helpers

    private var btsSourceLabel: String {
        guard let meta = btsMeta else {
            return "US DOT Bureau of Transportation Statistics"
        }
        return "US DOT BTS — \(meta.sourcePeriod) (\(meta.recordCount) records)"
    }

    private var btsDetailString: String {
        guard let meta = btsMeta else {
            return "On-time percentages, average delay, cancellation rate, and average load factor per (carrier, flight number, origin, destination). Sourced from the DOT's Reporting Carrier On-Time Performance + T-100 Domestic Segment public datasets."
        }
        let carriers = meta.carriers.joined(separator: ", ")
        return """
On-time percentages, average delay, cancellation rate, and average load factor per (carrier, flight number, origin, destination). Sourced from the DOT's Reporting Carrier On-Time Performance + T-100 Domestic Segment public datasets.

Sample period: \(meta.sourcePeriod) — generated \(meta.downloadedAt). Filter: routes with at least \(meta.minFlightsFilter) operated flights.
Carriers covered: \(carriers).

\(meta.notes)
"""
    }

    // MARK: - Loaders

    private func loadMetadata() async {
        let bts = await BTSDataStore.shared.metadata()
        await MainActor.run {
            self.btsMeta = bts
        }
    }

    private func loadAppVersion() {
        let info = Bundle.main.infoDictionary ?? [:]
        appVersion = info["CFBundleShortVersionString"] as? String ?? "—"
        appBuild = info["CFBundleVersion"] as? String ?? "—"
    }
}

#Preview {
    SettingsView()
}
