<!DOCTYPE html>
<html>
<head>
    <title>SC2 Live Analysis</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">
    <style>
        .live-idle {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
            font-family: 'Rajdhani', sans-serif;
            font-size: 14px;
            color: rgba(255, 255, 255, 0.2);
            letter-spacing: 2px;
            text-transform: uppercase;
        }

        .live-game-header {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 12px 20px;
            border-bottom: 1px solid rgba(255, 120, 60, 0.2);
            font-family: 'Rajdhani', sans-serif;
            font-weight: 700;
        }

        .live-result {
            font-size: 22px;
            text-shadow: 0 0 10px currentColor;
        }

        .live-matchup {
            font-size: 16px;
            color: rgba(255, 255, 255, 0.7);
        }

        .live-map {
            font-size: 14px;
            color: rgba(255, 255, 255, 0.4);
        }

        .live-mmr {
            font-family: 'Roboto Mono', monospace;
            font-size: 12px;
            color: rgba(255, 255, 255, 0.3);
            margin-left: auto;
        }

        .live-fields {
            padding: 12px 20px;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px 16px;
        }

        .live-field {
            min-height: 1.2em;
        }

        .live-field-label {
            font-family: 'Rajdhani', sans-serif;
            font-size: 10px;
            font-weight: 600;
            color: rgba(255, 255, 255, 0.3);
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 2px;
        }

        .live-field-value {
            font-family: 'Rajdhani', sans-serif;
            font-size: 13px;
            color: rgba(255, 255, 255, 0.85);
            line-height: 1.3;
        }

        .live-field-value:empty::after {
            content: '\00a0';
            color: rgba(255, 255, 255, 0.08);
        }

        /* Typing cursor animation for the field being edited */
        .live-field-value.typing::after {
            content: '|';
            animation: blink 1s step-end infinite;
            color: rgba(255, 120, 60, 0.6);
        }

        @keyframes blink {
            50% { opacity: 0; }
        }

        /* Full-width for notes/textarea fields */
        .live-field.full-width {
            grid-column: 1 / -1;
        }

        .live-badge {
            position: absolute;
            top: 10px;
            right: 16px;
            font-family: 'Roboto Mono', monospace;
            font-size: 9px;
            font-weight: 700;
            color: #ff4444;
            text-transform: uppercase;
            letter-spacing: 1px;
            animation: pulse 2s ease-in-out infinite;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.4; }
        }
    </style>
</head>
<body>
    <div class="widget-container" id="widgetContainer">
        <div class="widget-header">
            <div class="widget-title">LIVE ANALYSIS</div>
        </div>
        <div id="liveContent" style="flex: 1; overflow: hidden; position: relative;">
            <div class="live-idle">Waiting for analysis...</div>
        </div>
    </div>
    <script>
        const POLL_INTERVAL_MS = 500;

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

        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 = [];
        let lastAnalysisJson = "";

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

        async function poll() {
            try {
                const res = await fetch("/api/v1/analysis/draft");
                const draft = await res.json();
                render(draft);
            } catch {
                // Silent failure
            }
        }

        function render(draft) {
            const container = document.getElementById("liveContent");

            if (!draft.active || !draft.replay) {
                if (lastAnalysisJson !== "idle") {
                    container.innerHTML = '<div class="live-idle">Waiting for analysis...</div>';
                    lastAnalysisJson = "idle";
                }
                return;
            }

            const r = draft.replay;
            const analysis = draft.analysis || {};

            // Only re-render if content changed
            const currentJson = JSON.stringify(analysis);
            const gameChanged = lastAnalysisJson === "idle";

            if (currentJson === lastAnalysisJson && !gameChanged) return;
            lastAnalysisJson = currentJson;

            const isWin = (r.result || "").toLowerCase() === "win";
            const resultColor = isWin ? "#00ff88" : "#ff4444";

            const fields = analysisFields.map(field => {
                const value = analysis[field.key] || "";
                const isFullWidth = field.type === "textarea";
                const widthClass = isFullWidth ? "full-width" : "";
                return `<div class="live-field ${widthClass}">
                    <div class="live-field-label">${escapeHtml(field.label)}</div>
                    <div class="live-field-value">${escapeHtml(value)}</div>
                </div>`;
            }).join("");

            container.innerHTML = `
                <div class="live-badge">LIVE</div>
                <div class="live-game-header">
                    <span class="live-result" style="color: ${resultColor}">${r.result || "?"}</span>
                    <span class="live-matchup">${r.matchup || "?"}</span>
                    <span class="live-map">${escapeHtml(r.map_name || "")}</span>
                    ${r.player_mmr ? `<span class="live-mmr">${r.player_mmr} MMR</span>` : ""}
                </div>
                <div class="live-fields">${fields}</div>
            `;
        }

        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();
            poll();
            setInterval(poll, POLL_INTERVAL_MS);
        })();
    </script>
</body>
</html>
