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

import SwiftUI
import Combine

/// Component for displaying date overlay
struct DateOverlayView: View {
    
    // MARK: - Properties
    let color: Color
    let opacity: Double
    let dateFormat: String
    
    @State private var dateString: String = ""
    @State private var minuteTimer: Timer.TimerPublisher?
    @State private var minuteCancellable: AnyCancellable?
    
    // MARK: - Body
    var body: some View {
        let clamped = ColorUtils.clampOpacity(opacity)
        
        Text(dateString)
            .foregroundColor(color)
            .opacity(clamped)
            .font(.callout.weight(.semibold))
            .onAppear {
                updateDate()
                startMinuteUpdates()
            }
            .onDisappear {
                stopMinuteUpdates()
            }
            .onChange(of: dateFormat) { _, _ in
                updateDate()
            }
    }
    
    // MARK: - Private Methods
    private func startMinuteUpdates() {
        let pub = Timer.publish(every: AppConstants.TimerIntervals.minute, on: .main, in: .common)
        minuteTimer = pub
        minuteCancellable = pub.autoconnect().sink { _ in
            updateDate()
        }
    }
    
    private func stopMinuteUpdates() {
        minuteCancellable?.cancel()
        minuteCancellable = nil
        minuteTimer = nil
    }
    
    private func updateDate() {
        dateString = Date().formattedForOverlay(format: dateFormat)
    }
}
