/*
 * 图片预览层：用于聊天消息图片的点击查看。
 * 作者: @ccfork
 */
(function() {
    let viewer = null;
    let viewerImage = null;
    let viewerClose = null;
    let lastFocus = null;

    function ensureViewer() {
        if (viewer) return;
        viewer = document.createElement('div');
        viewer.className = 'image-viewer';
        viewer.hidden = true;
        viewer.innerHTML = `
            <button class="image-viewer-close" type="button" aria-label="关闭预览">×</button>
            <img class="image-viewer-img" alt="图片预览">
        `;
        document.body.appendChild(viewer);
        viewerImage = viewer.querySelector('.image-viewer-img');
        viewerClose = viewer.querySelector('.image-viewer-close');
        viewer.addEventListener('click', (event) => {
            if (event.target === viewer || event.target === viewerClose) closeViewer();
        });
        viewerClose.addEventListener('click', closeViewer);
        document.addEventListener('keydown', (event) => {
            if (event.key === 'Escape') closeViewer();
        });
    }

    function openViewer(src, alt = '图片预览') {
        if (!src) return;
        ensureViewer();
        lastFocus = document.activeElement;
        viewerImage.src = src;
        viewerImage.alt = alt;
        viewer.hidden = false;
        document.body.classList.add('image-viewer-open');
        viewerClose.focus();
    }

    function closeViewer() {
        if (!viewer) return;
        viewer.hidden = true;
        viewerImage.src = '';
        document.body.classList.remove('image-viewer-open');
        if (lastFocus && typeof lastFocus.focus === 'function') lastFocus.focus();
    }

    function bind() {
        document.addEventListener('click', (event) => {
            const img = event.target.closest?.('.message-image');
            if (!img) return;
            event.preventDefault();
            openViewer(img.currentSrc || img.src, img.alt || '图片预览');
        });
    }

    document.addEventListener('DOMContentLoaded', bind);
})();
