const audio = document.getElementById("bg-music");

if (!audio) {
    console.warn("Audio element not found");
} else {
    console.log("Audio.js loaded");

    // Restore time
    const savedTime = sessionStorage.getItem("musicTime");
    if (savedTime !== null) {
        audio.currentTime = parseFloat(savedTime);
    }

    // Start audio after FIRST user interaction
    const startAudio = () => {
        audio.play().then(() => {
            console.log("Audio playing");
        }).catch(err => {
            console.warn("Play blocked:", err);
        });

        document.removeEventListener("click", startAudio);
        document.removeEventListener("touchstart", startAudio);
    };

    document.addEventListener("click", startAudio);
    document.addEventListener("touchstart", startAudio);

    // FORCE save time every 1 second
    setInterval(() => {
        if (!audio.paused && !isNaN(audio.currentTime)) {
            sessionStorage.setItem("musicTime", audio.currentTime);
        }
    }, 1000);
}
