const analyzeButton = document.getElementById('analyzeBtn');
const viewAnalysisButton = document.getElementById('viewAnalysisBtn');
const loader = document.getElementById('loader');
const resultsArea = document.getElementById('results');
const triageArea = document.getElementById('triageArea');
const statusCard = document.getElementById('statusCard');
const statusTitle = document.getElementById('statusTitle');
const statusText = document.getElementById('statusText');

const iconByType = { danger: '!', warning: 'i', success: 'OK', info: 'i' };
let latestState = null;

function setLoading(isLoading) {
    loader.hidden = !isLoading;
    analyzeButton.disabled = isLoading;
}

function getActiveTab() {
    return new Promise((resolve, reject) => {
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
            const runtimeError = chrome.runtime.lastError;
            if (runtimeError) {
                reject(new Error(runtimeError.message));
                return;
            }
            resolve(tabs[0]);
        });
    });
}

function sendTabMessage(tabId, message) {
    return new Promise((resolve, reject) => {
        chrome.tabs.sendMessage(tabId, message, (response) => {
            const runtimeError = chrome.runtime.lastError;
            if (runtimeError) {
                reject(new Error(runtimeError.message));
                return;
            }
            resolve(response);
        });
    });
}

function setStatus(tone, title, text) {
    statusCard.className = `status-card status-${tone}`;
    statusTitle.textContent = title;
    statusText.textContent = text;
}

function clearUi() {
    triageArea.innerHTML = '';
    resultsArea.innerHTML = '';
}

function setViewButtonEnabled(enabled) {
    viewAnalysisButton.disabled = !enabled;
}

function buildExecutiveSections(analysis) {
    const clauses = Array.isArray(analysis?.clauses) ? analysis.clauses : [];
    const topClause = clauses[0];
    const triage = analysis?.triage || { danger: 0, warning: 0, success: 0 };
    const hotCount = (triage.danger || 0) + (triage.warning || 0);

    return [
        { label: 'Quadro generale', value: analysis?.summary || '' },
        { label: 'Cosa cambia per l utente', value: topClause?.userImpact || topClause?.description || '' },
        { label: 'Mossa consigliata', value: analysis?.suggestedAction || '' },
        { label: 'Segnale chiave', value: hotCount > 0 ? `${hotCount} punti da leggere con attenzione` : 'Nessun punto critico forte in primo piano' },
    ].filter((section) => section.value);
}

function renderExecutiveCard(analysis) {
    appendCard({
        type: analysis?.riskLevel || 'info',
        title: analysis?.investorHeadline || 'Brief ClaraLex',
        description: analysis?.summary || 'Analisi completata.',
        extra: analysis?.clauses?.length ? `${analysis.clauses.length} punti ordinati per priorita` : 'Panoramica pronta',
        sections: buildExecutiveSections(analysis)
    });
}
function renderTriage(analysis) {
    const triage = analysis?.triage || { danger: 0, warning: 0, success: 0 };
    const total = (triage.danger || 0) + (triage.warning || 0) + (triage.success || 0);
    triageArea.innerHTML = `
        <div class="triage-panel">
            <div class="triage-panel__header">
                <div>
                    <strong>Triage visivo</strong>
                    <p>${analysis?.investorHeadline || analysis?.summary || 'Panoramica rapida delle clausole trovate.'}</p>
                </div>
                <span class="triage-panel__badge">${total} punti</span>
            </div>
            <div class="triage-grid">
                <div class="triage-box triage-danger"><strong>${triage.danger || 0}</strong><span>Rosse</span></div>
                <div class="triage-box triage-warning"><strong>${triage.warning || 0}</strong><span>Gialle</span></div>
                <div class="triage-box triage-success"><strong>${triage.success || 0}</strong><span>Verdi</span></div>
            </div>
        </div>
    `;
}

function openAnalysisCard(clauseId, referenceIndex = 0) {
    return getActiveTab().then((tab) => {
        if (!tab?.id) {
            throw new Error('Scheda attiva non disponibile.');
        }
        return sendTabMessage(tab.id, clauseId
            ? { action: 'claralex.focusClause', clauseId, shouldCycle: false, referenceIndex }
            : { action: 'claralex.openAnalysisPanel' });
    }).then(() => {
        window.close();
    });
}

function appendCard({ type = 'info', title, description, extra, quotes = [], clauseId, sections = [] }) {
    const card = document.createElement('article');
    card.className = `card card-${type}`;

    const icon = document.createElement('span');
    icon.className = 'left-icon';
    icon.textContent = iconByType[type] || iconByType.info;

    const content = document.createElement('div');
    content.className = 'card-content';

    const heading = document.createElement('strong');
    heading.textContent = title;
    content.appendChild(heading);

    if (description) {
        const descriptionNode = document.createElement('p');
        descriptionNode.textContent = description;
        content.appendChild(descriptionNode);
    }

    if (extra) {
        const extraNode = document.createElement('p');
        extraNode.className = 'card-extra';
        extraNode.textContent = extra;
        content.appendChild(extraNode);
    }

    sections.forEach((section) => {
        if (!section?.value) return;
        const sectionNode = document.createElement('div');
        sectionNode.className = 'card-section';

        const labelNode = document.createElement('strong');
        labelNode.className = 'card-section__label';
        labelNode.textContent = section.label;

        const valueNode = document.createElement('p');
        valueNode.className = 'card-section__value';
        valueNode.textContent = section.value;

        sectionNode.appendChild(labelNode);
        sectionNode.appendChild(valueNode);
        content.appendChild(sectionNode);
    });
    quotes.slice(0, 3).forEach((quote, referenceIndex) => {
        if (!quote) return;

        if (clauseId) {
            const quoteButton = document.createElement('button');
            quoteButton.type = 'button';
            quoteButton.className = 'card-quote card-quote-button';
            quoteButton.textContent = `"${quote}"`;
            quoteButton.addEventListener('click', (event) => {
                event.stopPropagation();
                openAnalysisCard(clauseId, referenceIndex).catch((error) => {
                    setStatus('danger', 'Navigazione non riuscita', error.message);
                });
            });
            content.appendChild(quoteButton);
            return;
        }

        const quoteNode = document.createElement('p');
        quoteNode.className = 'card-quote';
        quoteNode.textContent = `"${quote}"`;
        content.appendChild(quoteNode);
    });

    if (clauseId) {
        card.classList.add('card--interactive');
        card.style.cursor = 'pointer';
        card.addEventListener('click', (event) => {
            if (event.target.closest('button')) {
                return;
            }

            card.classList.remove('card--pressed');
            void card.offsetWidth;
            card.classList.add('card--pressed');
            openAnalysisCard(clauseId, 0).catch((error) => {
                setStatus('danger', 'Navigazione non riuscita', error.message);
            });
        });

        const actions = document.createElement('div');
        actions.className = 'card-actions';

        const button = document.createElement('button');
        button.className = 'card-button';
        button.textContent = 'Vai al testo';
        button.addEventListener('click', () => {
            card.classList.remove('card--pressed');
            void card.offsetWidth;
            card.classList.add('card--pressed');
            openAnalysisCard(clauseId).catch((error) => {
                setStatus('danger', 'Navigazione non riuscita', error.message);
            });
        });

        actions.appendChild(button);
        content.appendChild(actions);
    }

    card.appendChild(icon);
    card.appendChild(content);
    resultsArea.appendChild(card);
}

function buildClauseSections(clause) {
    return [
        { label: 'In breve', value: clause.clauseSummary || clause.description || '' },
        { label: 'Livello', value: clause.riskLabel || '' },
        { label: 'Perche conta', value: clause.whyItMatters || clause.description || '' },
        { label: 'Impatto per te', value: clause.userImpact || '' },
        { label: 'Base legale', value: clause.legalBasis || clause.legalReasoning || '' },
    ].filter((section) => section.value);
}
function renderHeuristics(heuristics) {
    if (!heuristics || !Array.isArray(heuristics.reasons) || heuristics.reasons.length === 0) {
        return;
    }

    appendCard({
        type: heuristics.isCandidate ? 'info' : 'success',
        title: heuristics.isCandidate ? 'Trigger contrattuale rilevato' : 'Pagina a basso segnale',
        description: `Segnale pagina: ${heuristics.score}.`,
        extra: heuristics.reasons.join(' | ')
    });
}

function renderAnalysis(state) {
    latestState = state;
    clearUi();
    setViewButtonEnabled(Boolean(state?.analysis || state?.status === 'done' || state?.status === 'analyzing'));

    if (!state) {
        setStatus('danger', 'Pagina non raggiungibile', 'Non riesco a leggere lo stato della scheda attiva.');
        appendCard({ type: 'danger', title: 'Content script non disponibile', description: 'Apri una normale pagina web http/https e riprova.' });
        return;
    }

    if (state.status === 'analyzing') {
        setStatus(
            state.analysis?.triage?.danger > 0 ? 'danger' : state.analysis?.triage?.warning > 0 ? 'warning' : 'info',
            'Analisi progressiva in corso',
            state.analysis?.summary || 'ClaraLex sta valutando la pagina in linguaggio semplice e aggiunge le clausole man mano.'
        );
        renderTriage(state.analysis);
        if (state.analysis?.clauses?.length) {
            renderExecutiveCard(state.analysis);
            if (Array.isArray(state.analysis.activityLog) && state.analysis.activityLog.length > 0) {
                appendCard({
                    type: 'info',
                    title: 'Flusso attivo',
                    description: state.analysis.activityLog.slice(-4).map((item) => item.message).join(' | ')
                });
            }
            state.analysis.clauses.forEach((clause) => {
                const extras = [];
                if (clause.confidence) extras.push(`Confidenza ${Math.round(Number(clause.confidence) * 100)}%`);
                if (clause.occurrenceCount) extras.push(`${clause.occurrenceCount} evidenziazioni nel testo`);
                appendCard({
                    type: clause.type || 'info',
                    title: clause.title || 'Clausola rilevata',
                    description: '',
                    extra: extras.join(' | '),
                    sections: buildClauseSections(clause),
                    quotes: Array.isArray(clause.references) && clause.references.length > 0 ? clause.references : [clause.textToFind || clause.quote || ''].filter(Boolean),
                    clauseId: clause.id
                });
            });
        } else {
            renderHeuristics(state.heuristics);
        }
        setTimeout(refreshState, 800);
        return;
    }

    if (state.status === 'error') {
        setStatus('danger', 'Analisi non disponibile', state.error || 'Il motore ClaraLex non ha restituito un risultato leggibile.');
        appendCard({ type: 'danger', title: 'Servizio momentaneamente non disponibile', description: 'Il backend ClaraLex non ha restituito un risultato valido. Riprova tra pochi secondi o rilancia l analisi manuale.' });
        return;
    }

    if (state.status === 'skipped') {
        setStatus('success', 'Pagina a basso rischio contrattuale', 'Questa pagina non sembra una schermata di accettazione o un contratto rilevante.');
        renderHeuristics(state.heuristics);
        appendCard({ type: 'info', title: 'Vuoi controllarla comunque?', description: 'Usa "Analizza adesso" per forzare la scansione anche su pagine fuori dai trigger automatici.' });
        return;
    }

    if (state.status === 'done' && state.analysis) {
        const analysis = state.analysis;
        const clauses = Array.isArray(analysis.clauses) ? analysis.clauses : [];

        renderTriage(analysis);

        if (!analysis.isContractLike) {
            setStatus('info', 'Pagina non contrattuale', analysis.summary || 'La pagina non sembra un contratto o una conferma vincolante.');
            appendCard({ type: 'info', title: 'Analisi leggera completata', description: analysis.summary || 'Questa pagina non sembra centrata su un contratto.', extra: analysis.suggestedAction || '' });
            return;
        }

        setStatus(analysis.riskLevel || 'info', analysis.summary || 'Analisi completata', analysis.suggestedAction || 'Apri il pannello nella pagina per navigare tra analisi e testo. Tocca una citazione per saltare al punto esatto.');
        renderExecutiveCard(analysis);

        if (Array.isArray(analysis.activityLog) && analysis.activityLog.length > 0) {
            appendCard({
                type: 'info',
                title: 'Log analisi',
                description: analysis.activityLog.slice(-4).map((item) => item.message).join(' | ')
            });
        }

        if (clauses.length === 0) {
            appendCard({ type: 'success', title: 'Nessuna clausola critica forte trovata', description: 'ClaraLex non ha rilevato passaggi chiaramente squilibrati nel testo analizzato.' });
            return;
        }

        clauses.forEach((clause) => {
            const extras = [];
            if (clause.confidence) {
                extras.push(`Confidenza ${Math.round(Number(clause.confidence) * 100)}%`);
            }
            if (clause.occurrenceCount) {
                extras.push(`${clause.occurrenceCount} evidenziazioni nel testo`);
            }
            if (Array.isArray(clause.references) && clause.references.length > 1) {
                extras.push(`${clause.references.length} citazioni navigabili`);
            }

            appendCard({
                type: clause.type || 'info',
                title: clause.title || 'Clausola rilevata',
                description: '',
                    extra: extras.join(' | '),
                    sections: buildClauseSections(clause),
                quotes: Array.isArray(clause.references) && clause.references.length > 0 ? clause.references : [clause.textToFind || clause.quote || ''].filter(Boolean),
                clauseId: clause.id
            });
        });
        return;
    }

    setStatus('info', 'ClaraLex in attesa', 'Apri una pagina con termini, checkout o schermate da accettare per far partire la scansione.');
    appendCard({ type: 'info', title: 'Autoscan selettivo pronto', description: 'ClaraLex si attiva soprattutto su pagine con termini, checkout, rinnovi, pagamenti e conferme esplicite.', extra: 'Per una demo pulita, l analisi automatica parte solo dove il segnale contrattuale e davvero forte.' });
}

async function refreshState() {
    try {
        const tab = await getActiveTab();
        if (!tab?.id || !/^https?:/i.test(tab.url || '')) {
            renderAnalysis(null);
            setLoading(false);
            return;
        }
        const state = await sendTabMessage(tab.id, { action: 'claralex.getScanState' });
        renderAnalysis(state);
        setLoading(state?.status === 'analyzing');
    } catch (error) {
        renderAnalysis({ status: 'error', error: error.message });
        setLoading(false);
    }
}

analyzeButton.addEventListener('click', async () => {
    setLoading(true);
    try {
        const tab = await getActiveTab();
        if (!tab?.id) {
            throw new Error('Scheda attiva non disponibile.');
        }
        const state = await sendTabMessage(tab.id, { action: 'claralex.manualScan' });
        renderAnalysis(state);
        setLoading(state?.status === 'analyzing');
    } catch (error) {
        renderAnalysis({ status: 'error', error: error.message });
        setLoading(false);
    }
});

viewAnalysisButton.addEventListener('click', () => {
    openAnalysisCard(latestState?.activeClauseId || null).catch((error) => {
        setStatus('danger', 'Pannello non disponibile', error.message);
    });
});

setLoading(true);
setViewButtonEnabled(false);
refreshState();




