import { ready, slideDown, slideUp, slideFadeToggle } from '@site/js/utils/dom.js';

/**
 * Site-wide bootstrap that runs after DOM + Vue mount.
 *
 * Initialises a grab-bag of small front-end behaviours: homepage tabs, smooth
 * scrolling, the mobile menu, password-reveal toggles, native form validation
 * opt-out, overlays, the responsive tables helper, and a couple of legacy
 * accordion / dropdown patterns. Each block self-gates on its own selectors
 * so this is safe to load on any page.
 */

// Smooth-scroll the page to the element targeted by `linkEl.href`. Browsers
// handle the easing natively when `behavior: 'smooth'` is set, so this
// replaces the legacy animated scrollTop the page used to do.
function scrollToHash(linkEl) {
    const href = linkEl.getAttribute('href');
    if (!href || !href.startsWith('#')) {
        return;
    }
    const target = document.querySelector(href);
    if (!target) {
        return;
    }
    const top = target.getBoundingClientRect().top + window.pageYOffset;
    window.scrollTo({ top, behavior: 'smooth' });
}

// Single-active-tab pattern: clear `.active` on siblings, apply it to the
// clicked tab, then point the content container at the same `data-target`.
function activateTab(clickedEl, titleSelector, contentSelector) {
    document.querySelectorAll(titleSelector).forEach((el) => el.classList.remove('active'));
    clickedEl.classList.add('active');

    const dataTarget = clickedEl.getAttribute('data-target');
    if (!dataTarget) {
        return;
    }

    document.querySelectorAll(`${contentSelector} > *`).forEach((el) => el.classList.remove('active'));
    document.querySelectorAll(`${contentSelector} ${dataTarget}`).forEach((el) => el.classList.add('active'));
}

ready(() => {

    document.body.classList.add('pageReady');

    // Homepage tabs (data-tabs-title) — single-active pattern.
    document.querySelectorAll('[data-tabs-title] li').forEach((li) => {
        li.addEventListener('click', () => {
            const titles = document.querySelectorAll('[data-tabs-title] li');
            titles.forEach((el) => el.classList.remove('active'));
            li.classList.add('active');

            const dataTarget = li.getAttribute('data-target');
            if (!dataTarget) {
                return;
            }
            document.querySelectorAll('[data-tabs-content] ul').forEach((el) => el.classList.remove('active'));
            document.querySelectorAll(`[data-tabs-content] ${dataTarget}`).forEach((el) => el.classList.add('active'));
        });
    });

    // Generic top-tabs / content-body pattern.
    document.querySelectorAll('.tabsTop li').forEach((li) => {
        li.addEventListener('click', () => activateTab(li, '.tabsTop li', '.contentBody'));
    });

    // Anchor scroll-to.
    document.querySelectorAll('.js_scrollTo').forEach((link) => {
        link.addEventListener('click', (event) => {
            event.preventDefault();
            scrollToHash(link);
        });
    });

    // Mobile menu init (see core/js/plugins/mtc_mobile_menu.js).
    if (document.querySelector('.flyoutWrap')) {
        window.mtcMobileMenu({
            move_site: false,
            position: 'left',
            is_fixed: true,
        });
    }

    // Member sidebar nav — clicking a link makes its row + target tab active.
    document.querySelectorAll('.js_sidenavLink').forEach((link) => {
        link.addEventListener('click', (event) => {
            event.preventDefault();

            const ul = link.closest('ul');
            if (ul) {
                ul.querySelectorAll('a').forEach((a) => a.classList.remove('active'));
            }
            link.classList.add('active');

            const targetId = link.getAttribute('href');
            if (!targetId) {
                return;
            }
            const target = document.querySelector(targetId);
            document.querySelectorAll('.tabContentWrap > section').forEach((s) => s.classList.remove('active'));
            if (target) {
                target.classList.add('active');
            }
        });
    });

    // Category / product sidebar accordion.
    if (document.querySelector('.sidebarTabs .sectionTitle')) {
        showHideMenus('.sidebarTabs .sectionTitle', 700);
        // Auto-expand the first section.
        const first = document.querySelector('.sidebarTabs section .sectionTitle');
        first?.click();
    }

    // Flyout button — toggles `.open` on every matching button (legacy behaviour).
    document.querySelectorAll('.flyoutButton').forEach((button) => {
        button.addEventListener('click', () => {
            document.querySelectorAll('.flyoutButton').forEach((b) => b.classList.toggle('open'));
        });
    });

    // Legacy compatibility flag previously set by jquery-mobile.
    document.documentElement.classList.add('noTouchevents');

    // Contact form — submitForm still lives in core/js/functions.js.
    if (document.querySelector('.js_contactForm')) {
        submitForm('.js_contactForm');
    }

    // Responsive tables.
    if (document.querySelector('table.responsive')) {
        mtcResponsiveTables({ breakpoint: 640 });
    }

    // Password reveal toggle. Wraps the input with an eye-icon button that
    // flips the input type between `password` and `text`.
    document.querySelectorAll('input[type="password"].passwordToggle:not(.toggleSet)').forEach((field) => {
        const parent = field.parentElement;
        if (!parent || !parent.classList.contains('inputWrap')) {
            return;
        }
        field.classList.add('toggleSet');
        parent.classList.add('passwordToggle');

        if (!parent.querySelector('.toggleButtons')) {
            const span = document.createElement('span');
            span.className = 'toggleButtons';
            span.innerHTML = '<i class="fas fa-eye disabled"></i><i class="fas fa-eye-slash enabled"></i>';
            parent.appendChild(span);
        }

        const toggleButtons = parent.querySelector('.toggleButtons');
        toggleButtons?.addEventListener('click', () => {
            const inputWrap = toggleButtons.parentElement;
            const targetField = inputWrap?.querySelector('.toggleSet');
            if (!targetField) {
                return;
            }
            inputWrap.classList.toggle('reveal');
            targetField.setAttribute('type', inputWrap.classList.contains('reveal') ? 'text' : 'password');
        });
    });

    // Back-to-top / generic anchor scroll.
    document.querySelectorAll('a.scrollLink').forEach((link) => {
        link.addEventListener('click', (event) => {
            event.preventDefault();
            scrollToHash(link);
        });
    });

    // Disable native HTML5 validation everywhere — the project uses custom
    // server-side validation messaging.
    document.querySelectorAll('form').forEach((form) => {
        form.setAttribute('novalidate', 'novalidate');
    });

    // Overlays (see sites/default/js/site_scripts/mtc_overlay.js).
    window.mtcOverlay('.mtcOverlay');
    window.mtcOverlay('.mtcPriceOverlay', {
        onOpen() {
            window.mtcTabs('.js_tabs');
        },
    });

    // Generic tabs init.
    window.mtcTabs('.js_tabs');

    // Mobile members menu — collapsible at flyout breakpoint.
    if (document.querySelector('.js_mobileMembersMenu')) {
        showHideMenus('.js_mobileMembersMenu', window.breakpoints.flyout);
    }

    // `<select>` that navigates to its selected value.
    document.querySelectorAll('.js_gotoSelect').forEach((select) => {
        select.addEventListener('change', () => {
            const val = (select.value || '').trim();
            if (val.length > 0 && val !== 'all') {
                window.location = val;
            }
        });
    });

    // FAQs "still need help" reveal.
    if (document.querySelector('.faqsHelp') && document.querySelector('.js_faqsHelp')) {
        document.querySelectorAll('.faqsHelp').forEach((field) => {
            field.addEventListener('change', () => {
                document.querySelectorAll('.js_faqsHelp').forEach((panel) => {
                    if (field.value === 'No') {
                        slideDown(panel);
                    } else {
                        slideUp(panel);
                    }
                });
            });
        });
    }

    // Hidden-list toggle (show more / show less).
    document.querySelectorAll('.js_revealList').forEach((trigger) => {
        trigger.addEventListener('click', (event) => {
            event.preventDefault();
            const target = trigger.parentElement?.parentElement?.querySelector('.hiddenList');
            if (!target) {
                return;
            }
            slideFadeToggle(target);
            // The toggle animation runs for ~300ms — update the button copy
            // after a frame so it reflects the resulting state.
            requestAnimationFrame(() => {
                const isHidden = target.classList.contains('is-hidden')
                    || getComputedStyle(target).display === 'none';
                trigger.textContent = isHidden ? 'Show more' : 'Show less';
            });
        });
    });

    // Legacy user-prompt auto-launch.
    document.getElementById('launchUserPrompt')?.click();

});

// Resize handler — keep mobile members menu in sync at the flyout breakpoint.
window.addEventListener('resize', window.debouncer(() => {
    window.windowWidth = window.outerWidth;

    if (document.querySelector('.js_mobileMembersMenu')) {
        showHideMenus('.js_mobileMembersMenu', window.breakpoints.flyout);
    }
}));
