document.addEventListener('DOMContentLoaded', () => {
    const root = document.getElementById('sip-root');
    const config = iic_check_config;

    // --- STATE ---
    const state = {
        urls: [],
        page: 1,
        limit: 20,
        total: 0,
        totalPages: 0,
        selection: new Set(),
        selectionMode: 'none',
        filter: '30days',
        scannedResults: null, // Cache for 'all' mode scan results
        checkedCache: {}, // Cache for statuses across pages
        stopRequested: false,
        lang: (config.locale && config.locale.startsWith('fr')) ? 'fr' : 'en'
    };

    const I18N = {
        fr: {
            welcome_title: "Bienvenue sur Instant Indexing",
            welcome_subtitle: "Boostez votre SEO en indexant vos contenus instantanément sur Google.",
            enter_license: "Entrez votre clé de licence...",
            activate_btn: "Activer ma licence",
            free_btn: "Continuer avec la version Gratuite",
            premium_offer: "💎 Voir les offres Premium",
            config_title: "Configuration API Google",
            json_label: "1. Clé JSON (Service Account)",
            json_desc: "Contenu du fichier JSON téléchargé depuis Google Cloud Console.",
            gsc_label: "2. URL Propriété Search Console",
            gsc_desc: "Doit correspondre exactement à la propriété dans GSC.",
            save_btn: "💾 Sauvegarder la configuration",
            tuto_title: "Tutoriel d'installation",
            tuto_intro: "Suivez ces étapes pour configurer l'API Google Indexing :",
            step1: "Créer un Service Account sur Google Cloud Platform.",
            step2: "Activer 'Indexing API' et 'Search Console API'.",
            step3: "Ajouter l'email du JSON comme Propriétaire dans Search Console.",
            video_tuto: "📹 Tutoriel Vidéo",
            dashboard_title: "Instant Indexing",
            credits_label: "Crédits",
            support_btn: "🆘 Support",
            config_btn: "⚙️ Config",
            logout_btn: "Déconnexion",
            articles_label: "Articles",
            last_7_days: "7 derniers jours",
            last_30_days: "30 derniers jours",
            all_time: "Tout",
            check_status: "⚡ Vérifier Status",
            stop_btn: "⏹ Stop",
            index_google: "🚀 Index Google",
            index_premium: "💎 Index Premium",
            select_global: "Sélectionner les",
            clear_selection: "Annuler",
            col_article: "Article / URL",
            col_date: "Date Modif",
            col_status: "Statut GSC",
            col_actions: "Actions",
            loading: "Chargement...",
            no_urls: "Aucune URL trouvée pour cette période.",
            status_unknown: "Inconnu",
            status_scan: "Scan...",
            status_waiting: "⏳ En attente",
            status_indexed: "✅ Indexée",
            status_not_indexed: "❌ Non Indexée",
            status_error: "Erreur",
            alert_invalid_key: "Clé invalide",
            alert_confirm_free: "En version gratuite, l'indexation est manuelle et limitée. Continuer ?",
            alert_premium_only: "Fonctionnalité Premium uniquement.",
            alert_no_selection: "Aucun élément à scanner.",
            confirm_scan: "Lancer la vérification de {n} URLs ? Cela peut prendre du temps.",
            scan_complete: "⚡ Vérification Terminée",
            confirm_bulk: "Lancer {type} pour {n} URLs (Non Indexées) ?",
            bulk_google: "l'indexation Google",
            bulk_premium: "l'indexation Premium",
            auto_index_title: "Auto Indexation",
            auto_index_desc: "Envoyer automatiquement les nouveaux articles lors de la publication.",
            auto_mode_disabled: "Désactivé",
            auto_mode_google: "API Google (Gratuit)",
            auto_mode_premium: "Premium Force",
            tooltip_scan: "Vérifie si vos pages sont indexées sur Google.",
            tooltip_google: "Envoie une demande d'indexation standard à Google.",
            tooltip_premium: "Force l'indexation même sur les pages récalcitrantes.",
            scan_summary: "Résultat du Scan :\n✅ Déjà Indexées : {indexed}\n❌ Non Indexées : {not_indexed}\n⏳ En attente : {waiting}\n⚠️ Erreurs : {error}",
            lang_label: "Langue",
            lang_fr: "Français",
            lang_label: "Langue",
            lang_fr: "Français",
            lang_en: "Anglais",
            upsell_title: "Débloquez la Puissance Premium 🚀",
            upsell_desc: "Automatisez l'indexation, forcez le crawl des pages récalcitrantes et gagnez du temps.",
            upsell_btn: "Passer Premium",
            premium_locked: "Premium (Verrouillé)",
            tooltip_locked: "Disponible uniquement dans la version Premium.",
            credits_only_title: "⚡ Vous avez des crédits en attente !",
            credits_only_desc: "Vous avez <strong>{credits} crédits</strong> sur votre compte, mais vous avez besoin d'un abonnement Premium actif pour les utiliser.",
            credits_only_btn: "🚀 Souscrire au Premium pour débloquer vos crédits",
            credits_only_sub: "Vos crédits seront immédiatement disponibles après l'activation Premium.",
            alert_invalid_key_short: "Clé invalide",
            btn_activating: "Activation...",
            alert_server_error: "Erreur serveur",
            btn_config_loading: "Configuration...",
            btn_back_dashboard: "Retour Dashboard",
            alert_invalid_json: "JSON invalide",
            btn_saving: "Sauvegarde...",
            confirm_logout: "Se déconnecter ?",
            btn_stop_loading: "Arrêt...",
            loading_error: "Erreur de chargement.",
            network_error: "Erreur réseau.",
            showing_range: "Affichage {start}-{end} sur {total}",
            alert_deselect_global: "Désélectionner un élément annule la sélection globale.",
            selection_page_msg: "Les <b>{n}</b> articles de cette page sont sélectionnés.",
            selection_global_msg: "Les <b>{n}</b> articles sont sélectionnés.",
            status_pending: "Initialisation...",
            status_scan_url: "Scan: {url}",
            tooltip_no_unindexed: "Aucune URL 'Non Indexée' trouvée. Lancez d'abord une vérification.",
            tooltip_force_google: "Forcer Index (Google Std)",
            tooltip_force_premium: "Forcer Index (Premium)",
            tooltip_check_google: "Vérifier sur Google",
            btn_prev: "« Précédent",
            btn_next: "Suivant »"
        },
        en: {
            welcome_title: "Welcome to Instant Indexing",
            welcome_subtitle: "Boost your SEO by indexing your content instantly on Google.",
            enter_license: "Enter your license key...",
            activate_btn: "Activate License",
            free_btn: "Continue with Free Version",
            premium_offer: "💎 View Premium Offers",
            config_title: "Google API Configuration",
            json_label: "1. JSON Key (Service Account)",
            json_desc: "Content of the JSON file downloaded from Google Cloud Console.",
            gsc_label: "2. Search Console Property URL",
            gsc_desc: "Must match exactly the property in GSC.",
            save_btn: "💾 Save Configuration",
            tuto_title: "Installation Tutorial",
            tuto_intro: "Follow these steps to configure Google Indexing API:",
            step1: "Create a Service Account on Google Cloud Platform.",
            step2: "Enable 'Indexing API' and 'Search Console API'.",
            step3: "Add the JSON email as Owner in Search Console.",
            video_tuto: "📹 Video Tutorial",
            dashboard_title: "Instant Indexing",
            credits_label: "Credits",
            support_btn: "🆘 Support",
            config_btn: "⚙️ Settings",
            logout_btn: "Logout",
            articles_label: "Articles",
            last_7_days: "Last 7 days",
            last_30_days: "Last 30 days",
            all_time: "All time",
            check_status: "⚡ Check Status",
            stop_btn: "⏹ Stop",
            index_google: "🚀 Index Google",
            index_premium: "💎 Index Premium",
            select_global: "Select all",
            clear_selection: "Cancel",
            col_article: "Article / URL",
            col_date: "Date Modif",
            col_status: "GSC Status",
            col_actions: "Actions",
            loading: "Loading...",
            no_urls: "No URLs found for this period.",
            status_unknown: "Unknown",
            status_scan: "Scanning...",
            status_waiting: "⏳ Waiting",
            status_indexed: "✅ Indexed",
            status_not_indexed: "❌ Not Indexed",
            status_error: "Error",
            alert_invalid_key: "Invalid key",
            alert_confirm_free: "In free version, indexing is manual and limited. Continue?",
            alert_premium_only: "Premium feature only.",
            alert_no_selection: "No items to scan.",
            confirm_scan: "Start verification for {n} URLs? This may take some time.",
            scan_complete: "⚡ Verification Complete",
            confirm_bulk: "Start {type} for {n} URLs (Not Indexed)?",
            bulk_google: "Google indexing",
            bulk_premium: "Premium indexing",
            auto_index_title: "Auto Indexing",
            auto_index_desc: "Automatically send new posts upon publication.",
            auto_mode_disabled: "Disabled",
            auto_mode_google: "Google API (Free)",
            auto_mode_premium: "Premium Force",
            tooltip_scan: "Checks if your pages are indexed on Google.",
            tooltip_google: "Standard Indexing (Low success rate ~10%).",
            tooltip_premium: "Premium Force Indexing (Success rate > 90%).",
            scan_summary: "Scan Results:\n✅ Already Indexed: {indexed}\n❌ Not Indexed: {not_indexed}\n⏳ Waiting: {waiting}\n⚠️ Errors: {error}",
            lang_label: "Language",
            lang_fr: "French",
            lang_en: "English",
            upsell_title: "Unlock Premium Power 🚀",
            upsell_desc: "Automate indexing, compel stubborn pages to crawl, and save time.",
            upsell_btn: "Go Premium",
            premium_locked: "Premium (Locked)",
            tooltip_locked: "Available only in Premium version.",
            credits_only_title: "⚡ You have pending credits!",
            credits_only_desc: "You have <strong>{credits} credits</strong> on your account, but you need an active Premium subscription to use them.",
            credits_only_btn: "🚀 Subscribe to Premium to unlock your credits",
            credits_only_sub: "Your credits will be immediately available after Premium activation.",
            alert_invalid_key_short: "Invalid key",
            btn_activating: "Activating...",
            alert_server_error: "Server error",
            btn_config_loading: "Configuring...",
            btn_back_dashboard: "Back to Dashboard",
            alert_invalid_json: "Invalid JSON",
            btn_saving: "Saving...",
            confirm_logout: "Log out?",
            btn_stop_loading: "Stopping...",
            loading_error: "Loading error.",
            network_error: "Network error.",
            showing_range: "Showing {start}-{end} of {total}",
            alert_deselect_global: "Deselecting an item cancels the global selection.",
            selection_page_msg: "The <b>{n}</b> articles on this page are selected.",
            selection_global_msg: "<b>{n}</b> articles are selected.",
            status_pending: "Initializing...",
            status_scan_url: "Scanning: {url}",
            tooltip_no_unindexed: "No 'Not Indexed' URLs found. Run a check first.",
            tooltip_force_google: "Force Index (Google Std)",
            tooltip_force_premium: "Force Index (Premium)",
            tooltip_check_google: "Check on Google",
            btn_prev: "« Previous",
            btn_next: "Next »"
        }
    };

    function t(key, params = {}) {
        let str = I18N[state.lang][key] || key;
        for (const k in params) {
            str = str.replace(`{${k}}`, params[k]);
        }
        return str;
    }

    // --- ROUTER ---
    if (!config.status || config.status === 'credits_only') { renderWelcome(); }
    else if (!config.hasKey) { renderSetup(false); }
    else { initDashboard(); }

    // --- 1. WELCOME ---
    function renderWelcome() {
        const isCreditsOnly = (config.status === 'credits_only');
        const creditsCount = config.credits || 0;

        // Credits-only upgrade banner
        let creditsOnlyBanner = '';
        if (isCreditsOnly && creditsCount > 0) {
            creditsOnlyBanner = `
                <div style="background: linear-gradient(135deg, rgba(245,158,11,0.12), rgba(234,88,12,0.12)); border: 2px solid rgba(245,158,11,0.5); border-radius: 16px; padding: 28px; margin-bottom: 28px; text-align: center;">
                    <div style="font-size: 40px; margin-bottom: 12px;">⚡</div>
                    <h2 style="font-size: 20px; font-weight: 700; color: #f59e0b; margin: 0 0 10px 0;">${t('credits_only_title')}</h2>
                    <p style="color: var(--text-main); font-size: 15px; margin: 0 0 20px 0;">${t('credits_only_desc', { credits: creditsCount })}</p>
                    <a href="https://checkout.dodopayments.com/buy/pdt_0NXM7BHApQeBfB5nMPD8r?quantity=1" target="_blank" class="sip-btn primary" style="width: 100%; height: 52px; font-size: 16px; display: flex; align-items: center; justify-content: center; text-decoration: none; margin-bottom: 12px; background: linear-gradient(135deg, #f59e0b, #ea580c); border: none;">${t('credits_only_btn')}</a>
                    <p style="color: var(--text-muted); font-size: 12px; margin: 0;">${t('credits_only_sub')}</p>
                </div>
            `;
        }

        root.innerHTML = `
            <div class="sip-welcome-container">
                <div class="sip-welcome-card sip-card">
                    <img src="${config.pluginUrl}logo.png" class="sip-welcome-icon">
                    <h1 style="font-size:24px; font-weight:700; margin-bottom:12px;">${t('welcome_title')}</h1>
                    <p style="color:var(--text-muted); margin-bottom:32px;">${t('welcome_subtitle')}</p>
                    
                    ${creditsOnlyBanner}

                    <div style="margin-bottom:24px;">
                        <input type="text" id="licence-input" class="sip-input" placeholder="${t('enter_license')}" style="text-align:center; font-family:monospace; font-size:16px;">
                    </div>
                    
                    <button id="btn-activate" class="sip-btn primary" style="width:100%; height:48px; font-size:16px; margin-bottom:16px;">${t('activate_btn')}</button>
                    
                    <button id="btn-free" class="sip-btn ghost" style="font-size:13px;">${t('free_btn')}</button>

                    <div style="margin-top:32px; padding-top:24px; border-top:1px solid var(--border);">
                        <a href="${config.salesUrl}" target="_blank" style="text-decoration:none; color:var(--primary); font-weight:600; font-size:14px;">${t('premium_offer')}</a>
                    </div>
                </div>
            </div>
        `;

        document.getElementById('btn-activate').addEventListener('click', async () => {
            const k = document.getElementById('licence-input').value.trim();
            if (k.length < 5) return alert(t('alert_invalid_key_short'));
            const btn = document.getElementById('btn-activate'); btn.innerText = t('btn_activating'); btn.disabled = true;

            const fd = new FormData(); fd.append('action', 'iic_check_activate_license'); fd.append('nonce', config.nonce); fd.append('key', k);
            try {
                const r = await fetch(config.ajaxUrl, { method: 'POST', body: fd });
                const j = await r.json();
                if (j.success) window.location.reload();
                else { alert(j.data.msg); btn.innerText = t('activate_btn'); btn.disabled = false; }
            } catch (e) { alert(t('alert_server_error')); btn.disabled = false; }
        });

        document.getElementById('btn-free').addEventListener('click', async () => {
            if (!confirm(t('alert_confirm_free'))) return;
            const btn = document.getElementById('btn-free'); btn.innerText = t('btn_config_loading');
            const fd = new FormData(); fd.append('action', 'iic_check_go_free'); fd.append('nonce', config.nonce);
            await fetch(config.ajaxUrl, { method: 'POST', body: fd });
            window.location.reload();
        });
    }

    // --- 2. CONFIG ---
    function renderSetup(isEdit) {
        root.innerHTML = `
            <div class="sip-card" style="max-width:900px; margin:0 auto;">
                <div class="sip-header" style="margin-bottom:24px;">
                    <div class="sip-title"><h1>${t('config_title')}</h1></div>
                    ${isEdit ? `<button id="btn-back" class="sip-btn secondary">${t('btn_back_dashboard')}</button>` : ''}
                </div>
                
                <div style="display:grid; grid-template-columns: 1fr 1fr; gap:32px;">
                    <div>
                        <div style="margin-bottom:24px;">
                            <label style="display:block; font-weight:600; margin-bottom:8px;">${t('json_label')}</label>
                            <textarea id="json-input" class="sip-input" placeholder='{"type": "service_account"...}' style="height:120px; font-family:monospace;"></textarea>
                            <p class="text-sm" style="color:var(--text-muted); margin-top:6px;">${t('json_desc')}</p>
                        </div>
                        <div style="margin-bottom:24px;">
                            <label style="display:block; font-weight:600; margin-bottom:8px;">${t('gsc_label')}</label>
                            <input type="text" id="gsc-url-input" class="sip-input" value="${config.siteUrl}/">
                            <p class="text-sm" style="color:var(--text-muted); margin-top:6px;">${t('gsc_desc')}</p>
                        </div>

                            <p class="text-sm" style="color:var(--text-muted); margin-top:6px;">${t('gsc_desc')}</p>
                        </div>

                        <div style="margin-bottom:24px; padding-top:24px; border-top:1px solid #eee;">
                            <label style="display:block; font-weight:600; margin-bottom:8px;">${t('lang_label')}</label>
                            <select id="lang-select" class="sip-input">
                                <option value="fr_FR" ${(config.locale.startsWith('fr') ? 'selected' : '')}>${t('lang_fr')}</option>
                                <option value="en_US" ${(config.locale.startsWith('en') ? 'selected' : '')}>${t('lang_en')}</option>
                            </select>
                        </div>

                        <button id="btn-save" class="sip-btn primary" style="width:100%;">${t('save_btn')}</button>
                    </div>

                    <div>
                        <div style="background:#f8fafc; padding:20px; border-radius:12px; border:1px solid #e2e8f0;">
                            <h3 style="margin-top:0; font-size:16px;">${t('tuto_title')}</h3>
                            <p class="text-sm" style="color:var(--text-muted);">${t('tuto_intro')}</p>
                            <ol class="text-sm" style="padding-left:20px; margin-top:16px; color:var(--text-muted);">
                                <li>${t('step1')}</li>
                                <li>${t('step2')}</li>
                                <li>${t('step3')}</li>
                            </ol>
                        </div>
                    </div>
                </div>

            </div>

            <div class="sip-card" style="max-width:900px; margin:24px auto; text-align:center;">
                <h3 style="margin-bottom:16px; font-size:18px;">${t('video_tuto')}</h3>
                <div style="display:flex; justify-content:center;">
                    <blockquote class="twitter-tweet">
                        <a href="https://twitter.com/ArthurseoFr/status/2015874223441391996"></a>
                    </blockquote>
                </div>
            </div>
        `;

        if (window.twttr && window.twttr.widgets) {
            window.twttr.widgets.load();
        } else {
            const script = document.createElement('script');
            script.src = "https://platform.twitter.com/widgets.js";
            script.async = true;
            document.head.appendChild(script);
        }

        document.getElementById('btn-save').addEventListener('click', saveKey);
        if (isEdit) document.getElementById('btn-back').addEventListener('click', () => { initDashboard(); });
    }

    async function saveKey() {
        const json = document.getElementById('json-input').value;
        const gsc = document.getElementById('gsc-url-input').value;
        const lang = document.getElementById('lang-select').value;

        if (json.length < 10) return alert(t('alert_invalid_json'));

        const btn = document.getElementById('btn-save'); btn.innerText = t('btn_saving'); btn.disabled = true;

        // Save Language
        const fd2 = new FormData(); fd2.append('action', 'iic_check_save_sys_config'); fd2.append('nonce', config.nonce); fd2.append('locale', lang);
        await fetch(config.ajaxUrl, { method: 'POST', body: fd2 });

        // Save Keys
        const fd = new FormData(); fd.append('action', 'iic_check_save_key'); fd.append('nonce', config.nonce);
        fd.append('json_key', json); fd.append('gsc_url', gsc);
        await fetch(config.ajaxUrl, { method: 'POST', body: fd });

        window.location.reload();
    }

    // --- 3. DASHBOARD INIT ---
    function initDashboard() {
        renderDashboardStructure();
        fetchUrls(); // Load initial data
        refreshLogs();
    }

    function renderDashboardStructure() {
        const isPrem = (config.status === 'premium');
        const badgeClass = isPrem ? 'premium' : 'free';
        const badgeLabel = isPrem ? 'PREMIUM' : 'GRATUIT';

        // Conditional Logic for Free vs Premium UI
        const premiumOptionText = isPrem ? t('auto_mode_premium') : t('premium_locked');

        // Upsell Banner
        let upsellHtml = '';
        if (!isPrem) {
            upsellHtml = `
                <div class="sip-banner-upsell">
                    <div>
                        <h3>${t('upsell_title')}</h3>
                        <p>${t('upsell_desc')}</p>
                    </div>
                    <a href="${config.salesUrl}" target="_blank" class="sip-banner-btn">${t('upsell_btn')}</a>
                </div>
            `;
        }

        root.innerHTML = `
            <div class="sip-header">
                <div class="sip-title">
                    <h1>${t('dashboard_title')}</h1>
                    <span class="sip-badge-status ${badgeClass}">${badgeLabel}</span>
                </div>
                <div class="sip-header-actions">
                    ${!isPrem ? `<a href="${config.salesUrl}" target="_blank" class="sip-btn primary">🚀 ${t('upsell_btn')}</a>` : ''}
                    <a href="https://x.com/ArthurseoFr" target="_blank" class="sip-btn secondary" style="border-radius:20px;">Support</a>
                    <button id="btn-config" class="sip-btn secondary">${t('config_btn')}</button>
                    <button id="btn-logout" class="sip-btn ghost">${t('logout_btn')}</button>
                </div>
            </div>

            ${upsellHtml}

            <!-- Status Bar (Auto Index & Credits) -->
            <div class="sip-card" style="display:flex; align-items:center; justify-content:space-between; padding:16px 24px; background:#f8fafc; border:1px solid #e2e8f0; margin-bottom:24px;">
                <div style="display:flex; align-items:center; gap:16px;">
                    <div style="font-weight:600; font-size:14px; color:var(--text-main);">${t('auto_index_title')}</div>
                    <div style="display:flex; align-items:center;">
                        <select id="dash-auto-mode" class="sip-input" style="width:auto; padding:6px 12px; font-weight:500; border-color:${config.autoMode !== 'disabled' ? 'var(--primary)' : 'var(--border)'};">
                            <option value="disabled" ${config.autoMode === 'disabled' ? 'selected' : ''}>${t('auto_mode_disabled')}</option>
                            <option value="google" ${config.autoMode === 'google' ? 'selected' : ''}>${t('auto_mode_google')}</option>
                            <option value="premium" ${config.autoMode === 'premium' ? 'selected' : ''} ${!isPrem ? 'disabled' : ''}>${premiumOptionText}</option>
                        </select>
                        <span style="cursor:help; font-size:14px; margin-left:8px; color:var(--text-muted);" title="${t('auto_index_desc')}">?</span>
                    </div>
                </div>

                ${isPrem ? `
                <div style="display:flex; align-items:center; gap:12px;">
                     <div style="text-align:right;">
                        <div style="font-size:11px; font-weight:600; color:var(--text-muted); text-transform:uppercase; letter-spacing:0.5px;">${t('credits_label')}</div>
                        <div id="sip-credits-display" style="font-size:16px; font-weight:700; color:var(--primary);">${config.credits}</div>
                     </div>
                     <a href="${config.salesUrl}" target="_blank" class="sip-btn secondary" style="padding:4px 8px; height:32px;">+</a>
                </div>` : ''}
            </div>

            <!-- Stats & Filters -->
            <div class="sip-card" style="padding:0; overflow:hidden;">
                <div class="sip-filters-bar">
                    <div style="font-weight:600; margin-right:12px;">${t('articles_label')}</div>
                    <select id="filter-date" class="sip-input" style="width:auto; padding:6px 12px;">
                        <option value="7days">${t('last_7_days')}</option>
                        <option value="30days" selected>${t('last_30_days')}</option>
                        <option value="all">${t('all_time')}</option>
                    </select>
                    
                    <div class="flex-spacer"></div>

                    <div style="display:flex; gap:8px; align-items:center;">
                        <button id="btn-scan" class="sip-btn secondary" disabled>${t('check_status')}</button>
                        <span style="cursor:help; font-size:11px; margin-right:4px;" title="${t('tooltip_scan')}">?</span>
                        <button id="btn-stop" class="sip-btn ghost" style="display:none; color:#ef4444; border-color:#ef4444;">${t('stop_btn')}</button>
                        
                        <div style="height:32px; width:1px; background:#e2e8f0; margin:0 4px;"></div>
                        
                        <button id="btn-bulk-google" class="sip-btn secondary" disabled>${t('index_google')}</button>
                        <span style="cursor:help; font-size:11px; margin-right:4px;" title="${t('tooltip_google')}">?</span>

                        <button id="btn-bulk-premium" class="sip-btn primary ${!isPrem ? 'btn-locked' : ''}" disabled>
                            ${t('index_premium')}
                        </button>
                        <span style="cursor:help; font-size:11px; margin-right:4px;" title="${isPrem ? t('tooltip_premium') : t('tooltip_locked')}">?</span>
                    </div>
                </div>
                
                <!-- Progress Bar -->
                <div id="scan-progress-container" style="display:none; background:#f8fafc; padding:12px 24px; border-bottom:1px solid #e2e8f0;">
                    <div style="background:#e2e8f0; border-radius:4px; overflow:hidden; height:8px;">
                        <div id="scan-progress-bar" style="width:0%; background:var(--primary); height:100%; transition:width 0.2s;"></div>
                    </div>
                    <div style="display:flex; justify-content:space-between; margin-top:4px; font-size:12px; color:var(--text-muted);">
                        <span id="scan-progress-text">0/0</span>
                        <span id="scan-status-text">${t('status_pending')}</span>
                    </div>
                </div>

                <div id="selection-banner" class="sip-selection-banner">
                    <span id="selection-msg"></span>
                    <span id="btn-select-all-global" class="sip-selection-action">${t('select_global')} <span id="total-global-count">0</span> URLs ?</span>
                    <span id="btn-clear-selection" class="sip-selection-action" style="color:#ef4444;">${t('clear_selection')}</span>
                </div>

                <div class="sip-table-container">
                    <table class="sip-table">
                        <thead>
                            <tr>
                                <th class="sip-cell-check"><input type="checkbox" id="check-all-page" class="sip-checkbox"></th>
                                <th>${t('col_article')}</th>
                                <th>${t('col_date')}</th>
                                <th>${t('col_status')}</th>
                                <th>${t('col_actions')}</th>
                            </tr>
                        </thead>
                        <tbody id="tb">
                            <tr><td colspan="5" class="text-center" style="padding:40px;">${t('loading')}</td></tr>
                        </tbody>
                    </table>
                </div>

                <!-- Footer Pagination -->
                <div class="sip-pagination">
                    <div class="sip-pagination-info"><span id="showing-range">0-0</span> <span id="total-items">0</span></div>
                    <div class="sip-pagination-controls">
                        <button id="btn-prev" class="sip-btn secondary" disabled>${t('btn_prev')}</button>
                        <div id="pagination-pages" class="sip-pagination-pages"></div>
                        <button id="btn-next" class="sip-btn secondary" disabled>${t('btn_next')}</button>
                    </div>
                </div>
            </div>

            <div class="sip-logs" id="logs-content"></div>
        `;

        // Event Listeners
        document.getElementById('btn-config').addEventListener('click', () => renderSetup(true));
        document.getElementById('dash-auto-mode').addEventListener('change', async (e) => {
            const mode = e.target.value;
            const fd = new FormData(); fd.append('action', 'iic_check_save_auto_mode'); fd.append('nonce', config.nonce); fd.append('mode', mode);
            await fetch(config.ajaxUrl, { method: 'POST', body: fd });
            // Optional: flash success or toast
        });
        document.getElementById('btn-logout').addEventListener('click', () => {
            if (confirm(t('confirm_logout'))) fetch(config.ajaxUrl, { method: 'POST', body: new URLSearchParams({ action: 'iic_check_logout', nonce: config.nonce }) }).then(() => window.location.reload());
        });

        document.getElementById('filter-date').addEventListener('change', (e) => { state.filter = e.target.value; state.page = 1; fetchUrls(); });
        document.getElementById('btn-prev').addEventListener('click', () => { if (state.page > 1) { state.page--; fetchUrls(); } });
        document.getElementById('btn-next').addEventListener('click', () => { if (state.page < state.totalPages) { state.page++; fetchUrls(); } });
        document.getElementById('pagination-pages').addEventListener('click', (e) => {
            const btn = e.target.closest('[data-page]');
            if (!btn) return;
            const p = parseInt(btn.dataset.page);
            if (p !== state.page) { state.page = p; fetchUrls(); }
        });

        // Selection Logic
        document.getElementById('check-all-page').addEventListener('change', toggleSelectPage);
        document.getElementById('btn-select-all-global').addEventListener('click', selectAllGlobal);
        document.getElementById('btn-clear-selection').addEventListener('click', clearSelection);

        // Actions
        document.getElementById('btn-scan').addEventListener('click', startScan);
        document.getElementById('btn-stop').addEventListener('click', () => {
            state.stopRequested = true;
            document.getElementById('btn-stop').innerText = t('btn_stop_loading');
        });
        document.getElementById('btn-bulk-google').addEventListener('click', () => startBulk('google'));
        document.getElementById('btn-bulk-premium').addEventListener('click', () => startBulk('premium'));

        // Row Actions Delegation
        document.getElementById('tb').addEventListener('click', handleRowAction);
        
        // Auto-refresh credits when tab regains focus (e.g. after purchase)
        document.addEventListener('visibilitychange', () => {
            if (document.visibilityState === 'visible') {
                syncCredits();
            }
        });
    }
    
    // --- CREDITS SYNCHRONIZATION ---
    async function syncCredits() {
        if (!config.hasKey) return;
        try {
            const url = `${config.ajaxUrl}?action=iic_check_get_credits&nonce=${config.nonce}&t=${Date.now()}`;
            const r = await fetch(url);
            const j = await r.json();
            if (j.success && j.data) {
                config.credits = j.data.credits;
                const creditsDisplay = document.getElementById('sip-credits-display');
                if (creditsDisplay) {
                    creditsDisplay.innerText = config.credits;
                }
                
                // If they were credits_only and just bought premium, we could reload, but for MVP just updating credits is good
                if (j.data.status === 'premium' && config.status !== 'premium') {
                    window.location.reload(); // Force refresh to unlock premium UI if status upgraded
                }
            }
        } catch (e) {
            console.error('Failed to sync credits');
        }
    }

    // --- DATA LOADING ---
    async function fetchUrls() {
        const tbody = document.getElementById('tb');
        tbody.innerHTML = `<tr><td colspan="5" class="text-center" style="color:var(--text-muted);">${t('loading')}</td></tr>`;

        // Reset selection if mode is page only (UX choice) - actually keeping global selection across pages is complex, let's reset for simplicity first unless global mode
        if (state.selectionMode === 'page') clearSelection();

        try {
            // Fix: Use 'paged' instead of 'page' to match WP/PHP expectation, add timestamp to prevent caching
            const url = `${config.ajaxUrl}?action=iic_check_fetch_urls&nonce=${config.nonce}&filter=${state.filter}&paged=${state.page}&limit=${state.limit}&t=${Date.now()}`;
            const r = await fetch(url);
            const j = await r.json(); // Expected: { success:true, data: { items:[], total:100, pages:5 } }

            // Compatibility check: fetchUrls returns direct array in old version? 
            // We updated PHP to return { items: ..., total: ... } inside wp_send_json_success => data.items

            if (j.success && j.data.items) {
                state.urls = j.data.items.map(u => ({
                    ...u,
                    status: state.checkedCache[u.id] || u.saved_status || 'unknown'
                }));
                state.total = j.data.total;
                state.totalPages = j.data.pages;

                // Populate checkedCache with resolved statuses so they persist across page navigation
                state.urls.forEach(u => {
                    if (u.status && u.status !== 'unknown') {
                        state.checkedCache[u.id] = u.status;
                    }
                });

                renderTable();
                updatePaginationControls();
            } else {
                tbody.innerHTML = `<tr><td colspan="5" class="text-center">${t('loading_error')}</td></tr>`;
            }
        } catch (e) { console.error(e); tbody.innerHTML = `<tr><td colspan="5" class="text-center">${t('network_error')}</td></tr>`; }
    }

    function renderTable() {
        const tbody = document.getElementById('tb');
        if (state.urls.length === 0) {
            tbody.innerHTML = `<tr><td colspan="5" class="text-center" style="padding:40px;">${t('no_urls')}</td></tr>`;
            return;
        }

        tbody.innerHTML = state.urls.map(u => {
            const isSelected = state.selectionMode === 'all' || state.selection.has(u.id);
            const statusHtml = getStatusBadge(u);
            const actionsHtml = getActionsHtml(u);
            const safeTitle = escapeHtml(u.title);

            return `
                <tr id="row-${u.id}" class="${isSelected ? 'selected' : ''}">
                    <td class="sip-cell-check">
                        <input type="checkbox" class="sip-checkbox row-check" data-id="${u.id}" ${isSelected ? 'checked' : ''}>
                    </td>
                    <td>
                        <div class="sip-url-col">
                            <span class="sip-url-title">${safeTitle}</span>
                            <a href="${u.url}" target="_blank" class="sip-url-link">${u.url}</a>
                        </div>
                    </td>
                    <td class="text-sm" style="color:var(--text-muted);">${u.date}</td>
                    <td>${statusHtml}</td>
                    <td>${actionsHtml}</td>
                </tr>
            `;
        }).join('');

        // Re-attach check listeners
        document.querySelectorAll('.row-check').forEach(cb => {
            cb.addEventListener('change', (e) => {
                toggleRowSelection(parseInt(e.target.dataset.id), e.target.checked);
            });
        });

        // Update master checkbox state
        const allChecked = state.urls.length > 0 && state.urls.every(u => state.selection.has(u.id));
        document.getElementById('check-all-page').checked = allChecked || state.selectionMode === 'all';
    }

    function escapeHtml(text) {
        if (!text) return text;
        return text
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    function getStatusBadge(u) {
        if (u.status === 'unknown') return `<span class="status-badge pending">${t('status_unknown')}</span>`;
        if (u.status === 'checking') return `<span class="status-badge scanning">${t('status_scan')}</span>`;
        if (u.status === 'waiting') return `<span class="status-badge waiting">${t('status_waiting')}</span>`;
        if (u.status === 'indexed') return `<span class="status-badge indexed">${t('status_indexed')}</span>`;
        if (u.status === 'not_indexed') return `<span class="status-badge not-indexed">${t('status_not_indexed')}</span>`;
        if (u.status === 'error') return `<span class="status-badge waiting" ${u.error_msg ? `title="${escapeHtml(u.error_msg)}"` : ''}>${t('status_error')}</span>`;
        return '';
    }

    function getActionsHtml(u) {
        const gscLink = `https://www.google.com/search?q=site:${encodeURIComponent(u.url)}`;

        // Show Google/Premium buttons if NOT indexed (or unknown)
        if (u.status !== 'indexed') {
            const isWaiting = (u.status === 'waiting');
            const disabledAttr = isWaiting ? 'disabled style="opacity:0.5; cursor:not-allowed;"' : '';

            const isPrem = (config.status === 'premium');
            const premClass = isPrem ? 'btn-action-premium' : 'btn-action-premium btn-locked';
            const premTitle = isPrem ? t('tooltip_force_premium') : t('tooltip_locked');

            return `
                <div class="action-group">
                    <button class="btn-icon btn-action-google" data-id="${u.id}" title="${t('tooltip_force_google')}" ${disabledAttr}>🚀</button>
                    <button class="btn-icon ${premClass}" data-id="${u.id}" title="${premTitle}" ${disabledAttr}>💎</button>
                    <a href="${gscLink}" target="_blank" class="btn-icon" title="${t('tooltip_check_google')}">🔍</a>
                </div>
            `;
        }

        // If already indexed, just show check link
        return `
            <div class="action-group">
                <a href="${gscLink}" target="_blank" class="btn-icon" title="${t('tooltip_check_google')}">🔍</a>
            </div>
        `;
    }

    function updatePaginationControls() {
        const startR = state.urls.length > 0 ? (state.page - 1) * state.limit + 1 : 0;
        const endR = (state.page - 1) * state.limit + state.urls.length;
        document.getElementById('showing-range').innerText = t('showing_range', {start: startR, end: endR, total: state.total});
        document.getElementById('total-items').style.display = 'none'; // Replaced by the template above, hide the old element just in case

        document.getElementById('btn-prev').disabled = state.page <= 1;
        document.getElementById('btn-next').disabled = state.page >= state.totalPages;

        // Build numbered page buttons
        const pagesContainer = document.getElementById('pagination-pages');
        if (!pagesContainer) return;
        const tp = state.totalPages;
        const cp = state.page;

        if (tp <= 1) { pagesContainer.innerHTML = ''; return; }

        // Determine which page numbers to show
        const pages = [];
        const delta = 2; // pages around current

        // Always show page 1
        pages.push(1);

        // Range around current page
        const rangeStart = Math.max(2, cp - delta);
        const rangeEnd = Math.min(tp - 1, cp + delta);

        if (rangeStart > 2) pages.push('...');
        for (let i = rangeStart; i <= rangeEnd; i++) pages.push(i);
        if (rangeEnd < tp - 1) pages.push('...');

        // Always show last page
        if (tp > 1) pages.push(tp);

        pagesContainer.innerHTML = pages.map(p => {
            if (p === '...') return '<span class="sip-pagination-ellipsis">…</span>';
            const active = (p === cp) ? ' active' : '';
            return `<button class="sip-pagination-page${active}" data-page="${p}">${p}</button>`;
        }).join('');
    }

    // --- SELECTION LOGIC ---
    function toggleRowSelection(id, checked) {
        if (state.selectionMode === 'all') {
            alert(t('alert_deselect_global'));
            clearSelection();
            return;
        }

        if (checked) state.selection.add(id); else state.selection.delete(id);
        updateSelectionUI();
    }

    function toggleSelectPage(e) {
        const checked = e.target.checked;
        if (checked) {
            state.urls.forEach(u => state.selection.add(u.id));
            state.selectionMode = 'page';

            // Show banner if total > page
            if (state.total > state.urls.length) {
                document.getElementById('selection-banner').style.display = 'block';
                document.getElementById('selection-msg').innerHTML = t('selection_page_msg', {n: state.urls.length});
                document.getElementById('total-global-count').innerText = state.total;
                document.getElementById('btn-select-all-global').style.display = 'inline';
            }
        } else {
            clearSelection();
        }
        renderTable();
        updateSelectionUI(); // Updates buttons state
    }

    async function selectAllGlobal() {
        state.selectionMode = 'all';
        state.selection.clear(); // We don't track individual IDs in global mode
        document.getElementById('selection-msg').innerHTML = t('selection_global_msg', {n: state.total});
        document.getElementById('btn-select-all-global').style.display = 'none';
        renderTable();

        // Fetch all URLs to populate checkedCache with their saved_status
        try {
            const url = `${config.ajaxUrl}?action=iic_check_fetch_urls&nonce=${config.nonce}&filter=${state.filter}&paged=1&limit=999999&t=${Date.now()}`;
            const r = await fetch(url);
            const j = await r.json();
            if (j.success && j.data.items) {
                j.data.items.forEach(u => {
                    if (!state.checkedCache[u.id]) {
                        const status = u.saved_status || 'unknown';
                        if (status !== 'unknown') state.checkedCache[u.id] = status;
                    }
                });
            }
        } catch(e) { console.error('Failed to fetch all statuses:', e); }

        updateSelectionUI();
    }

    function clearSelection() {
        state.selectionMode = 'none';
        state.selection.clear();
        state.scannedResults = null; // Clear cache
        document.getElementById('selection-banner').style.display = 'none';
        document.getElementById('check-all-page').checked = false;
        renderTable();
        updateSelectionUI();
    }

    function updateSelectionUI() {
        let notIndexedCount = 0;
        let scanCount = 0;

        if (state.selectionMode === 'all') {
            scanCount = state.total;
            if (state.scannedResults) {
                // If we have scanned results, use them
                notIndexedCount = state.scannedResults.filter(u => u.status === 'not_indexed').length;
            } else {
                // Count from current page URLs + checkedCache for known statuses
                const countedIds = new Set();
                state.urls.forEach(u => {
                    countedIds.add(u.id);
                    if (u.status === 'not_indexed') notIndexedCount++;
                });
                for (const [id, status] of Object.entries(state.checkedCache)) {
                    if (!countedIds.has(parseInt(id)) && status === 'not_indexed') notIndexedCount++;
                }
            }
        } else {
            scanCount = state.selection.size;
            notIndexedCount = state.urls.filter(u => state.selection.has(u.id) && u.status === 'not_indexed').length;
        }

        const hasSelection = (state.selectionMode === 'all' || state.selection.size > 0);

        const btnScan = document.getElementById('btn-scan');
        const btnGoogle = document.getElementById('btn-bulk-google');
        const btnPrem = document.getElementById('btn-bulk-premium');

        btnScan.disabled = !hasSelection;
        // Fix: Removed double emoji (Lightning is already in t('check_status'))
        btnScan.innerText = hasSelection ? `${t('check_status')} (${scanCount})` : t('check_status');

        const canBulk = (notIndexedCount > 0);

        btnGoogle.disabled = !canBulk;
        btnPrem.disabled = !canBulk;

        btnGoogle.innerText = `🚀 Google (${notIndexedCount})`;
        btnPrem.innerText = `💎 Premium (${notIndexedCount})`;

        if (hasSelection && notIndexedCount === 0) {
            btnGoogle.title = t('tooltip_no_unindexed');
        } else {
            btnGoogle.title = "";
        }
    }

    // --- ACTIONS ---
    function handleRowAction(e) {
        const btn = e.target.closest('button');
        if (!btn || btn.disabled) return;

        // Scan Button removed from row, but check logic anyway
        if (btn.classList.contains('btn-action-scan')) {
            const id = parseInt(btn.dataset.id);
            scanUrl(state.urls.find(u => u.id === id));
        }

        // Google Button
        if (btn.classList.contains('btn-action-google')) {
            const id = parseInt(btn.dataset.id);
            requestIndexing(state.urls.find(u => u.id === id), btn); // Updated: Pass button
        }

        // Premium Button
        if (btn.classList.contains('btn-action-premium')) {
            const id = parseInt(btn.dataset.id);
            requestPremium(state.urls.find(u => u.id === id), btn); // Updated: Pass button
        }
    }

    // --- PROCESSING LOGIC ---
    async function startScan() {
        const items = await getTargetItems();
        if (items.length === 0) return alert(t('alert_no_selection'));

        if (!confirm(t('confirm_scan', { n: items.length }))) return;

        // Cache results immediately for global mode so updates are tracked
        if (state.selectionMode === 'all') {
            state.scannedResults = items;
        }

        const btn = document.getElementById('btn-scan');
        const btnStop = document.getElementById('btn-stop');
        const progressContainer = document.getElementById('scan-progress-container');
        const progressBar = document.getElementById('scan-progress-bar');
        const progressText = document.getElementById('scan-progress-text');
        const statusText = document.getElementById('scan-status-text');

        btn.style.display = 'none';
        btnStop.style.display = 'inline-block';
        btnStop.disabled = false;
        btnStop.innerText = t('stop_btn');
        state.stopRequested = false;

        // Init Progress UI
        progressContainer.style.display = 'block';
        progressBar.style.width = '0%';
        progressText.innerText = `0/${items.length}`;

        for (let i = 0; i < items.length; i++) {
            if (state.stopRequested) {
                break;
            }

            // Update Status text
            statusText.innerText = t('status_scan_url', {url: items[i].url});

            const u = state.urls.find(row => row.id === items[i].id);
            if (u) { u.status = 'checking'; renderTable(); }

            await checkStatus(items[i]);

            // Update Progress
            const pct = Math.round(((i + 1) / items.length) * 100);
            progressBar.style.width = `${pct}%`;
            progressText.innerText = `${i + 1}/${items.length}`;

            if (u) { renderTable(); updateSelectionUI(); }
        }

        btn.style.display = 'inline-block';
        btnStop.style.display = 'none';
        progressContainer.style.display = 'none'; // Hide progress after done

        btn.innerText = t('scan_complete');
        updateSelectionUI();
        refreshLogs();
    }

    async function startBulk(type) {
        if (type === 'premium' && config.status !== 'premium') {
            if (confirm(t('tooltip_locked') + " " + t('upsell_btn') + " ?")) {
                window.open(config.salesUrl, '_blank');
            }
            return;
        }

        const allSelected = await getTargetItems();

        // FILTER: Only not_indexed (Strict match to button count)
        const items = allSelected.filter(u => u.status === 'not_indexed');

        if (items.length === 0) return alert(t('alert_no_selection'));

        const actionWords = type === 'premium' ? t('bulk_premium') : t('bulk_google');
        if (!confirm(t('confirm_bulk', { type: actionWords, n: items.length }))) return;

        const btn = document.getElementById(type === 'premium' ? 'btn-bulk-premium' : 'btn-bulk-google');
        btn.disabled = true;

        for (let i = 0; i < items.length; i++) {
            btn.innerText = `${i + 1}/${items.length}`;
            const item = items[i];

            updateItemStatus(item.id, 'waiting');

            try {
                let res;
                if (type === 'premium') {
                    res = await sendPremium(item);
                    if (res && res.success) {
                        // Update local history
                        if (!config.history) config.history = {};
                        config.history[item.url] = Date.now();
                        // Keep 'waiting' status for Premium until verified by scan
                    } else {
                        updateItemStatus(item.id, 'error', res ? (res.data ? res.data.msg : res.msg) : null);
                    }
                } else {
                    res = await sendGoogle(item);
                    if (res && res.success) updateItemStatus(item.id, 'indexed');
                    else updateItemStatus(item.id, 'error', res ? (res.data ? res.data.msg : res.msg) : null);
                }
            } catch (e) {
                updateItemStatus(item.id, 'error', e.message);
            }
        }

        btn.disabled = false;
        updateSelectionUI();
        refreshLogs();
    }

    // Helper to get ALL selected items (even those not on page if mode=all)
    async function getTargetItems() {
        if (state.selectionMode === 'all') {
            // Use cached results if available (so we keep statuses)
            if (state.scannedResults) return state.scannedResults;

            // Fetch ALL IDs from server
            const url = `${config.ajaxUrl}?action=iic_check_fetch_urls&nonce=${config.nonce}&filter=${state.filter}&paged=1&limit=999999`; // Hacky but works for MVP
            const r = await fetch(url);
            const j = await r.json();
            if (j.success) {
                // Use checkedCache > saved_status > 'unknown' (same logic as fetchUrls)
                return j.data.items.map(u => ({ ...u, status: state.checkedCache[u.id] || u.saved_status || 'unknown' }));
            }
            return [];
        } else {
            return state.urls.filter(u => state.selection.has(u.id));
        }
    }

    async function checkStatus(item) {
        const fd = new FormData(); fd.append('action', 'iic_check_check_url'); fd.append('nonce', config.nonce); fd.append('url', item.url);
        try {
            const r = await fetch(config.ajaxUrl, { method: 'POST', body: fd });
            const j = await r.json();

            const newStatus = j.success ? j.data.status : 'error';
            const errorMsg = j.success ? (j.data ? j.data.msg : null) : (j.data ? j.data.msg : j.msg);

            // SPECIAL LOGIC: If currently 'waiting' OR in history AND new status is 'not_indexed', KEEP 'waiting'
            // This prevents overwriting a Premium request that hasn't been processed by Google yet.
            const inHistory = config.history && config.history.hasOwnProperty(item.url);
            if ((item.status === 'waiting' || inHistory) && newStatus === 'not_indexed') {
                updateItemStatus(item.id, 'waiting', errorMsg);
            } else {
                updateItemStatus(item.id, newStatus, errorMsg);
            }
        } catch (e) {
            updateItemStatus(item.id, 'error', e.message);
        }
    }

    async function sendGoogle(item) {
        const fd = new FormData(); fd.append('action', 'iic_check_request_indexing'); fd.append('nonce', config.nonce); fd.append('url', item.url);
        const r = await fetch(config.ajaxUrl, { method: 'POST', body: fd });
        return await r.json();
    }

    async function sendPremium(item) {
        const fd = new FormData(); fd.append('action', 'iic_check_premium_force'); fd.append('nonce', config.nonce); fd.append('url', item.url);
        const r = await fetch(config.ajaxUrl, { method: 'POST', body: fd });
        return await r.json();
    }

    // --- INDIVIDUAL ROW REQUESTS (Added back for new buttons) ---
    async function requestIndexing(item, btn) {
        if (btn) { btn.disabled = true; }
        updateItemStatus(item.id, 'waiting');

        try {
            const res = await sendGoogle(item);
            if (res && res.success) updateItemStatus(item.id, 'indexed');
            else updateItemStatus(item.id, 'error', res ? (res.data ? res.data.msg : res.msg) : null);
        } catch (e) {
            updateItemStatus(item.id, 'error', e.message);
        }
        refreshLogs();
    }

    async function requestPremium(item, btn) {
        if (config.status !== 'premium') {
            if (confirm(t('tooltip_locked') + " " + t('upsell_btn') + " ?")) {
                window.open(config.salesUrl, '_blank');
            }
            return;
        }
        if (btn) { btn.disabled = true; }
        updateItemStatus(item.id, 'waiting');

        try {
            const res = await sendPremium(item);
            if (res && res.success) {
                // Update local history
                if (!config.history) config.history = {};
                config.history[item.url] = Date.now();
                // Keep 'waiting' status. 
            } else {
                updateItemStatus(item.id, 'error', res ? (res.data ? res.data.msg : res.msg) : null);
            }
        } catch (e) {
            updateItemStatus(item.id, 'error', e.message);
        }
        refreshLogs();
    }

    function updateItemStatus(id, status, errorMsg = null) {
        // Update persistent cache
        state.checkedCache[id] = status;

        // Update in current page view
        const visible = state.urls.find(u => u.id === id);
        if (visible) {
            visible.status = status;
            visible.saved_status = status;
            if (errorMsg) visible.error_msg = errorMsg;
        }

        // Update in global scan cache if exists
        if (state.scannedResults) {
            const cached = state.scannedResults.find(u => u.id === id);
            if (cached) {
                cached.status = status;
                cached.saved_status = status;
                if (errorMsg) cached.error_msg = errorMsg;
            }
        }

        // Trigger UI updates
        renderTable();
        updateSelectionUI();
    }

    // --- UTILS ---
    function refreshLogs() {
        fetch(`${config.ajaxUrl}?action=iic_check_get_logs&nonce=${config.nonce}`).then(r => r.json()).then(j => {
            if (j.success) {
                document.getElementById('logs-content').innerHTML = j.data.map(l => `<div class="log-item"><span class="${l.type === 'success' ? 'log-success' : 'log-error'}">${l.msg}</span> <span style="opacity:0.5;">${l.date}</span></div>`).join('');
            }
        });
    }
});