import SwiftUI

// MARK: - PentagonChartView

/// Pentagon-Diagramm für das OCEAN-Persönlichkeitsprofil.
/// Verwendet SwiftUI Path (kein Charts-Framework). Animiert beim Erscheinen.
struct PentagonChartView: View {
    let profile: PersonalityProfile
    var size: CGFloat = 200
    /// Achsenbeschriftungen anzeigen (für Miniatur-Variante deaktivieren).
    var showLabels: Bool = true

    @State private var scale: CGFloat = 0

    /// Dimensionsreihenfolge: oben → oben-rechts → unten-rechts → unten-links → oben-links
    private let dimensions: [OceanDimension] = [
        .openness, .conscientiousness, .extraversion, .agreeableness, .neuroticism
    ]

    var body: some View {
        ZStack {
            // Hintergrundgitter bei 50 % und 100 %
            pentagonPath(factor: 1.0)
                .stroke(Color.secondary.opacity(0.15), lineWidth: 1)
            pentagonPath(factor: 0.5)
                .stroke(Color.secondary.opacity(0.10), lineWidth: 1)

            // Datenprofil (Füllung + Kontur)
            dataPolygon
                .fill(NahbarInsightStyle.accentPetrol.opacity(0.25))
            dataPolygon
                .stroke(NahbarInsightStyle.accentPetrol, lineWidth: 2)

            // Achsenbeschriftungen
            if showLabels {
                axisLabels
            }
        }
        .frame(width: size, height: size)
        .scaleEffect(scale)
        .onAppear {
            withAnimation(.spring(dampingFraction: 0.7)) { scale = 1.0 }
        }
    }

    // MARK: Pentagon-Pfade

    private func pentagonPath(factor: CGFloat) -> Path {
        let inset: CGFloat = showLabels ? 20 : 4
        return Path { path in
            let center = CGPoint(x: size / 2, y: size / 2)
            let radius = (size / 2 - inset) * factor
            for (i, _) in dimensions.enumerated() {
                let pt = pointOnCircle(center: center, radius: radius, index: i)
                if i == 0 { path.move(to: pt) } else { path.addLine(to: pt) }
            }
            path.closeSubpath()
        }
    }

    private var dataPolygon: Path {
        let inset: CGFloat = showLabels ? 20 : 4
        return Path { path in
            let center    = CGPoint(x: size / 2, y: size / 2)
            let maxRadius = size / 2 - inset
            for (i, dim) in dimensions.enumerated() {
                let radius = maxRadius * profile.normalized(for: dim)
                let pt     = pointOnCircle(center: center, radius: radius, index: i)
                if i == 0 { path.move(to: pt) } else { path.addLine(to: pt) }
            }
            path.closeSubpath()
        }
    }

    // MARK: Achsenbeschriftungen

    private var axisLabels: some View {
        GeometryReader { geo in
            let center      = CGPoint(x: geo.size.width / 2, y: geo.size.height / 2)
            let labelRadius = geo.size.width / 2 - 2

            ForEach(Array(dimensions.enumerated()), id: \.element) { index, dim in
                let angle = angleForIndex(index)
                let x     = center.x + labelRadius * sin(angle)
                let y     = center.y - labelRadius * cos(angle)

                Text(dim.axisLabel)
                    .font(.system(size: max(8, size * 0.045)))
                    .foregroundStyle(.secondary)
                    .fixedSize()
                    .position(x: x, y: y)
            }
        }
    }

    // MARK: Hilfsgeometrie

    private func pointOnCircle(center: CGPoint, radius: CGFloat, index: Int) -> CGPoint {
        let angle = angleForIndex(index)
        return CGPoint(
            x: center.x + radius * sin(angle),
            y: center.y - radius * cos(angle)
        )
    }

    private func angleForIndex(_ index: Int) -> CGFloat {
        2 * .pi * CGFloat(index) / CGFloat(dimensions.count)
    }
}

// MARK: - PersonalityResultView

/// Ergebnis-Screen nach Abschluss des Persönlichkeitsquiz.
/// Zeigt Pentagon-Diagramm, Zusammenfassungstext und alle Dimensionszeilen.
struct PersonalityResultView: View {
    let profile: PersonalityProfile
    let onContinue: () -> Void

    var body: some View {
        ScrollView {
            VStack(spacing: 28) {

                // Titel
                Text("Dein Profil")
                    .font(.title.bold())
                    .padding(.top, 32)
                    .accessibilityAddTraits(.isHeader)

                // Pentagon-Diagramm
                PentagonChartView(profile: profile)
                    .accessibilityLabel("Persönlichkeits-Pentagon-Diagramm")

                // Zusammenfassungstext
                Text(profile.summaryText)
                    .font(.body)
                    .multilineTextAlignment(.center)
                    .foregroundStyle(.secondary)
                    .padding(.horizontal, NahbarInsightStyle.horizontalPadding)

                // Dimensionszeilen
                VStack(spacing: 10) {
                    ForEach(OceanDimension.allCases, id: \.self) { dim in
                        dimensionRow(for: dim)
                    }
                }
                .padding(.horizontal, NahbarInsightStyle.horizontalPadding)

                // Datenschutz-Badge
                PrivacyBadgeView(context: .localOnly)
                    .padding(.horizontal, NahbarInsightStyle.horizontalPadding)

                // Weiter-Button
                Button(action: onContinue) {
                    Text("Weiter")
                        .font(.headline)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 14)
                        .background(NahbarInsightStyle.accentPetrol)
                        .foregroundStyle(.white)
                        .clipShape(RoundedRectangle(cornerRadius: 12))
                }
                .padding(.horizontal, NahbarInsightStyle.horizontalPadding)
                .padding(.bottom, 40)
                .accessibilityLabel("Ergebnis bestätigen und fortfahren")
            }
        }
    }

    // MARK: Dimensionszeile

    @ViewBuilder
    private func dimensionRow(for dim: OceanDimension) -> some View {
        let level = profile.level(for: dim)

        HStack(spacing: 12) {
            Image(systemName: dim.icon)
                .font(.body)
                .foregroundStyle(NahbarInsightStyle.color(for: dim))
                .frame(width: 28)
                .accessibilityHidden(true)

            VStack(alignment: .leading, spacing: 2) {
                Text(dim.displayName)
                    .font(.subheadline.weight(.medium))
                Text(interpretationText(dim: dim, level: level))
                    .font(.caption)
                    .foregroundStyle(.secondary)
            }

            Spacer()

            levelBadge(level)
        }
        .padding(12)
        .background(NahbarInsightStyle.cardBackground)
        .clipShape(RoundedRectangle(cornerRadius: 10))
        .accessibilityElement(children: .combine)
        .accessibilityLabel("\(dim.displayName): \(levelLabel(level)), \(interpretationText(dim: dim, level: level))")
    }

    @ViewBuilder
    private func levelBadge(_ level: TraitLevel) -> some View {
        Text(levelLabel(level))
            .font(NahbarInsightStyle.badgeFont)
            .padding(.horizontal, 8)
            .padding(.vertical, 4)
            .background(NahbarInsightStyle.color(for: level).opacity(0.15))
            .foregroundStyle(NahbarInsightStyle.color(for: level))
            .clipShape(Capsule())
    }

    private func levelLabel(_ level: TraitLevel) -> String {
        switch level {
        case .low:    return "Niedrig"
        case .medium: return "Mittel"
        case .high:   return "Hoch"
        }
    }

    private func interpretationText(dim: OceanDimension, level: TraitLevel) -> String {
        switch (dim, level) {
        case (.openness, .high):            return "Neugierig und experimentierfreudig"
        case (.openness, .medium):          return "Ausgeglichene Offenheit"
        case (.openness, .low):             return "Verlässt sich auf Bewährtes"
        case (.conscientiousness, .high):   return "Strukturiert und verlässlich"
        case (.conscientiousness, .medium): return "Flexibel und zuverlässig"
        case (.conscientiousness, .low):    return "Spontan und adaptiv"
        case (.extraversion, .high):        return "Energiegeladen im Kontakt"
        case (.extraversion, .medium):      return "Kontaktfreudig und reflektiert"
        case (.extraversion, .low):         return "Genießt die eigene Gesellschaft"
        case (.agreeableness, .high):       return "Empathisch und kooperativ"
        case (.agreeableness, .medium):     return "Ausgewogen und fair"
        case (.agreeableness, .low):        return "Direkt und eigenständig"
        case (.neuroticism, .high):         return "Feinfühlig und empathisch"
        case (.neuroticism, .medium):       return "Ausgewogen emotional"
        case (.neuroticism, .low):          return "Gelassen und stabil"
        }
    }
}
