function iccbCookieListTranslate(key) {
    return (window.ICCB_COOKIE_LIST_I18N && window.ICCB_COOKIE_LIST_I18N[key]) || key;
}

function iccbAppendCell(row, value) {
    const cell = document.createElement('td');
    cell.textContent = value;
    row.appendChild(cell);
}

function iccbGroupCookiesByType(definitions) {
    const grouped = {};
    Object.entries(definitions).forEach(([name, definition]) => {
        const type = definition.type || 'Uncategorized';
        if (!grouped[type]) {
            grouped[type] = [];
        }
        grouped[type].push({
            name,
            purpose: definition.purpose || '-',
            domain: definition.domain || window.location.hostname,
            path: definition.path || '/',
            duration: definition.duration || 'Unknown',
            provider: definition.provider || 'Unknown',
            type
        });
    });
    return grouped;
}

function iccbCreateCheckboxFilters(categories) {
    const wrapper = document.createElement('div');
    wrapper.id = 'cookie-category-filters';

    const label = document.createElement('strong');
    label.textContent = iccbCookieListTranslate('filterLabel');
    wrapper.appendChild(label);
    wrapper.appendChild(document.createElement('br'));

    categories.forEach((category) => {
        const id = `toggle-${category}`;
        const option = document.createElement('label');
        option.style.marginRight = '10px';

        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.id = id;
        checkbox.dataset.category = category;
        checkbox.checked = true;

        option.appendChild(checkbox);
        option.append(` ${iccbCookieListTranslate(category.toLowerCase())}`);
        wrapper.appendChild(option);
    });

    wrapper.addEventListener('change', (event) => {
        const category = event.target.dataset.category;
        const section = document.querySelector(`[data-cookie-category="${category}"]`);
        if (section) {
            section.style.display = event.target.checked ? 'block' : 'none';
        }
    });

    return wrapper;
}

function iccbDisplayGroupedCookies(definitions) {
    const grouped = iccbGroupCookiesByType(definitions);
    const output = document.getElementById('iccb-definitions-table');
    if (!output) {
        return;
    }

    output.textContent = '';
    if (!definitions || Object.keys(definitions).length === 0) {
        const empty = document.createElement('p');
        empty.textContent = iccbCookieListTranslate('no_definitions_available');
        empty.style.fontStyle = 'italic';
        output.appendChild(empty);
        return;
    }

    const categories = Object.keys(grouped);
    output.appendChild(iccbCreateCheckboxFilters(categories));
    categories.forEach((category) => {
        const items = grouped[category];
        const section = document.createElement('div');
        section.setAttribute('data-cookie-category', category);

        const heading = document.createElement('h4');
        heading.style.textTransform = 'capitalize';
        heading.textContent = iccbCookieListTranslate(category.toLowerCase());

        const wrapper = document.createElement('div');
        wrapper.className = 'iccb-table-wrapper';

        const table = document.createElement('table');
        table.className = 'iccb-cookie-table';

        const head = document.createElement('thead');
        const headerRow = document.createElement('tr');
        ['name', 'purpose', 'domain', 'path', 'duration', 'type', 'provider'].forEach((column) => {
            const header = document.createElement('th');
            header.textContent = iccbCookieListTranslate(column);
            headerRow.appendChild(header);
        });
        head.appendChild(headerRow);

        const body = document.createElement('tbody');
        items.forEach((item) => {
            const row = document.createElement('tr');
            iccbAppendCell(row, item.name);
            iccbAppendCell(row, item.purpose);
            iccbAppendCell(row, item.domain);
            iccbAppendCell(row, item.path);
            iccbAppendCell(row, item.duration);
            iccbAppendCell(row, iccbCookieListTranslate(item.type));
            iccbAppendCell(row, item.provider);
            body.appendChild(row);
        });

        table.appendChild(head);
        table.appendChild(body);
        wrapper.appendChild(table);
        section.appendChild(heading);
        section.appendChild(wrapper);
        output.appendChild(section);
    });
}

function iccbScanCookies() {
    fetch(window.ICCB_CONFIG.cookie_json_url)
        .then((response) => response.json())
        .then((definitions) => iccbDisplayGroupedCookies(definitions))
        .catch((error) => console.error('Failed to load cookie definitions:', error));
}

function iccbPopulateConsentUI() {
    const prefs = JSON.parse(localStorage.getItem('iccb_prefs_v1') || '{}');
    const analytics = document.getElementById('iccb-analytics');
    const marketing = document.getElementById('iccb-marketing');
    const functional = document.getElementById('iccb-functional');
    if (analytics) {
        analytics.checked = prefs.analytics || false;
    }
    if (marketing) {
        marketing.checked = prefs.marketing || false;
    }
    if (functional) {
        functional.checked = prefs.functional || false;
    }
}

document.addEventListener('DOMContentLoaded', () => {
    iccbScanCookies();
    const openBanner = document.getElementById('open-iccb-banner');
    if (openBanner) {
        openBanner.addEventListener('click', (event) => {
            event.preventDefault();
            const banner = document.getElementById('iccb-cookie-banner');
            if (banner) {
                iccbPopulateConsentUI();
                banner.classList.remove('iccb-hidden');
            }
        });
    }

    if (!localStorage.getItem('iccb_prefs_v1')) {
        iccbPopulateConsentUI();
        document.getElementById('iccb-cookie-banner')?.classList.remove('iccb-hidden');
    }
});
