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

import Foundation
import Observation

/// ViewModel for sound/audio playback
@available(iOS 17.0, tvOS 17.0, *)
@Observable
public class SoundViewModel {
    
    // MARK: - Properties
    private let soundPlayer: SoundPlayer
    private let soundConfigurationService: SoundConfigurationService
    public var isPreviewing: Bool = false
    public var previewSound: Sound?
    
    public var isPlaying: Bool {
        soundPlayer.isPlaying
    }
    
    public var availableSounds: [Sound] {
        return soundConfigurationService.getAvailableSounds()
    }
    
    // MARK: - Initialization
    public init(soundPlayer: SoundPlayer = SoundPlayer.shared, soundConfigurationService: SoundConfigurationService = SoundConfigurationService.shared) {
        self.soundPlayer = soundPlayer
        self.soundConfigurationService = soundConfigurationService
    }
    
    // MARK: - Public Interface
    public func playSound(_ sound: Sound) {
        soundPlayer.playSound(sound)
    }
    
    public func stopSound() {
        soundPlayer.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)
        soundPlayer.playSound(sound)
        
        // Auto-stop preview after 3 seconds
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
            self.stopPreview()
        }
    }
    
    public func stopPreview() {
        if isPreviewing {
            soundPlayer.stopSound()
            isPreviewing = false
            previewSound = nil
        }
    }
}
