/**
 * 圖片燈箱：技師頭像（店家頁／討論區）、店家照片。
 * 觸控裝置點擊開啟；桌機技師頭像仍以 hover 預覽為主，Enter／Space 或點擊照片亦可開啟。
 */
(function () {
    'use strict';

    var COARSE_POINTER = window.matchMedia('(hover: none), (pointer: coarse)').matches;

    function createLightbox() {
        var root = document.createElement('div');
        root.className = 'fate-image-lightbox';
        root.hidden = true;
        root.innerHTML =
            '<div class="fate-image-lightbox__backdrop" data-close="1" aria-hidden="true"></div>' +
            '<div class="fate-image-lightbox__dialog" role="dialog" aria-modal="true" aria-label="圖片大圖">' +
            '<button type="button" class="fate-image-lightbox__close" data-close="1" aria-label="關閉">×</button>' +
            '<figure class="fate-image-lightbox__figure">' +
            '<img class="fate-image-lightbox__img" alt="">' +
            '<figcaption class="fate-image-lightbox__caption"></figcaption>' +
            '</figure>' +
            '</div>';
        document.body.appendChild(root);

        var dialog = root.querySelector('.fate-image-lightbox__dialog');
        var img = root.querySelector('.fate-image-lightbox__img');
        var caption = root.querySelector('.fate-image-lightbox__caption');
        var closeBtn = root.querySelector('.fate-image-lightbox__close');
        var lastFocus = null;

        function close() {
            root.hidden = true;
            document.body.classList.remove('fate-image-lightbox-open');
            if (lastFocus && typeof lastFocus.focus === 'function') {
                lastFocus.focus();
            }
            lastFocus = null;
        }

        function open(src, alt, label, dialogLabel) {
            if (!src) {
                return;
            }
            lastFocus = document.activeElement;
            img.src = src;
            img.alt = alt || label || '圖片';
            caption.textContent = label || alt || '';
            caption.hidden = caption.textContent === '';
            if (dialogLabel) {
                dialog.setAttribute('aria-label', dialogLabel);
            } else {
                dialog.setAttribute('aria-label', '圖片大圖');
            }
            root.hidden = false;
            document.body.classList.add('fate-image-lightbox-open');
            closeBtn.focus();
        }

        root.addEventListener('click', function (e) {
            if (e.target.closest('[data-close="1"]')) {
                close();
            }
        });

        document.addEventListener('keydown', function (e) {
            if (!root.hidden && e.key === 'Escape') {
                e.preventDefault();
                close();
            }
        });

        return { open: open, close: close };
    }

    function bindOpenOnActivate(trigger, lightbox, getPayload, coarseOnly) {
        function activate(e) {
            if (e) {
                e.preventDefault();
                e.stopPropagation();
            }
            var payload = getPayload();
            if (!payload || !payload.src) {
                return;
            }
            lightbox.open(payload.src, payload.alt, payload.label, payload.dialogLabel);
        }

        if (COARSE_POINTER || !coarseOnly) {
            trigger.addEventListener('click', activate);
        }

        trigger.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' || e.key === ' ') {
                activate(e);
            }
        });
    }

    function setupAvatarTrigger(avatarEl, lightbox, name, coarseOnly) {
        var thumb = avatarEl.querySelector('img');
        if (!thumb || !thumb.getAttribute('src')) {
            return;
        }

        var displayName = name || thumb.getAttribute('alt') || '技師';
        avatarEl.classList.add('fate-image-lightbox-avatar');
        avatarEl.setAttribute('tabindex', '0');
        avatarEl.setAttribute('role', 'button');
        avatarEl.setAttribute(
            'aria-label',
            COARSE_POINTER ? '點擊查看「' + displayName + '」大圖' : '查看「' + displayName + '」大圖（Enter 鍵）'
        );

        bindOpenOnActivate(
            avatarEl,
            lightbox,
            function () {
                return {
                    src: thumb.getAttribute('src'),
                    alt: thumb.getAttribute('alt') || displayName,
                    label: displayName,
                    dialogLabel: '技師頭像大圖',
                };
            },
            coarseOnly
        );
    }

    function bindStoreMasseurAvatars(lightbox) {
        document.querySelectorAll('.masseur-avatar-wrap--has-photo').forEach(function (wrap) {
            var avatar = wrap.querySelector('.masseur-row__avatar');
            if (!avatar) {
                return;
            }
            var thumb = avatar.querySelector('img');
            setupAvatarTrigger(avatar, lightbox, thumb ? thumb.getAttribute('alt') : '技師', true);
        });
    }

    function bindForumMasseurAvatars(lightbox) {
        document.querySelectorAll(
            '.forum-masseur-chip:not(.forum-masseur-chip--add) .forum-masseur-chip__avatar,'
            + '.forum-masseur-card:not(.forum-masseur-card--add) .forum-masseur-card__avatar,'
            + '.forum-masseur-hero__avatar'
        ).forEach(function (avatar) {
            if (!avatar.querySelector('img')) {
                return;
            }
            var chip = avatar.closest('.forum-masseur-chip, .forum-masseur-card');
            var nameNode = chip ? chip.querySelector('.forum-masseur-chip__name, .forum-masseur-card__name') : null;
            if (!nameNode) {
                nameNode = avatar.closest('.forum-masseur-hero') && avatar.closest('.forum-masseur-hero').querySelector('.forum-h1');
            }
            setupAvatarTrigger(avatar, lightbox, nameNode ? nameNode.textContent.trim() : '', true);
        });
    }

    function bindStorePhotos(lightbox) {
        document.querySelectorAll('.store-photo-tile-fate a, .store-photo-cell a').forEach(function (anchor) {
            var thumb = anchor.querySelector('img');
            if (!thumb || !thumb.getAttribute('src')) {
                return;
            }
            anchor.classList.add('fate-image-lightbox-trigger');
            anchor.setAttribute('role', 'button');
            var alt = thumb.getAttribute('alt') || '店家照片';
            anchor.setAttribute('aria-label', COARSE_POINTER ? '點擊查看大圖：' + alt : '查看大圖：' + alt);

            bindOpenOnActivate(
                anchor,
                lightbox,
                function () {
                    return {
                        src: thumb.getAttribute('src'),
                        alt: alt,
                        label: alt,
                        dialogLabel: '店家照片',
                    };
                },
                false
            );
        });
    }

    function init() {
        var hasTargets =
            document.querySelector('.masseur-avatar-wrap--has-photo')
            || document.querySelector('.forum-masseur-chip__avatar img, .forum-masseur-card__avatar img, .forum-masseur-hero__avatar img')
            || document.querySelector('.store-photo-tile-fate a, .store-photo-cell a');
        if (!hasTargets) {
            return;
        }

        var lightbox = createLightbox();
        bindStoreMasseurAvatars(lightbox);
        bindForumMasseurAvatars(lightbox);
        bindStorePhotos(lightbox);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
