(function () {
    // Sort search table
    var sel = document.getElementById('stl-sort');
    var tbl = document.getElementById('stl-search-table');
    if (sel && tbl) {
        sel.addEventListener('change', function () {
            var rows = Array.from(tbl.querySelectorAll('tbody tr'));
            var dir = this.value;
            rows.sort(function (a, b) {
                var ia = parseInt(a.dataset.idx), ib = parseInt(b.dataset.idx);
                var ra = parseInt(a.dataset.results), rb = parseInt(b.dataset.results);
                switch (dir) {
                    case 'time-desc': return ia - ib;
                    case 'time-asc': return ib - ia;
                    case 'results-desc': return rb - ra || ia - ib;
                    case 'results-asc': return ra - rb || ia - ib;
                    default: return 0;
                }
            });
            rows.forEach(function (r) { tbl.querySelector('tbody').appendChild(r); });
        });
    }

    // Restore wizard step progress from localStorage
    try {
        var stored = localStorage.getItem('stl_wizard_seen');
        if (stored) {
            var seen = JSON.parse(stored);
            document.querySelectorAll('.stl-wizard-step').forEach(function (step) {
                var num = step.dataset.step || (Array.from(step.parentNode.children).indexOf(step) + 1);
                if (seen.indexOf(num) !== -1) {
                    step.classList.add('stl-wizard-step--done');
                    var bullet = step.querySelector('.stl-wizard-step-bullet');
                    if (bullet) bullet.textContent = '✓';
                }
            });
        }
    } catch (e) {}

    // Mark visible steps as seen
    var wizardCard = document.getElementById('stl-openai-guide');
    if (wizardCard && wizardCard.style.display !== 'none') {
        setTimeout(function () {
            try {
                var seen = [];
                document.querySelectorAll('.stl-wizard-step').forEach(function (step) {
                    seen.push(step.dataset.step || (Array.from(step.parentNode.children).indexOf(step) + 1));
                });
                localStorage.setItem('stl_wizard_seen', JSON.stringify(seen));
            } catch (e) {}
        }, 500);
    }
})();

function stlCopy(id, btn) {
    var el = document.getElementById(id);
    navigator.clipboard.writeText(el.textContent).then(function () {
        btn.classList.add('stl-copy-btn--copied');
        setTimeout(function () {
            btn.classList.remove('stl-copy-btn--copied');
        }, 1500);
    });
}

function stlCopyMCP() {
    var el = document.getElementById('stl-mcp-url');
    var btn = document.getElementById('stl-copy-mcp-btn');
    if (!el || !btn) return;
    navigator.clipboard.writeText(el.textContent.trim()).then(function () {
        btn.classList.add('stl-copy-btn--copied');
        btn.textContent = '✓ Copied';
        setTimeout(function () {
            btn.classList.remove('stl-copy-btn--copied');
            btn.textContent = '📋 Copy';
        }, 2000);
        var step2 = document.querySelector('.stl-wizard-step[data-step="2"]');
        if (step2) {
            step2.classList.add('stl-wizard-step--done');
            step2.querySelector('.stl-wizard-step-bullet').textContent = '✓';
        }
    });
}

function stlToggleWizard() {
    var card = document.getElementById('stl-openai-guide');
    var btn = document.getElementById('stl-wizard-toggle-btn');
    if (!card || !btn) return;
    if (card.style.display === 'none') {
        card.style.display = '';
        btn.classList.add('stl-wizard-toggle--active');
        card.scrollIntoView({ behavior: 'smooth', block: 'start' });
    } else {
        card.style.display = 'none';
        btn.classList.remove('stl-wizard-toggle--active');
    }
}

function stlCloseWizard() {
    var card = document.getElementById('stl-openai-guide');
    var btn = document.getElementById('stl-wizard-toggle-btn');
    if (card) card.style.display = 'none';
    if (btn) btn.classList.remove('stl-wizard-toggle--active');
}

function stlDismissWizard() {
    stlCloseWizard();
}

function stlDismissGuide() {
    stlCloseWizard();
}

// ─── AI Visibility Score: Health Scanner ─────────────────────────────

function stlScanHealth() {
    var btn = document.getElementById('stl-scan-now-btn');
    var text = document.getElementById('stl-scan-now-text');
    var spinner = document.getElementById('stl-scan-now-spinner');

    if (!btn || !text || !spinner) return;
    btn.disabled = true;
    text.style.display = 'none';
    spinner.style.display = 'inline';

    var formData = new FormData();
    formData.append('action', 'shop2llm_scan_health');
    formData.append('nonce', (window.shop2llm && window.shop2llm.nonce) || '');

    fetch(ajaxurl, {
        method: 'POST',
        body: formData
    })
    .then(function (res) { return res.json(); })
    .then(function (data) {
        if (data.success) {
            var score = Math.round(data.data.global_score);
            var totalProducts = data.data.total_products;
            var lowCount = data.data.low_score_count;
            var scannedAt = data.data.scanned_at;

            // Update score circle
            var scoreArea = document.getElementById('stl-health-score-area');
            if (scoreArea) {
                var scoreDiv = scoreArea.querySelector('.stl-health-score');
                if (scoreDiv) {
                    scoreDiv.textContent = score;
                    var sc = score >= 80 ? '#166534' : (score >= 60 ? '#92400e' : '#991b1b');
                    var sb = score >= 80 ? '#dcfce7' : (score >= 60 ? '#fef3c7' : '#fee2e2');
                    scoreDiv.style.color = sc;
                    scoreDiv.style.background = sb;
                }
            }

            // Update products scanned text
            var infoDivs = scoreArea ? scoreArea.querySelectorAll('div') : [];
            for (var i = 0; i < infoDivs.length; i++) {
                if (infoDivs[i].style.fontSize === '14px') {
                    infoDivs[i].textContent = totalProducts + ' products scanned';
                    break;
                }
            }

            // Update low count
            var lowCountEl = document.getElementById('stl-health-low-count');
            if (lowCountEl) {
                lowCountEl.textContent = lowCount + ' products below 60';
            }

            // Update scanned at
            var scannedAtEl = document.getElementById('stl-health-scanned-at');
            if (scannedAtEl) {
                scannedAtEl.textContent = 'Scanned: ' + scannedAt;
            }

            // Update warning icon in title
            var card = document.getElementById('stl-health-card');
            if (card) {
                var h2 = card.querySelector('h2');
                if (h2) {
                    var warnSpan = h2.querySelector('span[style*="color:#f97316"]');
                    if (score < 60 && globalScore > 0) {
                        // Show or keep warning
                        var warningDivs = card.querySelectorAll('div');
                        for (var j = 0; j < warningDivs.length; j++) {
                            if (warningDivs[j].style.background && warningDivs[j].style.background.indexOf('fff7ed') !== -1) {
                                warningDivs[j].style.display = '';
                            }
                        }
                    } else {
                        // Hide warning
                        if (warnSpan) warnSpan.style.display = 'none';
                        var allDivs = card.querySelectorAll('div');
                        for (var k = 0; k < allDivs.length; k++) {
                            if (allDivs[k].style.background && allDivs[k].style.background.indexOf('fff7ed') !== -1) {
                                allDivs[k].style.display = 'none';
                            }
                        }
                    }
                }
            }
        }
    })
    .catch(function () {
        // Silently handle errors
    })
    .finally(function () {
        btn.disabled = false;
        text.style.display = 'inline';
        spinner.style.display = 'none';
    });
}

function stlExportLowScoreCSV() {
    var url = ajaxurl + '?action=shop2llm_export_low_score&nonce=' + encodeURIComponent((window.shop2llm && window.shop2llm.nonce) || '') + '&threshold=60';
    window.location.href = url;
}

// ─── AI Channels: Toggle & Copy Config ────────────────────────────

function stlToggleChannel(channelId, btn) {
    if (!btn) return;
    var originalText = btn.textContent;
    btn.disabled = true;
    btn.textContent = '...';

    var formData = new FormData();
    formData.append('action', 'shop2llm_toggle_channel');
    formData.append('channel', channelId);
    formData.append('nonce', (window.shop2llm && window.shop2llm.nonce) || '');

    fetch(ajaxurl, {
        method: 'POST',
        body: formData
    })
    .then(function (res) { return res.json(); })
    .then(function (data) {
        if (data.success && data.data) {
            var newStatus = data.data.status;
            // Update button text
            btn.textContent = newStatus === 'active' ? 'Disable' : 'Enable';

            // Update status indicator
            var item = btn.closest('.stl-channel-item');
            if (item) {
                var statusEl = item.querySelector('.stl-channel-status');
                if (statusEl) {
                    statusEl.className = 'stl-channel-status';
                    if (newStatus === 'active') {
                        statusEl.classList.add('stl-status-active');
                        statusEl.textContent = '● Active';
                        statusEl.removeAttribute('title');
                    } else {
                        statusEl.classList.add('stl-status-inactive');
                        statusEl.textContent = '● Inactive';
                        statusEl.removeAttribute('title');
                    }
                }
            }
        } else {
            // Revert on failure
            btn.textContent = originalText;
        }
    })
    .catch(function () {
        btn.textContent = originalText;
    })
    .finally(function () {
        btn.disabled = false;
    });
}

function stlCopyChannelConfig(channelId, btn) {
    if (!btn) return;
    var originalText = btn.textContent;

    var url = ajaxurl + '?action=shop2llm_get_channel_config&channel=' + encodeURIComponent(channelId) + '&nonce=' + encodeURIComponent((window.shop2llm && window.shop2llm.nonce) || '');

    fetch(url)
    .then(function (res) { return res.json(); })
    .then(function (data) {
        if (data.success && data.data && data.data.config) {
            return navigator.clipboard.writeText(data.data.config);
        }
        throw new Error('No config');
    })
    .then(function () {
        btn.classList.add('stl-copy-btn--copied');
        btn.textContent = '✓ Copied';
        setTimeout(function () {
            btn.classList.remove('stl-copy-btn--copied');
            btn.textContent = originalText;
        }, 1500);
    })
    .catch(function () {
        btn.textContent = 'Error';
        setTimeout(function () {
            btn.textContent = originalText;
        }, 1500);
    });
}

// ─── Merchant AI Chat ───────────────────────────────────────────────

function stlSendMerchantChat() {
    var input = document.getElementById('stl-ai-chat-input');
    var messages = document.getElementById('stl-ai-chat-messages');
    var sendBtn = document.getElementById('stl-ai-chat-send-btn');

    if (!input || !messages) return;

    var message = input.value.trim();
    if (!message) return;

    // Show user message
    var userMsg = document.createElement('div');
    userMsg.className = 'stl-ai-msg stl-ai-msg-user';
    userMsg.textContent = message;
    messages.appendChild(userMsg);

    // Show typing indicator
    var typing = document.createElement('div');
    typing.className = 'stl-ai-msg stl-ai-msg-bot stl-ai-typing';
    typing.textContent = 'Thinking...';
    typing.id = 'stl-ai-typing';
    messages.appendChild(typing);

    // Scroll to bottom
    messages.scrollTop = messages.scrollHeight;

    // Clear input and disable
    input.value = '';
    if (sendBtn) sendBtn.disabled = true;

    // Call REST API
    var nonce = (window.shop2llm && window.shop2llm.nonce) || '';
    fetch('/wp-json/shop2llm/v1/merchant/chat', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': nonce
        },
        body: JSON.stringify({ message: message })
    })
    .then(function (res) { return res.json(); })
    .then(function (data) {
        // Remove typing indicator
        var typingEl = document.getElementById('stl-ai-typing');
        if (typingEl) typingEl.remove();

        // Show AI reply
        var botMsg = document.createElement('div');
        botMsg.className = 'stl-ai-msg stl-ai-msg-bot';
        botMsg.textContent = data.reply || 'Sorry, no response.';
        messages.appendChild(botMsg);

        // Render suggestions
        if (data.suggestions && data.suggestions.length > 0) {
            stlRenderSuggestionButtons(data.suggestions);
        }

        // Scroll to bottom
        messages.scrollTop = messages.scrollHeight;
    })
    .catch(function () {
        var typingEl = document.getElementById('stl-ai-typing');
        if (typingEl) typingEl.remove();

        var botMsg = document.createElement('div');
        botMsg.className = 'stl-ai-msg stl-ai-msg-bot';
        botMsg.textContent = 'Sorry, something went wrong. Please try again.';
        messages.appendChild(botMsg);
        messages.scrollTop = messages.scrollHeight;
    })
    .finally(function () {
        if (sendBtn) sendBtn.disabled = false;
    });
}

function stlRenderSuggestionButtons(suggestions) {
    var container = document.getElementById('stl-ai-chat-suggestions');
    if (!container) return;

    container.innerHTML = '';
    suggestions.forEach(function (text) {
        var btn = document.createElement('button');
        btn.type = 'button';
        btn.className = 'stl-ai-suggestion-btn';
        btn.textContent = text;
        btn.onclick = function () { stlQuickChat(text); };
        container.appendChild(btn);
    });
}

function stlQuickChat(message) {
    var input = document.getElementById('stl-ai-chat-input');
    if (input) {
        input.value = message;
    }
    stlSendMerchantChat();
}

// Enter key to send message
document.addEventListener('DOMContentLoaded', function () {
    var chatInput = document.getElementById('stl-ai-chat-input');
    if (chatInput) {
        chatInput.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                stlSendMerchantChat();
            }
        });
    }
});
