//
//  ClockView.swift
//  TheNoiseClock
//
//  Created by Matt Bruce on 9/7/25.
//

import SwiftUI
import Bedrock

/// Main clock display view with settings and display mode
struct ClockView: View {
    
    // MARK: - Properties
    @Bindable var viewModel: ClockViewModel
    @State private var idleTimer: Timer?
    @State private var didHandleTouch = false
    
    // MARK: - Body
    var body: some View {
        ZStack {
            viewModel.style.effectiveBackgroundColor
                .ignoresSafeArea()
            
            GeometryReader { geometry in
                ZStack {
                    // Main clock display container
                    ClockDisplayContainer(
                        currentTime: viewModel.currentTime,
                        style: viewModel.style,
                        isDisplayMode: viewModel.isDisplayMode
                    )
                    
                    // Top overlay container
                    ClockOverlayContainer(style: viewModel.style)
                    
                }
            }
        }
        .ignoresSafeArea()
        .toolbar(.hidden, for: .navigationBar)
        .overlay {
            // Tab bar management overlay
            ClockTabBarManager(isDisplayMode: viewModel.isDisplayMode)
        }
        .simultaneousGesture(
            DragGesture(minimumDistance: 0)
                .onChanged { _ in
                    guard !didHandleTouch else { return }
                    didHandleTouch = true
                    handleUserInteraction()
                }
                .onEnded { _ in
                    didHandleTouch = false
                }
        )
        .onAppear {
            resetIdleTimer()
        }
        .onDisappear {
            idleTimer?.invalidate()
            idleTimer = nil
        }
        .onChange(of: viewModel.isDisplayMode) { _, isDisplayMode in
            if isDisplayMode {
                idleTimer?.invalidate()
                idleTimer = nil
            } else {
                resetIdleTimer()
            }
        }
    }

    // MARK: - Idle Timer
    private func resetIdleTimer() {
        idleTimer?.invalidate()
        idleTimer = nil
        guard !viewModel.isDisplayMode else { return }
        idleTimer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: false) { _ in
            enterDisplayModeFromIdle()
        }
    }

    private func enterDisplayModeFromIdle() {
        guard !viewModel.isDisplayMode else { return }
        viewModel.toggleDisplayMode()
    }

    private func handleUserInteraction() {
        if viewModel.isDisplayMode {
            viewModel.toggleDisplayMode()
        }
        resetIdleTimer()
    }
}

// MARK: - Preview
#Preview {
    NavigationStack {
        ClockView(viewModel: ClockViewModel())
    }
    .frame(width: 400, height: 600)
    .background(Color.black)
}
