(() => {
    'use strict';
    const form = document.querySelector('#madc-form');
    if (!form) return;
    const cleanupButton = document.querySelector('#madc-cleanup-button');
    let running = false;
    let cleanupToken = null;
    const busy = value => {
        running = value;
        document.querySelector('#madc-controls').disabled = value;
        cleanupButton.disabled = value;
    };
    const send = async (url, payload) => {
        const response = await fetch(url, {method: 'POST', credentials: 'same-origin', headers: {'Content-Type': 'application/json', 'X-WP-Nonce': madc.nonce}, body: JSON.stringify(payload)});
        const data = await response.json();
        if (!response.ok) { const error = new Error(data.message || madc.failed); error.code = data.code; throw error; }
        return data;
    };
    form.addEventListener('change', () => {
        const products = form.elements.kind.value !== 'posts';
        document.querySelector('#madc-quantity').hidden = products;
        document.querySelector('#madc-refresh').hidden = products;
    });
    window.addEventListener('beforeunload', event => {
        if (running) { event.preventDefault(); event.returnValue = ''; }
    });
    form.addEventListener('submit', async event => {
        event.preventDefault();
        if (running) return;
        const payload = {language: form.elements.language.value, kind: form.elements.kind.value, quantity: Number(form.elements.quantity.value), status: form.elements.status.value, refresh: form.elements.refresh.checked};
        const result = document.querySelector('#madc-result');
        const progress = document.querySelector('#madc-progress');
        const item = document.querySelector('#madc-item');
        document.querySelector('#madc-progress-panel').hidden = false;
        busy(true);
        let total = payload.kind === 'posts' ? payload.quantity : 28;
        let created = 0, skipped = 0, updated = 0;
        progress.value = 0; item.textContent = ''; result.textContent = madc.working;
        try {
            for (let index = 0; index < total; index++) {
                const data = await send(madc.url, {...payload, index});
                total = data.total;
                if (data.result === 'created') created++;
                else if (data.result === 'updated') updated++;
                else skipped++;
                progress.value = ((index + 1) / total) * 100;
                result.textContent = `${madc.working} ${index + 1} / ${total}`;
                item.textContent = data.title;
            }
            result.textContent = `${madc.done} ${madc.created}: ${created} · ${madc.updated}: ${updated} · ${madc.skipped}: ${skipped}`;
        } catch (error) { result.textContent = `${madc.failed} ${error.message}`; }
        finally { busy(false); }
    });
    cleanupButton.addEventListener('click', async () => {
        if (running) return;
        busy(true);
        const result = document.querySelector('#madc-cleanup-result');
        const progress = document.querySelector('#madc-cleanup-bar');
        document.querySelector('#madc-cleanup-progress').hidden = false;
        result.textContent = madc.cleanupWorking;
        try {
            if (!cleanupToken) {
                const preview = await send(madc.cleanupPreviewUrl, {});
                if (!preview.total) { result.textContent = madc.nothing; progress.value = 100; return; }
                const counts = Object.entries(preview.counts).map(([key, count]) => `${madc.cleanupLabels[key]}: ${count}`).join('\n');
                if (!window.confirm(`${madc.cleanupConfirm}\n\n${counts}`)) { document.querySelector('#madc-cleanup-progress').hidden = true; result.textContent = ''; return; }
                cleanupToken = preview.token;
                progress.value = 0;
            }
            for (;;) {
                const data = await send(madc.cleanupUrl, {token: cleanupToken, confirm: true});
                progress.value = data.total ? data.processed / data.total * 100 : 100;
                result.textContent = `${data.done ? madc.cleanupDone : madc.cleanupWorking} ${madc.deleted}: ${data.deleted} · ${madc.kept}: ${data.kept}`;
                if (data.done) { cleanupToken = null; break; }
            }
        } catch (error) { if (error.code === 'madc_cleanup_token') cleanupToken = null; result.textContent = `${madc.cleanupFailed} ${error.message}`; }
        finally { busy(false); }
    });
})();
