/**
 * PFA Detection Management - detections_page.js
 * Handles all interactions for the detection management page
 */

// ─── State ────────────────────────────────────────────────────────────────────
let currentPage  = 1;
let totalPages   = 1;
let allDetections = [];
let filtered     = [];
const PAGE_SIZE  = 20;

// ─── Bootstrap ────────────────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
    loadDetections();

    document.getElementById('searchInput').addEventListener('input',  applyFilters);
    document.getElementById('riskFilter').addEventListener('change',  applyFilters);
    document.getElementById('statusFilter').addEventListener('change', applyFilters);

    // Close modal clicking backdrop
    document.getElementById('detectionModal').addEventListener('click', e => {
        if (e.target === document.getElementById('detectionModal')) closeModal();
    });

    // ESC key closes modal
    document.addEventListener('keydown', e => {
        if (e.key === 'Escape') closeModal();
    });
});

// ─── Data Loading ─────────────────────────────────────────────────────────────
async function loadDetections() {
    showTableLoading();

    try {
        const res  = await fetch(`detection_api.php?action=get_detections&page=${currentPage}&per_page=${PAGE_SIZE}`);
        const data = await res.json();

        if (!data.success) throw new Error(data.error || 'Failed to load detections');

        allDetections = data.detections || [];
        filtered      = [...allDetections];
        totalPages    = data.total_pages || 1;

        updateStats(data.stats);
        renderTable(filtered);
        renderPagination();

    } catch (err) {
        showTableError(err.message);
    }
}

// ─── Stats Cards ──────────────────────────────────────────────────────────────
function updateStats(stats) {
    if (!stats) return;
    animateCount('statTotal',    stats.total    || 0);
    animateCount('statPending',  stats.pending  || 0);
    animateCount('statHighRisk', stats.high_risk|| 0);
    animateCount('statResolved', stats.resolved || 0);
}

function animateCount(id, target) {
    const el    = document.getElementById(id);
    const start = parseInt(el.textContent) || 0;
    const diff  = target - start;
    const steps = 30;
    let   step  = 0;

    const timer = setInterval(() => {
        step++;
        el.textContent = Math.round(start + diff * (step / steps));
        if (step >= steps) {
            el.textContent = target;
            clearInterval(timer);
        }
    }, 20);
}

// ─── Table Rendering ──────────────────────────────────────────────────────────
function renderTable(detections) {
    if (!detections || detections.length === 0) {
        document.getElementById('tableContent').innerHTML = `
            <div class="empty-state">
                <div class="empty-state-icon">🔍</div>
                <p>No detections found</p>
                <p style="font-size:13px; margin-top:8px; color:#86868b;">
                    Try adjusting your search or filters
                </p>
            </div>`;
        return;
    }

    const rows = detections.map(d => `
        <tr onclick="openDetectionModal(${d.id})">
            <td>
                <span style="font-family:monospace; font-size:12px; color:#86868b;">
                    ${escHtml(truncate(d.detection_id, 14))}
                </span>
            </td>
            <td><strong>${escHtml(d.query)}</strong></td>
            <td><strong>${escHtml(d.matched_entity)}</strong></td>
            <td>
                <span style="background:#f0f0f5; padding:4px 10px; border-radius:6px;
                             font-weight:700; font-size:13px;">
                    ${d.score}%
                </span>
            </td>
            <td>${riskBadge(d.risk_level)}</td>
            <td>${statusBadge(d.status)}</td>
            <td style="color:#86868b;">${escHtml(d.created_date)}</td>
            <td onclick="event.stopPropagation()">${actionButtons(d)}</td>
        </tr>
    `).join('');

    document.getElementById('tableContent').innerHTML = `
        <table>
            <thead>
                <tr>
                    <th>Detection ID</th>
                    <th>Query</th>
                    <th>Matched Entity</th>
                    <th>Score</th>
                    <th>Risk</th>
                    <th>Status</th>
                    <th>Created</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>${rows}</tbody>
        </table>`;
}

// ─── Badges ───────────────────────────────────────────────────────────────────
function riskBadge(level) {
    const map = {
        'Critical': 'risk-critical',
        'High':     'risk-high',
        'Medium':   'risk-medium',
        'Low':      'risk-low'
    };
    return `<span class="badge ${map[level] || 'risk-low'}">${escHtml(level)}</span>`;
}

function statusBadge(status) {
    const cfg = {
        'New':          { cls: 'status-new',      icon: '⚠️' },
        'Under Review': { cls: 'status-review',   icon: '🕐' },
        'Reviewed':     { cls: 'status-review',   icon: '🕐' },
        'Confirmed':    { cls: 'status-confirmed', icon: '⚠️' },
        'Resolved':     { cls: 'status-resolved', icon: '✓'  },
        'False Positive':{ cls:'status-resolved', icon: '✓'  }
    };
    const c = cfg[status] || { cls: '', icon: '' };
    return `<span class="badge ${c.cls}">${c.icon} ${escHtml(status)}</span>`;
}

// ─── Action Buttons ───────────────────────────────────────────────────────────
function actionButtons(d) {
    switch (d.status) {
        case 'New':
            return `<div class="actions">
                        <button class="btn btn-review"
                            onclick="changeStatus(${d.id},'Under Review',event)">Review</button>
                        <button class="btn btn-accept"
                            onclick="changeStatus(${d.id},'Confirmed',event)">Accept</button>
                    </div>`;

        case 'Under Review':
            return `<div class="actions">
                        <button class="btn btn-accept"
                            onclick="changeStatus(${d.id},'Confirmed',event)">Accept</button>
                        <button class="btn btn-reject"
                            onclick="changeStatus(${d.id},'False Positive',event)">Reject</button>
                    </div>`;

        case 'Confirmed':
        case 'Reviewed':
            return `<div class="actions">
                        <button class="btn btn-accept"
                            onclick="changeStatus(${d.id},'Resolved',event)">Resolve</button>
                        <button class="btn btn-reject"
                            onclick="changeStatus(${d.id},'False Positive',event)">Reject</button>
                    </div>`;

        default:
            return `<span style="color:#86868b; font-size:12px;">Completed</span>`;
    }
}

// ─── Status Update ────────────────────────────────────────────────────────────
async function changeStatus(detectionId, newStatus, event) {
    if (event) event.stopPropagation();

    const row = event.currentTarget.closest('tr');
    if (row) row.style.opacity = '0.5';

    try {
        const res  = await fetch('detection_api.php', {
            method:  'POST',
            headers: { 'Content-Type': 'application/json' },
            body:    JSON.stringify({ action: 'update_status', detection_id: detectionId, status: newStatus })
        });
        const data = await res.json();

        if (data.success) {
            // Update in-memory record
            const idx = allDetections.findIndex(d => d.id === detectionId);
            if (idx !== -1) {
                allDetections[idx].status = newStatus;
                filtered = [...allDetections];
                applyFilters();
            }
            // Refresh stats
            loadStats();
        } else {
            throw new Error(data.error || 'Update failed');
        }
    } catch (err) {
        alert('Error: ' + err.message);
        if (row) row.style.opacity = '1';
    }
}

async function loadStats() {
    try {
        const res  = await fetch('detection_api.php?action=get_stats');
        const data = await res.json();
        if (data.success) updateStats(data.stats);
    } catch (_) {}
}

// ─── Detection Modal ──────────────────────────────────────────────────────────
async function openDetectionModal(detectionId) {
    document.getElementById('modalBody').innerHTML = `
        <div class="loading">Loading details...</div>`;
    document.getElementById('detectionModal').classList.add('show');

    try {
        const res  = await fetch(`detection_api.php?action=get_detection_details&id=${detectionId}`);
        const data = await res.json();

        if (!data.success) throw new Error(data.error || 'Failed to load details');

        renderModal(data.detection, data.related_detections || []);
    } catch (err) {
        document.getElementById('modalBody').innerHTML = `
            <div class="empty-state">
                <div class="empty-state-icon">⚠️</div>
                <p>Error: ${escHtml(err.message)}</p>
            </div>`;
    }
}

function closeModal() {
    document.getElementById('detectionModal').classList.remove('show');
}

function renderModal(det, related) {
    let html = '';

    // ── Alert Banner ──
    if (det.risk_level === 'Critical' || det.risk_level === 'High') {
        const isCritical = det.risk_level === 'Critical';
        html += `
            <div class="alert-box ${isCritical ? 'critical' : ''}">
                <div class="alert-title">⚠️ ${escHtml(det.risk_level)} Risk Detection</div>
                <div class="alert-message">
                    This detection has been flagged as <strong>${escHtml(det.risk_level.toLowerCase())}</strong>
                    risk and requires ${isCritical ? 'immediate' : 'prompt'} attention.
                </div>
            </div>`;
    }

    // ── Detection Info ──
    html += `
        <div class="detail-section">
            <h3>Detection Information</h3>
            <div class="detail-grid">
                ${detailItem('Detection ID', det.detection_id)}
                ${detailItem('Search Query', `<strong>${escHtml(det.query)}</strong>`)}
                ${detailItem('Match Score',  `<strong style="font-size:18px;">${det.score}%</strong>`)}
                ${detailItem('Confidence',   det.confidence || 'N/A')}
                ${detailItem('Risk Level',   riskBadge(det.risk_level))}
                ${detailItem('Status',       statusBadge(det.status))}
                ${detailItem('Detected At',  escHtml(det.created_date || ''))}
            </div>
        </div>`;

    // ── Matched Entity ──
    html += `
        <div class="detail-section">
            <h3>Matched Entity</h3>
            <div class="detail-grid">
                ${detailItem('Full Name',    `<strong>${escHtml(det.matched_entity)}</strong>`)}
                ${detailItem('External ID',  escHtml(det.external_id  || 'N/A'))}
                ${detailItem('Nationality',  escHtml(det.nationality  || 'N/A'))}
                ${detailItem('Date of Birth',escHtml(det.dob          || 'N/A'))}
                ${detailItem('Entity Status',escHtml(det.entity_status|| 'N/A'))}
            </div>`;

    // Matched fields tags
    const fields = parseJson(det.matched_fields, []);
    if (fields.length > 0) {
        html += `
            <div class="matched-fields" style="margin-top:16px;">
                <strong style="font-size:11px; color:#86868b; margin-right:8px; text-transform:uppercase; letter-spacing:.5px;">
                    Matched Fields:
                </strong>
                ${fields.map(f => `<span class="field-tag">${escHtml(f)}</span>`).join('')}
            </div>`;
    }
    html += `</div>`;

    // ── Score Breakdown ──
    const breakdown = parseJson(det.score_breakdown, null);
    if (breakdown && typeof breakdown === 'object' && Object.keys(breakdown).length > 0) {
        html += `
            <div class="detail-section">
                <h3>Score Breakdown</h3>
                <div class="detail-grid">
                    ${Object.entries(breakdown).map(([k, v]) =>
                        detailItem(formatKey(k), `
                            <div style="display:flex; align-items:center; gap:10px;">
                                <div style="flex:1; height:6px; background:#e5e5e7; border-radius:3px; overflow:hidden;">
                                    <div style="width:${v}%; height:100%; background:linear-gradient(90deg,#667eea,#764ba2); border-radius:3px;"></div>
                                </div>
                                <strong style="min-width:38px;">${v}%</strong>
                            </div>`)
                    ).join('')}
                </div>
            </div>`;
    }

    // ── All Detections from Same Search ──
    if (related.length > 0) {
        html += `
            <div class="detail-section">
                <h3>All Detections from This Search
                    <span style="font-size:14px; font-weight:400; color:#86868b; margin-left:6px;">
                        (${related.length} result${related.length !== 1 ? 's' : ''})
                    </span>
                </h3>
                <div class="detection-list">
                    ${related.map(r => relatedCard(r)).join('')}
                </div>
            </div>`;
    }

    // ── Review Notes ──
    if (det.review_notes) {
        html += `
            <div class="detail-section">
                <h3>Review Notes</h3>
                <div style="padding:16px; background:#f5f5f7; border-radius:8px; font-size:14px; color:#1d1d1f;">
                    ${escHtml(det.review_notes)}
                </div>
            </div>`;
    }

    // ── Modal Action Buttons ──
    html += `
        <div style="display:flex; gap:12px; margin-top:8px; padding-top:20px; border-top:1px solid #e5e5e7;">
            ${modalActionButtons(det)}
        </div>`;

    document.getElementById('modalBody').innerHTML = html;
}

function relatedCard(r) {
    const fields = parseJson(r.matched_fields, []);
    return `
        <div class="detection-item">
            <div class="detection-item-header">
                <div>
                    <div class="detection-item-title">${escHtml(r.matched_entity)}</div>
                    <div style="font-size:12px; color:#86868b; margin-top:4px;">
                        ${escHtml(r.nationality || 'Unknown Nationality')} &bull; ${escHtml(r.created_date || '')}
                    </div>
                </div>
                <span class="score-badge">${r.score}%</span>
            </div>
            <div style="display:flex; gap:8px; flex-wrap:wrap;">
                ${riskBadge(r.risk_level)}
                ${statusBadge(r.status)}
            </div>
            ${fields.length > 0 ? `
                <div class="matched-fields">
                    ${fields.map(f => `<span class="field-tag">${escHtml(f)}</span>`).join('')}
                </div>` : ''}
        </div>`;
}

function modalActionButtons(det) {
    const btnBase = 'style="padding:10px 24px; border-radius:8px; font-size:14px; font-weight:600; cursor:pointer; border:none; transition:all .2s;"';

    switch (det.status) {
        case 'New':
            return `
                <button ${btnBase} style="background:#f5f5f7; color:#1d1d1f;"
                    onclick="changeStatusFromModal(${det.id},'Under Review')">Mark Under Review</button>
                <button ${btnBase} style="background:#34c759; color:white;"
                    onclick="changeStatusFromModal(${det.id},'Confirmed')">Accept Match</button>
                <button ${btnBase} style="background:white; color:#ff3b30; border:1px solid #ff3b30;"
                    onclick="changeStatusFromModal(${det.id},'False Positive')">Reject</button>`;

        case 'Under Review':
            return `
                <button ${btnBase} style="background:#34c759; color:white;"
                    onclick="changeStatusFromModal(${det.id},'Confirmed')">Confirm Match</button>
                <button ${btnBase} style="background:white; color:#ff3b30; border:1px solid #ff3b30;"
                    onclick="changeStatusFromModal(${det.id},'False Positive')">False Positive</button>`;

        case 'Confirmed':
            return `
                <button ${btnBase} style="background:#007aff; color:white;"
                    onclick="changeStatusFromModal(${det.id},'Resolved')">Mark Resolved</button>`;

        default:
            return `<span style="color:#86868b; font-size:14px;">No further actions required.</span>`;
    }
}

async function changeStatusFromModal(detectionId, newStatus) {
    try {
        const res  = await fetch('detection_api.php', {
            method:  'POST',
            headers: { 'Content-Type': 'application/json' },
            body:    JSON.stringify({ action: 'update_status', detection_id: detectionId, status: newStatus })
        });
        const data = await res.json();
        if (data.success) {
            closeModal();
            loadDetections();
        } else {
            throw new Error(data.error || 'Update failed');
        }
    } catch (err) {
        alert('Error: ' + err.message);
    }
}

// ─── Filters ──────────────────────────────────────────────────────────────────
function applyFilters() {
    const q      = document.getElementById('searchInput').value.toLowerCase().trim();
    const risk   = document.getElementById('riskFilter').value;
    const status = document.getElementById('statusFilter').value;

    filtered = allDetections.filter(d => {
        const matchQ = !q ||
            d.query.toLowerCase().includes(q) ||
            d.matched_entity.toLowerCase().includes(q) ||
            d.detection_id.toLowerCase().includes(q);
        const matchR = !risk   || d.risk_level === risk;
        const matchS = !status || d.status     === status;
        return matchQ && matchR && matchS;
    });

    currentPage = 1;
    renderTable(filtered);
    renderPagination();
}

// ─── Pagination ───────────────────────────────────────────────────────────────
function renderPagination() {
    const pag = document.getElementById('pagination');
    if (totalPages <= 1) { pag.style.display = 'none'; return; }

    pag.style.display = 'flex';
    document.getElementById('pageInfo').textContent = `Page ${currentPage} of ${totalPages}`;
    document.querySelector('.prev-btn').disabled = currentPage === 1;
    document.querySelector('.next-btn').disabled = currentPage === totalPages;
}

function previousPage() {
    if (currentPage > 1) { currentPage--; loadDetections(); }
}

function nextPage() {
    if (currentPage < totalPages) { currentPage++; loadDetections(); }
}

// ─── Helpers ──────────────────────────────────────────────────────────────────
function showTableLoading() {
    document.getElementById('tableContent').innerHTML =
        '<div class="loading">Loading detections…</div>';
}

function showTableError(msg) {
    document.getElementById('tableContent').innerHTML = `
        <div class="empty-state">
            <div class="empty-state-icon">⚠️</div>
            <p>Error loading detections</p>
            <p style="font-size:13px; margin-top:8px; color:#86868b;">${escHtml(msg)}</p>
        </div>`;
}

function detailItem(label, value) {
    return `
        <div class="detail-item">
            <div class="detail-label">${label}</div>
            <div class="detail-value">${value}</div>
        </div>`;
}

function escHtml(text) {
    if (text == null) return '';
    const d = document.createElement('div');
    d.textContent = String(text);
    return d.innerHTML;
}

function truncate(str, max) {
    if (!str) return '';
    return str.length > max ? str.slice(0, max) + '…' : str;
}

function formatKey(key) {
    return key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
}

function parseJson(val, fallback) {
    if (!val) return fallback;
    if (typeof val === 'object') return val;
    try { return JSON.parse(val); } catch (_) { return fallback; }
}
