(function () {
    'use strict';

    var cfg = window.ccprAdmin || {};
    var activeScanId = Number(cfg.latestScanId || 0);
    var processing = false;
    var currentPage = 1;

    function byId(id) { return document.getElementById(id); }
    function sleep(ms) { return new Promise(function (resolve) { window.setTimeout(resolve, ms); }); }
    function setText(id, value) { var node = byId(id); if (node) { node.textContent = value; } }
    function setHidden(id, hidden) { var node = byId(id); if (node) { node.hidden = hidden; } }
    function formatString(template, values) {
        return (values || []).reduce(function (output, value, index) {
            return output.replace('%' + (index + 1) + '$s', value).replace('%s', value);
        }, template || '');
    }
    function showTechnicalError(message) {
        var details = byId('ccpr-error-technical');
        setText('ccpr-error-message', message || '');
        if (details) { details.hidden = !message; details.open = false; }
    }

    function request(path, options) {
        options = options || {};
        path = path.replace(/^\//, '');
        if (cfg.restUrl.indexOf('?') !== -1 && path.indexOf('?') !== -1) { path = path.replace('?', '&'); }
        options.headers = Object.assign({ 'X-WP-Nonce': cfg.nonce, 'Content-Type': 'application/json' }, options.headers || {});
        return window.fetch(cfg.restUrl + path, options).then(function (response) {
            return response.json().catch(function () { return {}; }).then(function (body) {
                if (!response.ok) { throw new Error(body.message || cfg.strings.requestFailed + ' (' + response.status + ')'); }
                return { body: body, response: response };
            });
        });
    }

    function showHomeState(state) {
        setHidden('ccpr-home-empty', state !== 'empty');
        setHidden('ccpr-home-scanning', state !== 'scanning');
        setHidden('ccpr-home-complete', state !== 'complete');
        setHidden('ccpr-home-error', state !== 'error');
    }

    function updateBestTask(tasks) {
        var task = Array.isArray(tasks) && tasks.length ? tasks[0] : null;
        var card = byId('ccpr-best-action');
        if (card) { card.hidden = !task; }
        if (!task) { return; }
        setText('ccpr-best-task-title', task.title || task.rule);
        setText('ccpr-best-task-reason', task.reason || '');
        setText('ccpr-best-task-impact', Number(task.affected_products || 0).toLocaleString());
        setText('ccpr-best-task-confidence', task.confidence === 'high' ? cfg.strings.highConfidence : (task.confidence === 'medium' ? cfg.strings.reviewNeeded : ''));
        var link = byId('ccpr-best-task-link');
        if (link) { link.href = cfg.tasksUrl + '&task=' + encodeURIComponent(task.rule); }
    }

    function setStatus(status) {
        var progress = Number(status.progress || 0);
        var isActive = status.status === 'running' || status.status === 'queued';
        var isComplete = status.status === 'completed';
        var isError = status.status === 'failed' || status.status === 'cancelled';

        if (cfg.page === 'ccpr-readiness') {
            showHomeState(isActive ? 'scanning' : (isComplete ? 'complete' : (isError ? 'error' : 'empty')));
        }

        var label = cfg.strings.running;
        if (isComplete) { label = cfg.strings.complete; }
        else if (status.status === 'failed') { label = cfg.strings.failed; }
        else if (status.status === 'cancelled') { label = cfg.strings.cancelled; }
        setText('ccpr-status-label', label);
        setText('ccpr-status-detail', formatString(cfg.strings.productsChecked, [Number(status.processed_products || 0).toLocaleString(), Number(status.total_products || 0).toLocaleString()]));
        setText('ccpr-progress-number', progress.toFixed(progress % 1 ? 1 : 0) + '%');

        var bar = byId('ccpr-progress-bar');
        if (bar) { bar.style.width = progress + '%'; }
        var track = byId('ccpr-progress-track');
        if (track) { track.setAttribute('aria-valuenow', String(progress)); }
        var ring = byId('ccpr-progress-ring');
        if (ring) { ring.style.setProperty('--ccpr-progress', String(progress)); }
        var cancelButton = byId('ccpr-cancel-scan');
        if (cancelButton) { cancelButton.hidden = !isActive; cancelButton.disabled = false; }

		if (isComplete) {
			var hasProducts = Number(status.total_products || 0) > 0;
			var hasScope = hasProducts && Number(status.in_scope_products || 0) > 0;
			var scoreAvailable = hasScope && status.score_available !== false;
			var needsScopeConfirmation = status.scope_confirmation_required === true;
			var score = scoreAvailable ? Number(status.overall_score || 0) : 0;
            var tasks = Array.isArray(status.tasks) ? status.tasks : [];
            var hasIssues = tasks.length > 0;
			setText('ccpr-score', scoreAvailable ? score.toFixed(1) + '%' : cfg.strings.notApplicable);
            var scoreRing = byId('ccpr-score-ring');
            if (scoreRing) { scoreRing.style.setProperty('--ccpr-score', String(score)); }
            setText('ccpr-processed', Number(status.processed_products || 0).toLocaleString());
            setText('ccpr-affected', Number(status.affected_products || 0).toLocaleString());
            setText('ccpr-task-count', Number(status.task_count || 0).toLocaleString());
            setText('ccpr-high-confidence', Number(status.high_confidence_task_count || 0).toLocaleString());
			setText('ccpr-home-title', !hasProducts ? cfg.strings.noProductsTitle : (needsScopeConfirmation ? cfg.strings.reviewReadyTitle : (!hasScope ? cfg.strings.chooseScopeTitle : (hasIssues ? formatString(cfg.strings.homeScore, [score.toFixed(1)]) : cfg.strings.allClear))));
			setText('ccpr-home-subtitle', !hasProducts ? cfg.strings.noProductsSubtitle : (needsScopeConfirmation ? cfg.strings.reviewReadySubtitle : (!hasScope ? cfg.strings.chooseScopeSubtitle : (hasIssues ? cfg.strings.homeIssuesSubtitle : cfg.strings.allClearSubtitle))));
            setHidden('ccpr-add-product', hasProducts);
			setHidden('ccpr-set-scope', !hasProducts || !needsScopeConfirmation);
            setHidden('ccpr-start-scan-complete', !hasScope);
            updateBestTask(hasScope ? tasks : []);
        }

        if (isError) {
            setText('ccpr-error-title', status.status === 'cancelled' ? cfg.strings.cancelled : cfg.strings.failed);
            setText('ccpr-error-detail', cfg.strings.productDataUnchanged);
            showTechnicalError(status.status === 'failed' ? (status.error_message || '') : '');
        }
    }

    function processScan() {
        if (!activeScanId || processing) { return; }
        processing = true;
        request('scans/' + activeScanId + '/process', { method: 'POST', body: '{}' }).then(function (result) {
            setStatus(result.body);
            processing = false;
            if (result.body.status === 'running' || result.body.status === 'queued') {
                return sleep(result.body.busy ? 500 : 50).then(processScan);
            }
            if (result.body.status === 'completed') { currentPage = 1; loadResults(); }
        }).catch(function (error) {
            processing = false;
            showHomeState('error');
            setText('ccpr-error-title', cfg.strings.failed);
            setText('ccpr-error-detail', cfg.strings.productDataUnchanged);
            showTechnicalError(error.message);
        });
    }

    function loadStatus() {
        if (!activeScanId) { return; }
        request('scans/' + activeScanId, { method: 'GET' }).then(function (result) {
            setStatus(result.body);
            if (result.body.status === 'running' || result.body.status === 'queued') { processScan(); }
            else if (result.body.status === 'completed' && cfg.page === 'ccpr-tasks') { loadResults(); }
        }).catch(function (error) { setText('ccpr-status-detail', error.message); });
    }

    function makeLink(url, label) {
        var link = document.createElement('a');
        link.href = url || '#';
        link.textContent = label;
        if (!url) { link.setAttribute('aria-disabled', 'true'); }
        return link;
    }

    function visibleFindings(findings) {
        var rules = Array.isArray(cfg.selectedTaskRules) ? cfg.selectedTaskRules : [];
        if (!cfg.selectedTask || cfg.selectedTask === 'all' || !rules.length) { return findings || []; }
        return (findings || []).filter(function (finding) { return rules.indexOf(finding.rule) !== -1; });
    }

    function renderResults(rows, totalPages) {
        var body = byId('ccpr-results-body');
        if (!body) { return; }
        body.textContent = '';
        if (!rows.length) {
            var emptyRow = document.createElement('tr');
            var emptyCell = document.createElement('td');
            emptyCell.colSpan = 4;
            emptyCell.textContent = cfg.strings.noResults;
            emptyRow.appendChild(emptyCell);
            body.appendChild(emptyRow);
            renderPagination(totalPages);
            return;
        }
        rows.forEach(function (row) {
            var tr = document.createElement('tr');
            var name = document.createElement('td');
            var strong = document.createElement('strong');
            strong.textContent = row.product_name;
            name.appendChild(strong);
            var id = document.createElement('div');
            id.className = 'ccpr-product-id';
            id.textContent = '#' + row.product_id;
            name.appendChild(id);
            tr.appendChild(name);

            var score = document.createElement('td');
            var badge = document.createElement('span');
            badge.className = 'ccpr-score-badge';
			badge.textContent = row.score_available === false || row.in_scope === false ? cfg.strings.notApplicable : Number(row.score).toFixed(1);
            score.appendChild(badge);
            tr.appendChild(score);

            var findingsCell = document.createElement('td');
            var list = document.createElement('ul');
            list.className = 'ccpr-findings';
            visibleFindings(row.findings).forEach(function (finding) {
                var item = document.createElement('li');
                item.className = 'ccpr-severity--' + finding.severity;
                item.textContent = finding.message;
                list.appendChild(item);
            });
            if (list.children.length) { findingsCell.appendChild(list); }
            else { findingsCell.textContent = cfg.strings.ready; }
            tr.appendChild(findingsCell);

            var actions = document.createElement('td');
            actions.className = 'column-actions';
            actions.appendChild(makeLink(row.edit_url, cfg.strings.edit));
            actions.appendChild(document.createTextNode(' · '));
            actions.appendChild(makeLink(row.view_url, cfg.strings.view));
            tr.appendChild(actions);
            body.appendChild(tr);
        });
        renderPagination(totalPages);
    }

    function renderPagination(totalPages) {
        var wrap = byId('ccpr-pagination');
        if (!wrap) { return; }
        wrap.textContent = '';
        totalPages = Math.max(1, Number(totalPages || 1));
        if (totalPages <= 1) { return; }
        var start = Math.max(1, currentPage - 2);
        var end = Math.min(totalPages, start + 4);
        start = Math.max(1, end - 4);
        for (var page = start; page <= end; page++) {
            (function (targetPage) {
                var button = document.createElement('button');
                button.type = 'button';
                button.className = 'button';
                button.textContent = targetPage;
                if (targetPage === currentPage) { button.setAttribute('aria-current', 'page'); }
                button.addEventListener('click', function () { currentPage = targetPage; loadResults(); });
                wrap.appendChild(button);
            }(page));
        }
    }

    function loadResults() {
        if (!activeScanId || !byId('ccpr-results-body')) { return; }
        var severity = byId('ccpr-filter-severity') ? byId('ccpr-filter-severity').value : '';
        var search = byId('ccpr-search-products') ? byId('ccpr-search-products').value : '';
        var query = new URLSearchParams({ page: String(currentPage), per_page: '20', severity: severity, search: search, task: cfg.selectedTask || '' });
        request('scans/' + activeScanId + '/results?' + query.toString(), { method: 'GET' }).then(function (result) {
            renderResults(result.body, result.response.headers.get('X-WP-TotalPages'));
        }).catch(function (error) {
            var body = byId('ccpr-results-body');
            if (body) { body.innerHTML = '<tr><td colspan="4"></td></tr>'; body.firstChild.firstChild.textContent = error.message; }
        });
    }

    function startScan(euScope) {
        showHomeState('scanning');
        setText('ccpr-status-label', cfg.strings.starting);
        setText('ccpr-status-detail', cfg.strings.preparing);
        var body = euScope ? { eu_scope: euScope } : {};
        request('scans', { method: 'POST', body: JSON.stringify(body) }).then(function (result) {
            activeScanId = result.body.id;
            setStatus(result.body);
            processScan();
        }).catch(function (error) {
            showHomeState('error');
            setText('ccpr-error-title', cfg.strings.failed);
            setText('ccpr-error-detail', cfg.strings.productDataUnchanged);
            showTechnicalError(error.message);
        });
    }

    function stopScan() {
        if (!activeScanId) { return; }
        var button = byId('ccpr-cancel-scan');
        if (button) { button.disabled = true; }
        setText('ccpr-status-label', cfg.strings.cancelling);
        request('scans/' + activeScanId + '/cancel', { method: 'POST', body: '{}' }).then(function (result) {
            processing = false;
            setStatus(result.body);
        }).catch(function (error) {
            if (button) { button.disabled = false; }
            setText('ccpr-status-detail', error.message);
        });
    }

    function setupMedia() {
        var select = byId('ccpr-select-notice');
        var clear = byId('ccpr-clear-notice');
        var input = byId('ccpr-notice-attachment-id');
        var preview = byId('ccpr-notice-preview');
        if (!select || !input || !window.wp || !window.wp.media) { return; }
        var frame;
        select.addEventListener('click', function () {
            if (frame) { frame.open(); return; }
            frame = window.wp.media({ title: select.textContent, button: { text: select.textContent }, library: { type: 'image' }, multiple: false });
            frame.on('select', function () {
                var item = frame.state().get('selection').first().toJSON();
                input.value = item.id;
                preview.textContent = '';
                var image = document.createElement('img');
                image.src = item.sizes && item.sizes.medium ? item.sizes.medium.url : item.url;
                image.alt = '';
                preview.appendChild(image);
            });
            frame.open();
        });
        if (clear) { clear.addEventListener('click', function () { input.value = '0'; preview.textContent = ''; }); }
    }

    document.addEventListener('DOMContentLoaded', function () {
		var taskContext = byId('ccpr-task-context');
		if (taskContext) {
			cfg.selectedTask = taskContext.getAttribute('data-task') || '';
			try { cfg.selectedTaskRules = JSON.parse(taskContext.getAttribute('data-rules') || '[]'); } catch (ignore) { cfg.selectedTaskRules = []; }
		}
        ['ccpr-start-scan', 'ccpr-start-scan-complete', 'ccpr-start-scan-error'].forEach(function (id) {
            var button = byId(id);
            if (button) { button.addEventListener('click', function () { startScan(''); }); }
        });
        var cancel = byId('ccpr-cancel-scan');
        if (cancel) { cancel.addEventListener('click', stopScan); }
        var filter = byId('ccpr-apply-filters');
        if (filter) { filter.addEventListener('click', function () { currentPage = 1; loadResults(); }); }
        var search = byId('ccpr-search-products');
        if (search) { search.addEventListener('keydown', function (event) { if (event.key === 'Enter') { event.preventDefault(); currentPage = 1; loadResults(); } }); }
        setupMedia();
        if (cfg.autoStart && cfg.page === 'ccpr-readiness') { startScan(cfg.autoStartScope || ''); }
        else if (activeScanId && (cfg.page === 'ccpr-readiness' || cfg.page === 'ccpr-tasks')) { loadStatus(); }
    });
}());
