// --- 状態管理用の変数定義 ---
let currentBook = "";
let currentPage = 1; 
let totalPages = 1;
let playlist = {};
let currentMusicUrl = "";
let zoomPercent = 100; // 元アプリの50%〜300%のズーム管理を移植

let touchStartX = 0;
let touchStartY = 0;
let isPinched = false;
let initialPinchDist = 0;
let initialZoomPercent = 100;

const bookSelect = document.getElementById("book-select");
const urlInput = document.getElementById("url-input");
const btnUrlOpen = document.getElementById("btn-url-open");
const btnNext = document.getElementById("btn-next"); 
const btnPrev = document.getElementById("btn-prev"); 
const pageInfo = document.getElementById("page-info");
const pageImage = document.getElementById("page-image");
const pageSlider = document.getElementById("page-slider");
const totalPageLbl = document.getElementById("total-page-lbl");
const currentPageLbl = document.getElementById("current-page-lbl");
const bgmPlayer = document.getElementById("bgm-player");
const volSlider = document.getElementById("vol-slider");
const musicInfo = document.getElementById("music-info");
const btnPlayPause = document.getElementById("btn-play-pause");
const viewerContainer = document.getElementById("viewer-container");
const btnFullscreen = document.getElementById("btn-fullscreen");

// --- イベントリスナーの設定 ---
if (bookSelect) {
    bookSelect.addEventListener("change", function() {
        if (this.value) loadBook(this.value);
    });
}

if (btnUrlOpen) {
    btnUrlOpen.addEventListener("click", () => {
        const url = urlInput.value.trim();
        if (url) loadBook(url);
    });
}
if (urlInput) {
    urlInput.addEventListener("keydown", (e) => {
        if (e.key === "Enter") {
            const url = urlInput.value.trim();
            if (url) loadBook(url);
        }
    });
}

if (btnNext) btnNext.addEventListener("click", nextPages);
if (btnPrev) btnPrev.addEventListener("click", prevPages);
if (volSlider) volSlider.addEventListener("input", (e) => {
    if (bgmPlayer) bgmPlayer.volume = e.target.value / 100;
});
if (btnPlayPause) btnPlayPause.addEventListener("click", togglePlayPause);

// 右開きシークバー完全同期
if (pageSlider) {
    pageSlider.addEventListener("input", (e) => {
        // 【修正】つまみを左に動かす（valueが増える）ほど、ページが進むようにそのまま代入
        currentPage = parseInt(e.target.value);
        updateUIOnly();
    });
    pageSlider.addEventListener("change", (e) => {
        currentPage = parseInt(e.target.value);
        changePage(currentPage);
    });
}

// キーボード操作対応（右開きの直感に完全統一）
window.addEventListener("keydown", (e) => {
    if (!currentBook) return;
    
    if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
        if (document.activeElement === bookSelect || document.activeElement === urlInput) {
            document.activeElement.blur(); 
        }
    }

    if (e.key === "ArrowLeft") {
        e.preventDefault(); 
        nextPages(); // 左矢印 ＝ ページを進める（左へめくる）
    }
    if (e.key === "ArrowRight") {
        e.preventDefault(); 
        prevPages(); // 右矢印 ＝ ページを戻す（右へ戻る）
    }
    if (e.key === " ") { 
        if (document.activeElement === urlInput) return;
        e.preventDefault(); 
        togglePlayPause(); 
    }
});

// 全画面制御
if (btnFullscreen) {
    btnFullscreen.addEventListener("click", () => {
        if (document.fullscreenElement) {
            document.exitFullscreen().catch(err => console.log(err));
        } else {
            document.documentElement.requestFullscreen().catch(err => {
                alert(`全画面表示に失敗しました: ${err.message}`);
            });
        }
    });
}
document.addEventListener("fullscreenchange", () => {
    if (!btnFullscreen) return;
    if (document.fullscreenElement) {
        btnFullscreen.innerText = "✖ 全画面を解除";
    } else {
        btnFullscreen.innerText = "全画面表示";
    }
});

// --- タッチジェスチャー & マウスホイールズーム (元アプリの感度70を再現) ---
if (viewerContainer) {
    // トラックパッドやマウスホイールでのズーム対応を移植
    viewerContainer.addEventListener("wheel", (e) => {
        if (!currentBook || !pageImage) return;
        e.preventDefault();
        if (e.deltaY < 0) {
            zoomPercent = Math.min(300, zoomPercent + 10);
        } else {
            zoomPercent = Math.max(50, zoomPercent - 10);
        }
        pageImage.style.transform = `scale(${zoomPercent / 100})`;
    }, { passive: false });

    viewerContainer.addEventListener("touchstart", (e) => {
        if (e.touches.length === 1) {
            touchStartX = e.touches[0].clientX;
            touchStartY = e.touches[0].clientY;
            isPinched = false;
        } else if (e.touches.length === 2) {
            isPinched = true;
            initialPinchDist = Math.hypot(
                e.touches[0].clientX - e.touches[1].clientX, 
                e.touches[0].clientY - e.touches[1].clientY
            );
            initialZoomPercent = zoomPercent;
        }
    }, { passive: true });

    viewerContainer.addEventListener("touchmove", (e) => {
        if (isPinched && e.touches.length === 2 && pageImage) {
            const currentDist = Math.hypot(
                e.touches[0].clientX - e.touches[1].clientX, 
                e.touches[0].clientY - e.touches[1].clientY
            );
            const factor = currentDist / initialPinchDist;
            zoomPercent = Math.max(50, Math.min(300, initialZoomPercent * factor));
            pageImage.style.transform = `scale(${zoomPercent / 100})`; 
        }
    }, { passive: true });

    viewerContainer.addEventListener("touchend", (e) => {
        if (isPinched) {
            if (e.touches.length === 0) {
                isPinched = false;
                changePage(currentPage);
            }
            return;
        }
        
        if (e.changedTouches.length === 1) {
            const deltaX = e.changedTouches[0].clientX - touchStartX;
            const deltaY = e.changedTouches[0].clientY - touchStartY;
            
            // 【仕様統一】誤作動防止の判定距離を「70ピクセル」に完全同期
            if (Math.abs(deltaX) > 70 && Math.abs(deltaX) > Math.abs(deltaY)) {
                if (deltaX > 0) {
                    // 【修正後】右へスワイプ（指を右に動かした） ＝ ◀ 進む
                    nextPages(); 
                } else {
                    // 【修正後】左へスワイプ（指を左に動かした） ＝ 戻る ▶
                    prevPages(); 
                }
            }
        }
    }, { passive: true });
}

// --- 読書ロジック・API通信処理 ---

function nextPages() { if (currentPage < totalPages) { changePage(currentPage + 1); } }
function prevPages() { if (currentPage > 1) { changePage(currentPage - 1); } }

async function loadBook(bookNameOrUrl) {
    currentBook = bookNameOrUrl;
    zoomPercent = 100; // リセット
    
    const bookRes = await fetch(`/api/book/${encodeURIComponent(bookNameOrUrl)}`);
    const bookData = await bookRes.json();
    
    if (bookData.error) {
        alert(bookData.error);
        return;
    }

    totalPages = bookData.total_pages;
    playlist = bookData.playlist;

    if (pageSlider) {
        pageSlider.min = 1;
        pageSlider.max = totalPages;
        pageSlider.disabled = false;
    }
    if (totalPageLbl) totalPageLbl.innerText = totalPages;

    const bookmarkRes = await fetch(`/bookmark/${encodeURIComponent(bookNameOrUrl)}`);
    const bookmarkData = await bookmarkRes.json();
    const savedPage = bookmarkData.page_number;

    if (savedPage > 1) {
        const choice = confirm(`前回の続き (${savedPage} ページ目) から読みますか？\n\n【OK】: 続きから再開\n【キャンセル】: はじめから読む`);
        if (choice) {
            currentPage = savedPage;
        } else {
            currentPage = 1;
        }
    } else {
        currentPage = 1;
    }

    document.body.focus();
    if (document.activeElement) document.activeElement.blur();

    changePage(currentPage);
}

// 【画像読み込みと音楽再生の最適化関数】
function changePage(page) {
    if (page < 1 || page > totalPages) return;
    currentPage = page;
    
    manageMusic(page);
    updateUIOnly();
    saveBookmark(page);

    if (pageImage) {
        // バックエンドへのリクエスト時にベースとなるズーム倍率を2.2として調整
        const calculatedZoom = (zoomPercent / 100) * 2.2;
        pageImage.src = `/page/${encodeURIComponent(currentBook)}/${page}?zoom=${calculatedZoom}`;
        pageImage.style.display = "block";
        pageImage.style.transform = "scale(1)"; 
    }
}

function updateUIOnly() {
    if (pageInfo) pageInfo.innerText = `ページ: ${currentPage} / ${totalPages}`;
    if (currentPageLbl) currentPageLbl.innerText = `ページ: ${currentPage}`;
    
    if (pageSlider) {
        // 【修正】現在のページ番号（currentPage）を、そのままつまみの位置（value）に適用
        pageSlider.value = currentPage; 
    }

    if (btnNext) btnNext.disabled = (currentPage >= totalPages);
    if (btnPrev) btnPrev.disabled = (currentPage <= 1);
}

// BGM直接ストリーミング再生（遡り二分探索の完全再現）
function manageMusic(page) {
    if (!playlist) return;
    
    const targetInternalPage = page - 1;
    const sortedPages = Object.keys(playlist).map(Number).sort((a, b) => a - b);
    let targetMusicUrl = null;

    for (let i = 0; i < sortedPages.length; i++) {
        if (sortedPages[i] <= targetInternalPage) {
            targetMusicUrl = playlist[sortedPages[i]];
        } else {
            break;
        }
    }

    if (targetMusicUrl) {
        if (targetMusicUrl !== currentMusicUrl) {
            currentMusicUrl = targetMusicUrl;
            
            if (musicInfo) {
                const musicName = decodeURIComponent(targetMusicUrl.split("/").pop());
                musicInfo.innerText = `再生中の曲: ${musicName}`;
            }
            
            if (bgmPlayer) {
                let currentVol = bgmPlayer.volume;
                const fadeInterval = setInterval(() => {
                    if (currentVol > 0.05) {
                        currentVol -= 0.1;
                        bgmPlayer.volume = Math.max(0, currentVol);
                    } else {
                        clearInterval(fadeInterval);
                        
                        bgmPlayer.src = targetMusicUrl;
                        if (volSlider) bgmPlayer.volume = volSlider.value / 100;
                        
                        bgmPlayer.play().then(() => {
                            if (btnPlayPause) btnPlayPause.innerText = "一時停止";
                        }).catch(err => {
                            console.log("自動再生ロック作動。画面クリックで流れます:", err);
                            if (btnPlayPause) btnPlayPause.innerText = "再生";
                        });
                    }
                }, 50); 
            }
            
            if (btnPlayPause) btnPlayPause.disabled = false;
        }
    } else {
        if (bgmPlayer && !bgmPlayer.paused) {
            let currentVol = bgmPlayer.volume;
            const fadeInterval = setInterval(() => {
                if (currentVol > 0.05) {
                    currentVol -= 0.1;
                    bgmPlayer.volume = Math.max(0, currentVol);
                } else {
                    clearInterval(fadeInterval);
                    bgmPlayer.pause();
                    currentMusicUrl = "";
                    if (musicInfo) musicInfo.innerText = `再生中の曲: なし`;
                    if (btnPlayPause) btnPlayPause.disabled = true;
                }
            }, 50);
        } else {
            currentMusicUrl = "";
            if (musicInfo) musicInfo.innerText = `再生中の曲: なし`;
            if (btnPlayPause) btnPlayPause.disabled = true;
        }
    }
}

// 栞の自動保存
async function saveBookmark(page) {
    try {
        await fetch(`/bookmark/${encodeURIComponent(currentBook)}`, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ page_number: page })
        });
    } catch (err) {
        console.error("栞の保存失敗:", err);
    }
}

// 一時停止・再生の切り替え
function togglePlayPause() {
    if (!currentMusicUrl || !bgmPlayer) return;
    
    if (bgmPlayer.paused) {
        bgmPlayer.play().catch(err => console.log(err));
        if (btnPlayPause) btnPlayPause.innerText = "一時停止";
    } else {
        bgmPlayer.pause();
        if (btnPlayPause) btnPlayPause.innerText = "再生";
    }
}
