/**
 * TNC FlipBook — WordPress Frontend Helper
 *
 * Lightweight script for the parent page. Handles:
 *   - Popup mode for link / image-link blocks (opens flipbook in an animated lightbox)
 *   - New-tab mode for link blocks
 *
 * The actual flipbook loads inside an <iframe> served by ?tncfb3d_viewer=ID,
 * so this script does NOT import Three.js, PDF.js, or the flipbook module.
 */
(function () {
    'use strict';

    // Links with data-tncfb-id (shortcode/block links)
    document.querySelectorAll('[data-tncfb-id][data-tncfb-mode]').forEach(function (el) {
        var mode = el.dataset.tncfbMode;
        var id   = el.dataset.tncfbId;

        if ('popup' === mode) {
            el.addEventListener('click', function (e) {
                e.preventDefault();
                openPopup(id, el);
            });
        } else if ('new_tab' === mode) {
            el.addEventListener('click', function (e) {
                e.preventDefault();
                var url = getViewerUrl(id);
                window.open(url, '_blank', 'noopener');
            });
        }
        // same_tab: default href behaviour
    });


    // ── Popup overlay ──────────────────────────────────────────────────────────

    var activeOverlay = null;

    function _decorateViewerUrl(url, triggerEl) {
        if (triggerEl.dataset.tncfbLockTheme) {
            url += (url.indexOf('?') > -1 ? '&' : '?') + 'locktheme=1';
        }
        // Popup theme biases the viewer's polarity to match the popup
        // surround. Pass both light and dark so the viewer can also handle
        // the symmetric mismatch (dark popup + user-toggled light page).
        // Block markup omits the data attribute for the default ('dark'),
        // so fall back to 'dark' when missing.
        var popupTheme = triggerEl.dataset.tncfbPopupTheme === 'light' ? 'light' : 'dark';
        url += (url.indexOf('?') > -1 ? '&' : '?') + 'popuptheme=' + popupTheme;
        return url;
    }

    function openPopupWithUrl(viewerUrl, triggerEl) {
        _createPopup(_decorateViewerUrl(viewerUrl, triggerEl), triggerEl);
    }

    function openPopup(flipbookId, triggerEl) {
        var iframeSrc = triggerEl.dataset.tncfbViewerUrl || getViewerUrl(flipbookId);
        _createPopup(_decorateViewerUrl(iframeSrc, triggerEl), triggerEl);
    }

    function _createPopup(iframeSrc, triggerEl) {
        // Prevent stacking multiple popups
        if (activeOverlay) return;

        var popupWidth  = triggerEl.dataset.tncfbPopupWidth  || '90vw';
        var popupHeight = triggerEl.dataset.tncfbPopupHeight || '90vh';
        var popupTheme  = triggerEl.dataset.tncfbPopupTheme  || 'dark';

        var overlay = document.createElement('div');
        overlay.className = 'tncfb-popup-overlay' + (popupTheme === 'light' ? ' tncfb-popup-light' : '');
        overlay.setAttribute('role', 'dialog');
        overlay.setAttribute('aria-modal', 'true');
        overlay.setAttribute('aria-label', 'FlipBook viewer');

        var inner = document.createElement('div');
        inner.className = 'tncfb-popup-inner';
        inner.style.width  = popupWidth;
        inner.style.height = popupHeight;

        var closeBtn = document.createElement('button');
        closeBtn.type = 'button';
        closeBtn.className = 'tncfb-popup-close';
        closeBtn.setAttribute('aria-label', 'Close flipbook');
        closeBtn.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" width="22" height="22"><path d="M18 6L6 18M6 6l12 12"/></svg>';
        closeBtn.addEventListener('click', closeOverlay);

        var iframe = document.createElement('iframe');
        iframe.src = iframeSrc;
        iframe.className = 'tncfb-popup-iframe';
        iframe.setAttribute('allowfullscreen', '');
        iframe.setAttribute('title', 'FlipBook');

        inner.appendChild(iframe);
        overlay.appendChild(closeBtn);
        overlay.appendChild(inner);
        document.body.appendChild(overlay);
        activeOverlay = overlay;

        // Lock scroll
        document.body.classList.add('tncfb-scroll-locked');

        // Trigger entrance animation on next frame
        requestAnimationFrame(function () {
            overlay.classList.add('tncfb-popup-active');
        });

        // Backdrop click to close
        overlay.addEventListener('click', function (e) {
            if (e.target === overlay) closeOverlay();
        });

        // Escape key
        document.addEventListener('keydown', onKeyDown);

        // Focus trap: move focus into the close button
        closeBtn.focus();

        function onKeyDown(e) {
            if ('Escape' === e.key || 27 === e.keyCode) closeOverlay();
        }

        function closeOverlay() {
            if (!activeOverlay) return;
            document.removeEventListener('keydown', onKeyDown);

            // Animate out
            overlay.classList.remove('tncfb-popup-active');
            overlay.classList.add('tncfb-popup-closing');

            // Remove after transition completes
            overlay.addEventListener('transitionend', function handler() {
                overlay.removeEventListener('transitionend', handler);
                if (overlay.parentNode) overlay.parentNode.removeChild(overlay);
                document.body.classList.remove('tncfb-scroll-locked');
                activeOverlay = null;
                if (triggerEl && triggerEl.focus) triggerEl.focus();
            });

            // Fallback in case transitionend doesn't fire
            setTimeout(function () {
                if (overlay.parentNode) overlay.parentNode.removeChild(overlay);
                document.body.classList.remove('tncfb-scroll-locked');
                activeOverlay = null;
            }, 500);
        }
    }

    // ── Viewer URL helper ─────────────────────────────────────────────────────

    function getViewerUrl(flipbookId) {
        // Look for a pre-built viewer URL from inline data
        var el = document.querySelector('[data-tncfb-id="' + flipbookId + '"][data-tncfb-viewer-url]');
        if (el && el.dataset.tncfbViewerUrl) {
            return el.dataset.tncfbViewerUrl;
        }
        // Fallback: REST preview endpoint
        if (window.tncfb3dData && window.tncfb3dData.viewerBaseUrl) {
            return window.tncfb3dData.viewerBaseUrl + '&tncfb3d_viewer=' + flipbookId;
        }
        return window.location.origin + '/?tncfb3d_viewer=' + flipbookId;
    }
})();
