document.addEventListener('DOMContentLoaded', () => {
    const typeLabels = {
        necessary: 'Necessary',
        functional: 'Functional',
        analytics: 'Analytics',
        performance: 'Performance',
        marketing: 'Marketing',
        uncategorized: 'Uncategorized'
    };

    const appendTextInputCell = (row, name, value = '') => {
        const cell = document.createElement('td');
        const input = document.createElement('input');
        input.name = name;
        input.value = value;
        cell.appendChild(input);
        row.appendChild(cell);
        return cell;
    };

    const appendNameCell = (row, definition = {}) => {
        const cell = appendTextInputCell(row, 'cookie_name[]', definition.name || '');
        const source = document.createElement('input');
        source.type = 'hidden';
        source.name = 'cookie_source[]';
        source.value = definition.source || '';
        cell.appendChild(source);

        if (definition.source) {
            const badge = document.createElement('span');
            badge.className = 'description';
            badge.textContent = ` [${definition.source}]`;
            cell.appendChild(badge);
        }
    };

    const appendTypeCell = (row, value = 'uncategorized') => {
        const cell = document.createElement('td');
        const select = document.createElement('select');
        select.name = 'cookie_type[]';
        Object.entries(typeLabels).forEach(([type, label]) => {
            const option = document.createElement('option');
            option.value = type;
            option.textContent = label;
            option.selected = type === value;
            select.appendChild(option);
        });
        cell.appendChild(select);
        row.appendChild(cell);
    };

    const appendDefinitionRow = (body, definition = {}) => {
        const row = document.createElement('tr');
        appendNameCell(row, definition);
        appendTypeCell(row, definition.type || 'uncategorized');
        appendTextInputCell(row, 'cookie_domain[]', definition.domain || window.location.hostname);
        appendTextInputCell(row, 'cookie_path[]', definition.path || '/');
        appendTextInputCell(row, 'cookie_duration[]', definition.duration || '');
        appendTextInputCell(row, 'cookie_purpose[]', definition.purpose || '');
        appendTextInputCell(row, 'cookie_provider[]', definition.provider || '');
        appendActionCell(row);
        body.appendChild(row);
    };

    const showScanResult = (message, type = 'success') => {
        const result = document.getElementById('iccb-scan-result');
        if (!result) {
            return;
        }

        result.className = `notice inline notice-${type}`;
        result.textContent = message;
    };

    const scanBrowserCookies = () => {
        const names = document.cookie
            .split(';')
            .map((cookie) => cookie.trim().split('=')[0])
            .filter(Boolean);

        const cookies = [...new Set(names)].map((name) => ({
            name,
            source: 'client'
        }));

        const config = window.ICCB_ADMIN_DEFINITIONS || {};
        const messages = config.messages || {};
        const body = document.querySelector('#cookie-definitions-table tbody');

        if (!config.ajax_url || !config.nonce) {
            showScanResult(messages.scanFailed || 'Cookie scan failed. Please reload the page and try again.', 'error');
            return Promise.resolve();
        }

        showScanResult(messages.scanning || 'Scanning browser cookies...', 'info');

        return fetch(config.ajax_url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                action: 'iccb_scan_cookies',
                nonce: config.nonce,
                cookies: JSON.stringify(cookies)
            })
        })
            .then((response) => response.json())
            .then((response) => {
                if (!response.success) {
                    const errorMessage = response.data && response.data.message ? response.data.message : messages.scanFailed || 'Cookie scan failed.';
                    throw new Error(errorMessage);
                }

                const added = response.data && response.data.added ? response.data.added : {};
                Object.entries(added).forEach(([name, definition]) => {
                    if (body) {
                        appendDefinitionRow(body, { name, ...definition });
                    }
                });

                if (Object.keys(added).length === 0) {
                    showScanResult(messages.noneFound || 'No new cookies found.', 'info');
                    return;
                }

                showScanResult(`${messages.scanComplete || 'Cookie scan complete.'} ${messages.reviewAdded || ''}`, 'success');
            })
            .catch((error) => {
                showScanResult(error.message || messages.scanFailed || 'Cookie scan failed.', 'error');
            });
    };

    const appendActionCell = (row) => {
        const cell = document.createElement('td');
        const button = document.createElement('button');
        button.type = 'button';
        button.className = 'button remove-row';
        button.textContent = 'x';
        cell.appendChild(button);
        row.appendChild(cell);
    };

    const tabs = document.querySelectorAll('.nav-tab-wrapper a');
    const panels = document.querySelectorAll('.iccb-tab-content');

    tabs.forEach((tab) => {
        tab.addEventListener('click', (event) => {
            event.preventDefault();
            tabs.forEach((item) => item.classList.remove('nav-tab-active'));
            panels.forEach((panel) => panel.classList.add('iccb-hidden'));
            tab.classList.add('nav-tab-active');

            const target = document.querySelector(tab.getAttribute('href'));
            if (target) {
                target.classList.remove('iccb-hidden');
            }
        });
    });

    const add = document.getElementById('add-cookie-row');
    if (add) {
        add.addEventListener('click', () => {
            const body = document.querySelector('#cookie-definitions-table tbody');
            if (!body) {
                return;
            }

            const row = document.createElement('tr');
            appendNameCell(row);
            appendTypeCell(row);
            appendTextInputCell(row, 'cookie_domain[]');
            appendTextInputCell(row, 'cookie_path[]');
            appendTextInputCell(row, 'cookie_duration[]');
            appendTextInputCell(row, 'cookie_purpose[]');
            appendTextInputCell(row, 'cookie_provider[]');
            appendActionCell(row);
            body.appendChild(row);
        });
    }

    document.addEventListener('click', (event) => {
        if (event.target.classList.contains('remove-row')) {
            const row = event.target.closest('tr');
            if (row) {
                row.remove();
            }
        }
    });

    const scan = document.getElementById('iccb-scan-cookies');
    if (scan) {
        scan.addEventListener('click', () => {
            scan.disabled = true;
            scanBrowserCookies().then(() => {
                scan.disabled = false;
            }).catch(() => {
                scan.disabled = false;
            });
        });
    }
});
