(function () {
    const btn = document.getElementById('aiRiskBtn');
    if (!btn) return;

    btn.addEventListener('click', async function () {
        const body    = document.getElementById('aiRiskBody');
        const spinner = document.getElementById('aiRiskSpinner');
        const errEl   = document.getElementById('aiRiskError');
        const insights = document.getElementById('aiRiskInsights');
        const table   = document.getElementById('aiRiskTable');
        const rows    = document.getElementById('aiRiskRows');

        body.classList.remove('d-none');
        spinner.classList.remove('d-none');
        errEl.classList.add('d-none');
        table.classList.add('d-none');
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Analyzing…';

        try {
            const token = document.querySelector('input[name="__RequestVerificationToken"]')?.value ?? '';
            const resp = await fetch('/Reports/PredictLatePayments', {
                method: 'POST',
                headers: { 'RequestVerificationToken': token }
            });
            const data = await resp.json();

            spinner.classList.add('d-none');

            if (!data.success) {
                errEl.textContent = data.errorMessage || 'AI service unavailable.';
                errEl.classList.remove('d-none');
                return;
            }

            const preds = data.predictions || [];
            const insightList = data.insights || [];

            insights.innerHTML = insightList
                .map(i => `<i class="bi bi-lightbulb text-warning me-1"></i>${i}`)
                .join('<br>');

            const riskBadge = level => {
                if (level === 'high')   return 'bg-danger text-white';
                if (level === 'medium') return 'bg-warning text-dark';
                return 'bg-success text-white';
            };

            rows.innerHTML = preds.map(p => `
                <tr>
                    <td class="fw-medium">${p.customerName}</td>
                    <td><span class="badge ${riskBadge(p.riskLevel)}">${p.riskLevel.charAt(0).toUpperCase() + p.riskLevel.slice(1)}</span></td>
                    <td>${p.estimatedDaysToPayment > 0 ? p.estimatedDaysToPayment + ' days' : 'Soon'}</td>
                    <td class="text-muted small">${p.reasoning}</td>
                </tr>
            `).join('');

            if (preds.length > 0) table.classList.remove('d-none');
            else insights.innerHTML += '<br><span class="text-muted">No open invoices to predict.</span>';

        } catch (err) {
            spinner.classList.add('d-none');
            errEl.textContent = 'Error contacting AI service.';
            errEl.classList.remove('d-none');
        } finally {
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-magic me-1"></i>Predict Payment Risk';
        }
    });
})();
