import SwiftUI
import NaturalLanguage

// MARK: - Language Detection

/// Gibt die dominante Sprache eines Textes zurück (via NLLanguageRecognizer).
/// Interne Sichtbarkeit, damit Unit-Tests darauf zugreifen können.
func detectsDominantLanguage(_ text: String) -> NLLanguage? {
    let recognizer = NLLanguageRecognizer()
    recognizer.processString(text)
    return recognizer.dominantLanguage
}

// MARK: - API Response Models

private struct ZitatServiceResponse: Decodable {
    let quote: String
    let authorName: String
}

private struct ZenQuoteResponse: Decodable {
    let q: String   // quote text
    let a: String   // author
}

// MARK: - Fallback Quotes

private struct LocalQuote {
    let text: String
    let author: String
}

private let fallbackQuotesDE: [LocalQuote] = [
    LocalQuote(text: "Der Mensch ist dem Menschen am nötigsten.", author: "Lucius Annaeus Seneca"),
    LocalQuote(text: "Glück ist nur real, wenn es geteilt wird.", author: "Christopher McCandless"),
    LocalQuote(text: "Freundschaft ist wie Gesundheit: Ihren Wert kennt man erst, wenn man sie verloren hat.", author: ""),
    LocalQuote(text: "Ein Freund ist jemand, der dich kennt und trotzdem mag.", author: "Elbert Hubbard"),
    LocalQuote(text: "Wer einen Freund hat, hat einen Schatz.", author: ""),
    LocalQuote(text: "Nähe entsteht nicht durch Distanz.", author: ""),
    LocalQuote(text: "Der beste Spiegel ist ein alter Freund.", author: "George Herbert"),
    LocalQuote(text: "Echte Freundschaft zeigt sich in schwierigen Zeiten.", author: "Aristoteles"),
    LocalQuote(text: "Das Leben wird vorwärts gelebt und rückwärts verstanden.", author: "Søren Kierkegaard"),
    LocalQuote(text: "Verbindung ist das, worum es im Leben geht.", author: "Brené Brown"),
    LocalQuote(text: "Kleine Gesten der Fürsorge können das Leben eines Menschen verändern.", author: ""),
    LocalQuote(text: "Zeit ist das Wertvollste, das ein Mensch verschenken kann.", author: ""),
]

private let fallbackQuotesEN: [LocalQuote] = [
    LocalQuote(text: "The greatest gift of life is friendship, and I have received it.", author: "Hubert H. Humphrey"),
    LocalQuote(text: "Happiness is only real when shared.", author: "Christopher McCandless"),
    LocalQuote(text: "A real friend is one who walks in when the rest of the world walks out.", author: "Walter Winchell"),
    LocalQuote(text: "The quality of your life is the quality of your relationships.", author: "Anthony Robbins"),
    LocalQuote(text: "Connection is why we're here.", author: "Brené Brown"),
    LocalQuote(text: "A friend is someone who knows all about you and still loves you.", author: "Elbert Hubbard"),
    LocalQuote(text: "The best mirror is an old friend.", author: "George Herbert"),
    LocalQuote(text: "Real friendship shows itself in difficult times.", author: "Aristotle"),
    LocalQuote(text: "Life is lived forward, but understood backward.", author: "Søren Kierkegaard"),
    LocalQuote(text: "Time is the most valuable thing you can give someone.", author: ""),
    LocalQuote(text: "Small acts of kindness can change someone's life.", author: ""),
]

// MARK: - SplashView

struct SplashView: View {
    @Environment(\.nahbarTheme) private var theme
    var onFinished: () -> Void

    @State private var quoteText: String = ""
    @State private var authorName: String = ""
    @State private var logoScale: CGFloat = 0.85
    @State private var logoOpacity: CGFloat = 0
    @State private var quoteShownAt: Date? = nil

    private var isGerman: Bool {
        Locale.current.language.languageCode?.identifier == "de"
    }

    /// Locale-korrekte Anführungszeichen: „..." auf Deutsch, "..." auf Englisch
    private var openQuote:  String { isGerman ? "\u{201E}" : "\u{201C}" }
    private var closeQuote: String { isGerman ? "\u{201C}" : "\u{201D}" }

    var body: some View {
        ZStack {
            theme.backgroundPrimary.ignoresSafeArea()

            VStack(spacing: 0) {
                Spacer()

                // App Logo
                Image("AppLogo")
                    .resizable()
                    .frame(width: 140, height: 140)
                    .clipShape(RoundedRectangle(cornerRadius: 32, style: .continuous))
                    .scaleEffect(logoScale)
                    .opacity(logoOpacity)

                Spacer()

                // Quote
                if !quoteText.isEmpty {
                    VStack(spacing: 10) {
                        Text("\(openQuote)\(quoteText)\(closeQuote)")
                            .font(.system(.title3, design: theme.displayDesign))
                            .foregroundStyle(theme.contentSecondary)
                            .multilineTextAlignment(.center)
                            .fixedSize(horizontal: false, vertical: true)

                        if !authorName.isEmpty {
                            Text("— \(authorName)")
                                .font(.system(.subheadline, design: theme.displayDesign))
                                .foregroundStyle(theme.contentTertiary)
                        }
                    }
                    .padding(.horizontal, 36)
                    .padding(.bottom, 52)
                    .transition(.opacity.combined(with: .move(edge: .bottom)))
                }
            }
        }
        .onAppear {
            withAnimation(.spring(duration: 0.6)) {
                logoScale = 1.0
                logoOpacity = 1.0
            }
            Task {
                if let fetched = await fetchQuote() {
                    showQuote(text: fetched.text, author: fetched.author)
                } else {
                    showFallbackQuote()
                }

                let elapsed = quoteShownAt.map { Date().timeIntervalSince($0) } ?? 0
                let remaining = max(0, readingDuration(for: quoteText) - elapsed)
                if remaining > 0 {
                    try? await Task.sleep(for: .seconds(remaining))
                }

                withAnimation(.easeInOut(duration: 0.4)) {
                    onFinished()
                }
            }
        }
    }

    // MARK: - Reading Duration

    /// Anzeigedauer basierend auf Textlänge (ca. 150 WPM ≈ 2,5 Wörter/Sek.).
    /// Minimum 3 s, Maximum 8 s.
    private func readingDuration(for text: String) -> TimeInterval {
        let wordCount = max(1, text.split(separator: " ").count)
        let seconds = Double(wordCount) / 2.5
        return min(max(seconds, 3.0), 8.0)
    }

    // MARK: - Quote Logic

    private func showQuote(text: String, author: String) {
        withAnimation(.easeIn(duration: 0.5)) {
            quoteText = text
            authorName = author
        }
        quoteShownAt = Date()
    }

    private func showFallbackQuote() {
        let pool = isGerman ? fallbackQuotesDE : fallbackQuotesEN
        guard let local = pool.randomElement() else { return }
        showQuote(text: local.text, author: local.author)
    }

    /// Wählt API je nach Systemsprache: zitat-service.de (DE) oder zenquotes.io (EN).
    private func fetchQuote() async -> (text: String, author: String)? {
        if isGerman {
            return await fetchZitatService()
        } else {
            return await fetchZenQuote()
        }
    }

    /// https://api.zitat-service.de – kostenlos, Deutsch
    /// Wiederholt den Abruf bis zu 3x, falls die API ein nicht-deutsches Zitat liefert.
    private func fetchZitatService() async -> (text: String, author: String)? {
        guard let url = URL(string: "https://api.zitat-service.de/v1/quote?language=de") else { return nil }
        for _ in 0..<3 {
            do {
                let (data, _) = try await URLSession.shared.data(for: URLRequest(url: url, timeoutInterval: 1))
                let r = try JSONDecoder().decode(ZitatServiceResponse.self, from: data)
                guard isGermanText(r.quote) else { continue }
                let author = (r.authorName == "Unbekannt") ? "" : r.authorName
                return (r.quote, author)
            } catch {
                return nil
            }
        }
        return nil
    }

    private func isGermanText(_ text: String) -> Bool {
        detectsDominantLanguage(text) == .german
    }

    /// https://zenquotes.io – kostenlos, kein API-Key, Englisch
    private func fetchZenQuote() async -> (text: String, author: String)? {
        guard let url = URL(string: "https://zenquotes.io/api/random") else { return nil }
        do {
            let (data, _) = try await URLSession.shared.data(for: URLRequest(url: url, timeoutInterval: 2))
            let responses = try JSONDecoder().decode([ZenQuoteResponse].self, from: data)
            guard let first = responses.first else { return nil }
            let author = (first.a == "Unknown") ? "" : first.a
            return (first.q, author)
        } catch {
            return nil
        }
    }
}
