document.getElementById('start-button').addEventListener('click', startGame);
document.getElementById('continue-button').addEventListener('click', continueGame);
document.getElementById('save-button').addEventListener('click', saveGame);
document.getElementById('initial-play-button').addEventListener('click', showTitleScreen);

let currentBGM = '';
let bgmPosition = 0;
let bgmElement = document.getElementById('bgm');

// タイトル画面のBGMパス
const titleBGM = './data/bgm/歩む者【大同高校⧸Original BGM】.mp3';

// 変数管理オブジェクト
let gameVariables = {
    scene1VisitedCount: 0,
};

// スイッチ管理オブジェクト
let switches = {
    'あ': false,
};

// 現在のシーンIDをグローバルに保持
let currentSceneId = 0;

// ゲーム開始時にセーブデータの有無を確認し、Continueボタンを有効化
window.onload = function () {
    const savedData = localStorage.getItem('gameSave');
    if (savedData) {
        document.getElementById('continue-button').disabled = false;
    }
};

function showTitleScreen() {
    document.getElementById('initial-screen').style.display = 'none';
    document.getElementById('title-screen').style.display = 'block';

    // タイトル画面　背景画像
    document.getElementById('title-screen').style.backgroundImage = "url()"; 
    document.getElementById('title-screen').style.backgroundSize = "cover";

    // ゲームのタイトル
    document.getElementById('game-title').textContent = "New Project"; 

    changeBGM(titleBGM);
}

function startGame() {
    document.getElementById('title-screen').style.display = 'none';
    document.getElementById('game-screen').style.display = 'block';
    showScene(0); 
}

function continueGame() {
    const savedData = JSON.parse(localStorage.getItem('gameSave'));
    if (savedData) {
        document.getElementById('title-screen').style.display = 'none';
        document.getElementById('game-screen').style.display = 'block';
        gameVariables = savedData.gameVariables;
        switches = savedData.switches;
        showScene(savedData.sceneId);
    }
}

function saveGame() {
    const saveData = {
        sceneId: currentSceneId,
        gameVariables: gameVariables,
        switches: switches
    };
    localStorage.setItem('gameSave', JSON.stringify(saveData));
    document.getElementById('continue-button').disabled = false;
    alert('ゲームが保存されました！');
}

const scenes = [
    {
        "id": 0,
        "background": "./data/img/background",
        "defaultLeftCharacter": "./data/img/character/",
        "defaultCenterCharacter": "./data/img/character/",
        "defaultRightCharacter": "./data/img/character/",
        "dialogue": "これは最初のシーンです。",
        "bgm": "./data/bgm/",
        "sfx": "./data/se/",
        "textTickSFX": "./data/se/text-se/会話パート0.mp3",
        "choices": [
            {
                "text": "インデックス番号１",
                "nextScene": 1
            },
            {
                "text": "インデックス番号0",
                "nextScene": 0
            }
        ],
        "alternateScenes": {
            "あ": {
                "background": "./data/img/background",
                "defaultLeftCharacter": "./data/img/character/",
                "defaultCenterCharacter": "./data/img/character/",
                "defaultRightCharacter": "./data/img/character/",
                "dialogue": "これはスイッチ「あ」がオンの場合のシーンです。",
                "bgm": "./data/bgm/",
                "sfx": "./data/se/",
                "textTickSFX": "./data/se/text-se/会話パート1.mp3",
                "choices": [
                    {
                        "text": "インデックス番号３",
                        "nextScene": 3
                    },
                    {
                        "text": "インデックス番号０",
                        "nextScene": 0
                    }
                ]
            }
        }
    },
    {
        "id": 1,
        "background": "./data/img/background",
        "defaultLeftCharacter": "./data/img/character/",
        "defaultCenterCharacter": "./data/img/character/",
        "defaultRightCharacter": "./data/img/character/",
        "dialogue": "インデックス番号１のシーンです。",
        "bgm": "./data/bgm/",
        "sfx": "./data/se/",
        "textTickSFX": "./data/se/text-se/会話パート0.mp3",
        "choices": [
            {
                "text": "インデックス番号１",
                "nextScene": 1
            },
            {
                "text": "インデックス番号２",
                "nextScene": 2
            }
        ]
    },
    {
        "id": 2,
        "background": "./data/img/background",
        "defaultLeftCharacter": "./data/img/character/",
        "defaultCenterCharacter": "./data/img/character/",
        "defaultRightCharacter": "./data/img/character/",
        "dialogue": "これはインデックス番号２のシーンです。",
        "bgm": "./data/bgm/",
        "sfx": "./data/se/",
        "textTickSFX": "./data/se/text-se/会話パート0.mp3",
        "choices": [
            {
                "text": "インデックス番号１",
                "nextScene": 1
            },
            {
                "text": "インデックス番号０",
                "nextScene": 0
            }
        ]
    },
    {
        "id": 3,
        "background": "./data/img/background",
        "defaultLeftCharacter": "./data/img/character/",
        "defaultCenterCharacter": "./data/img/character/",
        "defaultRightCharacter": "./data/img/character/",
        "dialogue": "ゲームオーバー",
        "bgm": "./data/bgm/",
        "sfx": "./data/se/",
        "textTickSFX": "./data/se/text-se/会話パート1.mp3",
        "choices": [
            {
                "text": "インデックス番号０に戻る",
                "nextScene": 0
            }
        ]
    }
];

function showScene(index) {
    const scene = scenes.find(s => s.id === index);
    if (!scene) {
        console.error("Scene not found:", index);
        return;
    }
    currentSceneId = scene.id;

    // --- Generated Switch Logic ---
    
    if (scene.id === 1) {
        gameVariables.scene1VisitedCount++;
    }
    if (gameVariables.scene1VisitedCount >= 5) {
        setSwitch('あ', true);
        gameVariables.scene1VisitedCount = 0;
    }
    // ------------------------------

    if (scene.alternateScenes) {
        for (let key in scene.alternateScenes) {
            if (switches[key]) {
                const alternateScene = scene.alternateScenes[key];
                scene.background = alternateScene.background;
                scene.defaultLeftCharacter = alternateScene.defaultLeftCharacter;
                scene.defaultCenterCharacter = alternateScene.defaultCenterCharacter;
                scene.defaultRightCharacter = alternateScene.defaultRightCharacter;
                scene.dialogue = alternateScene.dialogue;
                scene.bgm = alternateScene.bgm;
                scene.sfx = alternateScene.sfx;
                scene.textTickSFX = alternateScene.textTickSFX;
                scene.choices = alternateScene.choices;
                break;
            }
        }
    }

    document.getElementById('background').style.backgroundImage = scene.background ? `url(${scene.background})` : 'none';
    document.getElementById('left-character').style.backgroundImage = scene.defaultLeftCharacter ? `url(${scene.defaultLeftCharacter})` : 'none';
    document.getElementById('center-character').style.backgroundImage = scene.defaultCenterCharacter ? `url(${scene.defaultCenterCharacter})` : 'none';
    document.getElementById('right-character').style.backgroundImage = scene.defaultRightCharacter ? `url(${scene.defaultRightCharacter})` : 'none';
    
    changeBGM(scene.bgm);
    playSFX(scene.sfx);
    typeDialogue(scene.dialogue, scene.textTickSFX, () => {
        if (scene.choices.length > 0) {
            showChoices(scene.choices);
        }
    });
}

function setSwitch(switchName, state) {
    if (switches.hasOwnProperty(switchName)) {
        switches[switchName] = state;
    }
}

function changeBGM(bgm) {
    if (bgm === currentBGM) {
        if(bgm && bgmElement.paused) bgmElement.play().catch(err => console.error(err));
    } else {
        fadeOut(bgmElement, () => {
            if(bgm) {
                bgmElement.src = bgm;
                bgmElement.currentTime = 0;
                bgmElement.play().catch(err => console.error("BGM play error:", err));
                fadeIn(bgmElement);
                currentBGM = bgm;
                bgmPosition = 0;
            } else {
                bgmElement.pause();
                currentBGM = '';
            }
        });
    }
}

function fadeIn(audioElement) {
    let volume = 0;
    audioElement.volume = volume;
    const fadeInInterval = setInterval(() => {
        if (volume < 1) {
            volume += 0.1;
            if(volume > 1) volume = 1;
            audioElement.volume = volume;
        } else {
            clearInterval(fadeInInterval);
        }
    }, 100);
}

function fadeOut(audioElement, callback) {
    let volume = audioElement.volume;
    const fadeOutInterval = setInterval(() => {
        if (volume > 0) {
            volume -= 0.1;
            if(volume < 0) volume = 0;
            audioElement.volume = volume;
        } else {
            clearInterval(fadeOutInterval);
            callback();
        }
    }, 100);
}

function playSFX(sfx) {
    if (sfx) {
        const sfxElement = new Audio(sfx);
        sfxElement.play().catch(err => console.error("SFX play error:", err));
    }
}

bgmElement.addEventListener('timeupdate', () => {
    bgmPosition = bgmElement.currentTime;
});

function typeDialogue(text, textTickSFX, callback) {
    const dialogueText = document.getElementById('dialogue-text');
    dialogueText.textContent = '';
    if(!text) {
        if(callback) callback();
        return;
    }
    let i = 0;
    const typingSpeed = 60;
    const interval = setInterval(() => {
        if (i < text.length) {
            dialogueText.textContent += text.charAt(i);
            if (textTickSFX && text.charAt(i).trim() !== '') {
                const tickSFX = new Audio(textTickSFX);
                tickSFX.volume = 0.5; 
                tickSFX.play().catch(err => console.error("Text tick SFX play error:", err));
            }
            i++;
        } else {
            clearInterval(interval);
            setTimeout(callback, 500);
        }
    }, typingSpeed);
}

function showChoices(choices) {
    const choicesContainer = document.getElementById('choices');
    choicesContainer.style.display = 'block';
    choicesContainer.innerHTML = '';
    choices.forEach(choice => {
        const button = document.createElement('button');
        button.className = 'choice-button';
        button.textContent = choice.text;
        button.addEventListener('click', () => {
            choicesContainer.style.display = 'none';
            showScene(choice.nextScene);
        });
        choicesContainer.appendChild(button);
    });
}
