import SpriteKit

enum SFXEvent {
    case select, slide, destroy, complete, merge
}

final class SFXManager {
    static let shared = SFXManager()
    private init() {}

    private var isMuted = false

    func play(_ event: SFXEvent) {
        guard !isMuted else { return }
        let filename: String
        switch event {
        case .select:   filename = "select.mp3"
        case .slide:    filename = "slide.mp3"
        case .destroy:  filename = "destroy.mp3"
        case .complete: filename = "complete.mp3"
        case .merge:    filename = "merge.wav"  // TODO: replace with real audio
        }
        // SKAction.playSoundFileNamed silently ignores missing files — safe for placeholder TODOs
        let action = SKAction.playSoundFileNamed(filename, waitForCompletion: false)
        // We need a scene to run the action; post to a shared coordinator node
        SFXRunner.shared.run(action)
    }

    func playMerge() {
        play(.merge)
    }

    func setMuted(_ muted: Bool) {
        isMuted = muted
    }
}

// A long-lived SKNode that can run audio actions without being in a scene tree.
// Attach it to the active scene on first use.
final class SFXRunner {
    static let shared = SFXRunner()
    private(set) var node = SKNode()
    private init() {}

    func attach(to scene: SKScene) {
        if node.parent == nil {
            scene.addChild(node)
        }
    }

    func run(_ action: SKAction) {
        node.run(action)
    }
}
