(function () {
    'use strict';

    if (window.ICYTableSort && window.ICYTableSort.version === '6.19') return;

    const collator = new Intl.Collator('es', { numeric: true, sensitivity: 'base' });

    function injectStyles() {
        if (document.getElementById('icy-table-sort-styles')) return;
        const style = document.createElement('style');
        style.id = 'icy-table-sort-styles';
        style.textContent = `
            .icy-table-sort-button {
                appearance: none;
                border: 0;
                background: transparent;
                color: inherit;
                font: inherit;
                font-weight: inherit;
                letter-spacing: inherit;
                text-transform: inherit;
                width: 100%;
                min-width: 0;
                padding: 0;
                display: inline-flex;
                align-items: center;
                justify-content: flex-start;
                gap: 6px;
                cursor: pointer;
                text-align: left;
            }
            .icy-table-sort-button:hover,
            .icy-table-sort-button:focus-visible {
                color: var(--text-primary, #111827);
            }
            .icy-table-sort-button:focus-visible {
                outline: 2px solid var(--color-primary, #00c83c);
                outline-offset: 3px;
                border-radius: 4px;
            }
            .icy-table-sort-indicator {
                flex: 0 0 auto;
                width: 12px;
                text-align: center;
                color: var(--text-muted, #6b7280);
                font-size: .72rem;
                line-height: 1;
            }
            .icy-table-sort-indicator::before { content: '↕'; }
            th[aria-sort="ascending"] .icy-table-sort-indicator::before { content: '↑'; }
            th[aria-sort="descending"] .icy-table-sort-indicator::before { content: '↓'; }
            th[aria-sort="ascending"] .icy-table-sort-button,
            th[aria-sort="descending"] .icy-table-sort-button {
                color: var(--text-primary, #111827);
            }
        `;
        document.head.appendChild(style);
    }

    function normalizeDate(value) {
        const raw = String(value || '').trim();
        if (!raw || raw === '—' || raw === '-') return null;
        if (/^\d{4}-\d{2}-\d{2}/.test(raw)) return raw.slice(0, 10);
        const match = raw.match(/^(\d{1,2})[-\/]([0-1]?\d)[-\/](\d{4})$/);
        if (match) return `${match[3]}-${String(match[2]).padStart(2, '0')}-${String(match[1]).padStart(2, '0')}`;
        const timestamp = Date.parse(raw);
        return Number.isFinite(timestamp) ? timestamp : raw;
    }

    function normalizeNumber(value) {
        const raw = String(value || '').trim();
        if (!raw || raw === '—' || raw === '-') return null;
        const normalized = raw
            .replace(/[^0-9,.-]/g, '')
            .replace(/\.(?=\d{3}(?:\D|$))/g, '')
            .replace(',', '.');
        const number = Number(normalized);
        return Number.isFinite(number) ? number : null;
    }

    function valueFor(cell, type) {
        const raw = cell && cell.dataset && Object.prototype.hasOwnProperty.call(cell.dataset, 'sortValue')
            ? cell.dataset.sortValue
            : (cell ? cell.textContent : '');
        if (type === 'number') return normalizeNumber(raw);
        if (type === 'date') return normalizeDate(raw);
        return String(raw || '').trim();
    }

    function compareValues(a, b, type, direction) {
        const aEmpty = a === null || a === '' || typeof a === 'undefined';
        const bEmpty = b === null || b === '' || typeof b === 'undefined';
        if (aEmpty && bEmpty) return 0;
        if (aEmpty) return 1;
        if (bEmpty) return -1;

        let result = 0;
        if (type === 'number') result = Number(a) - Number(b);
        else if (type === 'date') {
            const av = typeof a === 'number' ? a : String(a);
            const bv = typeof b === 'number' ? b : String(b);
            result = av < bv ? -1 : (av > bv ? 1 : 0);
        } else result = collator.compare(String(a), String(b));
        return direction === 'descending' ? -result : result;
    }

    function sortFromButton(button) {
        const th = button.closest('th');
        const table = th && th.closest('table');
        const tbody = table && table.tBodies && table.tBodies[0];
        if (!th || !table || !tbody) return;

        const headerCells = Array.from(th.parentElement.children);
        const columnIndex = headerCells.indexOf(th);
        if (columnIndex < 0) return;

        const currentDirection = th.getAttribute('aria-sort') || 'none';
        const type = button.dataset.sortType || 'text';
        const firstDirection = (type === 'number' || type === 'date') ? 'descending' : 'ascending';
        const direction = currentDirection === 'none'
            ? firstDirection
            : (currentDirection === 'ascending' ? 'descending' : 'ascending');
        headerCells.forEach((cell) => {
            if (cell.hasAttribute('aria-sort')) cell.setAttribute('aria-sort', cell === th ? direction : 'none');
        });

        const rows = Array.from(tbody.rows)
            .filter((row) => !row.classList.contains('empty-state-row') && row.cells.length > columnIndex)
            .map((row, index) => ({ row, index, value: valueFor(row.cells[columnIndex], type) }));

        rows.sort((left, right) => {
            const compared = compareValues(left.value, right.value, type, direction);
            return compared || (left.index - right.index);
        });

        const fragment = document.createDocumentFragment();
        rows.forEach((entry) => fragment.appendChild(entry.row));
        tbody.appendChild(fragment);

        const viewport = table.closest('.billing-document-group-scroll, .quotes-table-wrap, .crm-ui-table-scroll');
        if (viewport) viewport.scrollTop = 0;
    }

    function clickHandler(event) {
        const button = event.target && typeof event.target.closest === 'function'
            ? event.target.closest('.icy-table-sort-button')
            : null;
        if (!button) return;
        event.preventDefault();
        sortFromButton(button);
    }

    injectStyles();
    if (!window.__ICY_TABLE_SORT_BOUND__) {
        document.addEventListener('click', clickHandler);
        window.__ICY_TABLE_SORT_BOUND__ = true;
    }

    window.ICYTableSort = { version: '6.19', sortFromButton };
})();
