(function () {
    'use strict';

    const verdictLabels = {
        allow: "Safe",
        warn: "Suspicious",
        hard_block: "Likely Scam",
        ignored: "Not Scanned",
        unscanned: "Unscanned",
        analyzing: "Analyzing",
        offline: "Offline",
        setup: "Setup Needed"
    };
    const recommendedActionLabels = {
        allow: "No urgent action needed",
        ignore: "Ignore this message",
        verify_directly: "Contact the real company or person another way",
        ask_guardian: "Ask a family member before responding",
        archive: "Archive this message",
        move_to_spam: "Move this message to spam"
    };

    function providerLabel(provider) {
        if (!provider)
            return "";
        if (provider === "gmail")
            return "Gmail";
        if (provider === "yahoo")
            return "Yahoo Mail";
        if (provider === "outlook")
            return "Outlook";
        if (provider === "imap")
            return "IMAP Mail";
        return provider;
    }
    function riskLabel(risk) {
        if (risk === "high")
            return "high risk";
        if (risk === "medium")
            return "medium risk";
        return "low risk";
    }
    function formatLinkFinding(link) {
        const reasons = Array.isArray(link.reasons) && link.reasons.length > 0 ? ` ${link.reasons.join("; ")}` : "";
        return `${link.actualDomain} is marked ${riskLabel(link.risk)}.${reasons}`.trim();
    }
    function summarizeLinkFindings(linkFindings) {
        if (linkFindings.length === 0) {
            return ["No risky links were found."];
        }
        const grouped = new Map();
        for (const link of linkFindings) {
            const key = JSON.stringify({
                actualDomain: link.actualDomain,
                risk: link.risk,
                reasons: Array.isArray(link.reasons) ? [...link.reasons].sort() : []
            });
            const existing = grouped.get(key);
            if (existing) {
                existing.count += 1;
                continue;
            }
            grouped.set(key, { link, count: 1 });
        }
        return Array.from(grouped.values()).map(({ link, count }) => {
            const base = formatLinkFinding(link);
            if (count <= 1) {
                return base;
            }
            return `${base} Appears ${count} times in this email.`;
        });
    }
    function formatAttachmentFinding(attachment) {
        const reasons = Array.isArray(attachment.reasons) && attachment.reasons.length > 0
            ? ` ${attachment.reasons.join("; ")}`
            : "";
        return `${attachment.filename} is marked ${riskLabel(attachment.risk)}.${reasons}`.trim();
    }
    function summarizeDeepScanLinkPolicy(verdict) {
        if (verdict.deepScan) {
            return verdict.deepScan;
        }
        const linkFindings = verdict.linkFindings;
        let noFetchCount = 0;
        let eligibleCount = 0;
        let prioritizedCount = 0;
        for (const link of linkFindings) {
            const reasons = Array.isArray(link.reasons) ? link.reasons : [];
            if (reasons.some((reason) => reason.startsWith("Deep scan policy would not open this link"))) {
                noFetchCount += 1;
            }
            if (reasons.some((reason) => reason.startsWith("Deep scan policy would prioritize this link") ||
                reason.startsWith("Deep scan policy could fetch this link"))) {
                eligibleCount += 1;
            }
            if (reasons.some((reason) => reason.startsWith("Deep scan policy would prioritize this link for a controlled cloud fetch"))) {
                prioritizedCount += 1;
            }
        }
        return {
            analyzedLinkCount: linkFindings.length,
            noFetchCount,
            eligibleCount,
            prioritizedCount,
            liveFetchEnabled: false,
            liveFetchedCount: 0,
            redirectedCount: 0,
            passwordCount: 0,
            paymentCount: 0,
            interactiveCount: 0,
            truncatedCount: 0,
            fetchErrorCount: 0
        };
    }
    function buildSidepanelView(active) {
        if (!active?.verdict) {
            if (active?.analysisJob?.state === "error") {
                return {
                    summary: `${active.sender || "Unknown sender"}: ${active.subject || "(no subject)"}`,
                    overview: [
                        active.summary?.provider ? `Mailbox: ${providerLabel(active.summary.provider)}` : "",
                        active.summary?.fromAddress ? `Real sender: ${active.summary.fromAddress}` : "",
                        `Status: ${active.analysisJob.userMessage}`
                    ].filter(Boolean),
                    reasons: active.analysisJob.partialReasons && active.analysisJob.partialReasons.length > 0
                        ? active.analysisJob.partialReasons
                        : ["We could not finish the full scan. Links stay blocked for now."],
                    links: ["Link details are still blocked until the full scan finishes."],
                    attachments: ["Attachment details will appear after a successful scan."],
                    actionCopy: "Wait for the server to reconnect, then run Check this email now."
                };
            }
            if (active?.analysisJob) {
                return {
                    summary: `${active.sender || "Unknown sender"}: ${active.subject || "(no subject)"}`,
                    overview: [
                        active.summary?.provider ? `Mailbox: ${providerLabel(active.summary.provider)}` : "",
                        active.summary?.fromAddress ? `Real sender: ${active.summary.fromAddress}` : "",
                        `Status: ${active.analysisJob.userMessage}`
                    ].filter(Boolean),
                    reasons: active.analysisJob.partialReasons && active.analysisJob.partialReasons.length > 0
                        ? active.analysisJob.partialReasons
                        : ["We are still collecting the main safety reasons."],
                    links: ["Link details will appear after the scan finishes."],
                    attachments: ["Attachment details will appear after the scan finishes."],
                    actionCopy: active.analysisJob.userMessage
                };
            }
            if (active?.summary) {
                return {
                    summary: `${active.sender || "Unknown sender"}: ${active.subject || "(no subject)"}`,
                    overview: [
                        active.summary.provider ? `Mailbox: ${providerLabel(active.summary.provider)}` : "",
                        active.summary.fromAddress ? `Real sender: ${active.summary.fromAddress}` : "",
                        "Status: No saved safety result yet."
                    ].filter(Boolean),
                    reasons: ["Run Check this email now if you want a fresh safety scan for this message."],
                    links: ["No link details are saved yet."],
                    attachments: ["No attachment details are saved yet."],
                    actionCopy: "Run Check this email now if this message feels unusual."
                };
            }
            return {
                summary: "Open an email to see why it may be risky.",
                overview: ["No email is selected yet."],
                reasons: ["No safety reasons yet."],
                links: ["Open an email to load link details."],
                attachments: ["Open an email to load attachment details."],
                actionCopy: "No next step suggested yet."
            };
        }
        const verdict = active.verdict;
        const verdictLabel = verdictLabels[verdict.level] ?? verdict.level;
        const deepScanPolicy = summarizeDeepScanLinkPolicy(verdict);
        return {
            summary: `${active.sender || "Unknown sender"}: ${active.subject || "(no subject)"}`,
            overview: [
                `Safety result: ${verdictLabel}`,
                `Confidence: ${Math.round(verdict.confidence * 100)}%`,
                active.summary?.provider ? `Mailbox: ${providerLabel(active.summary.provider)}` : "",
                active.summary?.fromAddress ? `Real sender: ${active.summary.fromAddress}` : "",
                active.summary?.replyTo?.length
                    ? `Reply-to address: ${active.summary.replyTo.join(", ")}`
                    : "",
                deepScanPolicy.noFetchCount > 0
                    ? `Deep scan held back ${deepScanPolicy.noFetchCount} personalized ${deepScanPolicy.noFetchCount === 1 ? "link" : "links"}.`
                    : "",
                deepScanPolicy.eligibleCount > 0
                    ? `Deep scan marked ${deepScanPolicy.eligibleCount} ${deepScanPolicy.eligibleCount === 1 ? "link" : "links"} as cloud-fetch candidates.`
                    : "",
                deepScanPolicy.liveFetchedCount > 0
                    ? `Deep scan live-checked ${deepScanPolicy.liveFetchedCount} ${deepScanPolicy.liveFetchedCount === 1 ? "destination" : "destinations"}.`
                    : "",
                `Last checked: ${new Date(verdict.updatedAt).toLocaleString()}`
            ].filter(Boolean),
            reasons: verdict.reasons.length > 0 ? verdict.reasons : ["No main safety reasons were returned."],
            links: summarizeLinkFindings(verdict.linkFindings),
            attachments: verdict.attachmentFindings.length > 0
                ? verdict.attachmentFindings.map(formatAttachmentFinding)
                : ["No risky attachments were found."],
            actionCopy: `Suggested next step: ${recommendedActionLabels[verdict.recommendedAction] ?? verdict.recommendedAction}.`
        };
    }

    const summary = document.getElementById("summary");
    const overview = document.getElementById("overview");
    const reasons = document.getElementById("reasons");
    const links = document.getElementById("links");
    const attachments = document.getElementById("attachments");
    const actionCopy = document.getElementById("action-copy");
    function renderList(target, values) {
        target.replaceChildren(...values.map((value) => {
            const item = document.createElement("li");
            item.textContent = value;
            if (value.toLowerCase().startsWith("no ") || value.toLowerCase().startsWith("open ")) {
                item.className = "muted";
            }
            return item;
        }));
    }
    async function load() {
        const activeResponse = await chrome.runtime.sendMessage({ type: "get-active-message" });
        const active = activeResponse.activeMessage;
        const view = buildSidepanelView(active);
        summary.textContent = view.summary;
        renderList(overview, view.overview);
        renderList(reasons, view.reasons);
        renderList(links, view.links);
        renderList(attachments, view.attachments);
        actionCopy.textContent = view.actionCopy;
    }
    chrome.storage.local.onChanged.addListener((changes) => {
        if (changes.activeMessage) {
            void load();
        }
    });
    void load();

})();
//# sourceMappingURL=sidepanel.js.map
