let currentImageDialog = null;

document.addEventListener('DOMContentLoaded', async () => {
    document.querySelectorAll("[data-thumbnail]").forEach(e => {
        e.addEventListener("click", function (e) {
            e.preventDefault();
            img = this.getElementsByTagName("img")[0];
            imageDialog(img.dataset.src, img.dataset.width, img.dataset.height);
        });
    });

    // ブラウザの戻るボタンで画像を閉じる
    window.addEventListener('popstate', () => {
        currentImageDialog.close();
    });
});

function imageDialog(imageUrl, width, height) {
    const body = document.body;

    // overlay
    const overlay = document.createElement('div');
    overlay.className = 'p-image-dialog-overlay';

    // dialog
    const dialog = document.createElement('div');
    dialog.className = 'p-image-dialog-image-box';

    // image
    const img = document.createElement('img');
    img.src = imageUrl;
    img.id = 'popupcontents';
    img.width = width;
    img.height = height;

    dialog.appendChild(img);
    overlay.appendChild(dialog);
    body.appendChild(overlay);

    // layout control
    const winW = window.innerWidth;
    const winH = window.innerHeight;

    dialog.style.display = 'flex';
    dialog.style.flexDirection = 'column';

    if (width < winW) {
        dialog.style.alignItems = 'center';
    }
    if (height < winH) {
        dialog.style.justifyContent = 'center';
    }

    // disable scroll
    body.style.overflow = 'hidden';

    // ヒストリにエントリを追加
    history.pushState({ imageDialog: true }, '', null);

    let isClosed = false;

    function onClose(useHistoryBack = true) {
        if (isClosed) return;
        isClosed = true;

        body.style.overflow = 'auto';
        overlay.remove();
        currentImageDialog = null;

        // クリックで閉じる場合は、追加したヒストリエントリを削除
        if (useHistoryBack && history.state && history.state.imageDialog) {
            history.back();
        }
    }

    dialog.tabIndex = -1;
    dialog.focus();

    // グローバル変数に保存（popstateイベントから参照するため）
    currentImageDialog = {
        close: () => onClose(false)
    };

    return new Promise((resolve) => {
        const handler = () => {
            onClose(true);
            resolve('OK');
        };

        img.addEventListener('click', handler);
        dialog.addEventListener('click', handler);
        overlay.addEventListener('click', handler);
    });
}
