/**
 * Responsive tables (vanilla front-end copy).
 *
 * Below `options.breakpoint` (default 640px), every `<table class="responsive">`
 * is split into:
 *   <div class="tableWrapper">
 *     <div class="pinned">    ← cloned table showing only the first column
 *     <div class="scrollable"> ← original table, horizontally scrollable
 *
 * The clone's row heights are sync'd to the originals so columns line up.
 * Above the breakpoint, the wrapping is unwound and the original table is
 * left in its natural layout.
 *
 * Replaces the previous mtcResponsiveTables plugin. Only consumer is
 * `sites/default/js/script.js`.
 */
let listenersBound = false;

export default function mtcResponsiveTables(options = {}) {
    const settings = {
        breakpoint: 640,
        ...options,
    };
    let switched = false;

    const isMobile = () => window.innerWidth < settings.breakpoint;

    const splitTable = (table) => {
        // Wrap original in .tableWrapper.
        const wrapper = document.createElement('div');
        wrapper.className = 'tableWrapper';
        table.parentNode.insertBefore(wrapper, table);
        wrapper.appendChild(table);

        // Clone the table, hide every cell except the first column.
        const copy = table.cloneNode(true);
        copy.classList.remove('responsive');
        copy.querySelectorAll('td:not(:first-child), th:not(:first-child)').forEach((cell) => {
            cell.style.display = 'none';
        });

        // Pin the clone, make the original scrollable.
        const pinned = document.createElement('div');
        pinned.className = 'pinned';
        pinned.appendChild(copy);
        wrapper.appendChild(pinned);

        const scrollable = document.createElement('div');
        scrollable.className = 'scrollable';
        wrapper.insertBefore(scrollable, pinned);
        scrollable.appendChild(table);

        setCellHeights(table, copy);
    };

    const unsplitTable = (table) => {
        const wrapper = table.closest('.tableWrapper');
        if (!wrapper) {
            return;
        }
        const pinned = wrapper.querySelector('.pinned');
        pinned?.remove();
        const scrollable = wrapper.querySelector('.scrollable');
        if (scrollable) {
            wrapper.insertBefore(table, scrollable);
            scrollable.remove();
        }
        wrapper.parentNode.insertBefore(table, wrapper);
        wrapper.remove();
        // Remove any inline heights we set on cloned rows.
        table.querySelectorAll('tr').forEach((tr) => { tr.style.height = ''; });
    };

    const setCellHeights = (original, copy) => {
        const originalRows = original.querySelectorAll('tr');
        const copyRows = copy.querySelectorAll('tr');
        const heights = [];

        originalRows.forEach((row, i) => {
            row.querySelectorAll('th, td').forEach((cell) => {
                const h = cell.getBoundingClientRect().height;
                heights[i] = Math.max(heights[i] || 0, h);
            });
        });

        copyRows.forEach((row, i) => {
            if (heights[i]) {
                row.style.height = `${heights[i]}px`;
            }
        });
    };

    const updateTables = () => {
        const responsive = document.querySelectorAll('table.responsive');
        if (!responsive.length) {
            return;
        }
        if (isMobile() && !switched) {
            switched = true;
            responsive.forEach(splitTable);
        } else if (switched && !isMobile()) {
            switched = false;
            // After splitting, the original lives inside a wrapper — re-query.
            document.querySelectorAll('.tableWrapper .scrollable > table').forEach(unsplitTable);
        }
    };

    if (!listenersBound) {
        listenersBound = true;
        window.addEventListener('load', updateTables);
        window.addEventListener('redraw', () => { switched = false; updateTables(); });
        window.addEventListener('resize', updateTables);
    } else {
        // Already wired — just rerun once so a fresh call still updates the page.
        updateTables();
    }
}

// Legacy global — `sites/default/js/script.js` still calls this by name.
// Drop the alias once script.js is converted in a later Phase 3 batch.
window.mtcResponsiveTables = mtcResponsiveTables;

