import SwiftUI

struct LevelSelectView: View {
    @Environment(\.dismiss) private var dismiss
    @ObservedObject private var progress = ProgressStore.shared
    @State private var selectedLevel: LevelEntry? = nil
    @State private var selectedWorld: Int = 1

    private struct LevelEntry: Identifiable {
        let id: String
        let number: Int
        let title: String
        let file: String
        let world: Int
    }

    // MARK: - World 2 unlock condition

    private var world2Unlocked: Bool {
        ProgressStore.shared.totalStars() >= 15
    }

    private var worlds: [WorldMeta] {
        LevelLoader.loadMetadata()?.worlds ?? []
    }

    private var currentWorld: WorldMeta? {
        worlds.first(where: { $0.id == selectedWorld })
    }

    private var levels: [LevelEntry] {
        guard let world = currentWorld else { return [] }
        return world.levels.enumerated().map { idx, l in
            LevelEntry(id: l.id, number: idx + 1, title: l.title, file: l.file, world: world.id)
        }
    }

    private let columns = [GridItem(.adaptive(minimum: 80), spacing: 12)]

    var body: some View {
        NavigationView {
            ZStack {
                Color(hex: "#1A1A2E").ignoresSafeArea()

                VStack(spacing: 0) {
                    worldSelector
                        .padding(.horizontal, 20)
                        .padding(.top, 12)
                        .padding(.bottom, 4)

                    ScrollView {
                        LazyVGrid(columns: columns, spacing: 12) {
                            ForEach(levels) { entry in
                                LevelCell(entry: entry) {
                                    selectedLevel = entry
                                }
                            }
                        }
                        .padding(20)
                    }
                }
            }
            .navigationTitle(currentWorld.map { "\($0.name)" } ?? "Levels")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("Back") { dismiss() }
                        .foregroundColor(Color(hex: "#E63946"))
                }
            }
        }
        .preferredColorScheme(.dark)
        .fullScreenCover(item: $selectedLevel) { entry in
            GameContainerView(levelId: entry.id, levelNumber: entry.number,
                              worldNumber: entry.world) {
                selectedLevel = nil
            }
        }
    }

    // MARK: - World Selector

    private var worldSelector: some View {
        HStack(spacing: 10) {
            ForEach(worlds, id: \.id) { world in
                let isSelected = selectedWorld == world.id
                let isLocked = world.id == 2 && !world2Unlocked

                Button {
                    if !isLocked {
                        selectedWorld = world.id
                    }
                } label: {
                    HStack(spacing: 6) {
                        if isLocked {
                            Image(systemName: "lock.fill")
                                .font(.system(size: 11))
                        }
                        Text(world.name)
                            .font(.system(size: 14, weight: .semibold, design: .rounded))
                        if isLocked {
                            Text("15 \u{2605}")
                                .font(.system(size: 11, weight: .medium, design: .rounded))
                        }
                    }
                    .foregroundColor(isLocked ? .white.opacity(0.35) : isSelected ? .white : .white.opacity(0.6))
                    .padding(.horizontal, 16)
                    .padding(.vertical, 8)
                    .background(
                        Capsule().fill(
                            isSelected ? Color(hex: "#E63946") :
                            isLocked ? Color.white.opacity(0.05) :
                            Color(hex: "#2A2A4E")
                        )
                    )
                    .overlay(
                        Capsule().stroke(
                            isSelected ? Color.clear :
                            isLocked ? Color.white.opacity(0.08) :
                            Color.white.opacity(0.12),
                            lineWidth: 1
                        )
                    )
                    .opacity(isLocked ? 0.4 : 1.0)
                }
                .disabled(isLocked)
            }
        }
    }

    // MARK: - Level Cell

    private struct LevelCell: View {
        let entry: LevelEntry
        let action: () -> Void

        var body: some View {
            let stars = ProgressStore.shared.starsFor(levelId: entry.id)
            let completed = ProgressStore.shared.isCompleted(levelId: entry.id)

            Button(action: action) {
                VStack(spacing: 6) {
                    Text("\(entry.number)")
                        .font(.system(size: 22, weight: .bold, design: .rounded))
                        .foregroundColor(completed ? .white : .white.opacity(0.6))

                    HStack(spacing: 2) {
                        ForEach(0..<3, id: \.self) { i in
                            Text("\u{2605}")
                                .font(.system(size: 10))
                                .foregroundColor(i < stars ? Color(hex: "#F4D35E") : .white.opacity(0.2))
                        }
                    }
                }
                .frame(width: 80, height: 80)
                .background(Color(hex: completed ? "#2A2A4E" : "#1E1E38"))
                .clipShape(RoundedRectangle(cornerRadius: 14))
                .overlay(
                    RoundedRectangle(cornerRadius: 14)
                        .stroke(completed ? Color(hex: "#457B9D") : Color.white.opacity(0.08),
                                lineWidth: 1)
                )
            }
        }
    }
}
