/**
 * EAC Repeater & Gallery Blocks - Accessibility & obfuscated emails & keyboard support & global link for grid mode
 * @since 2.4.7 (refactor)
 */

document.addEventListener('DOMContentLoaded', () => {
    const SPACE_KEYS = new Set(['Space', ' ', 'Spacebar']);
    const focusableSelector = 'button, a, [tabindex]:not([tabindex="-1"])';

    // Helpers
    const qs = (sel, ctx = document) => (ctx || document).querySelector(sel);
    const qsAll = (sel, ctx = document) => Array.from((ctx || document).querySelectorAll(sel));
    const isSpaceKey = (evt) => SPACE_KEYS.has(evt.code || evt.key || '');

    // Convert space keydown -> click for keyboard activation
    const triggerKeyDownToClickEvent = (evt) => {
        if (!isSpaceKey(evt)) return;
        evt.preventDefault();
        const el = document.activeElement;
        if (!el) return;
        el.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
    };

    // 1) Grid-level keyboard handling (Home / End / Escape / Tab passthrough)
    const gallerySelector = '.eac-gallery__block-grid';
    const galleryGrid = qs(gallerySelector);

    if (galleryGrid) {
        galleryGrid.addEventListener('keydown', (evt) => {
            const id = evt.code || evt.key || '';
            if (id === 'Tab') return;
            const articles = qsAll('.eac-gallery__block-grid .acf-gallery__wrapper', galleryGrid);
            if (!articles.length) return;

            if (id === 'Home') {
                evt.preventDefault();
                // premier article -> premier élément focusable visible
                for (const art of articles) {
                    const targets = Array.from(art.querySelectorAll(focusableSelector))
                        .filter(el => !el.hasAttribute('disabled') && el.offsetParent !== null);
                    if (targets.length) { targets[0].focus(); break; }
                }
            } else if (id === 'End') {
                evt.preventDefault();
                // dernier article -> dernier élément focusable visible
                for (let i = articles.length - 1; i >= 0; i--) {
                    const art = articles[i];
                    const targets = Array.from(art.querySelectorAll(focusableSelector))
                        .filter(el => !el.hasAttribute('disabled') && el.offsetParent !== null);
                    if (targets.length) { targets[targets.length - 1].focus(); break; }
                }
            } else if (id === 'Escape') {
                const skip = qs('.eac-gallery__block-grid .eac-skip-grid');
                if (skip) skip.focus();
            }
        });
    }

    // 2) Global link behavior for cards (repeater + gallery)
    const cards = [
        ...qsAll('.eac-repeater__block-grid .acf-repeater__wrapper'),
        ...qsAll('.eac-gallery__block-grid .acf-gallery__wrapper')
    ];

    cards.forEach((card) => {
        if (!card) return;
        const cardLink = card.querySelector('a.card-link');
        // Prevent internal links from bubbling to card click
        const clickableSelector = 'a:not([data-fancybox]):not(.button-cart):not(.avatar-link)';
        qsAll(clickableSelector, card).forEach((el) => {
            el.addEventListener('click', (evt) => evt.stopPropagation());
            // Allow keyboard activation (space) on those inner links
            el.addEventListener('keydown', (evt) => {
                if (evt.target === el) triggerKeyDownToClickEvent(evt);
            });
        });

        if (cardLink) {
            card.style.cursor = 'pointer';
            card.addEventListener('click', (evt) => {
                // If user selected text, don't follow link
                const noTextSelected = !window.getSelection().toString();
                if (noTextSelected) {
                    cardLink.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
                }
            });
            // Make card activable by Space when focused
            card.addEventListener('keydown', (evt) => {
                if (document.activeElement === card) triggerKeyDownToClickEvent(evt);
            });
        }
    });

    // 3) Accessible links inside content: space => click
    const accessibleLinks = [
        ...qsAll('.eac-repeater__block-grid .acf-repeater__wrapper-content a.eac-accessible-link'),
        ...qsAll('.eac-gallery__block-grid .acf-gallery__wrapper-content a.eac-accessible-link')
    ];
    accessibleLinks.forEach((link) => {
        link.addEventListener('keydown', (evt) => {
            if (evt.target === link) triggerKeyDownToClickEvent(evt);
        });
    });

    // 4) Obfuscated mailto links: data-link => href
    qsAll('.eac-repeater__block-grid .acf-repeater__wrapper-content a.eac-accessible-link.obfuscated-link')
        .forEach((item) => {
            const dataHref = item.getAttribute('data-link');
            if (!dataHref) return;
            const dataMask = '#actus.'; // replace mask with '@'
            const mailTo = 'mailto:';
            const newHref = dataHref.replace(dataMask, '@');
            item.setAttribute('href', mailTo + newHref);
            item.removeAttribute('data-link');
        });
});
