<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SC2 Replay Analyzer - Analysis Feed</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <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@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="/static/css/app.css">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        display: ['Rajdhani', 'sans-serif'],
                        mono: ['Roboto Mono', 'monospace'],
                    },
                    colors: {
                        sc2: { bg: '#0f141e', card: '#141923', accent: '#ff9d5c', win: '#00ff88', loss: '#ff4444' }
                    }
                }
            }
        }
    </script>
</head>
<body class="min-h-screen">
    <div class="top-glow"></div>

    <header class="px-6 py-3 flex items-center justify-between border-b border-white/[0.08]">
        <div class="flex items-center gap-3">
            <a href="/" class="font-display font-bold text-xl tracking-wider uppercase text-white hover:text-[var(--accent-terran)]">
                SC2 Replay Analyzer
            </a>
            <span class="text-white/30">/</span>
            <span class="font-display font-bold text-sm tracking-wider uppercase text-white/60">Analysis Feed</span>
        </div>
    </header>

    <main class="px-6 py-4 max-w-screen-xl mx-auto space-y-4">
        <!-- Filters -->
        <div class="filter-bar flex flex-wrap items-center gap-2 p-3 bg-[var(--bg-card)] rounded-lg border border-white/[0.08]">
            <select id="filterMatchup" onchange="loadFeed()" class="w-24">
                <option value="">Matchup</option>
                <option value="TvZ">TvZ</option>
                <option value="TvP">TvP</option>
                <option value="TvT">TvT</option>
                <option value="ZvP">ZvP</option>
                <option value="ZvZ">ZvZ</option>
                <option value="PvP">PvP</option>
            </select>
            <select id="filterDays" onchange="loadFeed()" class="w-28">
                <option value="">All Time</option>
                <option value="7">Last 7 Days</option>
                <option value="30">Last 30 Days</option>
                <option value="90">Last 90 Days</option>
            </select>
            <select id="filterLimit" onchange="loadFeed()" class="w-24">
                <option value="20">Last 20</option>
                <option value="50" selected>Last 50</option>
                <option value="100">Last 100</option>
                <option value="">All</option>
            </select>
            <div id="feedStatus" class="ml-auto text-xs font-display text-white/40"></div>
        </div>

        <!-- Feed -->
        <div id="feedContainer" class="space-y-3"></div>
    </main>

    <footer class="px-6 py-3 text-center border-t border-white/[0.05]">
        <span class="font-display text-xs text-white/20 tracking-wider">Developed by YAWI</span>
    </footer>

    <script>
        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()]} ${String(d.getDate()).padStart(2, "0")} ${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
            } catch { return isoDate.substring(0, 16); }
        }

        let analysisFields = [];

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

        async function loadFeed() {
            const params = new URLSearchParams();
            const days = document.getElementById("filterDays").value;
            const limit = document.getElementById("filterLimit").value;
            if (days) params.set("days", days);
            if (limit) params.set("limit", limit);

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

            const container = document.getElementById("feedContainer");
            const statusEl = document.getElementById("feedStatus");
            statusEl.textContent = `${notes.length} analyses`;

            if (notes.length === 0) {
                container.innerHTML = '<div class="text-center py-12 text-white/30 font-display">No analyses yet. Go to the main page and click a replay to add one.</div>';
                return;
            }

            container.innerHTML = notes.map(note => {
                const analysis = note.analysis || {};
                const resultClass = (note.result || "").toLowerCase() === "win" ? "text-[var(--color-win)]" : "text-[var(--color-loss)]";

                const fields = Object.entries(analysis)
                    .filter(([, v]) => v && v.trim())
                    .map(([k, v]) => {
                        const fieldDef = analysisFields.find(f => f.key === k);
                        const label = fieldDef ? fieldDef.label : k;
                        return `<div class="py-1">
                            <span class="text-xs font-display text-white/40 uppercase tracking-wide">${escapeHtml(label)}</span>
                            <div class="text-sm text-white/80">${escapeHtml(v)}</div>
                        </div>`;
                    }).join("");

                return `<div class="bg-[var(--bg-card)] rounded-lg border border-white/[0.08] p-4">
                    <div class="flex items-center gap-3 mb-3">
                        <span class="${resultClass} font-bold font-display text-lg">${note.result || "?"}</span>
                        <span class="text-white/60 font-display">${note.matchup || "?"}</span>
                        <span class="text-white/50 font-display">${escapeHtml(note.map_name || "")}</span>
                        ${note.opponent_name ? `<span class="text-white/40 text-sm">vs ${escapeHtml(note.opponent_name)}</span>` : ""}
                        ${note.player_mmr ? `<span class="font-mono text-xs text-white/40">${note.player_mmr} MMR</span>` : ""}
                        <span class="text-white/30 text-xs ml-auto">${formatDate(note.played_at)}</span>
                    </div>
                    <div class="space-y-1 border-t border-white/[0.05] pt-2">
                        ${fields || '<span class="text-white/30 text-sm">No analysis data</span>'}
                    </div>
                </div>`;
            }).join("");
        }

        document.addEventListener("DOMContentLoaded", async () => {
            await loadAnalysisConfig();
            loadFeed();
        });
    </script>
</body>
</html>
