import Foundation
import Observation

@MainActor
@Observable
final class TimerService {
    var elapsedSeconds: Int = 0
    private var task: Task<Void, Never>?
    private var isRunning = false

    func start() {
        guard !isRunning else { return }
        isRunning = true
        task = Task { [weak self] in
            while !Task.isCancelled {
                try? await Task.sleep(for: .seconds(1))
                guard let self, self.isRunning else { break }
                self.elapsedSeconds += 1
            }
        }
    }

    func stop() {
        isRunning = false
        task?.cancel()
        task = nil
    }

    func reset() {
        stop()
        elapsedSeconds = 0
    }

    var formattedTime: String {
        let minutes = elapsedSeconds / 60
        let seconds = elapsedSeconds % 60
        return String(format: "%d:%02d", minutes, seconds)
    }
}
