import SwiftUI
import SwiftData
import LocalAuthentication
import EventKit

struct SettingsView: View {
    @Environment(\.nahbarTheme) var theme
    @AppStorage("activeThemeID") private var activeThemeIDRaw: String = ThemeID.linen.rawValue
    @EnvironmentObject private var callWindowManager: CallWindowManager
    @EnvironmentObject private var appLockManager: AppLockManager
    @EnvironmentObject private var cloudSyncMonitor: CloudSyncMonitor

    @AppStorage("upcomingDaysAhead") private var daysAhead: Int = 7
    @AppStorage("selectedCalendarID") private var defaultCalendarID: String = ""
    @State private var settingsCalendars: [EKCalendar] = []
    @AppStorage("aftermathNotificationsEnabled") private var aftermathNotificationsEnabled: Bool = true
    @AppStorage("aftermathDelayOption") private var aftermathDelayRaw: String = AftermathDelayOption.hours36.rawValue
    @AppStorage("icloudSyncEnabled") private var icloudSyncEnabled: Bool = false
    @State private var icloudToggleChanged = false
    @AppStorage("aiAPIKey") private var aiAPIKey: String = AIConfig.fallback.apiKey
    @AppStorage("aiModel")  private var aiModel:  String = AIConfig.fallback.model
    @StateObject private var store = StoreManager.shared
    @StateObject private var personalityStore = PersonalityStore.shared

    @State private var showingPINSetup = false
    @State private var showingPINDisable = false
    @State private var showPaywall = false
    @State private var showingQuiz = false
    @AppStorage("hasSkippedPersonalityQuiz") private var hasSkippedPersonalityQuiz = false

    private var biometricLabel: String {
        switch appLockManager.biometricType {
        case .faceID:  return String(localized: "Face ID aktiviert")
        case .touchID: return String(localized: "Touch ID aktiviert")
        default:       return String(localized: "Aktiv")
        }
    }

    private var activeThemeID: ThemeID {
        ThemeID(rawValue: activeThemeIDRaw) ?? .linen
    }

    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(alignment: .leading, spacing: 32) {

                    // Header
                    Text("Einstellungen")
                        .font(.system(size: 32, weight: .light, design: theme.displayDesign))
                        .foregroundStyle(theme.contentPrimary)
                        .padding(.horizontal, 20)
                        .padding(.top, 12)

                    abonnementSection
                    darstellungSection
                    funktionenSection
                    systemSection

                    // Entwickler (versteckt, nur für Entwickler)
                    NavigationLink(destination: DeveloperSettingsView()) {
                        Text("Entwickler")
                            .font(.system(size: 12))
                            .foregroundStyle(theme.contentTertiary)
                            .frame(maxWidth: .infinity)
                            .padding(.vertical, 8)
                    }
                    .padding(.horizontal, 20)
                }
                .padding(.bottom, 40)
            }
            .background(theme.backgroundPrimary.ignoresSafeArea())
            .navigationBarHidden(true)
        }
        .sheet(isPresented: $showingPINSetup, onDismiss: { appLockManager.refreshBiometricType() }) {
            AppLockSetupView(isDisabling: false).environmentObject(appLockManager)
        }
        .sheet(isPresented: $showingPINDisable) {
            AppLockSetupView(isDisabling: true).environmentObject(appLockManager)
        }
        .sheet(isPresented: $showPaywall) {
            PaywallView(targeting: store.isPro ? .max : .pro)
        }
        .sheet(isPresented: $showingQuiz) {
            PersonalityQuizView { _ in }
        }
    }

    // MARK: - 1 · Abonnement (hervorgehoben)

    private var abonnementSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            SectionHeader(title: "Abonnement", icon: "star.fill")
                .padding(.horizontal, 20)

            if store.isMax {
                HStack(spacing: 14) {
                    Image(systemName: "checkmark.seal.fill")
                        .font(.system(size: 26))
                        .foregroundStyle(theme.accent)
                    VStack(alignment: .leading, spacing: 3) {
                        Text("Max aktiv")
                            .font(.system(size: 15, weight: .semibold))
                            .foregroundStyle(theme.contentPrimary)
                        Text("Alle Features freigeschaltet")
                            .font(.system(size: 12))
                            .foregroundStyle(theme.contentTertiary)
                    }
                    Spacer()
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 16)
                .background(
                    RoundedRectangle(cornerRadius: theme.radiusCard)
                        .fill(theme.accent.opacity(0.07))
                        .overlay(
                            RoundedRectangle(cornerRadius: theme.radiusCard)
                                .stroke(theme.accent.opacity(0.22), lineWidth: 1)
                        )
                )
                .padding(.horizontal, 20)
            } else {
                Button { showPaywall = true } label: {
                    HStack {
                        VStack(alignment: .leading, spacing: 4) {
                            Text(store.isPro ? "Auf Max upgraden" : "nahbar Pro oder Max")
                                .font(.system(size: 15, weight: .semibold))
                                .foregroundStyle(theme.accent)
                            Text(store.isPro
                                 ? "KI Insights freischalten"
                                 : "KI Insights, Themes & mehr")
                                .font(.system(size: 12))
                                .foregroundStyle(theme.contentTertiary)
                        }
                        Spacer()
                        Image(systemName: "chevron.right")
                            .font(.system(size: 12, weight: .medium))
                            .foregroundStyle(theme.accent.opacity(0.5))
                    }
                    .padding(.horizontal, 16)
                    .padding(.vertical, 16)
                    .background(
                        RoundedRectangle(cornerRadius: theme.radiusCard)
                            .fill(theme.accent.opacity(0.07))
                            .overlay(
                                RoundedRectangle(cornerRadius: theme.radiusCard)
                                    .stroke(theme.accent.opacity(0.22), lineWidth: 1)
                            )
                    )
                    .padding(.horizontal, 20)
                }
            }
        }
    }

    // MARK: - 2 · Darstellung & Profil

    private var darstellungSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            SectionHeader(title: "Darstellung & Profil", icon: "paintpalette")
                .padding(.horizontal, 20)

            VStack(spacing: 0) {
                // Theme
                NavigationLink(destination: ThemePickerView()) {
                    HStack(spacing: 14) {
                        ZStack(alignment: .bottomTrailing) {
                            RoundedRectangle(cornerRadius: 8)
                                .fill(NahbarTheme.theme(for: activeThemeID).backgroundPrimary)
                                .frame(width: 40, height: 40)
                                .overlay(
                                    RoundedRectangle(cornerRadius: 8)
                                        .stroke(theme.borderSubtle, lineWidth: 1)
                                )
                            RoundedRectangle(cornerRadius: 3)
                                .fill(NahbarTheme.theme(for: activeThemeID).accent)
                                .frame(width: 13, height: 13)
                                .padding(2)
                        }
                        VStack(alignment: .leading, spacing: 2) {
                            Text(activeThemeID.displayName)
                                .font(.system(size: 15, weight: .medium))
                                .foregroundStyle(theme.contentPrimary)
                            Text(activeThemeID.tagline)
                                .font(.system(size: 12))
                                .foregroundStyle(theme.contentTertiary)
                        }
                        Spacer()
                        Image(systemName: "chevron.right")
                            .font(.system(size: 12, weight: .medium))
                            .foregroundStyle(theme.contentTertiary)
                    }
                    .padding(.horizontal, 16)
                    .padding(.vertical, 12)
                }

                RowDivider()

                // Persönlichkeit
                if let profile = personalityStore.profile, profile.isComplete {
                    let days = PersonalityEngine.suggestedNudgeInterval(for: profile)
                    HStack {
                        VStack(alignment: .leading, spacing: 2) {
                            Text("Persönlichkeit")
                                .font(.system(size: 15))
                                .foregroundStyle(theme.contentPrimary)
                            Text("Nudge alle \(days) Tage · Quiz abgeschlossen")
                                .font(.system(size: 12))
                                .foregroundStyle(theme.contentTertiary)
                        }
                        Spacer()
                        Button {
                            personalityStore.reset()
                            hasSkippedPersonalityQuiz = false
                        } label: {
                            Text("Zurücksetzen")
                                .font(.system(size: 13))
                                .foregroundStyle(theme.contentTertiary)
                        }
                    }
                    .padding(.horizontal, 16)
                    .padding(.vertical, 12)
                } else {
                    Button {
                        hasSkippedPersonalityQuiz = false
                        showingQuiz = true
                    } label: {
                        HStack {
                            Text("Persönlichkeitsquiz")
                                .font(.system(size: 15))
                                .foregroundStyle(theme.accent)
                            Spacer()
                            Image(systemName: "chevron.right")
                                .font(.system(size: 12, weight: .medium))
                                .foregroundStyle(theme.contentTertiary)
                        }
                        .padding(.horizontal, 16)
                        .padding(.vertical, 12)
                    }
                }
            }
            .background(theme.surfaceCard)
            .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
            .padding(.horizontal, 20)
        }
    }

    // MARK: - 3 · Funktionen

    private var funktionenSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            SectionHeader(title: "Funktionen", icon: "slider.horizontal.3")
                .padding(.horizontal, 20)

            VStack(spacing: 0) {
                // Gesprächszeit
                HStack {
                    VStack(alignment: .leading, spacing: 2) {
                        Text("Gesprächszeit")
                            .font(.system(size: 15))
                            .foregroundStyle(theme.contentPrimary)
                        Text("Tägliche Erinnerung für Anrufe")
                            .font(.system(size: 12))
                            .foregroundStyle(theme.contentTertiary)
                    }
                    Spacer()
                    Toggle("", isOn: $callWindowManager.isEnabled)
                        .tint(theme.accent)
                        .onChange(of: callWindowManager.isEnabled) { _, enabled in
                            if enabled { callWindowManager.scheduleNotifications() }
                            else       { callWindowManager.cancelNotifications() }
                        }
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 12)

                if callWindowManager.isEnabled {
                    RowDivider()
                    NavigationLink {
                        CallWindowSetupView(manager: callWindowManager, isOnboarding: false, onDone: {})
                    } label: {
                        HStack {
                            Text("Zeitfenster")
                                .font(.system(size: 15))
                                .foregroundStyle(theme.contentPrimary)
                            Spacer()
                            Text(callWindowManager.windowDescription)
                                .font(.system(size: 14))
                                .foregroundStyle(theme.contentTertiary)
                            Image(systemName: "chevron.right")
                                .font(.system(size: 12, weight: .medium))
                                .foregroundStyle(theme.contentTertiary)
                        }
                        .padding(.horizontal, 16)
                        .padding(.vertical, 12)
                    }
                }

                RowDivider()

                // Kalender
                HStack {
                    Text("Termine & Geburtstage")
                        .font(.system(size: 15))
                        .foregroundStyle(theme.contentPrimary)
                    Spacer()
                    Picker("", selection: $daysAhead) {
                        Text("3 Tage").tag(3)
                        Text("1 Woche").tag(7)
                        Text("2 Wochen").tag(14)
                        Text("1 Monat").tag(30)
                    }
                    .tint(theme.accent)
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 8)

                if settingsCalendars.count > 1 {
                    RowDivider()
                    HStack {
                        Text("Kalender")
                            .font(.system(size: 15))
                            .foregroundStyle(theme.contentPrimary)
                        Spacer()
                        Picker("", selection: $defaultCalendarID) {
                            ForEach(settingsCalendars, id: \.calendarIdentifier) { cal in
                                HStack {
                                    Image(systemName: "circle.fill")
                                        .foregroundStyle(Color(cal.cgColor))
                                    Text(cal.title)
                                }
                                .tag(cal.calendarIdentifier)
                            }
                        }
                        .tint(theme.accent)
                    }
                    .padding(.horizontal, 16)
                    .padding(.vertical, 8)
                }

                RowDivider()

                // Treffen
                HStack {
                    VStack(alignment: .leading, spacing: 2) {
                        Text("Nachwirkungs-Erinnerung")
                            .font(.system(size: 15))
                            .foregroundStyle(theme.contentPrimary)
                        Text("Push nach dem Treffen")
                            .font(.system(size: 12))
                            .foregroundStyle(theme.contentTertiary)
                    }
                    Spacer()
                    Toggle("", isOn: $aftermathNotificationsEnabled)
                        .tint(theme.accent)
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 12)

                if aftermathNotificationsEnabled {
                    RowDivider()
                    HStack {
                        Text("Verzögerung")
                            .font(.system(size: 15))
                            .foregroundStyle(theme.contentPrimary)
                        Spacer()
                        Picker("", selection: $aftermathDelayRaw) {
                            ForEach(AftermathDelayOption.allCases, id: \.rawValue) { opt in
                                Text(opt.label).tag(opt.rawValue)
                            }
                        }
                        .tint(theme.accent)
                    }
                    .padding(.horizontal, 16)
                    .padding(.vertical, 8)
                }

                RowDivider()

                // KI Modell
                HStack {
                    HStack(spacing: 6) {
                        Text("KI Modell")
                            .font(.system(size: 15))
                            .foregroundStyle(theme.contentPrimary)
                        MaxBadge()
                    }
                    Spacer()
                    TextField(AIConfig.fallback.model, text: $aiModel)
                        .font(.system(size: 14))
                        .foregroundStyle(theme.contentSecondary)
                        .autocorrectionDisabled()
                        .textInputAutocapitalization(.never)
                        .multilineTextAlignment(.trailing)
                        .frame(maxWidth: 180)
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 12)
            }
            .background(theme.surfaceCard)
            .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
            .padding(.horizontal, 20)
            .task {
                guard settingsCalendars.isEmpty else { return }
                let calendars = await CalendarManager.shared.availableCalendars()
                settingsCalendars = calendars
                if defaultCalendarID.isEmpty || !calendars.map(\.calendarIdentifier).contains(defaultCalendarID) {
                    defaultCalendarID = CalendarManager.shared.defaultCalendarIdentifier ?? ""
                }
            }
        }
    }

    // MARK: - 4 · System

    private var systemSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            SectionHeader(title: "System", icon: "gear")
                .padding(.horizontal, 20)

            VStack(spacing: 0) {
                // App-Schutz
                HStack {
                    VStack(alignment: .leading, spacing: 2) {
                        Text("Code-Schutz")
                            .font(.system(size: 15))
                            .foregroundStyle(theme.contentPrimary)
                        if appLockManager.isEnabled {
                            Text(biometricLabel)
                                .font(.system(size: 12))
                                .foregroundStyle(theme.contentTertiary)
                        }
                    }
                    Spacer()
                    Toggle("", isOn: Binding(
                        get: { appLockManager.isEnabled },
                        set: { newValue in
                            if newValue { showingPINSetup = true }
                            else        { showingPINDisable = true }
                        }
                    ))
                    .tint(theme.accent)
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 12)

                if appLockManager.isEnabled {
                    RowDivider()
                    Button { showingPINSetup = true } label: {
                        HStack {
                            Text("Code ändern")
                                .font(.system(size: 15))
                                .foregroundStyle(theme.contentPrimary)
                            Spacer()
                            Image(systemName: "chevron.right")
                                .font(.system(size: 12, weight: .medium))
                                .foregroundStyle(theme.contentTertiary)
                        }
                        .padding(.horizontal, 16)
                        .padding(.vertical, 12)
                    }
                }

                RowDivider()

                // iCloud
                HStack {
                    VStack(alignment: .leading, spacing: 2) {
                        Text("iCloud-Sync")
                            .font(.system(size: 15))
                            .foregroundStyle(theme.contentPrimary)
                        Text(icloudSyncEnabled
                             ? "Geräteübergreifend synchronisiert"
                             : "Nur lokal gespeichert")
                            .font(.system(size: 12))
                            .foregroundStyle(theme.contentTertiary)
                    }
                    Spacer()
                    Toggle("", isOn: Binding(
                        get: { icloudSyncEnabled },
                        set: { newValue in
                            icloudSyncEnabled = newValue
                            icloudToggleChanged = true
                        }
                    ))
                    .tint(theme.accent)
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 12)

                if icloudSyncEnabled {
                    RowDivider()
                    HStack(spacing: 8) {
                        Image(systemName: cloudSyncMonitor.state.systemImage)
                            .font(.system(size: 12))
                            .foregroundStyle(cloudSyncMonitor.state.isError ? .red : theme.contentTertiary)
                            .symbolEffect(.pulse, isActive: cloudSyncMonitor.state == .syncing)
                        Text(cloudSyncMonitor.state.statusText)
                            .font(.system(size: 12))
                            .foregroundStyle(cloudSyncMonitor.state.isError ? .red : theme.contentTertiary)
                        Spacer()
                    }
                    .padding(.horizontal, 16)
                    .padding(.vertical, 10)
                }

                if icloudToggleChanged {
                    RowDivider()
                    HStack(spacing: 10) {
                        Image(systemName: "arrow.clockwise.circle.fill")
                            .font(.system(size: 14))
                            .foregroundStyle(theme.accent)
                        Text("Neustart erforderlich, um die Änderung zu übernehmen.")
                            .font(.system(size: 12))
                            .foregroundStyle(theme.contentSecondary)
                        Spacer()
                        Button("Jetzt") { exit(0) }
                            .font(.system(size: 12, weight: .semibold))
                            .foregroundStyle(theme.accent)
                    }
                    .padding(.horizontal, 16)
                    .padding(.vertical, 10)
                }

                RowDivider()

                // Über nahbar
                SettingsInfoRow(label: "Version", value: "1.0 Draft")
                RowDivider()
                SettingsInfoRow(label: "Datenschutz", value: "Deine Daten verlassen nicht dein Gerät")
            }
            .background(theme.surfaceCard)
            .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
            .padding(.horizontal, 20)
            .animation(.easeInOut(duration: 0.2), value: icloudSyncEnabled)
            .animation(.easeInOut(duration: 0.2), value: icloudToggleChanged)
            .animation(.easeInOut(duration: 0.2), value: cloudSyncMonitor.state == .syncing)
        }
    }
}

// MARK: - Settings TextField Helper

extension SettingsView {
    func settingsTextField(label: String, value: Binding<String>, placeholder: String) -> some View {
        HStack {
            Text(label)
                .font(.system(size: 15))
                .foregroundStyle(theme.contentPrimary)
                .frame(width: 90, alignment: .leading)
            TextField(placeholder, text: value)
                .font(.system(size: 14))
                .foregroundStyle(theme.contentSecondary)
                .autocorrectionDisabled()
                .textInputAutocapitalization(.never)
                .multilineTextAlignment(.trailing)
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }
}

// MARK: - Developer Settings View

private struct DeveloperSettingsView: View {
    @Environment(\.nahbarTheme) var theme
    @Environment(\.modelContext) private var modelContext
    @Environment(TourCoordinator.self) private var tourCoordinator
    @StateObject private var personalityStore = PersonalityStore.shared

    @AppStorage("nahbarOnboardingDone")      private var nahbarOnboardingDone = false
    @AppStorage("callWindowOnboardingDone")  private var callWindowOnboardingDone = false
    @AppStorage("photoRepairPassDone")       private var photoRepairPassDone = false
    @AppStorage("callSuggestionDate")        private var callSuggestionDate = ""
    @AppStorage("hasSkippedPersonalityQuiz") private var hasSkippedPersonalityQuiz = false

    @State private var showingResetConfirmation = false

    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 24) {
                VStack(spacing: 0) {
                    // App zurücksetzen
                    Button { showingResetConfirmation = true } label: {
                        HStack(spacing: 14) {
                            Image(systemName: "arrow.counterclockwise")
                                .font(.system(size: 15))
                                .foregroundStyle(.red)
                                .frame(width: 22)
                            VStack(alignment: .leading, spacing: 2) {
                                Text("App zurücksetzen")
                                    .font(.system(size: 15))
                                    .foregroundStyle(.red)
                                Text("Onboarding, Profil und alle Daten löschen")
                                    .font(.system(size: 12))
                                    .foregroundStyle(theme.contentTertiary)
                            }
                            Spacer()
                        }
                        .padding(.horizontal, 16)
                        .padding(.vertical, 12)
                    }

                    RowDivider()

                    // Entwickler-Log
                    NavigationLink(destination: LogExportView()) {
                        HStack(spacing: 14) {
                            Image(systemName: "doc.text")
                                .font(.system(size: 15))
                                .foregroundStyle(theme.contentTertiary)
                                .frame(width: 22)
                            VStack(alignment: .leading, spacing: 2) {
                                Text("Entwickler-Log")
                                    .font(.system(size: 15))
                                    .foregroundStyle(theme.contentPrimary)
                                Text("\(AppEventLog.shared.entries.count) Einträge – Export als Textdatei")
                                    .font(.system(size: 12))
                                    .foregroundStyle(theme.contentTertiary)
                            }
                            Spacer()
                            Image(systemName: "chevron.right")
                                .font(.system(size: 12, weight: .medium))
                                .foregroundStyle(theme.contentTertiary)
                        }
                        .padding(.horizontal, 16)
                        .padding(.vertical, 12)
                    }
                }
                .background(theme.surfaceCard)
                .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                .padding(.horizontal, 20)
            }
            .padding(.top, 16)
            .padding(.bottom, 40)
        }
        .background(theme.backgroundPrimary.ignoresSafeArea())
        .navigationTitle("Entwickler")
        .navigationBarTitleDisplayMode(.inline)
        .themedNavBar()
        .confirmationDialog(
            "App wirklich zurücksetzen?",
            isPresented: $showingResetConfirmation,
            titleVisibility: .visible
        ) {
            Button("Alles löschen und Onboarding starten", role: .destructive) { resetApp() }
            Button("Abbrechen", role: .cancel) {}
        } message: {
            Text("Alle Personen, Momente, Besuche und dein Profil werden unwiderruflich gelöscht. Die App startet neu.")
        }
    }

    private func resetApp() {
        try? modelContext.delete(model: Person.self)
        try? modelContext.delete(model: Moment.self)
        try? modelContext.delete(model: LogEntry.self)
        try? modelContext.delete(model: Visit.self)
        try? modelContext.delete(model: Rating.self)
        try? modelContext.delete(model: HealthSnapshot.self)
        try? modelContext.delete(model: PersonPhoto.self)

        UserProfileStore.shared.reset()
        ContactStore.shared.reset()

        nahbarOnboardingDone     = false
        callWindowOnboardingDone = false
        photoRepairPassDone      = false
        callSuggestionDate       = ""
        hasSkippedPersonalityQuiz = false
        UserDefaults.standard.removeObject(forKey: "visitMigrationPassDone")
        UserDefaults.standard.removeObject(forKey: "nextStepMigrationPassDone")
        tourCoordinator.resetSeenTours()

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { exit(0) }
    }
}

// MARK: - Theme Option Row

struct ThemeOptionRow: View {
    @Environment(\.nahbarTheme) var current
    let themeID: ThemeID
    let isActive: Bool
    let onSelect: () -> Void

    private var preview: NahbarTheme { NahbarTheme.theme(for: themeID) }

    var body: some View {
        Button(action: onSelect) {
            HStack(spacing: 14) {
                // Color swatch
                HStack(spacing: 3) {
                    RoundedRectangle(cornerRadius: 5)
                        .fill(preview.backgroundPrimary)
                        .frame(width: 32, height: 32)
                        .overlay(
                            RoundedRectangle(cornerRadius: 5)
                                .stroke(current.borderSubtle, lineWidth: 1)
                        )
                    RoundedRectangle(cornerRadius: 3)
                        .fill(preview.accent)
                        .frame(width: 10, height: 32)
                }

                VStack(alignment: .leading, spacing: 2) {
                    Text(themeID.displayName)
                        .font(.system(size: 15, weight: isActive ? .semibold : .regular))
                        .foregroundStyle(current.contentPrimary)
                    Text(themeID.tagline)
                        .font(.system(size: 12))
                        .foregroundStyle(current.contentTertiary)
                }

                Spacer()

                if themeID.isPremium {
                    Text("PRO")
                        .font(.system(size: 10, weight: .bold))
                        .foregroundStyle(current.accent)
                        .padding(.horizontal, 7)
                        .padding(.vertical, 3)
                        .background(current.accent.opacity(0.10))
                        .clipShape(Capsule())
                }

                if isActive {
                    Image(systemName: "checkmark")
                        .font(.system(size: 13, weight: .semibold))
                        .foregroundStyle(current.accent)
                }
            }
            .padding(.horizontal, 14)
            .padding(.vertical, 12)
            .background(current.surfaceCard)
            .clipShape(RoundedRectangle(cornerRadius: current.radiusCard))
        }
    }
}

// MARK: - AftermathDelayOption

enum AftermathDelayOption: String, CaseIterable {
    case hours24 = "24h"
    case hours36 = "36h"
    case hours48 = "48h"

    var label: String { rawValue }

    var seconds: TimeInterval {
        switch self {
        case .hours24: return 24 * 3600
        case .hours36: return 36 * 3600
        case .hours48: return 48 * 3600
        }
    }

    static func loadFromDefaults() -> AftermathDelayOption {
        let raw = UserDefaults.standard.string(forKey: "aftermathDelayOption") ?? AftermathDelayOption.hours36.rawValue
        return AftermathDelayOption(rawValue: raw) ?? .hours36
    }
}

// MARK: - AppLanguage

enum AppLanguage: String, CaseIterable {
    case german  = "de"
    case english = "en"

    var displayName: String {
        switch self {
        case .german:  return "Deutsch"
        case .english: return "English"
        }
    }

    /// System prompt für die KI – gibt die Antwortsprache vor.
    var systemPrompt: String {
        switch self {
        case .german:
            return "Du bist ein einfühlsamer Assistent für persönliche Beziehungspflege. Antworte ausschließlich auf Deutsch. Keine Emojis. Vermeide Wörter in GROSSBUCHSTABEN. Sei prägnant, warm und direkt. Strukturiere deine Antwort exakt wie verlangt. Nutze Markdown."
        case .english:
            return "You are an empathetic assistant for personal relationship management. Respond exclusively in English. No emojis. Avoid ALL CAPS words. Be concise, warm and direct. Structure your response exactly as requested. Use Markdown."
        }
    }

    /// Analyse-Prompt-Suffix (Anweisung + Formatvorgabe).
    /// Die Struktur-Labels MUSTER/BEZIEHUNG/EMPFEHLUNG bleiben sprachunabhängig – sie dienen als Parse-Token.
    var analysisInstruction: String {
        switch self {
        case .german:
            return "Analysiere diese Beziehung. Berücksichtige die Lebensphase der Person anhand des Geburtsjahres, sofern bekannt. Nutze Markdown. Verwende **fett** für wichtige Begriffe. Antworte in exakt diesem Format:\n\nMUSTER: [2-3 Sätze über wiederkehrende Themen und Muster]\nBEZIEHUNG: [2-3 Sätze über die Entwicklung und Qualität der Beziehung]\nEMPFEHLUNG: [1 konkreter, sofort umsetzbarer nächster Schritt]"
        case .english:
            return "Analyze this relationship. Consider the person's life stage based on their birth year if known. Use Markdown. Use **bold** for key terms. Respond in exactly this format:\n\nMUSTER: [2-3 sentences about recurring themes and patterns]\nBEZIEHUNG: [2-3 sentences about the development and quality of the relationship]\nEMPFEHLUNG: [1 concrete, immediately actionable next step]"
        }
    }

    /// Geschenkideen-Prompt-Suffix.
    /// IDEE 1/2/3 bleiben als Parse-Token erhalten.
    var giftInstruction: String {
        switch self {
        case .german:
            return "Der Geburtstag dieser Person steht bevor. Schlage 3 konkrete, persönliche Geschenkideen vor. Berücksichtige Interessen und bisherige gemeinsame Momente. Sei kreativ aber realistisch. Kein Smalltalk, keine Erklärungen außerhalb der Ideen. Nenne erwartete Kosten. Antworte in exakt diesem Format:\n\nIDEE 1: [Geschenkidee – 1 Satz Begründung]\nIDEE 2: [Geschenkidee – 1 Satz Begründung]\nIDEE 3: [Geschenkidee – 1 Satz Begründung]"
        case .english:
            return "This person's birthday is coming up. Suggest 3 concrete, personal gift ideas. Consider their interests and past shared moments. Be creative but realistic. No small talk, no explanations outside the ideas. Mention expected costs. Respond in exactly this format:\n\nIDEE 1: [Gift idea – 1 sentence reason]\nIDEE 2: [Gift idea – 1 sentence reason]\nIDEE 3: [Gift idea – 1 sentence reason]"
        }
    }

    var conversationInstruction: String {
        switch self {
        case .german:
            return "Du bereitest mich auf ein bevorstehendes Treffen mit dieser Person vor. Halte dich STRIKT an die vorhandenen Momente und Log-Einträge. Erfinde KEINE Details, Erlebnisse oder Themen die nicht explizit in den Daten stehen. Gib mir sehr knappe Vorschläge – maximal 8 Wörter pro Punkt, nur Stichwörter oder kurze Fragen. Antworte in exakt diesem Format:\n\nTHEMEN: [2-3 Stichworte oder kurze Fragen aus den echten Daten, kommasepariert]\nGESPRAECHSRETTER: [2-3 kurze Impulse, je max. 8 Wörter, kommasepariert]\nTIEFE: [ein konkreter Tipp, max. 12 Wörter]"
        case .english:
            return "You are preparing me for an upcoming meeting with this person. Stick STRICTLY to the available moments and log entries. Do NOT invent details, experiences or topics that are not explicitly in the data. Give very concise suggestions – maximum 8 words per point, keywords or short questions only. Respond in exactly this format:\n\nTHEMEN: [2-3 keywords or short questions from the actual data, comma-separated]\nGESPRAECHSRETTER: [2-3 short impulses, max. 8 words each, comma-separated]\nTIEFE: [one concrete tip, max. 12 words]"
        }
    }

    var momentsLabel:            String { self == .english ? "Moments"             : "Momente" }
    var logEntriesLabel:         String { self == .english ? "Log entries"         : "Log-Einträge" }
    var birthYearLabel:          String { self == .english ? "Birth year"          : "Geburtsjahr" }
    var interestsLabel:          String { self == .english ? "Interests"           : "Interessen" }
    var culturalBackgroundLabel: String { self == .english ? "Cultural background" : "Kultureller Hintergrund" }

    /// Leitet die KI-Antwortsprache aus der iOS-Systemsprache ab.
    /// Unterstützte Sprachen: de, en – alle anderen fallen auf .german zurück.
    static var current: AppLanguage {
        let code = Locale.current.language.languageCode?.identifier ?? "de"
        return AppLanguage(rawValue: code) ?? .german
    }
}

// MARK: - Settings Info Row

struct SettingsInfoRow: View {
    @Environment(\.nahbarTheme) var theme
    let label: String
    let value: String

    var body: some View {
        HStack(alignment: .top) {
            Text(label)
                .font(.system(size: 15))
                .foregroundStyle(theme.contentPrimary)
            Spacer()
            Text(value)
                .font(.system(size: 14))
                .foregroundStyle(theme.contentTertiary)
                .multilineTextAlignment(.trailing)
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }
}
