// Audio playing stuff

function getParentAudio(button) { // Gets the parent audio for distincting audio(s) played at once
    const parentSection = button.closest("section"); // section where audio element is present
    const audio = parentSection.querySelector("audio"); // audio selected from inputed audio element

    return { //returns parent section and audio element
        parentSection,
        audio
    };
}

function playAudio(button) { 
    const { parentSection, audio } = getParentAudio(button); // parent selection and audio taken from Parent Audio

    audio.play(); // Play audio
    parentSection.classList.add("flashing"); // Add flashing
    parentSection.classList.remove("blue"); // Remove pause color
}

function pauseAudio(button) {
    const { parentSection, audio } = getParentAudio(button); // parent selection and audio taken from Parent Audio
        if (audio.currentTime > 0) { // If time of audio is greater than 0, or has been played, allow pausing
            audio.pause(); // pause audio
            parentSection.classList.remove("flashing"); // Remove flashing
            parentSection.classList.add("blue"); // Add pause color
        }
}

function replayAudio(button) {
    const { parentSection, audio } = getParentAudio(button); // parent selection and audio taken from Parent Audio
    if (audio.currentTime > 0) { // if time of audio is greater than 0, or has been played, allow replaying
            audio.currentTime = 0; // reset time of audio to 0
            audio.pause(); // pause (or in this case, stops) audio
            parentSection.classList.remove("flashing"); // Remove flashing
            parentSection.classList.remove("blue"); // remove pause color
        }
}

// speed control for audio playback

let playbackSpeed = 1; // starting playback speed

function changeSpeed(amount) { 
    playbackSpeed = Math.min(10, Math.max(0.25, playbackSpeed + amount)); // starting value is 1, with max value of 10 and min value of 0.25
    playbackSpeed = Number(playbackSpeed.toFixed(2)); // number of decimal places available

    document.querySelectorAll("audio").forEach((audio) => {
        audio.playbackRate = playbackSpeed; // set playbackrate to playback speed
    });

    document.getElementById("speedDisplay").textContent = `${playbackSpeed}x`; // set the speed to a string presentable?
    saveSettings({ playbackSpeed }); // save playback speed to local storage
}

// Splitup for Settings management

const settingsKey = "minecraftAudioPlayerSettings"; // Key for localStorage to store settings
const defaultSettings = { userName: "", background: "backdrop1", font: "pixel", playbackSpeed: 1 }; // Series of default settings for the audio player, including user name, background, font, and speed
const backgroundOptions = {
    backdrop1: "Images/Backdrop.jpg", // All
    backdrop2: "Images/Backdrop2.jpg", // The
    backdrop3: "Images/Backdrop3.jpg" // Backdrops
};
const fontOptions = { // as shown, font options for the audio player, including pixel, clean, and serif
    pixel: "'Trebuchet MS', sans-serif",
    clean: "Verdana, sans-serif",
    serif: "Georgia, serif"
};

function getSettings() { // Pull settings from json file, or if not present, use default settings
    try {
        return { ...defaultSettings, ...JSON.parse(localStorage.getItem(settingsKey)) };
    } catch (error) {
        return { ...defaultSettings };
    }
}

function saveSettings(changes) {
    const settings = { ...getSettings(), ...changes }; // Settings is the settings gotten from all the values
    localStorage.setItem(settingsKey, JSON.stringify(settings)); // Save the settings to localStorage as a JSON string
}

function applySettings(settings) { // Apply the selected settings to the audio player
    const selectedBackground = backgroundOptions[settings.background] || backgroundOptions.backdrop1; // specify background setting
    const selectedFont = fontOptions[settings.font] || fontOptions.pixel; // specify font setting
    playbackSpeed = Math.min(10, Math.max(0.25, Number(settings.playbackSpeed) || 1)); // Min = 0.25, Max = 10, default = 1
    document.documentElement.style.setProperty("--player-background", `url('${selectedBackground}')`); // set background settings
    document.documentElement.style.setProperty("--player-font", selectedFont); // set font settings
    document.querySelectorAll("audio").forEach((audio) => {
        audio.playbackRate = playbackSpeed;
    });
    document.getElementById("speedDisplay").textContent = `${playbackSpeed}x`; // Display playback speed
    document.title = settings.userName ? `${settings.userName}'s Audio Player` : "Audio Player"; // Change Tab label to listed username + "'s Audio Player", if username is different from default.
}

function openSettings() { // Activate settings dialogue and use current settings, including font, background, and user name, to populate the settings dialog
    const settings = getSettings(); // Get current settings from localStorage for other function use
    const dialog = document.getElementById("settingsDialog");
    document.getElementById("userName").value = settings.userName; // username value
    document.getElementById("backgroundChoice").value = settings.background; // background value
    document.getElementById("fontChoice").value = settings.font; // font value
    document.getElementById("settingsStatus").textContent = "";
    dialog.showModal(); // Show the settings dialog box
}

function closeSettings() { // Close the settings without accessing data
    document.getElementById("settingsDialog").close();
}

document.addEventListener("DOMContentLoaded", () => { // When the document is loaded, apply the settings and add an event listener to the settings form
    applySettings(getSettings());
    document.getElementById("settingsForm").addEventListener("submit", (event) => {
        event.preventDefault();
        const formData = new FormData(event.currentTarget);
        const settings = {
            userName: formData.get("userName").trim(), // Actively apply username settings 
            background: formData.get("backgroundChoice"), // Actively apply background settings
            font: formData.get("fontChoice"), // Actively apply font settings
            playbackSpeed // Actively apply playback speed
        };
        localStorage.setItem(settingsKey, JSON.stringify(settings)); // storage for website settings
        applySettings(settings); // Apply the settings to the audio player
        document.getElementById("settingsStatus").textContent = "Settings saved."; // show when settings are saved
        window.setTimeout(closeSettings, 500); // Close the settings dialog after 500 milliseconds
    });
});