import SwiftUI

struct FuloraPaywallView: View {

    @Environment(\.dismiss) private var dismiss
    @Environment(\.colorScheme) private var colorScheme
    @State private var selectedPlan: PaywallPlan = .yearly

    // Card order: streak(0) · moment(1) · vocab(2) · ambient(3) · monthly(4)
    // vocab starts centered
    @State private var scrolledID: Int? = 2
    @State private var displayedIndex: Int = 2

    private let plans: [PaywallPlan] = [.yearly, .monthly]

    private let cardText: [(title: String, subtitle: String)] = [
        ("Build your habit",
         "Track daily reading streaks and stay consistent over time."),
        ("Stay in the zone",
         "Set a focus timer and enter a distraction-free reading session."),
        ("Remember more",
         "Save words as you read and review them as flashcards later."),
        ("Your ideal atmosphere",
         "Café, forest, or rain — the perfect backdrop for deep reading."),
        ("See your progress",
         "Monthly heatmaps and stats that show how far you've come."),
    ]

    var body: some View {
        GeometryReader { geo in
            ZStack(alignment: .bottom) {

                ScrollView(.vertical, showsIndicators: false) {
                    VStack(spacing: 0) {

                        heroCarousel
                            .padding(.top, 32)

                        dynamicText
                            .padding(.top, 22)
                            .padding(.horizontal, 36)

                        pricingSection
                            .padding(.top, 28)
                            .padding(.horizontal, 26)

                        Spacer(minLength: 130)
                    }
                    .padding(.horizontal, 26)
                }

                VStack(spacing: 0) {
                    LinearGradient(
                        colors: [
                            FuloraPaywall.background.opacity(0),
                            FuloraPaywall.background.opacity(0.88),
                            FuloraPaywall.background,
                        ],
                        startPoint: .top,
                        endPoint: .bottom
                    )
                    .frame(height: 40)
                    .allowsHitTesting(false)

                    ctaSection
                        .padding(.horizontal, 26)
                        .padding(.bottom, geo.safeAreaInsets.bottom > 0
                            ? geo.safeAreaInsets.bottom + 6 : 24)
                        .background(FuloraPaywall.background)
                }
            }
        }
        .background(FuloraPaywall.background.ignoresSafeArea())
        .presentationDetents([.large])
        .presentationDragIndicator(.visible)
        .presentationCornerRadius(28)
        .onChange(of: scrolledID) { _, newVal in
            withAnimation(.spring(response: 0.38, dampingFraction: 0.82)) {
                displayedIndex = newVal ?? 2
            }
        }
    }

    // MARK: - Hero Carousel

    private var heroCarousel: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 14) {
                ForEach(0..<5, id: \.self) { i in
                    heroCard(index: i)
                        .containerRelativeFrame(.horizontal) { w, _ in w - 160 }
                        .frame(height: 240)
                        .id(i)
                        .scrollTransition(
                            .animated(.spring(response: 0.38, dampingFraction: 0.80))
                        ) { content, phase in
                            content
                                .scaleEffect(phase.isIdentity ? 1.0 : 0.68)
                                .opacity(phase.isIdentity ? 1.0 : 0.42)
                                .rotationEffect(.degrees(phase.isIdentity ? 0 : (phase.value > 0 ? 9 : -9)))
                                .offset(y: phase.isIdentity ? 0 : 18)
                        }
                }
            }
            .scrollTargetLayout()
        }
        .scrollTargetBehavior(.viewAligned)
        .scrollPosition(id: $scrolledID)
        .contentMargins(.horizontal, 80, for: .scrollContent)
        .frame(height: 260)
        .padding(.horizontal, -26)
    }

    // MARK: - Cards

    @ViewBuilder
    private func heroCard(index: Int) -> some View {
        switch index {
        case 0: streakCard
        case 1: momentCard
        case 2: vocabCard
        case 3: ambientCard
        default: monthlyCard
        }
    }

    // ── Vocab (index 2) — 3-card stacking hero
    private var vocabCard: some View {
        ZStack {
            // Back card
            RoundedRectangle(cornerRadius: 18, style: .continuous)
                .fill(Color(hex: "EDE4D9"))
                .frame(width: 200, height: 220)
                .shadow(color: Color(hex: "C4A882").opacity(0.22), radius: 10, x: 0, y: 6)
                .rotationEffect(.degrees(7))
                .offset(x: 18, y: 10)

            // Mid card
            RoundedRectangle(cornerRadius: 18, style: .continuous)
                .fill(Color(hex: "F5ECD7"))
                .frame(width: 200, height: 220)
                .shadow(color: Color(hex: "C4A882").opacity(0.16), radius: 8, x: 0, y: 4)
                .rotationEffect(.degrees(-4))
                .offset(x: -10, y: 5)

            // Front card
            RoundedRectangle(cornerRadius: 18, style: .continuous)
                .fill(Color(hex: "FDFAF7"))
                .frame(width: 200, height: 220)
                .shadow(color: FuloraPaywall.orange.opacity(0.14), radius: 18, x: 0, y: 8)
                .overlay(vocabFront.frame(width: 200, height: 220)
                    .clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous)))
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }

    private var vocabFront: some View {
        VStack(alignment: .leading, spacing: 0) {
            cardLabel("VOCABULARY")
            Spacer(minLength: 12)
            Text("Luminous")
                .font(.custom("Georgia-Bold", size: 26))
                .foregroundStyle(Color(hex: "2C1810"))
                .padding(.horizontal, 20)
            Text("adjective")
                .font(.system(size: 12, weight: .medium))
                .foregroundStyle(Color(hex: "9A8070"))
                .padding(.horizontal, 20)
                .padding(.top, 3)
            Rectangle()
                .fill(Color(hex: "E8D9C8"))
                .frame(height: 0.5)
                .padding(.horizontal, 20)
                .padding(.vertical, 12)
            Text("Full of or shedding light; bright or shining, especially from reflected light.")
                .font(.system(size: 12, weight: .regular))
                .foregroundStyle(Color(hex: "5A4535"))
                .lineSpacing(3)
                .padding(.horizontal, 20)
            Spacer(minLength: 12)
            HStack(spacing: 6) {
                masteryDot(true); masteryDot(false); masteryDot(false)
                Text("learning")
                    .font(.system(size: 10, weight: .medium))
                    .foregroundStyle(Color(hex: "9A8070"))
            }
            .padding(.horizontal, 20)
            .padding(.bottom, 18)
        }
    }

    // ── Streak (index 0)
    private var streakCard: some View {
        cardShell {
            cardLabel("STREAK")
            Spacer()
            HStack(alignment: .lastTextBaseline, spacing: 5) {
                Image(systemName: "flame.fill")
                    .font(.system(size: 22, weight: .medium))
                    .foregroundStyle(FuloraPaywall.orange)
                    .offset(y: -3)
                Text("14")
                    .font(.custom("Georgia-Bold", size: 46))
                    .foregroundStyle(Color(hex: "2C1810"))
            }
            .padding(.horizontal, 20)
            Text("days in a row")
                .font(.system(size: 12, weight: .medium))
                .foregroundStyle(Color(hex: "9A8070"))
                .padding(.horizontal, 20)
                .padding(.top, 2)
            Spacer()
            HStack(spacing: 6) {
                ForEach(0..<7, id: \.self) { i in
                    Circle()
                        .fill(i < 6 ? FuloraPaywall.orange : Color(hex: "E8D9C8"))
                        .frame(width: 9, height: 9)
                }
            }
            .padding(.horizontal, 20)
            .padding(.bottom, 20)
        }
    }

    // ── Moment (index 1)
    private var momentCard: some View {
        cardShell {
            cardLabel("MOMENT")
            Spacer()
            Image(systemName: "timer")
                .font(.system(size: 26, weight: .medium))
                .foregroundStyle(FuloraPaywall.orange)
                .padding(.horizontal, 20)
            Text("25:00")
                .font(.custom("Georgia-Bold", size: 44))
                .foregroundStyle(Color(hex: "2C1810"))
                .padding(.horizontal, 20)
                .padding(.top, 4)
            Text("focus session")
                .font(.system(size: 12, weight: .medium))
                .foregroundStyle(Color(hex: "9A8070"))
                .padding(.horizontal, 20)
                .padding(.top, 2)
            Spacer()
            HStack(spacing: 8) {
                Image(systemName: "waveform")
                    .font(.system(size: 12))
                    .foregroundStyle(FuloraPaywall.orange.opacity(0.75))
                Text("Rain ambience")
                    .font(.system(size: 11, weight: .medium))
                    .foregroundStyle(Color(hex: "9A8070"))
            }
            .padding(.horizontal, 20)
            .padding(.bottom, 20)
        }
    }

    // ── Ambient (index 3)
    private var ambientCard: some View {
        let heights: [CGFloat] = [0.40, 0.65, 1.0, 0.55, 0.85,
                                  0.45, 0.75, 0.50, 0.90, 0.60,
                                  0.70, 0.40, 0.80, 0.50]
        return cardShell {
            cardLabel("AMBIENT")
            Spacer()
            HStack(alignment: .center, spacing: 4) {
                ForEach(heights.indices, id: \.self) { i in
                    RoundedRectangle(cornerRadius: 2.5, style: .continuous)
                        .fill(FuloraPaywall.orange.opacity(0.72))
                        .frame(width: 6, height: 42 * heights[i])
                }
            }
            .padding(.horizontal, 20)
            Text("Café Rain")
                .font(.custom("Georgia-Bold", size: 22))
                .foregroundStyle(Color(hex: "2C1810"))
                .padding(.horizontal, 20)
                .padding(.top, 14)
            Text("now playing")
                .font(.system(size: 11, weight: .medium))
                .foregroundStyle(Color(hex: "9A8070"))
                .padding(.horizontal, 20)
                .padding(.top, 2)
            Spacer(minLength: 18)
        }
    }

    // ── Monthly (index 4)
    private var monthlyCard: some View {
        let filled: [[Bool]] = [
            [false, true,  true,  false, true,  false, true ],
            [true,  true,  false, true,  true,  true,  false],
            [false, true,  true,  true,  false, true,  true ],
            [true,  false, true,  true,  true,  false, false],
        ]
        return cardShell {
            cardLabel("MONTHLY")
            Spacer()
            Text("April")
                .font(.custom("Georgia-Bold", size: 22))
                .foregroundStyle(Color(hex: "2C1810"))
                .padding(.horizontal, 20)
            VStack(spacing: 5) {
                ForEach(0..<4, id: \.self) { row in
                    HStack(spacing: 5) {
                        ForEach(0..<7, id: \.self) { col in
                            RoundedRectangle(cornerRadius: 3, style: .continuous)
                                .fill(filled[row][col]
                                    ? FuloraPaywall.orange.opacity(0.78)
                                    : Color(hex: "EDE4D9"))
                                .frame(width: 14, height: 14)
                        }
                    }
                }
            }
            .padding(.horizontal, 20)
            .padding(.top, 10)
            Text("15 reading days")
                .font(.system(size: 11, weight: .medium))
                .foregroundStyle(Color(hex: "9A8070"))
                .padding(.horizontal, 20)
                .padding(.top, 8)
            Spacer(minLength: 18)
        }
    }

    // ── Shared shell for non-vocab cards
    private func cardShell<C: View>(@ViewBuilder content: () -> C) -> some View {
        ZStack(alignment: .topLeading) {
            RoundedRectangle(cornerRadius: 18, style: .continuous)
                .fill(Color(hex: "FDFAF7"))
                .shadow(color: Color(hex: "C4A882").opacity(0.20), radius: 16, x: 0, y: 7)
            VStack(alignment: .leading, spacing: 0) {
                content()
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
        }
    }

    private func cardLabel(_ text: String) -> some View {
        Text(text)
            .font(.system(size: 8, weight: .semibold))
            .foregroundStyle(FuloraPaywall.orange)
            .tracking(1.3)
            .padding(.horizontal, 9)
            .padding(.vertical, 4)
            .background(
                RoundedRectangle(cornerRadius: 6, style: .continuous)
                    .fill(FuloraPaywall.orange.opacity(0.10))
            )
            .padding(.top, 18)
            .padding(.leading, 20)
    }

    private func masteryDot(_ on: Bool) -> some View {
        Circle()
            .fill(on ? FuloraPaywall.orange : Color(hex: "E8D9C8"))
            .frame(width: 8, height: 8)
    }

    // MARK: - Dynamic Text

    private var dynamicText: some View {
        VStack(spacing: 8) {
            Text(cardText[displayedIndex].title)
                .font(.system(size: 26, weight: .bold))
                .multilineTextAlignment(.center)
                .foregroundColor(.primary)
            Text(cardText[displayedIndex].subtitle)
                .font(.system(size: 15, weight: .regular))
                .multilineTextAlignment(.center)
                .foregroundColor(Color(.systemGray))
                .lineSpacing(2)
        }
        .id(displayedIndex)
        .transition(.asymmetric(
            insertion: .opacity.combined(with: .offset(y: 10)),
            removal:   .opacity.combined(with: .offset(y: -10))
        ))
        .animation(.spring(response: 0.38, dampingFraction: 0.82), value: displayedIndex)
    }

    // MARK: - Pricing

    private var pricingSection: some View {
        VStack(spacing: 10) {
            ForEach(plans) { plan in
                PricingCardView(
                    plan: plan,
                    isSelected: selectedPlan == plan,
                    onTap: {
                        withAnimation(.spring(response: 0.32, dampingFraction: 0.72)) {
                            selectedPlan = plan
                        }
                    }
                )
            }
        }
    }

    // MARK: - CTA

    private var ctaSection: some View {
        VStack(spacing: 12) {
            Text("No commitment. Cancel anytime.")
                .font(.system(size: 13, weight: .regular))
                .foregroundColor(Color(.systemGray))

            Button {
                // StoreKit goes here
            } label: {
                Text("Start 3-Day Free Trial")
                    .font(.system(size: 17, weight: .semibold))
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .frame(height: 56)
                    .background(FuloraPaywall.orange)
                    .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                    .shadow(color: FuloraPaywall.orange.opacity(0.28), radius: 12, x: 0, y: 5)
            }
            .buttonStyle(PaywallCTAButtonStyle())
        }
    }
}

// MARK: - Button Style

private struct PaywallCTAButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .scaleEffect(configuration.isPressed ? 0.97 : 1.0)
            .animation(.spring(response: 0.22, dampingFraction: 0.65), value: configuration.isPressed)
    }
}

// MARK: - Preview

#Preview {
    Color(.systemGray6).ignoresSafeArea()
        .sheet(isPresented: .constant(true)) {
            FuloraPaywallView()
        }
}
