//
//  NoiseViewModel.swift
//  AudioPlaybackKit
//
//  Created by Matt Bruce on 9/8/25.
//

import Foundation
import Observation

/// ViewModel for noise/audio playback
@available(iOS 17.0, tvOS 17.0, *)
@Observable
public class NoiseViewModel {
    
    // MARK: - Properties
    private let noisePlayer: NoisePlayer
    private let soundConfigurationService: SoundConfigurationService
    public var isPreviewing: Bool = false
    public var previewSound: Sound?
    
    public var isPlaying: Bool {
        noisePlayer.isPlaying
    }
    
    public var availableSounds: [Sound] {
        return soundConfigurationService.getAvailableSounds()
    }
    
    // MARK: - Initialization
    public init(noisePlayer: NoisePlayer = NoisePlayer.shared, soundConfigurationService: SoundConfigurationService = SoundConfigurationService.shared) {
        self.noisePlayer = noisePlayer
        self.soundConfigurationService = soundConfigurationService
    }
    
    // MARK: - Public Interface
    public func playSound(_ sound: Sound) {
        noisePlayer.playSound(sound)
    }
    
    public func stopSound() {
        noisePlayer.stopSound()
    }
    
    public func selectSound(_ sound: Sound) {
        // Stop any current playback when selecting a new sound
        if isPlaying {
            stopSound()
        }
        // Stop any preview
        stopPreview()
    }
    
    // MARK: - Preview Functionality
    public func previewSound(_ sound: Sound) {
        // Stop any current preview
        stopPreview()
        
        // Set preview state
        previewSound = sound
        isPreviewing = true
        
        // Play preview (3 seconds)
        noisePlayer.playSound(sound)
        
        // Auto-stop preview after 3 seconds
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
            self.stopPreview()
        }
    }
    
    public func stopPreview() {
        if isPreviewing {
            noisePlayer.stopSound()
            isPreviewing = false
            previewSound = nil
        }
    }
}
