import SwiftUI
import Bedrock
import MijickCamera

struct SettingsView: View {
    @Bindable var viewModel: SettingsViewModel
    @Binding var showPaywall: Bool
    @Environment(\.dismiss) private var dismiss
    
    /// Whether premium features are unlocked (for UI gating)
    private var isPremiumUnlocked: Bool {
        viewModel.isPremiumUnlocked
    }
    
    /// Shows paywall after dismissing settings
    private func showPaywallAfterDismiss() {
        dismiss()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            showPaywall = true
        }
    }

    
    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(spacing: Design.Spacing.medium) {

                    // MARK: - Ring Light Section

                    SettingsSectionHeader(title: "Ring Light", systemImage: "light.max")

                    // Ring Light Enabled
                    SettingsToggle(
                        title: String(localized: "Enable Ring Light"),
                        subtitle: String(localized: "Show colored light ring around camera preview"),
                        isOn: $viewModel.isRingLightEnabled
                    )
                    .accessibilityHint(String(localized: "Enables or disables the ring light overlay"))

                    // Ring Size Slider
                    ringSizeSlider

                    // Color Preset
                    colorPresetSection

                    // Ring Light Brightness
                    ringLightBrightnessSlider

                    // MARK: - Camera Controls Section

                    SettingsSectionHeader(title: "Camera Controls", systemImage: "camera")

                    // Camera Position
                    cameraPositionPicker

                    // Flash Mode
                    flashModePicker

                    // Flash Sync (premium)
                    premiumToggle(
                        title: String(localized: "Flash Sync"),
                        subtitle: String(localized: "Use ring light color for screen flash"),
                        isOn: $viewModel.isFlashSyncedWithRingLight,
                        accessibilityHint: String(localized: "Syncs flash color with ring light color")
                    )

                    // Front Flash
                    SettingsToggle(
                        title: String(localized: "Front Flash"),
                        subtitle: String(localized: "Hide preview during capture for flash effect"),
                        isOn: $viewModel.isFrontFlashEnabled
                    )
                    .accessibilityHint(String(localized: "Uses screen flash when taking front camera photos"))

                    // HDR Mode
                    hdrModePicker

                    // Center Stage (premium feature)
                    centerStageToggle

                    // Photo Quality
                    photoQualityPicker

                    // MARK: - Display Section

                    SettingsSectionHeader(title: "Display", systemImage: "eye")

                    // True Mirror (premium)
                    premiumToggle(
                        title: String(localized: "True Mirror"),
                        subtitle: String(localized: "Shows horizontally flipped preview like a real mirror"),
                        isOn: $viewModel.isMirrorFlipped,
                        accessibilityHint: String(localized: "Flips the camera preview horizontally")
                    )

                    SettingsToggle(
                        title: String(localized: "Grid Overlay"),
                        subtitle: String(localized: "Shows rule of thirds grid for composition"),
                        isOn: $viewModel.isGridVisible
                    )
                    .accessibilityHint(String(localized: "Shows a grid overlay to help compose your shot"))

                    // Skin Smoothing (premium)
                    premiumToggle(
                        title: String(localized: "Skin Smoothing"),
                        subtitle: String(localized: "Applies subtle real-time skin smoothing"),
                        isOn: $viewModel.isSkinSmoothingEnabled,
                        accessibilityHint: String(localized: "Applies light skin smoothing to the camera preview")
                    )

                    // MARK: - Capture Section

                    SettingsSectionHeader(title: "Capture", systemImage: "photo.on.rectangle")

                    // Timer Selection
                    timerPicker

                    SettingsToggle(
                        title: String(localized: "Auto-Save"),
                        subtitle: String(localized: "Automatically save captures to Photo Library"),
                        isOn: $viewModel.isAutoSaveEnabled
                    )
                    .accessibilityHint(String(localized: "When enabled, photos and videos are saved immediately after capture"))

                    // MARK: - Pro Section

                    SettingsSectionHeader(title: "Pro", systemImage: "crown")

                    proSection

                    // MARK: - Sync Section

                    SettingsSectionHeader(title: String(localized: "iCloud Sync"), systemImage: "icloud")

                    iCloudSyncSection

                    // MARK: - About Section

                    SettingsSectionHeader(title: "About", systemImage: "info.circle")

                    acknowledgmentsSection
                    
                    // MARK: - Debug Section
                    
                    #if DEBUG
                    SettingsSectionHeader(title: "Debug", systemImage: "ant.fill")
                    
                    brandingDebugSection
                    #endif
                    
                    Spacer(minLength: Design.Spacing.xxxLarge)
                }
                .padding(.horizontal, Design.Spacing.large)
            }
            .background(Color.Surface.overlay)
            .navigationTitle(String(localized: "Settings"))
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Button(String(localized: "Done")) {
                        dismiss()
                    }
                    .foregroundStyle(Color.Accent.primary)
                }
            }
        }
    }
    
    // MARK: - Ring Size Slider
    
    private var ringSizeSlider: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.small) {
            HStack {
                Text(String(localized: "Ring Size"))
                    .font(.system(size: Design.BaseFontSize.medium, weight: .medium))
                    .foregroundStyle(.white)
                
                Spacer()
                
                Text("\(Int(viewModel.ringSize))pt")
                    .font(.system(size: Design.BaseFontSize.body, weight: .medium, design: .rounded))
                    .foregroundStyle(.white.opacity(Design.Opacity.medium))
            }
            
            HStack(spacing: Design.Spacing.medium) {
                // Small ring icon
                Image(systemName: "circle")
                    .font(.system(size: Design.BaseFontSize.small))
                    .foregroundStyle(.white.opacity(Design.Opacity.medium))
                
                Slider(
                    value: $viewModel.ringSize,
                    in: SettingsViewModel.minRingSize...SettingsViewModel.maxRingSize,
                    step: 5
                )
                .tint(Color.Accent.primary)
                
                // Large ring icon
                Image(systemName: "circle")
                    .font(.system(size: Design.BaseFontSize.large))
                    .foregroundStyle(.white.opacity(Design.Opacity.medium))
            }
            
            Text(String(localized: "Adjusts the size of the light ring around the camera preview"))
                .font(.system(size: Design.BaseFontSize.caption))
                .foregroundStyle(.white.opacity(Design.Opacity.medium))
        }
        .padding(.vertical, Design.Spacing.xSmall)
        .accessibilityLabel(String(localized: "Ring size"))
        .accessibilityValue("\(Int(viewModel.ringSize)) points")
    }
    
    // MARK: - Color Preset Section
    
    private var colorPresetSection: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.small) {
            Text(String(localized: "Light Color"))
                .font(.system(size: Design.BaseFontSize.medium, weight: .medium))
                .foregroundStyle(.white)
            
            LazyVGrid(
                columns: [GridItem(.adaptive(minimum: 80), spacing: Design.Spacing.small)],
                spacing: Design.Spacing.small
            ) {
                // Preset colors
                ForEach(RingLightColor.allPresets) { preset in
                    ColorPresetButton(
                        preset: preset,
                        isSelected: viewModel.selectedLightColor == preset,
                        isPremiumUnlocked: isPremiumUnlocked
                    ) {
                        // Premium colors require unlock
                        if preset.isPremium && !isPremiumUnlocked {
                            dismiss()
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                showPaywall = true
                            }
                        } else {
                            viewModel.selectedLightColor = preset
                        }
                    }
                }
                
                // Custom color picker (premium) - one-step: opens picker, selects on change
                CustomColorPickerButton(
                    customColor: Binding(
                        get: { viewModel.customColor },
                        set: { viewModel.selectCustomColor($0) }
                    ),
                    isSelected: viewModel.isCustomColorSelected,
                    isPremiumUnlocked: isPremiumUnlocked,
                    onPremiumRequired: {
                        dismiss()
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                            showPaywall = true
                        }
                    }
                )
            }
        }
        .padding(.vertical, Design.Spacing.xSmall)
    }
    
    // MARK: - Flash Mode Picker

    private var flashModePicker: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
            Text(String(localized: "Flash Mode"))
                .font(.system(size: Design.BaseFontSize.medium, weight: .medium))
                .foregroundStyle(.white)

            Text(String(localized: "Controls automatic flash behavior for photos"))
                .font(.system(size: Design.BaseFontSize.caption))
                .foregroundStyle(.white.opacity(Design.Opacity.medium))

            SegmentedPicker(
                title: "",
                options: CameraFlashMode.allCases.map { ($0.displayName, $0) },
                selection: $viewModel.flashMode
            )
            .accessibilityLabel(String(localized: "Select flash mode"))
        }
    }

    // MARK: - HDR Mode Picker (Premium)

    private var hdrModePicker: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
            HStack(spacing: Design.Spacing.xSmall) {
                Text(String(localized: "HDR Mode"))
                    .font(.system(size: Design.BaseFontSize.medium, weight: .medium))
                    .foregroundStyle(.white)
                
                Image(systemName: "crown.fill")
                    .font(.system(size: Design.BaseFontSize.small))
                    .foregroundStyle(Color.Status.warning)
            }

            Text(String(localized: "High Dynamic Range for better lighting in photos"))
                .font(.system(size: Design.BaseFontSize.caption))
                .foregroundStyle(.white.opacity(Design.Opacity.medium))

            SegmentedPicker(
                title: "",
                options: CameraHDRMode.allCases.map { ($0.displayName, $0) },
                selection: $viewModel.hdrMode
            )
            .disabled(!isPremiumUnlocked)
            .accessibilityLabel(String(localized: "Select HDR mode"))
        }
        .onTapGesture {
            if !isPremiumUnlocked {
                showPaywallAfterDismiss()
            }
        }
    }

    // MARK: - Photo Quality Picker (High/Maximum are Premium)

    private var photoQualityPicker: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
            HStack(spacing: Design.Spacing.xSmall) {
                Text(String(localized: "Photo Quality"))
                    .font(.system(size: Design.BaseFontSize.medium, weight: .medium))
                    .foregroundStyle(.white)
                
                Image(systemName: "crown.fill")
                    .font(.system(size: Design.BaseFontSize.small))
                    .foregroundStyle(Color.Status.warning)
            }

            Text(isPremiumUnlocked 
                ? String(localized: "File size and image quality for saved photos")
                : String(localized: "Upgrade to unlock High quality"))
                .font(.system(size: Design.BaseFontSize.caption))
                .foregroundStyle(.white.opacity(Design.Opacity.medium))

            // Custom picker with premium indicators
            HStack(spacing: Design.Spacing.small) {
                ForEach(PhotoQuality.allCases, id: \.self) { quality in
                    let isPremiumOption = quality == .high
                    let isDisabled = isPremiumOption && !isPremiumUnlocked
                    
                    Button {
                        if isDisabled {
                            showPaywallAfterDismiss()
                        } else {
                            viewModel.photoQuality = quality
                        }
                    } label: {
                        HStack(spacing: Design.Spacing.xxSmall) {
                            Text(quality.rawValue.capitalized)
                            if isPremiumOption && !isPremiumUnlocked {
                                Image(systemName: "lock.fill")
                                    .font(.system(size: Design.BaseFontSize.xSmall))
                            }
                        }
                        .font(.system(size: Design.BaseFontSize.body, weight: .medium))
                        .foregroundStyle(viewModel.photoQuality == quality ? .black : (isDisabled ? .white.opacity(Design.Opacity.light) : .white.opacity(Design.Opacity.strong)))
                        .padding(.vertical, Design.Spacing.small)
                        .frame(maxWidth: .infinity)
                        .background(
                            Capsule()
                                .fill(viewModel.photoQuality == quality ? Color.Accent.primary : Color.white.opacity(Design.Opacity.subtle))
                        )
                    }
                    .buttonStyle(.plain)
                }
            }
            .padding(.vertical, Design.Spacing.xSmall)
            .accessibilityLabel(String(localized: "Select photo quality"))
        }
    }

    // MARK: - Camera Position Picker

    private var cameraPositionPicker: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
            Text(String(localized: "Camera"))
                .font(.system(size: Design.BaseFontSize.medium, weight: .medium))
                .foregroundStyle(.white)

            Text(String(localized: "Choose between front and back camera lenses"))
                .font(.system(size: Design.BaseFontSize.caption))
                .foregroundStyle(.white.opacity(Design.Opacity.medium))

            SegmentedPicker(
                title: "",
                options: [
                    (String(localized: "Front"), CameraPosition.front),
                    (String(localized: "Back"), CameraPosition.back)
                ],
                selection: $viewModel.cameraPosition
            )
            .accessibilityLabel(String(localized: "Select camera position"))
        }
    }

    // MARK: - Ring Light Brightness Slider

    private var ringLightBrightnessSlider: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.small) {
            HStack {
                Text(String(localized: "Ring Light Brightness"))
                    .font(.system(size: Design.BaseFontSize.medium, weight: .medium))
                    .foregroundStyle(.white)

                Spacer()

                Text("\(Int(viewModel.ringLightOpacity * 100))%")
                    .font(.system(size: Design.BaseFontSize.body, weight: .medium, design: .rounded))
                    .foregroundStyle(.white.opacity(Design.Opacity.medium))
            }

            HStack(spacing: Design.Spacing.medium) {
                Image(systemName: "sun.min")
                    .font(.system(size: Design.BaseFontSize.small))
                    .foregroundStyle(.white.opacity(Design.Opacity.medium))

                Slider(
                    value: $viewModel.ringLightOpacity,
                    in: 0.1...1.0,
                    step: 0.05
                )
                .tint(Color.Accent.primary)

                Image(systemName: "sun.max.fill")
                    .font(.system(size: Design.BaseFontSize.large))
                    .foregroundStyle(.white.opacity(Design.Opacity.medium))
            }

            Text(String(localized: "Adjusts the brightness of the ring light"))
                .font(.system(size: Design.BaseFontSize.caption))
                .foregroundStyle(.white.opacity(Design.Opacity.medium))
        }
        .padding(.vertical, Design.Spacing.xSmall)
        .accessibilityLabel(String(localized: "Ring light brightness"))
        .accessibilityValue("\(Int(viewModel.ringLightOpacity * 100)) percent")
    }

    // MARK: - Center Stage Toggle

    private var centerStageToggle: some View {
        Toggle(isOn: $viewModel.isCenterStageEnabled) {
            VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
                HStack(spacing: Design.Spacing.xSmall) {
                    Text(String(localized: "Center Stage"))
                        .font(.system(size: Design.BaseFontSize.medium, weight: .medium))
                        .foregroundStyle(.white)
                    
                    Image(systemName: "crown.fill")
                        .font(.system(size: Design.BaseFontSize.small))
                        .foregroundStyle(Color.Status.warning)
                }
                
                Text(String(localized: "Automatically keeps you centered in the frame"))
                    .font(.system(size: Design.BaseFontSize.body))
                    .foregroundStyle(.white.opacity(Design.Opacity.medium))
            }
        }
        .tint(Color.Accent.primary)
        .padding(.vertical, Design.Spacing.xSmall)
        .disabled(!isPremiumUnlocked)
        .accessibilityLabel(String(localized: "Enable Center Stage"))
        .accessibilityHint(String(localized: "Automatically adjusts camera to keep subject centered"))
        .onTapGesture {
            if !isPremiumUnlocked {
                dismiss()
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    showPaywall = true
                }
            }
        }
    }

    // MARK: - Timer Picker (5s/10s are Premium)

    private var timerPicker: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
            HStack(spacing: Design.Spacing.xSmall) {
                Text(String(localized: "Self-Timer"))
                    .font(.system(size: Design.BaseFontSize.medium, weight: .medium))
                    .foregroundStyle(.white)
                
                Image(systemName: "crown.fill")
                    .font(.system(size: Design.BaseFontSize.small))
                    .foregroundStyle(Color.Status.warning)
            }

            Text(isPremiumUnlocked
                ? String(localized: "Delay before photo capture for self-portraits")
                : String(localized: "Upgrade to unlock 5s and 10s timers"))
                .font(.system(size: Design.BaseFontSize.caption))
                .foregroundStyle(.white.opacity(Design.Opacity.medium))

            // Custom picker with premium indicators
            HStack(spacing: Design.Spacing.small) {
                ForEach(TimerOption.allCases) { option in
                    let isPremiumOption = option == .five || option == .ten
                    let isDisabled = isPremiumOption && !isPremiumUnlocked
                    
                    Button {
                        if isDisabled {
                            showPaywallAfterDismiss()
                        } else {
                            viewModel.selectedTimer = option
                        }
                    } label: {
                        HStack(spacing: Design.Spacing.xxSmall) {
                            Text(option.displayName)
                            if isPremiumOption && !isPremiumUnlocked {
                                Image(systemName: "lock.fill")
                                    .font(.system(size: Design.BaseFontSize.xSmall))
                            }
                        }
                        .font(.system(size: Design.BaseFontSize.body, weight: .medium))
                        .foregroundStyle(viewModel.selectedTimer == option ? .black : (isDisabled ? .white.opacity(Design.Opacity.light) : .white.opacity(Design.Opacity.strong)))
                        .padding(.vertical, Design.Spacing.small)
                        .frame(maxWidth: .infinity)
                        .background(
                            Capsule()
                                .fill(viewModel.selectedTimer == option ? Color.Accent.primary : Color.white.opacity(Design.Opacity.subtle))
                        )
                    }
                    .buttonStyle(.plain)
                }
            }
            .padding(.vertical, Design.Spacing.xSmall)
            .accessibilityLabel(String(localized: "Select self-timer duration"))
        }
    }
    
    // MARK: - Pro Section
    
    private var proSection: some View {
        Button {
            dismiss()
            // Small delay to allow sheet to dismiss before showing paywall
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                showPaywall = true
            }
        } label: {
            HStack(spacing: Design.Spacing.medium) {
                Image(systemName: "crown.fill")
                    .font(.title2)
                    .foregroundStyle(Color.Status.warning)
                
                VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
                    Text(String(localized: "Upgrade to Pro"))
                        .font(.system(size: Design.BaseFontSize.medium, weight: .semibold))
                        .foregroundStyle(.white)
                    
                    Text(String(localized: "Premium colors, HDR, timers & more"))
                        .font(.system(size: Design.BaseFontSize.caption))
                        .foregroundStyle(.white.opacity(Design.Opacity.medium))
                }
                
                Spacer()
                
                Image(systemName: "chevron.right")
                    .font(.body)
                    .foregroundStyle(.white.opacity(Design.Opacity.medium))
            }
            .padding(Design.Spacing.medium)
            .background(
                RoundedRectangle(cornerRadius: Design.CornerRadius.medium)
                    .fill(Color.Accent.primary.opacity(Design.Opacity.subtle))
                    .strokeBorder(Color.Accent.primary.opacity(Design.Opacity.light), lineWidth: Design.LineWidth.thin)
            )
        }
        .buttonStyle(.plain)
        .accessibilityLabel(String(localized: "Upgrade to Pro"))
        .accessibilityHint(String(localized: "Opens upgrade options"))
    }
    
    // MARK: - iCloud Sync Section
    
    private var iCloudSyncSection: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.small) {
            // Sync toggle
            Toggle(isOn: $viewModel.iCloudEnabled) {
                VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
                    Text(String(localized: "Sync Settings"))
                        .font(.system(size: Design.BaseFontSize.medium, weight: .medium))
                        .foregroundStyle(.white)
                    
                    Text(viewModel.iCloudAvailable
                        ? String(localized: "Sync settings across all your devices")
                        : String(localized: "Sign in to iCloud to enable sync"))
                        .font(.system(size: Design.BaseFontSize.body))
                        .foregroundStyle(.white.opacity(Design.Opacity.medium))
                }
            }
            .tint(Color.Accent.primary)
            .padding(.vertical, Design.Spacing.xSmall)
            .disabled(!viewModel.iCloudAvailable)
            .accessibilityHint(String(localized: "Syncs settings across all your devices via iCloud"))
            
            // Sync status (show when enabled and available)
            if viewModel.iCloudEnabled && viewModel.iCloudAvailable {
                HStack(spacing: Design.Spacing.small) {
                    Image(systemName: syncStatusIcon)
                        .font(.system(size: Design.BaseFontSize.body))
                        .foregroundStyle(syncStatusColor)
                    
                    Text(syncStatusText)
                        .font(.system(size: Design.BaseFontSize.caption))
                        .foregroundStyle(.white.opacity(Design.Opacity.medium))
                    
                    Spacer()
                    
                    Button {
                        viewModel.forceSync()
                    } label: {
                        Text(String(localized: "Sync Now"))
                            .font(.system(size: Design.BaseFontSize.caption, weight: .medium))
                            .foregroundStyle(Color.Accent.primary)
                    }
                }
                .padding(.top, Design.Spacing.xSmall)
            }
        }
    }
    
    // MARK: - Sync Status Helpers
    
    private var syncStatusIcon: String {
        if !viewModel.hasCompletedInitialSync {
            return "arrow.triangle.2.circlepath"
        }
        return viewModel.syncStatus.isEmpty ? "checkmark.icloud" : "icloud"
    }
    
    private var syncStatusColor: Color {
        if !viewModel.hasCompletedInitialSync {
            return Color.Status.warning
        }
        return Color.Status.success
    }
    
    private var syncStatusText: String {
        if !viewModel.hasCompletedInitialSync {
            return String(localized: "Syncing...")
        }
        
        if let lastSync = viewModel.lastSyncDate {
            let formatter = RelativeDateTimeFormatter()
            formatter.unitsStyle = .abbreviated
            return String(localized: "Last synced \(formatter.localizedString(for: lastSync, relativeTo: Date()))")
        }
        
        return viewModel.syncStatus.isEmpty
            ? String(localized: "Synced")
            : viewModel.syncStatus
    }
    
    // MARK: - Acknowledgments Section
    
    private var acknowledgmentsSection: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.small) {
            NavigationLink {
                LicensesView()
            } label: {
                HStack {
                    VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
                        Text(String(localized: "Open Source Licenses"))
                            .font(.system(size: Design.BaseFontSize.body, weight: .medium))
                            .foregroundStyle(.white)
                        
                        Text(String(localized: "Third-party libraries used in this app"))
                            .font(.system(size: Design.BaseFontSize.caption))
                            .foregroundStyle(.white.opacity(Design.Opacity.medium))
                    }
                    
                    Spacer()
                    
                    Image(systemName: "chevron.right")
                        .font(.system(size: Design.BaseFontSize.caption))
                        .foregroundStyle(.white.opacity(Design.Opacity.medium))
                }
                .padding(Design.Spacing.medium)
                .background(Color.Surface.primary, in: RoundedRectangle(cornerRadius: Design.CornerRadius.medium))
            }
            .buttonStyle(.plain)
        }
    }
    
    // MARK: - Premium Toggle Helper
    
    /// Creates a toggle with premium indicator (crown icon)
    /// - Parameters:
    ///   - title: The toggle title
    ///   - subtitle: The toggle subtitle/description
    ///   - isOn: Binding to the toggle state
    ///   - accessibilityHint: Accessibility hint for the toggle
    /// - Returns: A view containing the premium toggle
    @ViewBuilder
    private func premiumToggle(
        title: String,
        subtitle: String,
        isOn: Binding<Bool>,
        accessibilityHint: String
    ) -> some View {
        Toggle(isOn: isOn) {
            VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
                HStack(spacing: Design.Spacing.xSmall) {
                    Text(title)
                        .font(.system(size: Design.BaseFontSize.medium, weight: .medium))
                        .foregroundStyle(.white)
                    
                    Image(systemName: "crown.fill")
                        .font(.system(size: Design.BaseFontSize.small))
                        .foregroundStyle(Color.Status.warning)
                }
                
                Text(subtitle)
                    .font(.system(size: Design.BaseFontSize.body))
                    .foregroundStyle(.white.opacity(Design.Opacity.medium))
            }
        }
        .tint(Color.Accent.primary)
        .padding(.vertical, Design.Spacing.xSmall)
        .disabled(!isPremiumUnlocked)
        .accessibilityHint(accessibilityHint)
        .onTapGesture {
            if !isPremiumUnlocked {
                showPaywallAfterDismiss()
            }
        }
    }
    
    // MARK: - Premium Section Header Helper
    
    /// Creates a section header with premium indicator (crown icon)
    /// - Parameters:
    ///   - title: The section title
    ///   - systemImage: The SF Symbol name for the section icon
    /// - Returns: A view containing the premium section header
    @ViewBuilder
    private func premiumSectionHeader(title: String, systemImage: String) -> some View {
        HStack(spacing: Design.Spacing.small) {
            Image(systemName: systemImage)
                .font(.system(size: Design.BaseFontSize.medium))
                .foregroundStyle(.white.opacity(Design.Opacity.accent))
            
            Text(title)
                .font(.system(size: Design.BaseFontSize.caption, weight: .semibold))
                .foregroundStyle(.white.opacity(Design.Opacity.accent))
                .textCase(.uppercase)
                .tracking(0.5)
            
            Image(systemName: "crown.fill")
                .font(.system(size: Design.BaseFontSize.small))
                .foregroundStyle(Color.Status.warning)
            
            Spacer()
        }
        .padding(.horizontal, Design.Spacing.xSmall)
        .padding(.top, Design.Spacing.large)
        .padding(.bottom, Design.Spacing.xSmall)
    }
    
    // MARK: - Branding Debug Section

    #if DEBUG
    private var brandingDebugSection: some View {
        VStack(spacing: Design.Spacing.small) {
            // Debug Premium Toggle
            SettingsToggle(
                title: "Enable Debug Premium",
                subtitle: "Unlock all premium features for testing",
                isOn: Binding(
                    get: { viewModel.premiumManager.isDebugPremiumToggleEnabled },
                    set: { viewModel.premiumManager.isDebugPremiumToggleEnabled = $0 }
                )
            )
            .tint(Color.Status.warning)
            // Icon Generator
            NavigationLink {
                IconGeneratorView(config: .selfieCam, appName: "SelfieCam")
            } label: {
                HStack {
                    VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
                        Text("Icon Generator")
                            .font(.system(size: Design.BaseFontSize.body, weight: .medium))
                            .foregroundStyle(.white)
                        
                        Text("Generate and save app icon to Files")
                            .font(.system(size: Design.BaseFontSize.caption))
                            .foregroundStyle(.white.opacity(Design.Opacity.medium))
                    }
                    
                    Spacer()
                    
                    Image(systemName: "chevron.right")
                        .font(.system(size: Design.BaseFontSize.caption))
                        .foregroundStyle(.white.opacity(Design.Opacity.medium))
                }
                .padding(Design.Spacing.medium)
                .background(Color.Surface.primary, in: RoundedRectangle(cornerRadius: Design.CornerRadius.medium))
            }
            .buttonStyle(.plain)
            
            // Branding Preview
            NavigationLink {
                BrandingPreviewView(
                    iconConfig: .selfieCam,
                    launchConfig: .selfieCam,
                    appName: "SelfieCam"
                )
            } label: {
                HStack {
                    VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
                        Text("Branding Preview")
                            .font(.system(size: Design.BaseFontSize.body, weight: .medium))
                            .foregroundStyle(.white)
                        
                        Text("Preview app icon and launch screen")
                            .font(.system(size: Design.BaseFontSize.caption))
                            .foregroundStyle(.white.opacity(Design.Opacity.medium))
                    }
                    
                    Spacer()
                    
                    Image(systemName: "chevron.right")
                        .font(.system(size: Design.BaseFontSize.caption))
                        .foregroundStyle(.white.opacity(Design.Opacity.medium))
                }
                .padding(Design.Spacing.medium)
                .background(Color.Surface.primary, in: RoundedRectangle(cornerRadius: Design.CornerRadius.medium))
            }
            .buttonStyle(.plain)
        }
    }
    #endif
}



#Preview {
    SettingsView(viewModel: SettingsViewModel(), showPaywall: .constant(false))
        .preferredColorScheme(.dark)
}
