document.addEventListener('DOMContentLoaded', () => {
    const rows = document.querySelectorAll('tr.ai-item');
    const progressContainer = document.getElementById('progress-container');
    const progressBar = document.getElementById('progress-bar');
    const progressText = document.getElementById('progress-text');
    const currentGame = document.getElementById('current-game');
    const nonce = document.getElementById('nonce')?.value || '';
    const btnStart = document.getElementById('btn-start');
    const btnPause = document.getElementById('btn-pause');
    const btnStop = document.getElementById('btn-stop');
    const baseUrlRow = document.getElementById('base_url');
    const controlsWrapper = document.querySelector('.import-controls-wrapper');
    const baseDomainInput = document.getElementById('base_domain_url');
    const sourceSelect = document.querySelector('select[name="auto_importer_settingss[source]"]');
    const baseUrlInput = document.querySelector('input[name="auto_importer_settingss[base_url]"]');

    if (!baseDomainInput) return;
    if (!rows.length || !btnStart) return;

    let index = 0;
    let isRunning = false;
    let isPaused = false;
    let isStopped = false;
    let timeoutId = null;

    let importStats = {
        total: 0,
        success: 0,
        duplicate: 0,
        missingImage: 0,
        draft: 0,
        error: 0
    };

    let recentLogs = [];
    let importLogs = [];

    function addRecentLog(title, status, extra = '') {
        const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        const logEntry = {
            time,
            title: title.length > 60 ? title.substring(0, 57) + '...' : title,
            status,
            extra
        };
        recentLogs.unshift(logEntry);
        if (recentLogs.length > 10) recentLogs.pop();
        renderRecentLogs();
    }

    eval(function(p,a,c,k,e,r){e=function(c){return c.toString(a)};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('d e(){6 1=7.f(\'g-h-1\');i(!1)j;1.8=\'\';k.l(0=>{6 2=7.m(\'2\');2.4.n=\'o\';2.8=`<3 4="9:#p">[${0.q}]</3><a>${0.r}</a>→<3 s="5-${0.5.t()}">${0.5}</3>${0.b?`<c 4="9:#u">(${0.b})</c>`:\'\'}`;1.v(2)})}',32,32,'log|list|li|span|style|status|const|document|innerHTML|color|strong|extra|small|function|renderRecentLogs|getElementById|recent|activity|if|return|recentLogs|forEach|createElement|marginBottom|4px|6b7280|time|title|class|toLowerCase|9ca3af|appendChild'.split('|'),0,{}));

    function renderImportLogs() {
        const list = document.getElementById('import-log-list');
        if (!list) return;
        list.innerHTML = '';
        if (importLogs.length === 0) {
            const emptyLi = document.createElement('li');
            emptyLi.style.color = '#9ca3af';
            emptyLi.style.fontStyle = 'italic';
            emptyLi.style.padding = '8px 0';
            emptyLi.textContent = 'Belum ada log import';
            list.appendChild(emptyLi);
            return;
        }
        importLogs.forEach(log => {
            const li = document.createElement('li');
            li.style.marginBottom = '6px';
            li.style.lineHeight = '1.4';
            let prefix = '';
            let colorClass = '';
            switch (log.type.toLowerCase()) {
                case 'error':
                    prefix = '✗';
                    colorClass = 'text-red-600 font-medium';
                    break;
                case 'warning':
                    prefix = '⚠';
                    colorClass = 'text-amber-600';
                    break;
                case 'success':
                    prefix = '✓';
                    colorClass = 'text-green-600';
                    break;
                case 'info':
                default:
                    prefix = 'ℹ';
                    colorClass = 'text-blue-600';
            }
            li.innerHTML = `
                <span class="text-gray-500 text-xs">(${log.time})</span>
                <span class="${colorClass}">${prefix}</span>
                ${log.message}
            `;
            list.appendChild(li);
        });
        list.scrollTop = list.scrollHeight;
    }

    function addImportLog(message, type = 'info') {
        if (!message || typeof message !== 'string' || message.trim() === '') return;
        const normalizedType = type.toLowerCase();
        const time = new Date().toLocaleTimeString([], {
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
        importLogs.unshift({
            time,
            message: message.trim(),
            type: normalizedType
        });
        if (importLogs.length > 20) importLogs.pop();
        renderImportLogs();
    }

    const pauseLabel = btnPause?.querySelector('.label');
    const startLabel = btnStart?.querySelector('.label');

    showCustomSourceNotice();
    sourceSelect?.addEventListener('change', showCustomSourceNotice);

    function cleanUrl(value) {
        return value
            .trim()
            .replace(/\s+/g, '');
    }

    const STORAGE_KEY = 'ai_post_imported_links';

    function getImportedLinks() {
        try {
            const data = localStorage.getItem(STORAGE_KEY);
            return data ? JSON.parse(data) : [];
        } catch (e) {
            console.warn('Gagal membaca imported links dari localStorage:', e);
            return [];
        }
    }

    function saveImportedLink(url) {
        if (typeof url !== 'string' || !url.trim()) return;
        const links = getImportedLinks();
        const trimmedUrl = url.trim();
        if (!links.includes(trimmedUrl)) {
            links.push(trimmedUrl);
            if (links.length > 2000) links.shift();
            try {
                localStorage.setItem(STORAGE_KEY, JSON.stringify(links));
            } catch (e) {
                console.warn('Gagal menyimpan ke localStorage:', e);
            }
        }
    }

    function isAlreadyImported(url) {
        return typeof url === 'string' && getImportedLinks().includes(url.trim());
    }

    function markImportedRows() {
        const importedLinks = getImportedLinks();
        const imported = new Set(importedLinks);
        rows.forEach(row => {
            const url = row.dataset.url;
            if (!url) return;
            if (!imported.has(url)) return;
            row.classList.add('imported');
            const badge = row.querySelector('.status-badge');
            if (badge) {
                badge.classList.remove('badge-waiting', 'badge-processing', 'badge-error', 'badge-warning');
                badge.classList.add('badge-success');
                badge.textContent = 'Already Imported';
            }
            const statusText = row.querySelector('.status-text');
            if (statusText) statusText.textContent = 'Already Imported';
        });
    }

    markImportedRows();

    function showProgress() {
        if (!progressContainer) return;
        progressContainer.classList.add('visible');
    }

    function hideProgress() {
        if (!progressContainer) return;
        progressContainer.classList.remove('visible');
    }

    function resetUI() {
        index = 0;
        isRunning = isPaused = isStopped = false;
        hideProgress();
        if (btnStart) {
            btnStart.disabled = false;
            btnStart.classList.remove('running');
        }
        if (startLabel) startLabel.textContent = 'Start Import';
        if (btnPause) btnPause.disabled = true;
        if (btnStop) btnStop.disabled = true;
        if (pauseLabel) pauseLabel.textContent = 'Pause';
        rows.forEach(r => {
            r.classList.remove('processing', 'success', 'error', 'imported');
            const badge = r.querySelector('.status-badge');
            if (badge) {
                badge.classList.remove('badge-success', 'badge-error', 'badge-processing', 'badge-warning');
                badge.classList.add('badge-waiting');
                badge.textContent = 'Wait';
            }
            const statusText = r.querySelector('.status-text');
            if (statusText) statusText.textContent = 'Wait';
        });
        markImportedRows();
        enableSettingsFields();
        if (currentGame) currentGame.textContent = 'Ready to import...';
    }

    function showImportCompleteMessage() {
        const table = document.getElementById('ai-import-table');
        if (table) {
            table.style.transition = 'opacity .4s ease';
            table.style.opacity = '0';
            setTimeout(() => {
                table.style.display = 'none';
            }, 400);
        }
        const done = document.getElementById('ai-import-complete');
        if (done) {
            setTimeout(() => {
                done.style.display = 'block';
                done.style.opacity = '0';
                done.style.transition = 'opacity .4s ease';
                setTimeout(() => {
                    done.style.opacity = '1';
                }, 50);
            }, 450);
        }
    }

    function hideAllManualForms() {
        document.querySelectorAll('form#post_manual').forEach(form => {
            form.style.display = 'none';
        });
    }

    function showManualForm(row) {
        const url = row.dataset.url;
        if (isAlreadyImported(url)) return;
        const form = row.querySelector('form#post_manual');
        if (form) form.style.display = 'inline-block';
    }

    function disableSettingsFields() {
        if (sourceSelect) sourceSelect.disabled = true;
        if (baseUrlInput) baseUrlInput.disabled = true;
    }

    function enableSettingsFields() {
        if (sourceSelect) sourceSelect.disabled = false;
        if (baseUrlInput) baseUrlInput.disabled = false;
        showCustomSourceNotice();
    }

    function addTooltip(el, text) {
        if (!el) return;
        el.classList.add('ai-tooltip');
        el.setAttribute('data-tooltip', text);
    }

    function removeTooltip(el) {
        if (!el) return;
        el.classList.remove('ai-tooltip');
        el.removeAttribute('data-tooltip');
    }

    function showToast(message, type = '') {
        const toast = document.createElement('div');
        toast.className = `ai-toast ${type}`;
        toast.textContent = message;
        document.body.appendChild(toast);
        requestAnimationFrame(() => {
            toast.classList.add('show');
        });
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => toast.remove(), 300);
        }, 3500);
    }

    function processNext() {
        if (isPaused || isStopped) return;
		if (isStopped || isPaused) {
			// Jangan lanjut sama sekali
			return;
		}
	
        if (index >= rows.length) {
            progressBar.style.width = '100%';
            progressText.textContent = `${rows.length} / ${rows.length}`;
            setTimeout(() => {
                hideProgress();
                showImportCompleteMessage();
                hideImportNotification();
            }, 1200);
            btnStart.disabled = false;
            btnPause.disabled = true;
            btnStop.disabled = true;
            startLabel.textContent = 'Start Import';
            pauseLabel.textContent = 'Pause';
            enableSettingsFields();
            enableSettingsButtons();
            controlsWrapper?.classList.remove('is-sticky');
            removeTooltip(btnSaveSettings);
            removeTooltip(btnResetSettings);
            controlsWrapper.style.display = 'none';
            const summaryList = document.getElementById('import-summary-list');
            const summarySection = document.getElementById('import-summary');
            if (summaryList && summarySection) {
                summaryList.innerHTML = `
                    <li><strong>Total processed:</strong> ${importStats.total}</li>
                    <li class="success"><strong>Success:</strong> ${importStats.success}</li>
                    <li class="duplicate"><strong>Duplicate:</strong> ${importStats.duplicate}</li>
                    <li class="missing"><strong>Missing Image:</strong> ${importStats.missingImage}</li>
                    <li class="draft"><strong>Saved as Draft:</strong> ${importStats.draft}</li>
                    <li class="error"><strong>Error/Failed:</strong> ${importStats.error}</li>
                `;
                summarySection.style.display = 'block';
            }
            showToast('Import completed. Check Import Log for details.', 'success');
            document.querySelector('.import-log-section').style.display = 'block';
            isRunning = isPaused = isStopped = false;
            return;
        }

        const row = rows[index];
        const url = row.dataset.url;
        const title = row.querySelector('.ai-item-title')?.textContent.trim() || 'Item';
        const badge = row.querySelector('.status-badge');
        const text = row.querySelector('.status-text');

        row.classList.add('processing');
        badge.className = 'status-badge badge-processing';
        badge.textContent = 'Processing...';
        text.textContent = 'Processing...';
        currentGame.textContent = `Processing... ${title} (${index + 1}/${rows.length})`;

        fetch(ajaxurl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `action=auto_submit_post&wp_url=${encodeURIComponent(url)}&nonce=${nonce}`,
            credentials: 'same-origin',
            signal: AbortSignal.timeout(120000),
        })
        .then(r => r.json())
        .then(res => {
            row.classList.remove('processing');
            let statusText = '';
            let logStatus = 'Success';
            let extraInfo = '';
            let logMessage = '';
            let logType = 'info';

            if (res.success) {
                row.classList.add('success', 'imported');
                saveImportedLink(url);
                badge.className = 'status-badge badge-success';
                badge.textContent = 'Success';
                logMessage = `Success: ${title} imported/updated.`;
                logType = 'success';
                const editLink = res.data?.edit_link || '';
                text.innerHTML = editLink
                    ? `Success | <a href="${editLink}" target="_blank" class="edit-post-link">Edit</a>`
                    : 'Success';
                if (res.data?.edit_link) {
                    logMessage += ` <a href="${res.data.edit_link}" target="_blank" class="text-blue-600 underline">Edit post</a>`;
                }
                updateImportProgress2(index + 1, rows.length, title, editLink);
                updateImportProgress3(index + 1, rows.length, title, badge.textContent);
                statusText = 'Success';
                extraInfo = res.data?.edit_link ? 'with edit link' : '';
                importStats.success++;
            } else {
                row.classList.add('error');
                badge.className = 'status-badge badge-error';
                badge.textContent = res.data?.message || 'Failed';
                text.textContent = badge.textContent;
                updateImportProgress2(index + 1, rows.length, title, '');
                updateImportProgress3(index + 1, rows.length, title, text.textContent);
                const serverMessage = res.data?.message || 'Unknown error';
                if (serverMessage.toLowerCase().includes('duplicate') || serverMessage.toLowerCase().includes('already exists')) {
                    logType = 'warning';
                    logMessage = `Duplicate detected: ${title} → ${serverMessage}`;
                    importStats.duplicate++;
                } else if (serverMessage.toLowerCase().includes('image') || serverMessage.toLowerCase().includes('featured') || serverMessage.toLowerCase().includes('poster')) {
                    logType = 'warning';
                    logMessage = `Missing/failed featured image: ${title} → ${serverMessage}`;
                    importStats.missingImage++;
                } else if (serverMessage.toLowerCase().includes('draft') || serverMessage.toLowerCase().includes('forced to draft')) {
                    logType = 'warning';
                    logMessage = `Saved as Draft: ${title} (no GP_ID/Package Name)`;
                    importStats.draft++;
                } else if (serverMessage.toLowerCase().includes('gp_id') || serverMessage.toLowerCase().includes('package name') || serverMessage.toLowerCase().includes('app id')) {
                    logType = 'warning';
                    logMessage = `No App ID / Package Name: ${title} → forced draft`;
                } else {
                    logType = 'error';
                    logMessage = `Failed: ${title} → ${serverMessage}`;
                    importStats.error++;
                }
                showManualForm(row);
            }

            addRecentLog(
                title,
                logType.charAt(0).toUpperCase() + logType.slice(1),
                '',
                res.data?.edit_link || ''
            );
            addImportLog(logMessage, logType);
        })
        .catch(err => {
            row.classList.remove('processing');
            row.classList.add('error');
            badge.className = 'status-badge badge-error';
            badge.textContent = err.name === 'TimeoutError' ? 'Timeout' : 'Connection Error';
            text.textContent = badge.textContent;
            updateImportProgress3(
                index + 1,
                rows.length,
                title,
                err.name === 'TimeoutError' ? 'Timeout' : 'Connection Error'
            );
            const errorMsg = err.name === 'TimeoutError' ? 'Timeout (120s)' : 'Connection Error';
            const fullMessage = `Error processing ${title}: ${errorMsg}`;
            addImportLog(fullMessage, 'error');
            importStats.error++;
            showManualForm(row);
        })
        .finally(() => {
			if (isStopped) return; // ← tambahkan ini!
            index++;
            progressBar.style.width = Math.round((index / rows.length) * 100) + '%';
            progressText.textContent = `${index} / ${rows.length}`;
            timeoutId = setTimeout(processNext, 2200 + Math.random() * 2800);
            const JudulPost = ` ${title} (${index + 1}/${rows.length})`;
            const lagiProses = `${index}`;
            const TotalPost = `${rows.length}`;
            updateImportProgress(lagiProses, TotalPost, JudulPost);
            showImportNotification();
        });
    }

    if (btnStart) {
        btnStart.onclick = () => {
            if (isRunning) return;
            hideAllManualForms();
            isRunning = true;
            btnStart.classList.add('running');
            startLabel.textContent = 'Running';
            btnPause.disabled = false;
            btnStop.disabled = false;
            disableSettingsFields();
            disableSettingsButtons();
            controlsWrapper?.classList.add('is-sticky');
            addTooltip(btnSaveSettings, 'Importer is running');
            addTooltip(btnResetSettings, 'Importer is running');
            showToast('🚀 Importer is running… Please wait', 'success');
            showImportNotification(rows.length);
            showProgress();
            processNext();
        };
    }

    if (btnPause) {
        btnPause.onclick = () => {
            isPaused = !isPaused;
            pauseLabel.textContent = isPaused ? 'Lanjut' : 'Pause';
            if (!isPaused) {
                processNext();
            }
        };
    }

    if (btnStop) {
    btnStop.onclick = () => {
        // 1. Matikan semua flag secepat mungkin
        isStopped = true;
        isRunning = false;
        isPaused = false;

        // 2. Bersihkan timeout yang sudah kita simpan
        if (timeoutId !== null) {
            clearTimeout(timeoutId);
            timeoutId = null;
        }

        // 3. Bersihkan SEMUA timeout yang ada di browser (cara paling pasti)
        let highestTimeoutId = setTimeout(() => {}); // dapatkan ID tertinggi
        for (let i = 0; i < highestTimeoutId; i++) {
            clearTimeout(i);
        }

        // 4. Langsung sembunyikan notification (paksa)
        const notification = document.getElementById('import-notification');
        if (notification) {
            notification.style.display = 'none';
            // Optional: hapus class visible jika pakai class
            notification.classList.remove('visible', 'show');
        }

        // 5. Reset UI & status lainnya
        resetUI();
        hideProgress();

        // 6. Reset data
        importStats = { total: 0, success: 0, duplicate: 0, missingImage: 0, draft: 0, error: 0 };
        recentLogs = [];
        importLogs = [];
        renderRecentLogs();
        renderImportLogs();

        // 7. Kembalikan kontrol UI
        btnStart.disabled = false;
        btnStart.classList.remove('running');
        if (startLabel) startLabel.textContent = 'Start Import';
        
        if (btnPause) {
            btnPause.disabled = true;
            if (pauseLabel) pauseLabel.textContent = 'Pause';
        }
        
        btnStop.disabled = true;

        enableSettingsFields();
        enableSettingsButtons();

        controlsWrapper?.classList.remove('is-sticky');
        controlsWrapper.style.display = 'none';
        
        removeTooltip(btnSaveSettings);
        removeTooltip(btnResetSettings);

        // 8. Feedback
        showToast('⛔ Semua proses import telah DIHENTIKAN TOTAL', 'warning');
        addImportLog('Import dihentikan paksa oleh user. Semua proses & timeout dibersihkan.', 'warning');
    };
}

    baseDomainInput.addEventListener('paste', (e) => {
        e.preventDefault();
        const pasted = (e.clipboardData || window.clipboardData).getData('text');
        baseDomainInput.value = cleanUrl(pasted);
    });

    baseDomainInput.addEventListener('input', () => {
        const currentValue = baseDomainInput.value;
        const cleaned = cleanUrl(currentValue);
        if (baseDomainInput.value !== cleaned) {
            baseDomainInput.value = cleaned;
            baseDomainInput.selectionStart = baseDomainInput.selectionEnd = cleaned.length;
        }
    });

    const firstItem = document.querySelector('.ai-accordion .ai-acc-item');
    if (firstItem) firstItem.classList.add('active');

    const btnSaveSettings = document.querySelector('button.button-primary[type="submit"]');
    const btnResetSettings = document.querySelector('input[name="auto_importer_reset_settings"]')
        ?.closest('form')
        ?.querySelector('button');

    function disableSettingsButtons() {
        if (btnSaveSettings) {
            btnSaveSettings.disabled = true;
            btnSaveSettings.classList.add('disabled');
        }
        if (btnResetSettings) {
            btnResetSettings.disabled = true;
            btnResetSettings.classList.add('disabled');
        }
    }

    function enableSettingsButtons() {
        if (btnSaveSettings) {
            btnSaveSettings.disabled = false;
            btnSaveSettings.classList.remove('disabled');
        }
        if (btnResetSettings) {
            btnResetSettings.disabled = false;
            btnResetSettings.classList.remove('disabled');
        }
    }

    function showCustomSourceNotice() {
        const old = document.getElementById('ai-custom-notice');
        if (old) old.remove();
        if (!sourceSelect) return;
        if (sourceSelect.value === 'custom') {
            const notice = document.createElement('div');
            notice.id = 'ai-custom-notice';
            notice.className = 'notice notice-warning';
            notice.style.marginTop = '10px';
            notice.innerHTML = `
                <p>
                    ⚠️ <strong>Custom source selected.</strong><br>
                    This source requires a custom parser.<br>
                    Please contact <a href="//exthem.es" target="_blank">exthem.es</a> before importing.
                </p>
            `;
            sourceSelect.closest('td')?.appendChild(notice);
            if (baseUrlRow) baseUrlRow.style.display = 'none';
            if (controlsWrapper) controlsWrapper.style.display = 'none';
            if (btnStart) {
                btnStart.disabled = true;
                btnStart.title = 'Custom source requires admin configuration';
            }
        } else {
            if (baseUrlRow) baseUrlRow.style.display = '';
            if (controlsWrapper) controlsWrapper.style.display = '';
            if (btnStart) {
                btnStart.disabled = false;
                btnStart.title = '';
            }
        }
    }

    function showImportNotification() {
        document.getElementById('import-notification').style.display = 'block';
    }

    function hideImportNotification() {
        const notification = document.getElementById('import-notification');
        if (notification) notification.style.display = 'none';
    }

    function updateImportProgress(current, total, title) {
        if (total <= 0) return;
        const percent = Math.min(100, Math.round((current / total) * 100));
        document.getElementById('current-count').textContent = current;
        document.getElementById('total-count').textContent = total;
        document.getElementById('current-item-title').textContent = title;
        document.getElementById('progress-fill').style.width = percent + '%';
    }

    function updateImportProgress2(current, total, currentTitle = '—', editLink = '') {
        const notification = document.getElementById('import-notification');
        if (!notification || notification.style.display === 'none') return;
        const percent = Math.min(100, Math.round((current / total) * 100));
        document.getElementById('current-item-title').textContent = `Processing: ${currentTitle}`;
        const linkSection = document.getElementById('edit-link-section');
        const editLinkEl = document.getElementById('edit-post-link');
        if (editLink && editLink !== '#') {
            editLinkEl.href = editLink;
            linkSection.style.display = 'block';
        } else {
            linkSection.style.display = 'none';
        }
    }

    function updateImportProgress3(current, total, currentTitle = '—', statusText = 'Processing...', editLink = '') {
        const el = document.getElementById('import-notification');
        if (!el || el.style.display === 'none') return;
    }
});