/**
 * Filter Tabs – Icon Injector v2
 * Injects recognizable SVG icons into .tab-button elements.
 * Icons are hand-crafted to be clearly representative of each category.
 */
(function () {
    'use strict';

    /* -------------------------------------------------------
       ICON MAP
       Each key is a lowercase substring matched against the
       button text. Values are full SVG inner content.
       viewBox is always "0 0 24 24".
       ------------------------------------------------------- */
    const ICON_MAP = [
        /* LAS VEGAS — 3D Dice */
        {
            keywords: ['las vegas', 'vegas'],
            svg: `<path d="M12 3l9 4.5-9 4.5-9-4.5z"/>
                  <path d="M3 7.5v8.5l9 4.5V12"/>
                  <path d="M21 7.5v8.5l-9 4.5V12"/>
                  <circle cx="12" cy="7.5" r="1" class="icon-fill"/>
                  <circle cx="6.5" cy="11" r="1" class="icon-fill"/>
                  <circle cx="9" cy="16.5" r="1" class="icon-fill"/>
                  <circle cx="17.5" cy="10.5" r="1" class="icon-fill"/>
                  <circle cx="16" cy="13" r="1" class="icon-fill"/>
                  <circle cx="14.5" cy="15.5" r="1" class="icon-fill"/>`
        },

        /* CRUCEROS — Ship / Cruise */
        {
            keywords: ['crucero', 'cruise'],
            svg: `<path d="M2 16.5l2.5-4h15l2.5 4"/>
                  <path d="M5.5 12.5V9.5h13v3"/>
                  <path d="M8 9.5V7h8v2.5"/>
                  <path d="M14.5 7V4.5h3V7"/>
                  <path d="M16 4.5c0-1 .8-1.8 1.5-1.2"/>
                  <circle cx="8.5" cy="11" r=".7" class="icon-fill"/>
                  <circle cx="12" cy="11" r=".7" class="icon-fill"/>
                  <circle cx="15.5" cy="11" r=".7" class="icon-fill"/>
                  <path d="M1 20c2-1.5 4-1.5 6 0s4 1.5 6 0 4-1.5 6 0"/>`
        },

        /* CANCÚN — Palm tree */
        {
            keywords: ['cancún', 'cancun'],
            svg: `<path d="M14 22V10"/>
                  <path d="M14 10c-2-4-7-4-9-2"/>
                  <path d="M14 10c0-4 3-6 7-5"/>
                  <path d="M14 10c-4-2-7 0-8 3"/>
                  <path d="M14 10c3-1 6 1 7 4"/>
                  <path d="M14 10c-3-3-1-7 2-8"/>
                  <path d="M10 22h8"/>`
        },

        /* COSTA RICA — Toucan */
        {
            keywords: ['costa rica'],
            svg: `<circle cx="15" cy="11" r="5"/>
                  <path d="M10 9C7 8 4 10 4 12.5S7 16 10 14"/>
                  <circle cx="13.5" cy="10" r="1" class="icon-fill"/>
                  <path d="M19 8l2-3"/>
                  <path d="M19.5 10l2.5-1"/>
                  <path d="M11 17h8"/>
                  <path d="M13 16v1"/>
                  <path d="M17 16v1"/>`
        },

        /* PERÚ — Machu Picchu / mountain ruins */
        {
            keywords: ['perú', 'peru'],
            svg: `<path d="M1 20L6 10l2 3 4-9 3 7 3-3 3 12"/>
                  <path d="M1 20h22"/>
                  <path d="M8.5 12h2.5"/>
                  <path d="M9.5 10h2"/>
                  <path d="M10.5 8h1.5"/>`
        },

        /* JAPÓN — Torii gate */
        {
            keywords: ['japón', 'japon', 'japan'],
            svg: `<path d="M4 5h16"/>
                  <path d="M3 5c0 0 1.5 1 9 1s9-1 9-1"/>
                  <path d="M6 5v3"/>
                  <path d="M18 5v3"/>
                  <path d="M5 8h14"/>
                  <path d="M7 8v14"/>
                  <path d="M17 8v14"/>`
        },

        /* EUROPA — Classical temple / Parthenon */
        {
            keywords: ['europa', 'europe'],
            svg: `<path d="M4 10l8-6 8 6"/>
                  <path d="M4 10h16"/>
                  <path d="M7 10v8"/>
                  <path d="M11 10v8"/>
                  <path d="M13 10v8"/>
                  <path d="M17 10v8"/>
                  <path d="M4 18h16"/>
                  <path d="M3 21h18"/>`
        },

        /* SKI — Skier */
        {
            keywords: ['ski', 'esquí', 'esqui', 'nieve'],
            svg: `<circle cx="13" cy="4" r="1.5"/>
                  <path d="M13 5.5L10.5 11"/>
                  <path d="M12 7.5L7 9.5 5.5 18"/>
                  <path d="M12 7.5L17.5 6.5 19 17"/>
                  <path d="M10.5 11L8 14.5 6.5 17"/>
                  <path d="M10.5 11L12.5 14.5 14 17"/>
                  <path d="M4 17.5l11 1.5"/>
                  <path d="M10.5 18.5l11 1.5"/>`
        },

        /* TODO / ALL — Grid / list */
        {
            keywords: ['todo', 'all', 'todos'],
            svg: `<rect x="3" y="3" width="7" height="7" rx="1"/>
                  <rect x="14" y="3" width="7" height="7" rx="1"/>
                  <rect x="3" y="14" width="7" height="7" rx="1"/>
                  <rect x="14" y="14" width="7" height="7" rx="1"/>`
        },
    ];

    /* Default icon — compass */
    const DEFAULT_SVG = `<circle cx="12" cy="12" r="9"/>
                         <path d="M16.2 7.8l-2 6.4-6.4 2 2-6.4z"/>`;

    /**
     * Find the best matching icon SVG content for a label.
     */
    function getIconSvg(label) {
        const lower = label.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').trim();
        for (const entry of ICON_MAP) {
            for (const kw of entry.keywords) {
                const kwNorm = kw.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
                if (lower.includes(kwNorm) || kwNorm.includes(lower)) {
                    return entry.svg;
                }
            }
        }
        return DEFAULT_SVG;
    }

    /**
     * Process all .tab-button elements, inject icon + label spans.
     */
    function injectIcons() {
        const buttons = document.querySelectorAll('.filter_tabs .tab-button');
        buttons.forEach(function (btn) {
            // Skip if already processed
            if (btn.querySelector('.tab-icon')) return;

            var label = btn.textContent.trim();
            if (!label) return;

            var svgContent = getIconSvg(label);

            var iconSpan = document.createElement('span');
            iconSpan.className = 'tab-icon';
            iconSpan.innerHTML = '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">' + svgContent + '</svg>';

            var textSpan = document.createElement('span');
            textSpan.className = 'tab-label';
            textSpan.textContent = label;

            btn.textContent = '';
            btn.appendChild(iconSpan);
            btn.appendChild(textSpan);
        });
    }

    /**
     * Check if the filter_tabs container overflows and show/hide arrows.
     */
    function updateArrowVisibility() {
        var container = document.querySelector('.filter_tabs');
        if (!container) return;

        var leftArrow = container.querySelector('.filter-nav-arrow.left');
        var rightArrow = container.querySelector('.filter-nav-arrow.right');
        if (!leftArrow || !rightArrow) return;

        var overflows = container.scrollWidth > container.clientWidth + 2; // 2px tolerance

        if (overflows) {
            // Show/hide based on scroll position
            var atStart = container.scrollLeft <= 5;
            var atEnd = container.scrollLeft + container.clientWidth >= container.scrollWidth - 5;

            leftArrow.classList.toggle('visible', !atStart);
            rightArrow.classList.toggle('visible', !atEnd);
        } else {
            // No overflow — hide both
            leftArrow.classList.remove('visible');
            rightArrow.classList.remove('visible');
        }
    }

    /**
     * Add left/right scroll arrows to the container.
     */
    function addNavArrows() {
        var container = document.querySelector('.filter_tabs');
        if (!container || container.querySelector('.filter-nav-arrow')) return;

        if (getComputedStyle(container).position === 'static') {
            container.style.position = 'relative';
        }

        var leftArrow = document.createElement('button');
        leftArrow.className = 'filter-nav-arrow left';
        leftArrow.setAttribute('aria-label', 'Anterior');
        leftArrow.innerHTML = '<svg viewBox="0 0 24 24"><path d="M15 18l-6-6 6-6"/></svg>';
        leftArrow.addEventListener('click', function () {
            container.scrollBy({ left: -200, behavior: 'smooth' });
        });

        var rightArrow = document.createElement('button');
        rightArrow.className = 'filter-nav-arrow right';
        rightArrow.setAttribute('aria-label', 'Siguiente');
        rightArrow.innerHTML = '<svg viewBox="0 0 24 24"><path d="M9 18l6-6-6-6"/></svg>';
        rightArrow.addEventListener('click', function () {
            container.scrollBy({ left: 200, behavior: 'smooth' });
        });

        container.appendChild(leftArrow);
        container.appendChild(rightArrow);

        // Update visibility on scroll and resize
        container.addEventListener('scroll', updateArrowVisibility, { passive: true });
        window.addEventListener('resize', updateArrowVisibility, { passive: true });

        // Initial check
        updateArrowVisibility();
    }

    /**
     * Initialize.
     */
    function init() {
        injectIcons();
        addNavArrows();
        // Delayed recheck after Alpine might have finished rendering
        setTimeout(updateArrowVisibility, 200);

        // Watch for Alpine re-rendering the template
        var container = document.querySelector('.filter_tabs');
        if (container) {
            var observer = new MutationObserver(function () {
                clearTimeout(observer._timer);
                observer._timer = setTimeout(function () {
                    injectIcons();
                    updateArrowVisibility();
                }, 50);
            });
            observer.observe(container, { childList: true, subtree: true });
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () { setTimeout(init, 100); });
    } else {
        setTimeout(init, 100);
    }

    document.addEventListener('alpine:initialized', function () { setTimeout(init, 50); });
})();