<!DOCTYPE html>
<html>
<head>
    <title>SC2 Analysis Widget</title>
    <link rel="stylesheet" href="/static/css/overlay.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@500;600;700&family=Roboto+Mono:wght@500;700&display=swap" rel="stylesheet">
</head>
<body>
    <div class="widget-container" id="widgetContainer">
        <div class="widget-header">
            <div class="widget-title">POST GAME ANALYSIS</div>
        </div>
        <div class="analysis-widget-content" id="analysisContent">
            <div style="padding: 16px; opacity: 0.3; font-family: Rajdhani, sans-serif; font-size: 13px;">
                No analyses yet
            </div>
        </div>
    </div>
    <script>
        const REFRESH_INTERVAL_MS = 5000;

        function getParams() {
            const p = new URLSearchParams(window.location.search);
            return {
                width: parseInt(p.get("width")) || 1200,
                height: parseInt(p.get("height")) || 600,
                count: parseInt(p.get("count")) || 3,
            };
        }

        function escapeHtml(text) {
            const div = document.createElement("div");
            div.textContent = text;
            return div.innerHTML;
        }

        function formatDate(isoDate) {
            if (!isoDate) return "";
            try {
                const d = new Date(isoDate);
                const months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
                return `${months[d.getMonth()]} ${d.getDate()} ${String(d.getHours()).padStart(2,"0")}:${String(d.getMinutes()).padStart(2,"0")}`;
            } catch { return ""; }
        }

        let analysisFields = [];

        async function loadConfig() {
            const res = await fetch("/api/v1/analysis/config");
            const data = await res.json();
            analysisFields = data.fields || [];
        }

        async function refresh() {
            const params = getParams();
            const res = await fetch(`/api/v1/notes/feed?limit=${params.count}`);
            const data = await res.json();
            const notes = data.notes || [];

            const container = document.getElementById("analysisContent");
            if (notes.length === 0) {
                container.innerHTML = '<div style="padding: 16px; opacity: 0.3; font-family: Rajdhani, sans-serif; font-size: 13px;">No analyses yet</div>';
                return;
            }

            container.innerHTML = notes.map(note => {
                const analysis = note.analysis || {};
                const isWin = (note.result || "").toLowerCase() === "win";
                const resultColor = isWin ? "#00ff88" : "#ff4444";

                const fields = Object.entries(analysis)
                    .filter(([, v]) => v && v.trim())
                    .map(([k, v]) => {
                        const def = analysisFields.find(f => f.key === k);
                        const label = def ? def.label : k;
                        return `<div class="analysis-field-compact">
                            <span class="analysis-label-compact">${escapeHtml(label)}:</span>
                            <span class="analysis-value-compact">${escapeHtml(v)}</span>
                        </div>`;
                    }).join("");

                return `<div class="analysis-entry-compact">
                    <div class="analysis-header">
                        <span style="color: ${resultColor}; font-weight: 700">${note.result || "?"}</span>
                        <span style="color: rgba(255,255,255,0.6)">${note.matchup || "?"}</span>
                        <span style="color: rgba(255,255,255,0.4)">${escapeHtml(note.map_name || "")}</span>
                        <span style="color: rgba(255,255,255,0.25); margin-left: auto; font-family: 'Roboto Mono', monospace; font-size: 11px">${formatDate(note.played_at)}</span>
                    </div>
                    <div class="analysis-fields-grid">${fields}</div>
                </div>`;
            }).join("");
        }

        function applyLayout() {
            const params = getParams();
            const container = document.getElementById("widgetContainer");
            container.style.width = `${params.width}px`;
            container.style.height = `${params.height}px`;
        }

        applyLayout();
        (async () => {
            await loadConfig();
            refresh();
            setInterval(refresh, REFRESH_INTERVAL_MS);
        })();
    </script>
</body>
</html>
