"use strict";
const TYRE_LETTER = { "Macio": "S", "Médio": "M", "Duro": "H", "Intermediário": "I", "Chuva": "W" };
const wearColor = (p) => p == null ? "#555" : p < 30 ? "#2ecc71" : p < 60 ? "#ffd400" : "#e10600";
function fmtLap(ms) {
    if (!ms || ms <= 0) return "—";
    const m = Math.floor(ms / 60000), s = Math.floor((ms % 60000) / 1000), mm = ms % 1000;
    return `${m}:${String(s).padStart(2, "0")}.${String(mm).padStart(3, "0")}`;
}
const fmtGap = (ms) => (ms == null || ms === 0) ? "—" : "+" + (ms / 1000).toFixed(3);
const cell = (k, v) => `<div class="c"><div class="k">${k}</div><div class="v">${v}</div></div>`;

async function tick() {
    let live, lb;
    try {
        [live, lb] = await Promise.all([
            fetch("/api/live").then((r) => r.json()),
            fetch("/api/leaderboard").then((r) => r.json())]);
    } catch (e) { return; }

    const hud = document.getElementById("hud");
    const tower = document.getElementById("tower");
    if (!live.connected) {
        hud.className = "offline";
        hud.innerHTML = "Aguardando o jogo…";
        tower.innerHTML = "";
        return;
    }
    hud.className = "hud";

    const gear = live.gear == null ? "—" : (live.gear < 0 ? "R" : live.gear === 0 ? "N" : live.gear);
    const tyre = live.tyre_compound || "—";
    const letter = TYRE_LETTER[tyre] || (tyre[0] || "?");
    let html = "";
    html += cell("Pos", live.position != null ? "P" + live.position : "—");
    html += cell("Volta", live.current_lap != null ? live.current_lap +
        (live.total_laps ? "/" + live.total_laps : "") : "—");
    html += cell("Vel", live.speed != null ? `${live.speed}<small>km/h</small>` : "—");
    html += cell("Marcha", gear);
    const drsCls = live.drs ? "drs-on" : live.drs_allowed ? "drs-ready" : "drs-off";
    const drsTxt = live.drs ? "▮▮" : live.drs_allowed ? "▮▮" : "—";
    html += cell("DRS", `<span class="${drsCls}">${drsTxt}</span>`);
    html += cell("Últ. volta", fmtLap(live.last_lap_time_ms));
    // pneu + desgaste
    let tyreCell = `<div class="c"><div class="k">Pneu ${live.tyre_age_laps != null ? live.tyre_age_laps + "v" : ""}</div>` +
        `<div class="tyre" style="border-color:${tyreColorByName(tyre)}">${letter}</div>`;
    if (live.tyre_wear && live.tyre_wear.length === 4) {
        tyreCell += `<div class="wear">` +
            live.tyre_wear.map((w) => `<span style="background:${wearColor(w)}" title="${w.toFixed(0)}%"></span>`).join("") +
            `</div>`;
    }
    tyreCell += `</div>`;
    html += tyreCell;
    html += cell("Comb", live.fuel_remaining_laps != null ? live.fuel_remaining_laps.toFixed(1) : "—");
    // aviso de chuva chegando (só aparece quando há previsão de chuva próxima)
    const fc = live.weather_forecast || [];
    const rainSoon = fc.find((s) => s.chuva_pct >= 40 && s.em_min > 0);
    if (rainSoon) {
        html += cell("Chuva", `<span class="rain-soon">🌧️ ${rainSoon.em_min}min<small>${rainSoon.chuva_pct}%</small></span>`);
    }
    hud.innerHTML = html;

    // flash do evento mais recente (punição/abandono), some após ~8s
    const flash = document.getElementById("ev-flash");
    const ev = (live.recent_events || [])[0];
    const FEED_ICON = { penalty: "⛔", warning: "⚠️", retire: "🏳️", info: "🏁" };
    if (ev && (Date.now() / 1000 - ev.t) < 8) {
        flash.className = "ev-flash " + ev.kind;
        flash.innerHTML = `<span>${FEED_ICON[ev.kind] || "•"}</span>` +
            (ev.lap != null ? `<span style="color:#9a9ab2;font-size:11px">V${ev.lap}</span>` : "") +
            `<span class="ev-car">${ev.car}</span><span class="ev-msg">${ev.msg}</span>`;
    } else {
        flash.className = "";
        flash.innerHTML = "";
    }

    // mini torre: jogador e vizinhos
    let rows = lb.rows || [];
    const meIdx = rows.findIndex((r) => r.is_player);
    if (meIdx >= 0) {
        const start = Math.max(0, meIdx - 2);
        rows = rows.slice(start, start + 5);
    } else {
        rows = rows.slice(0, 5);
    }
    tower.innerHTML = rows.map((r) => {
        const letter = TYRE_LETTER[r.tyre] || (r.tyre ? r.tyre[0] : "?");
        return `<div class="trow ${r.is_player ? "me" : ""}">` +
            `<span class="bar" style="background:${r.team_color}"></span>` +
            `<span class="pos">${r.position}</span>` +
            `<span class="nm">${r.name}</span>` +
            `<span class="ty" style="border-color:${r.tyre_color}">${letter}</span>` +
            `<span class="gp">${r.is_player ? fmtGap(r.delta_leader_ms) : fmtGap(r.delta_front_ms)}</span>` +
            `</div>`;
    }).join("");
}
function tyreColorByName(name) {
    return { "Macio": "#da291c", "Médio": "#ffd700", "Duro": "#f0f0f0",
        "Intermediário": "#43b02a", "Chuva": "#0067b1" }[name] || "#888";
}
setInterval(tick, 500);
tick();
