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

function preloadResources(resources) {
    const promises = [];
    resources.forEach(resource => {
        let promise;
        const extension = resource.split('.').pop().toLowerCase();
        if (['jpg', 'jpeg', 'png', 'gif'].includes(extension)) {
            promise = new Promise((resolve) => {
                const img = new Image();
                img.onload = () => resolve();
                img.onerror = () => { console.error('Failed to load image:', resource); resolve(); };
                img.src = resource;
            });
        } else if (['mp3', 'ogg', 'wav'].includes(extension)) {
            promise = new Promise((resolve) => {
                const audio = new Audio();
                audio.addEventListener('canplaythrough', () => resolve(), { once: true });
                audio.onerror = () => { console.error('Failed to load audio:', resource); resolve(); };
                audio.src = resource;
            });
        } else {
            promise = Promise.resolve();
        }
        promises.push(promise);
    });
    return Promise.all(promises);
}

function getAllResources() {
    const resources = new Set();
    const addResource = (path) => { if (path && !path.endsWith('/') && path.trim() !== '') resources.add(path); };
    scenes.forEach(scene => {
        addResource(scene.background);
        addResource(scene.defaultLeftCharacter);
        addResource(scene.defaultCenterCharacter);
        addResource(scene.defaultRightCharacter);
        addResource(scene.bgm);
        addResource(scene.sfx);
        addResource(scene.textTickSFX);
        if (scene.alternateScenes) {
            for (const key in scene.alternateScenes) {
                const alt = scene.alternateScenes[key];
                addResource(alt.background);
                addResource(alt.defaultLeftCharacter);
                addResource(alt.defaultCenterCharacter);
                addResource(alt.defaultRightCharacter);
                addResource(alt.bgm);
                addResource(alt.sfx);
                addResource(alt.textTickSFX);
            }
        }
    });
    return Array.from(resources);
}

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

document.getElementById('game-title').textContent = "New Project"; 
const titleBGM = './data/bgm/歩む者【大同高校⧸Original BGM】.mp3';
document.getElementById('title-screen').style.backgroundImage = "url(./data/img/background/ビルの間.jpg)"; 
document.getElementById('title-screen').style.backgroundSize = "cover";

let gameVariables = {
    scene1VisitedCount: 0,
};

let switches = {
    'あ': false,
};

let currentSceneId = 0;

const NUM_SLOTS = 6;
let currentSaves = [];

function loadSaves() {
    const saved = localStorage.getItem('gameSaves');
    if (saved) {
        currentSaves = JSON.parse(saved);
    } else {
        currentSaves = new Array(NUM_SLOTS).fill(null);
    }
}

function saveSavesToStorage() {
    localStorage.setItem('gameSaves', JSON.stringify(currentSaves));
}

window.onload = function() {
    loadSaves();
    const hasAnySave = currentSaves.some(s => s !== null);
    document.getElementById('continue-button').disabled = !hasAnySave;

    const initialPlayButton = document.getElementById('initial-play-button');
    const allResources = getAllResources();
    initialPlayButton.style.display = 'none';

    preloadResources(allResources).then(() => {
        console.log('すべてのリソースの読み込みが完了しました！');
        initialPlayButton.style.display = 'block';
    }).catch(err => {
        console.error('リソースの読み込み中にエラーが発生しました:', err);
        initialPlayButton.style.display = 'block';
    });
};

document.getElementById('save-button').addEventListener('click', showSaveMenu);
document.getElementById('continue-button').addEventListener('click', showLoadMenu);

function showSaveMenu() {
    document.getElementById('modal-title').textContent = 'セーブするスロットを選択';
    document.getElementById('save-modal').style.display = 'flex';
    renderSaveSlots(true);
}

function showLoadMenu() {
    document.getElementById('modal-title').textContent = 'ロードするスロットを選択';
    document.getElementById('save-modal').style.display = 'flex';
    renderSaveSlots(false);
}

function renderSaveSlots(isSaveMode) {
    const container = document.getElementById('save-slots');
    container.innerHTML = '';
    for (let i = 0; i < NUM_SLOTS; i++) {
        const slotData = currentSaves[i];
        const slotEl = document.createElement('div');
        slotEl.style.cssText = 'background:#2a2a2a; padding:15px; border-radius:5px; cursor:pointer; border:2px solid #444;';
        if (slotData) {
            slotEl.innerHTML = `<strong>スロット ${i+1}</strong><br><small>${slotData.timestamp}</small><br><small>シーン: ${slotData.sceneId}</small><small style="color:#aaa;">${slotData.preview || '---'}</small><br>`;
        } else {
            slotEl.innerHTML = `<strong>スロット ${i+1}</strong><br><small style="color:#666;">空き</small>`;
            slotEl.style.opacity = '0.6';
        }
        slotEl.onclick = () => {
            if (isSaveMode) saveToSlot(i);
            else if (slotData) loadFromSlot(i);
        };
        container.appendChild(slotEl);
    }
}

function saveToSlot(slotIndex) {
    const previewText = document.getElementById('dialogue-text').textContent.substring(0, 20) + (document.getElementById('dialogue-text').textContent.length > 20 ? '...' : '');
    const saveData = {
        sceneId: currentSceneId,
        gameVariables: JSON.parse(JSON.stringify(gameVariables)),
        switches: JSON.parse(JSON.stringify(switches)),
        timestamp: new Date().toLocaleString('ja-JP'),
        preview: previewText || '---'
    };
    currentSaves[slotIndex] = saveData;
    saveSavesToStorage();
    document.getElementById('continue-button').disabled = false;
    closeSaveModal();
    alert(`スロット ${slotIndex + 1} に保存しました！`);
}

function loadFromSlot(slotIndex) {
    const data = currentSaves[slotIndex];
    if (!data) return;
    gameVariables = JSON.parse(JSON.stringify(data.gameVariables));
    switches = JSON.parse(JSON.stringify(data.switches));
    closeSaveModal();
    document.getElementById('title-screen').style.display = 'none';
    document.getElementById('game-screen').style.display = 'block';
    showScene(data.sceneId);
}

function closeSaveModal() {
    document.getElementById('save-modal').style.display = 'none';
}

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

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

const scenes = [
    {
        "id": 0,
        "background": "./data/img/background/ビルの間.jpg",
        "background_Effect": "1",
        "defaultLeftCharacter": "",
        "LeftCharacter_Effect": "0",
        "defaultCenterCharacter": "./data/img/character/wolf-正面.png",
        "CenterCharacter_Effect": "2",
        "defaultRightCharacter": "",
        "RightCharacter_Effect": "0",
        "dialogue": "これは最初のシーンです。",
        "bgm": "",
        "sfx": "",
        "textTickSFX": "./data/se/text-se/会話パート0.mp3",
        "choices": [
            {
                "text": "インデックス番号１",
                "nextScene": 1
            },
            {
                "text": "インデックス番号0",
                "nextScene": 0
            }
        ],
        "alternateScenes": {
            "あ": {
                "background": "",
                "background_Effect": "0",
                "defaultLeftCharacter": "",
                "LeftCharacter_Effect": "0",
                "defaultCenterCharacter": "",
                "CenterCharacter_Effect": "0",
                "defaultRightCharacter": "",
                "RightCharacter_Effect": "0",
                "dialogue": "これはスイッチ「あ」がオンの場合のシーンです。",
                "bgm": "",
                "sfx": "",
                "textTickSFX": "./data/se/text-se/会話パート1.mp3",
                "choices": [
                    {
                        "text": "インデックス番号３",
                        "nextScene": 3
                    },
                    {
                        "text": "インデックス番号０",
                        "nextScene": 0
                    }
                ]
            }
        }
    },
    {
        "id": 1,
        "background": "./data/img/background/裏路地１.jpg",
        "background_Effect": "2",
        "defaultLeftCharacter": "./data/img/character/wolf-正面.png",
        "LeftCharacter_Effect": "2",
        "defaultCenterCharacter": "",
        "CenterCharacter_Effect": "0",
        "defaultRightCharacter": "",
        "RightCharacter_Effect": "0",
        "dialogue": "インデックス番号１のシーンです。",
        "bgm": "",
        "sfx": "",
        "textTickSFX": "./data/se/text-se/会話パート0.mp3",
        "choices": [
            {
                "text": "インデックス番号１",
                "nextScene": 1
            },
            {
                "text": "インデックス番号２",
                "nextScene": 2
            }
        ]
    },
    {
        "id": 2,
        "background": "./data/img/background",
        "background_Effect": "2",
        "defaultLeftCharacter": "./data/img/character/",
        "LeftCharacter_Effect": "2",
        "defaultCenterCharacter": "./data/img/character/",
        "CenterCharacter_Effect": "0",
        "defaultRightCharacter": "./data/img/character/",
        "RightCharacter_Effect": "0",
        "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",
        "background_Effect": "0",
        "defaultLeftCharacter": "./data/img/character/",
        "LeftCharacter_Effect": "0",
        "defaultCenterCharacter": "./data/img/character/",
        "CenterCharacter_Effect": "0",
        "defaultRightCharacter": "./data/img/character/",
        "RightCharacter_Effect": "0",
        "dialogue": "ゲームオーバー",
        "bgm": "./data/bgm/",
        "sfx": "./data/se/",
        "textTickSFX": "./data/se/text-se/会話パート1.mp3",
        "choices": [
            {
                "text": "インデックス番号０に戻る",
                "nextScene": 0
            }
        ]
    }
];

function applyFadeEffect(element, effect) {
    return new Promise(resolve => {
        if (!element) {
            console.error("Element not found for fade effect");
            resolve();
            return;
        }
        if (effect === '1') {
            element.style.opacity = '0';
            element.style.transition = 'opacity 1s ease';
            setTimeout(() => { element.style.opacity = '1'; setTimeout(resolve, 1000); }, 10);
        } else if (effect === '2') {
            element.style.opacity = '1';
            element.style.transition = 'opacity 1s ease';
            setTimeout(() => { element.style.opacity = '0'; setTimeout(resolve, 1000); }, 10);
        } else {
            element.style.opacity = '1';
            element.style.transition = 'none';
            resolve();
        }
    });
}

function showScene(index) {
    const scene = scenes.find(s => s.id === index);
    if (!scene) return;
    currentSceneId = scene.id;

    
    if (scene.id === 0) {
        gameVariables.scene1VisitedCount++;
    }
    if (gameVariables.scene1VisitedCount >= 5) {
        setSwitch('あ', true);
        
    }

    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.background_Effect = alternateScene.background_Effect;
                scene.LeftCharacter_Effect = alternateScene.LeftCharacter_Effect;
                scene.CenterCharacter_Effect = alternateScene.CenterCharacter_Effect;
                scene.RightCharacter_Effect = alternateScene.RightCharacter_Effect;
                scene.choices = alternateScene.choices;
                break;
            }
        }
    }

    const backgroundElement = document.getElementById('background');
    const leftCharacterElement = document.getElementById('left-character');
    const centerCharacterElement = document.getElementById('center-character');
    const rightCharacterElement = document.getElementById('right-character');

    if (scene.background_Effect !== '2') backgroundElement.style.backgroundImage = scene.background ? `url(${scene.background})` : 'none';
    if (scene.LeftCharacter_Effect !== '2') leftCharacterElement.style.backgroundImage = scene.defaultLeftCharacter ? `url(${scene.defaultLeftCharacter})` : 'none';
    if (scene.CenterCharacter_Effect !== '2') centerCharacterElement.style.backgroundImage = scene.defaultCenterCharacter ? `url(${scene.defaultCenterCharacter})` : 'none';
    if (scene.RightCharacter_Effect !== '2') rightCharacterElement.style.backgroundImage = scene.defaultRightCharacter ? `url(${scene.defaultRightCharacter})` : 'none';

    Promise.all([
        applyFadeEffect(backgroundElement, scene.background_Effect),
        applyFadeEffect(leftCharacterElement, scene.LeftCharacter_Effect),
        applyFadeEffect(centerCharacterElement, scene.CenterCharacter_Effect),
        applyFadeEffect(rightCharacterElement, scene.RightCharacter_Effect)
    ]).then(() => {
        if (scene.background_Effect === '2') backgroundElement.style.backgroundImage = scene.background ? `url(${scene.background})` : 'none';
        backgroundElement.style.opacity = '1';
        if (scene.LeftCharacter_Effect === '2') leftCharacterElement.style.backgroundImage = scene.defaultLeftCharacter ? `url(${scene.defaultLeftCharacter})` : 'none';
        leftCharacterElement.style.opacity = '1';
        if (scene.CenterCharacter_Effect === '2') centerCharacterElement.style.backgroundImage = scene.defaultCenterCharacter ? `url(${scene.defaultCenterCharacter})` : 'none';
        centerCharacterElement.style.opacity = '1';
        if (scene.RightCharacter_Effect === '2') rightCharacterElement.style.backgroundImage = scene.defaultRightCharacter ? `url(${scene.defaultRightCharacter})` : 'none';
        rightCharacterElement.style.opacity = '1';
        
        changeBGM(scene.bgm);
        playSFX(scene.sfx);
        typeDialogue(scene.dialogue, scene.textTickSFX, () => {
            if (scene.choices.length > 0) showChoices(scene.choices);
        });
    }).catch(err => console.error("Fade effect error:", err));
}

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

function changeBGM(bgm) {
    if (!bgmElement) return;
    if (bgm === currentBGM) {
        bgmElement.currentTime = bgmPosition;
        if(bgm) bgmElement.play().catch(err => console.error("BGM play 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');
    if (!dialogueText) return;
    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');
    if (!choicesContainer) return;
    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);
    });
}