class IccbBanner {
    constructor(options) {
        this.cookieUrl = options.cookieUrl;
        this.accordionId = options.accordionId;
        this.storageKey = options.storageKey;
    }

    translate(key) {
        return (window.ICCB_CONFIG && window.ICCB_CONFIG.iccbTranslateI18n && window.ICCB_CONFIG.iccbTranslateI18n[key]) || key;
    }

    getPrefs() {
        try {
            return JSON.parse(localStorage.getItem(this.storageKey) || '{}');
        } catch (error) {
            return {};
        }
    }

    setPrefs(preferences) {
        localStorage.setItem(this.storageKey, JSON.stringify(preferences));
    }

    async loadDefs() {
        const response = await fetch(this.cookieUrl, { cache: 'no-store' });
        return response.json();
    }

    group(definitions) {
        const grouped = {};
        ['necessary', 'functional', 'analytics', 'performance', 'marketing', 'uncategorized'].forEach((category) => {
            grouped[category] = [];
        });

        Object.entries(definitions).forEach(([name, definition]) => {
            const category = (definition.type || 'uncategorized').toLowerCase();
            if (!grouped[category]) {
                grouped[category] = [];
            }
            grouped[category].push({ name, ...definition });
        });

        return grouped;
    }

    renderAccordion(definitions, accordionId) {
        const prefs = this.getPrefs();
        const grouped = this.group(definitions);
        const accordion = document.getElementById(accordionId || this.accordionId);
        if (!accordion) {
            return;
        }

        accordion.textContent = '';
        Object.entries(grouped).forEach(([category, items]) => {
            const details = document.createElement('details');
            const summary = document.createElement('summary');
            const label = document.createElement('label');
            label.htmlFor = `iccb-${category}`;
            label.className = 'iccb-category-toggle';

            const input = document.createElement('input');
            input.id = `iccb-${category}`;
            input.name = `iccb-${category}`;
            input.type = 'checkbox';
            input.dataset.category = category;
            input.checked = Boolean(prefs[category]);
            input.disabled = category === 'necessary';

            label.appendChild(input);
            label.append(` ${this.translate(category)} (${items.length})`);
            summary.appendChild(label);
            details.appendChild(summary);

            if (items.length) {
                const list = document.createElement('ul');
                list.className = 'iccb-cookie-list';
                items.forEach((item) => {
                    const entry = document.createElement('li');
                    const name = document.createElement('strong');
                    name.textContent = item.name;
                    const meta = document.createElement('small');
                    meta.textContent = `${item.domain || location.hostname} | ${item.duration || 'Unknown'} | ${item.provider || 'Unknown'}`;

                    entry.appendChild(name);
                    entry.append(` - ${item.purpose || '-'}`);
                    entry.appendChild(document.createElement('br'));
                    entry.appendChild(meta);
                    list.appendChild(entry);
                });
                details.appendChild(list);
            } else {
                const empty = document.createElement('p');
                empty.className = 'iccb-empty';
                empty.textContent = this.translate('no_cookies');
                details.appendChild(empty);
            }

            accordion.appendChild(details);
        });

        accordion.addEventListener('change', (event) => {
            if (!event.target.matches('input[type="checkbox"][data-category]')) {
                return;
            }

            const prefs = this.getPrefs();
            prefs[event.target.dataset.category] = event.target.checked;
            this.setPrefs(prefs);
        }, { once: true });
    }

    async init() {
        const definitions = await this.loadDefs();
        this.renderAccordion(definitions);
    }
}
