const debugMode = false; // デバッグモード: trueでファイル名を表示

window.addEventListener('load', () => {
    if (typeof fileData === 'undefined' || typeof messageData === 'undefined' ||
        typeof secretLines === 'undefined' || typeof welcomeMessages === 'undefined' ||
        typeof sectionNames === 'undefined' || typeof finishMessages === 'undefined' ||
        typeof urlData === 'undefined') {
        alert("materials/messages.js の読み込みに失敗しました。");
        return;
    }

    const bgm = document.getElementById('bgm');
    const overlay = document.getElementById('welcome-overlay');
    const welcomeMsg = document.getElementById('welcome-message');
    const book = document.getElementById('book');
    const video = document.getElementById('book-video');
    const image = document.getElementById('book-image');
    let bgmUnlocked = false;

    welcomeMsg.textContent = welcomeMessages[Math.floor(Math.random() * welcomeMessages.length)];

    const unlockBGM = () => {
        if (bgmUnlocked) return;
        bgmUnlocked = true;
        bgm.volume = 0.5;
        bgm.play().catch(() => { });
        overlay.style.opacity = '0';
        setTimeout(() => { overlay.style.display = 'none'; }, 1000);
    };

    overlay.addEventListener('click', unlockBGM);
    document.body.addEventListener('click', unlockBGM, { once: true });

    const observer = new MutationObserver(() => {
        if (!bgmUnlocked) return;
        if (book.classList.contains('open')) {
            bgm.pause();
        } else {
            bgm.play().catch(() => { });
        }
    });
    observer.observe(book, { attributes: true, attributeFilter: ['class'] });

    // --- State & Settings ---
    let currentIndex = 0;
    let allVideos = [];

    // Load Settings
    const loadSettings = () => {
        const saved = localStorage.getItem('aoinu_settings');
        if (saved) {
            return JSON.parse(saved);
        }
        return { isRandom: false, isSequential: false, isFinishStop: false };
    };

    let settings = loadSettings();

    const saveSettings = () => {
        localStorage.setItem('aoinu_settings', JSON.stringify(settings));
    };

    const updateToggleUI = () => {
        const seqBtn = document.getElementById('toggle-seq');
        const randomBtn = document.getElementById('toggle-random');
        const finishStopBtn = document.getElementById('toggle-finish-stop');

        seqBtn.textContent = settings.isSequential ? "⏸ 連続再生 ON" : "▶ 連続再生 OFF";
        seqBtn.classList.toggle('active', settings.isSequential);

        randomBtn.textContent = settings.isRandom ? "🔀 ランダム ON" : "🔀 ランダム OFF";
        randomBtn.classList.toggle('active', settings.isRandom);

        finishStopBtn.textContent = settings.isFinishStop ? "⏹ Finish停止 ON" : "⏹ Finish停止 OFF";
        finishStopBtn.classList.toggle('active', settings.isFinishStop);
    };

    const getRandomSecret = () => secretLines[Math.floor(Math.random() * secretLines.length)];

    const getNextIndex = () => {
        if (settings.isRandom) {
            let next;
            do { next = Math.floor(Math.random() * allVideos.length); } while (next === currentIndex && allVideos.length > 1);
            return next;
        }
        return (currentIndex + 1) % allVideos.length;
    };

    const parseMessage = (text) => {
        if (!text) return "";
        const parts = text.split('|');
        return parts[Math.floor(Math.random() * parts.length)].trim();
    };

    const openBook = (filename) => {
        const ext = filename.split('.').pop().toLowerCase();
        const isImage = ['jpg', 'jpeg', 'png'].includes(ext);

        if (isImage) {
            video.style.display = 'none';
            video.pause();
            image.style.display = 'block';
            image.src = `Videos/${filename}`;
        } else {
            image.style.display = 'none';
            video.style.display = 'block';
            video.src = `Videos/${filename}`;
            video.loop = !settings.isSequential;
            video.play().catch(() => { });
        }

        let rawMessage = messageData[filename] || getRandomSecret();
        let displayMessage = parseMessage(rawMessage);

        // Link Button Logic
        const linkBtn = document.getElementById('link-button');
        const url = urlData[filename];
        if (url && url.length > 0) {
            linkBtn.style.display = 'block';
            linkBtn.href = url;
        } else {
            linkBtn.style.display = 'none';
            linkBtn.href = '#';
        }

        if (debugMode) {
            let storyHTML = `${displayMessage}<br><span style="font-size: 0.6em; color: #b7e4c7; display: block; margin-top: 15px; border-top: 1px dashed #4d6d4d; padding-top: 5px;">[DEBUG: ${filename}]</span>`;
            document.getElementById('story-text').innerHTML = storyHTML;
        } else {
            document.getElementById('story-text').textContent = displayMessage;
        }

        currentIndex = allVideos.findIndex(v => v.file === filename);

        // Auto page turn for sequential image playback? 
        // For now, images are just static. User manual turn.
        // If we wanted slideshow: setTimeout check settings.isSequential...
        if (isImage && settings.isSequential) {
            // Simple slideshow logic: 5 seconds duration
            setTimeout(() => {
                if (book.classList.contains('open') && allVideos[currentIndex]?.file === filename) {
                    // Check if still same page
                    currentIndex = getNextIndex();
                    openBook(allVideos[currentIndex].file);
                }
            }, 5000);
        }
    };

    const closeBook = () => {
        book.classList.remove('open');
        video.pause();
        video.src = '';
        image.src = '';
        document.getElementById('link-button').style.display = 'none';
        // 連続再生を一時的にリセット（ユーザーが設定したフラグは保持）
        // ただし、閉じるときに自動停止させる設計ならここで調整
    };

    const triggerFinish = () => {
        const currentFile = allVideos[currentIndex]?.file;
        if (!currentFile || !book.classList.contains('open')) return;

        playPyuSound();
        createWaterSprayEffect();

        const finishOverlay = document.getElementById('finish-overlay');
        if (finishOverlay) {
            const randomNum = Math.floor(Math.random() * 6) + 1; // 1 to 6
            finishOverlay.style.backgroundImage = `url('materials/finish${randomNum}.png')`;
            finishOverlay.classList.add('show');

            if (settings.isFinishStop) {
                if (video.style.display !== 'none') video.pause();
                setTimeout(() => {
                    finishOverlay.classList.remove('show');
                    if (book.classList.contains('open') && video.style.display !== 'none') video.play().catch(() => { });
                }, 3000);
            } else {
                setTimeout(() => {
                    finishOverlay.classList.remove('show');
                }, 3000);
            }
        }

        let candidates = [];
        const group = allVideos[currentIndex].group;
        if (finishMessages[group]) {
            candidates = finishMessages[group];
        } else if (finishMessages.start) {
            candidates = finishMessages.start;
        }

        if (candidates.length > 0) {
            const msg = candidates[Math.floor(Math.random() * candidates.length)];
            const story = document.getElementById('story-text');
            story.textContent = msg;
            story.style.animation = 'none';
            setTimeout(() => story.style.animation = 'shake 0.6s ease-in-out', 10);
        }
    };

    // --- Introduction Frame Setup ---
    const introFrame = document.getElementById('intro-frame');
    if (introFrame) {
        let allThumbnails = [];
        Object.keys(fileData).forEach(cat => {
            fileData[cat].forEach(file => {
                const parts = file.split('/');
                if (parts.length >= 2) {
                    const category = parts[0];
                    const filename = parts[1];
                    const thumb = filename.replace(/\.[^/.]+$/, "") + ".jpg";
                    const thumbPath = `Videos/${category}/Thumbnails/${thumb}`;
                    allThumbnails.push(thumbPath);
                }
            });
        });

        if (allThumbnails.length > 0) {
            const randomThumb = allThumbnails[Math.floor(Math.random() * allThumbnails.length)];
            introFrame.style.backgroundImage = `url('${encodeURI(randomThumb)}')`;
        }

        introFrame.onclick = () => {
            window.location.href = 'Materials/story.html';
        };

        const mainTitle = document.querySelector('h1');
        if (mainTitle) {
            mainTitle.style.cursor = "pointer";
            mainTitle.title = "クリックして詳細を表示";
            mainTitle.onclick = () => {
                introFrame.classList.toggle('show');
            };
        }
    }

    // --- Section Generation ---
    const pagesContainer = document.getElementById('pages');
    const categories = (typeof categoryOrder !== 'undefined') ? categoryOrder : Object.keys(fileData);

    categories.forEach(key => {
        const videos = fileData[key];
        if (!videos || videos.length === 0) return;

        const sectionTitle = document.createElement('h2');
        let titleText = sectionNames[key] || key;
        if (debugMode) titleText += ` (${videos.length}本)`;
        sectionTitle.textContent = titleText;
        sectionTitle.style.cssText = `
            width: 100%; text-align: center; margin: 50px 0 20px; 
            font-size: 2.4em; color: #d4a373; text-shadow: 0 0 20px rgba(212,163,115,0.6);
            border-bottom: 3px double #d4a373; padding-bottom: 15px;
        `;
        pagesContainer.appendChild(sectionTitle);

        const hr = document.createElement('hr');
        hr.style.cssText = 'border: none; border-top: 2px solid #5a4838; margin: 30px 0;';
        pagesContainer.appendChild(hr);

        const grid = document.createElement('div');
        grid.className = 'page-grid';

        videos.forEach(file => {
            allVideos.push({ file, group: key });
            const div = document.createElement('div');
            div.className = 'page';
            const parts = file.split('/');
            // Check if file is image itself or video
            const ext = file.split('.').pop().toLowerCase();
            const isImage = ['jpg', 'jpeg', 'png'].includes(ext);

            // FilenameBase:
            const baseName = (parts[1] || parts[0]).replace(/\.[^/.]+$/, "");
            const thumbPath = `Videos/${parts[0]}/Thumbnails/${baseName}.jpg`;

            const text = parseMessage(messageData[file] || getRandomSecret());
            let debugHTML = debugMode ? `<div style="font-size: 0.7em; color: #76c944; margin-bottom: 5px;">${file}</div>` : "";
            div.innerHTML = `
                <img src="${thumbPath}" onerror="this.src='materials/logo.svg'" style="background:#000">
                <p>${debugHTML}${text}</p>
            `;
            div.onclick = () => {
                book.classList.add('open');
                openBook(file);
            };
            grid.appendChild(div);
        });
        pagesContainer.appendChild(grid);
    });

    if (debugMode) {
        const mainTitle = document.querySelector('h1');
        if (mainTitle) {
            const countDiv = document.createElement('div');
            countDiv.style.cssText = "font-size: 0.8em; color: #76c944; text-align: center; margin: 10px 0; font-weight: bold;";
            countDiv.textContent = `総動画数：${allVideos.length}本`;
            mainTitle.after(countDiv);
        }
    }

    // --- Tag Search Logic ---
    const tagInput = document.getElementById('tag-search');
    const tagList = document.getElementById('tag-list');

    if (tagInput && tagList) {
        // Collect unique tags
        const allTags = new Set();
        Object.values(tagData).forEach(tStr => {
            if (tStr) {
                tStr.split(',').forEach(tag => allTags.add(tag.trim()));
            }
        });

        // Initialize Datalist
        allTags.forEach(tag => {
            if (tag) {
                const opt = document.createElement('option');
                opt.value = tag;
                tagList.appendChild(opt);
            }
        });

        // Filter Function
        const performSearch = () => {
            const keyword = tagInput.value.toLowerCase().trim();
            const pages = document.querySelectorAll('.page');

            pages.forEach((page, index) => {
                // Map index to allVideos (assuming order is preserved in generation)
                if (index >= allVideos.length) return;

                const videoInfo = allVideos[index];
                const videoTags = (tagData[videoInfo.file] || "").toLowerCase();

                if (keyword === "" || videoTags.includes(keyword)) {
                    page.style.display = 'block';
                } else {
                    page.style.display = 'none';
                }
            });
        };

        tagInput.addEventListener('input', performSearch);
    }

    // --- Control Handlers ---
    updateToggleUI();

    document.getElementById('toggle-seq').onclick = () => {
        settings.isSequential = !settings.isSequential;
        video.loop = !settings.isSequential;
        saveSettings();
        updateToggleUI();
    };

    document.getElementById('toggle-random').onclick = () => {
        settings.isRandom = !settings.isRandom;
        saveSettings();
        updateToggleUI();
    };

    document.getElementById('toggle-finish-stop').onclick = () => {
        settings.isFinishStop = !settings.isFinishStop;
        saveSettings();
        updateToggleUI();
    };

    document.getElementById('finish-btn').onclick = triggerFinish;

    document.getElementById('next-page').onclick = () => {
        currentIndex = getNextIndex();
        openBook(allVideos[currentIndex].file);
    };

    document.getElementById('prev-page').onclick = () => {
        currentIndex = settings.isRandom ? Math.floor(Math.random() * allVideos.length) : (currentIndex - 1 + allVideos.length) % allVideos.length;
        openBook(allVideos[currentIndex].file);
    };

    document.getElementById('close-book').onclick = closeBook;

    video.addEventListener('ended', () => {
        if (settings.isSequential) {
            currentIndex = getNextIndex();
            openBook(allVideos[currentIndex].file);
        }
    });

    // --- Keyboard Operations ---
    window.addEventListener('keydown', (e) => {
        if (!book.classList.contains('open')) return;

        switch (e.key) {
            case ' ': // Space: Play/Pause
                e.preventDefault();
                if (video.style.display !== 'none') {
                    if (video.paused) video.play();
                    else video.pause();
                }
                break;
            case 'ArrowRight': // Right: Next
                document.getElementById('next-page').click();
                break;
            case 'ArrowLeft': // Left: Prev
                document.getElementById('prev-page').click();
                break;
            case 'Escape': // Esc: Close
                closeBook();
                break;
            case 'f': // F: Finish
            case 'F':
                triggerFinish();
                break;
        }
    });

    // --- Effect Functions ---
    const playPyuSound = () => {
        const AudioContext = window.AudioContext || window.webkitAudioContext;
        if (!AudioContext) return;
        const ctx = new AudioContext();
        const osc = ctx.createOscillator();
        const gain = ctx.createGain();
        osc.connect(gain);
        gain.connect(ctx.destination);
        const now = ctx.currentTime;
        osc.type = 'sine';
        osc.frequency.setValueAtTime(1000, now);
        osc.frequency.exponentialRampToValueAtTime(100, now + 0.1);
        gain.gain.setValueAtTime(0, now);
        gain.gain.linearRampToValueAtTime(0.2, now + 0.05);
        gain.gain.exponentialRampToValueAtTime(0.01, now + 0.3);
        osc.start(now);
        osc.stop(now + 0.3);
    };

    const createWaterSprayEffect = () => {
        const container = document.querySelector('.left-page');
        if (!container) return;
        const particleCount = 8;
        for (let i = 0; i < particleCount; i++) {
            const drop = document.createElement('div');
            drop.className = 'water-particle';
            const tx = (Math.random() - 0.5) * 600;
            const scale = 0.4 + Math.random() * 2.0;
            drop.style.setProperty('--tx', `${tx}px`);
            drop.style.setProperty('--s', scale);
            const duration = 0.8 + Math.random() * 0.8;
            const delay = Math.random() * 0.4;
            drop.style.animation = `water-spray ${duration}s ease-out ${delay}s forwards`;
            container.appendChild(drop);
            setTimeout(() => { drop.remove(); }, (duration + delay) * 1000);
        }
    };
});
