// admin.jsx — Admin panel for editing races (localStorage + Supabase cloud sync)
const { useState: useAA, useEffect: useEA } = React;

function resizeImage(file, maxW = 900, maxH = 560, quality = 0.82) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = (ev) => {
      const img = new Image();
      img.onload = () => {
        const ratio = Math.min(maxW / img.width, maxH / img.height, 1);
        const w = Math.round(img.width * ratio), h = Math.round(img.height * ratio);
        const canvas = document.createElement("canvas");
        canvas.width = w; canvas.height = h;
        canvas.getContext("2d").drawImage(img, 0, 0, w, h);
        resolve(canvas.toDataURL("image/jpeg", quality));
      };
      img.src = ev.target.result;
    };
    reader.readAsDataURL(file);
  });
}

function getRomanianTz(year, month, day) {
  // Romania: EEST (UTC+3) last Sunday of March → last Sunday of October; EET (UTC+2) otherwise
  const lastSun = (m) => { const d = new Date(year, m, 0); return d.getDate() - d.getDay(); };
  const dstS = lastSun(3), dstE = lastSun(10);
  const inDst = (month > 3 && month < 10) || (month === 3 && day >= dstS) || (month === 10 && day < dstE);
  return inDst ? { tz: "EEST", offset: 3 } : { tz: "EET", offset: 2 };
}
function roTimeToUtc(timeStr, year, month, day) {
  const { tz, offset } = getRomanianTz(year, month, day);
  const m = timeStr.match(/^(\d{1,2}):(\d{2})$/);
  if (!m) return { tz, utcStr: "" };
  let h = parseInt(m[1]) - offset;
  if (h < 0) h += 24;
  return { tz, utcStr: `${String(h).padStart(2, "0")}:${m[2]} UTC` };
}

// Persist races to localStorage
function loadRaces() {
  try {
    const saved = localStorage.getItem("igs-races");
    return saved ? JSON.parse(saved) : [];
  } catch (e) { return []; }
}
function saveRaces(r) {
  try { localStorage.setItem("igs-races", JSON.stringify(r)); } catch (e) {}
  saveConfigToCloud('races', r);
}

// Cloud sync helpers
async function saveConfigToCloud(key, value) {
  if (!window.sbClient) return null;
  try {
    const { error } = await window.sbClient.from('site_config')
      .upsert({ id: key, value, updated_at: new Date().toISOString() }, { onConflict: 'id' });
    if (error) {
      console.error('[Admin] Supabase save error:', error);
      if (window._adminSetSaveError) window._adminSetSaveError(error.message || error.details || JSON.stringify(error));
      return error;
    }
    if (window._adminSetSaveError) window._adminSetSaveError(null);
    if (window._loadCloudConfig) window._loadCloudConfig();
    return null;
  } catch(e) {
    console.error('[Admin] Supabase exception:', e);
    if (window._adminSetSaveError) window._adminSetSaveError(String(e));
    return e;
  }
}

function VideoUploadAdmin({ id }) {
  const [hasVideo, setHasVideo] = useAA(false);
  const [loading, setLoading] = useAA(false);
  useEA(() => {
    window.loadVideoIDB && window.loadVideoIDB(id).then(b => setHasVideo(!!b)).catch(() => {});
  }, [id]);
  const handleFile = async (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    setLoading(true);
    try { await window.saveVideoIDB(id, file); setHasVideo(true); } catch(err) {}
    setLoading(false);
    e.target.value = '';
  };
  const handleDelete = async () => {
    await window.deleteVideoIDB(id);
    setHasVideo(false);
  };
  return (
    <div style={{ display: "flex", gap: "8px", alignItems: "center", flexWrap: "wrap" }}>
      {hasVideo && <span style={{ fontSize: "12px", color: "#3ecf8e", fontFamily: "var(--mono)" }}>✓ Video încărcat</span>}
      <label className="btn sm" style={{ cursor: "pointer" }}>
        <span>{loading ? "Se încarcă..." : hasVideo ? "Schimbă MP4" : "Încarcă MP4"}</span>
        <input type="file" accept="video/mp4,video/webm" hidden onChange={handleFile} disabled={loading} />
      </label>
      {hasVideo && <button className="btn sm ghost" onClick={handleDelete}><span>Șterge video</span></button>}
    </div>
  );
}

function ImageSlotAdmin({ id, label, height = "130px", placeholder }) {
  const trigger = (act) => {
    const el = document.getElementById(id);
    if (!el) return;
    const sr = el.shadowRoot;
    if (act === 'replace') {
      const btn = sr && sr.querySelector('[data-act="replace"]');
      if (btn) btn.click();
      else if (sr) { const inp = sr.querySelector('input[type="file"]'); if (inp) inp.click(); }
    } else if (act === 'clear') {
      const btn = sr && sr.querySelector('[data-act="clear"]');
      if (btn) btn.click();
    }
  };
  return (
    <div>
      {label && <div style={{ fontSize: "12px", color: "var(--muted)", marginBottom: "6px", fontFamily: "var(--mono)" }}>{label}</div>}
      <image-slot id={id} data-editable="" style={{ width: "100%", height, display: "block" }} shape="rect" fit="cover" placeholder={placeholder}></image-slot>
      <div style={{ display: "flex", gap: "6px", marginTop: "8px" }}>
        <button className="btn sm" onClick={() => trigger('replace')}><span>Schimbă / Adaugă</span></button>
        <button className="btn sm ghost" onClick={() => trigger('clear')}><span>Șterge</span></button>
      </div>
    </div>
  );
}

function TexteTab() {
  const [editLang, setEditLang] = useAA("ro");
  const [overrides, setOverrides] = useAA(() => loadTextOverrides());
  const keys = [
    { key: "hero.lead", label: "Hero — descriere" },
    { key: "home.do.title", label: "Secț. 'Ce facem' — titlu" },
    { key: "home.do.lead", label: "Secț. 'Ce facem' — paragraf" },
    { key: "feat.1.t", label: "Feature 1 — titlu" }, { key: "feat.1.p", label: "Feature 1 — text" },
    { key: "feat.2.t", label: "Feature 2 — titlu" }, { key: "feat.2.p", label: "Feature 2 — text" },
    { key: "feat.3.t", label: "Feature 3 — titlu" }, { key: "feat.3.p", label: "Feature 3 — text" },
    { key: "feat.4.t", label: "Feature 4 — titlu" }, { key: "feat.4.p", label: "Feature 4 — text" },
    { key: "cta.title", label: "CTA — titlu" }, { key: "cta.text", label: "CTA — text" },
    { key: "footer.tagline", label: "Footer — tagline" },
    { key: "about.eyebrow", label: "Despre noi — eyebrow" },
    { key: "about.titleA", label: "Despre noi — titlu (parte A)" },
    { key: "about.titleB", label: "Despre noi — titlu (parte B)" },
    { key: "about.p1", label: "Despre noi — paragraf 1" },
    { key: "about.p2", label: "Despre noi — paragraf 2" },
    { key: "about.p3", label: "Despre noi — paragraf 3" },
    { key: "about.fmt.eyebrow", label: "Format etapă — eyebrow" },
    { key: "about.fmt.title", label: "Format etapă — titlu" },
    { key: "step.practice.t", label: "Pasul Practice — titlu" }, { key: "step.practice.h", label: "Pasul Practice — durată" }, { key: "step.practice.p", label: "Pasul Practice — descriere" },
    { key: "step.quali.t", label: "Pasul Qualifying — titlu" }, { key: "step.quali.h", label: "Pasul Qualifying — durată" }, { key: "step.quali.p", label: "Pasul Qualifying — descriere" },
    { key: "step.race.t", label: "Pasul Race — titlu" }, { key: "step.race.h", label: "Pasul Race — durată" }, { key: "step.race.p", label: "Pasul Race — descriere" },
    { key: "about.rules.eyebrow", label: "Regulament — eyebrow" },
    { key: "about.rules.title", label: "Regulament — titlu" },
    { key: "about.rules.lead", label: "Regulament — lead" },
    { key: "rule.a.t", label: "Regula A — titlu" }, { key: "rule.a.p", label: "Regula A — text" },
    { key: "rule.b.t", label: "Regula B — titlu" }, { key: "rule.b.p", label: "Regula B — text" },
    { key: "rule.c.t", label: "Regula C — titlu" }, { key: "rule.c.p", label: "Regula C — text" },
    { key: "rule.d.t", label: "Regula D — titlu" }, { key: "rule.d.p", label: "Regula D — text" },
  ];
  const getVal = (key) => (overrides[editLang] && overrides[editLang][key] != null) ? overrides[editLang][key] : ((S[editLang] && S[editLang][key] != null) ? S[editLang][key] : (S.en[key] || ""));
  const handleChange = (key, val) => {
    saveTextOverride(editLang, key, val);
    setOverrides(loadTextOverrides());
  };
  const isOverridden = (key) => overrides[editLang] && overrides[editLang][key] != null;
  const reset = (key) => { saveTextOverride(editLang, key, null); setOverrides(loadTextOverrides()); };
  const iStyle = { width: "100%", padding: "8px", background: "var(--bg2)", color: "var(--text)", border: "1px solid var(--line)", boxSizing: "border-box", fontFamily: "inherit", resize: "vertical" };
  const lStyle = { display: "block", fontSize: "12px", color: "var(--muted)", marginBottom: "4px" };
  return (
    <div style={{ display: "grid", gap: "16px" }}>
      <div style={{ display: "flex", gap: "8px", alignItems: "center", flexWrap: "wrap" }}>
        <span style={{ fontSize: "13px", color: "var(--muted)", fontFamily: "var(--mono)" }}>Limbă:</span>
        {["en","ro","de","fr","es"].map(l => <button key={l} className={"btn sm" + (editLang !== l ? " ghost" : "")} onClick={() => setEditLang(l)}><span>{l.toUpperCase()}</span></button>)}
      </div>
      {keys.map(({ key, label }) => (
        <div key={key} style={{ background: "var(--panel)", padding: "14px", border: "1px solid var(--line)" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "6px" }}>
            <label style={{ ...lStyle, margin: 0 }}>{label} {isOverridden(key) && <span style={{ color: "var(--accent)", marginLeft: 4 }}>●</span>}</label>
            {isOverridden(key) && <button className="btn sm ghost" onClick={() => reset(key)} style={{ fontSize: "11px", padding: "2px 8px" }}><span>Reset</span></button>}
          </div>
          <textarea rows={getVal(key).length > 80 ? 3 : 2} value={getVal(key)} onChange={e => handleChange(key, e.target.value)} style={iStyle} />
        </div>
      ))}
    </div>
  );
}

/* ══════════════════════════════════════════════════════
   REZULTATE TAB
   ══════════════════════════════════════════════════════ */
const PTS_SCALE_ADMIN = [25, 18, 15, 12, 10, 8, 6, 4, 2, 1];
function calcPtsAdmin(pos, fl, dnf, dsq) {
  if (dnf || dsq || !pos) return 0;
  return (PTS_SCALE_ADMIN[pos - 1] || 0) + (fl ? 1 : 0);
}

function parseIRacingCSV(text) {
  const lines = text.trim().split(/\r?\n/).filter(l => l.trim());
  if (lines.length < 2) throw new Error("CSV prea scurt — trebuie cel puțin header + 1 rând.");

  const parseRow = (line) => {
    const res = []; let cur = '', inQ = false;
    for (let i = 0; i < line.length; i++) {
      const c = line[i];
      if (c === '"') { inQ = !inQ; continue; }
      if (c === ',' && !inQ) { res.push(cur.trim()); cur = ''; continue; }
      cur += c;
    }
    res.push(cur.trim());
    return res;
  };

  // iRacing exports have metadata blocks before the actual results table.
  // Find the header line that contains race result columns.
  let headerIdx = 0;
  for (let i = 0; i < lines.length; i++) {
    const lower = lines[i].toLowerCase();
    if (lower.includes('fin pos') || lower.includes('cust id') || (lower.includes('name') && lower.includes('laps comp'))) {
      headerIdx = i;
      break;
    }
  }

  const headers = parseRow(lines[headerIdx]).map(h => h.toLowerCase().replace(/[^a-z0-9#]/g, ' ').trim());

  // Try exact match first, then substring — avoids 'car id' matching before 'car'
  const find = (...names) => {
    for (const n of names) { const i = headers.findIndex(h => h === n); if (i >= 0) return i; }
    for (const n of names) { const i = headers.findIndex(h => h.includes(n)); if (i >= 0) return i; }
    return -1;
  };

  const colPos    = find('fin pos', 'finish pos', 'finish position', 'pos', 'position');
  const colNum    = find('car #', 'car#', 'number', 'num');
  const colDriver = find('name', 'driver', 'pilot');
  const colCar    = find('car', 'vehicle');
  const colTeam   = find('team');
  const colOut    = find('out', 'status', 'result', 'finished');
  const colFLap   = find('fastest lap time', 'fast lap', 'best lap');

  if (colDriver < 0) throw new Error("Nu găsesc coloana 'Name' / 'Driver' în CSV.");

  const rows = [];
  for (let i = headerIdx + 1; i < lines.length; i++) {
    const cols = parseRow(lines[i]);
    if (cols.length < 2) continue;
    const pilot = (cols[colDriver] || '').trim();
    if (!pilot) continue;
    const posRaw = colPos >= 0 ? cols[colPos] : '';
    const pos = parseInt(posRaw) || null;
    const outStr = colOut >= 0 ? (cols[colOut] || '').toLowerCase() : '';
    const isDNF = !!(outStr && !outStr.includes('running') && !outStr.includes('finish') && outStr !== '');
    const fastLap = colFLap >= 0 ? (cols[colFLap] || '').trim() : '';
    rows.push({
      position: isDNF ? null : pos,
      pilot_name: pilot,
      car_number: colNum >= 0 ? (cols[colNum] || '').replace('#','').trim() : '',
      car: colCar >= 0 ? (cols[colCar] || '').trim() : '',
      team_name: colTeam >= 0 ? (cols[colTeam] || '').trim() : '',
      fastest_lap_time: fastLap,
      dnf: isDNF, dsq: false, fastest_lap: false,
    });
  }
  if (!rows.length) throw new Error("Niciun rând valid găsit în CSV.");
  return rows;
}

function RezultateTab({ races }) {
  const [selRace, setSelRace] = useAA(races[0]?.id || "");
  const [allResults, setAllResults] = useAA([]);
  const [loading, setLoading] = useAA(false);
  const [form, setForm] = useAA({ position: "", pilot_name: "", car_number: "", car: "", team_name: "", fastest_lap: false, dnf: false, dsq: false });
  const [saving, setSaving] = useAA(false);
  const [importing, setImporting] = useAA(false);
  const [csvOpen, setCsvOpen] = useAA(false);
  const [csvRaw, setCsvRaw] = useAA("");
  const [csvRows, setCsvRows] = useAA([]);
  const [csvErr, setCsvErr] = useAA("");
  const [csvSaving, setCsvSaving] = useAA(false);

  // Load ALL results from Supabase, not filtered by race
  const load = async () => {
    if (!window.sbClient) return;
    setLoading(true);
    const { data } = await window.sbClient.from('race_results').select('*').order('race_id').order('position');
    setAllResults(data || []);
    setLoading(false);
  };

  useEA(() => { load(); }, []);

  // Results for selected race (for add form)
  const results = allResults.filter(r => r.race_id === selRace);

  // All distinct race_ids that have results in DB
  const raceMap = {};
  races.forEach(r => { raceMap[r.id] = r; });
  const resultRaceIds = [...new Set(allResults.map(r => r.race_id))];

  const addResult = async () => {
    if (!form.pilot_name.trim()) return;
    setSaving(true);
    const pos = parseInt(form.position) || null;
    const pts = calcPtsAdmin(pos, form.fastest_lap, form.dnf, form.dsq);
    const { error } = await window.sbClient.from('race_results').insert({
      race_id: selRace, position: pos, pilot_name: form.pilot_name.trim(),
      car_number: form.car_number || null, car: form.car || null,
      team_name: form.team_name || null, fastest_lap: form.fastest_lap,
      dnf: form.dnf, dsq: form.dsq, points: pts
    });
    if (!error) {
      setForm({ position: "", pilot_name: "", car_number: "", car: "", team_name: "", fastest_lap: false, dnf: false, dsq: false });
      load();
    } else alert("Eroare: " + error.message);
    setSaving(false);
  };

  const deleteResult = async (id) => {
    if (!window.confirm("Ștergi acest rezultat?")) return;
    await window.sbClient.from('race_results').delete().eq('id', id);
    setAllResults(prev => prev.filter(r => r.id !== id));
  };

  const deleteAllForRace = async (raceId) => {
    const count = allResults.filter(r => r.race_id === raceId).length;
    if (!window.confirm(`Ștergi toate cele ${count} rezultate?`)) return;
    const ids = allResults.filter(r => r.race_id === raceId).map(r => r.id);
    await window.sbClient.from('race_results').delete().in('id', ids);
    setAllResults(prev => prev.filter(r => r.race_id !== raceId));
  };

  const updatePts = async (r) => {
    const pts = calcPtsAdmin(r.position, r.fastest_lap, r.dnf, r.dsq);
    await window.sbClient.from('race_results').update({ points: pts }).eq('id', r.id);
    setResults(prev => prev.map(x => x.id === r.id ? { ...x, points: pts } : x));
  };

  const importFromSignups = async () => {
    setImporting(true);
    const { data } = await window.sbClient.from('signups').select('*').eq('race_id', selRace);
    if (data && data.length) {
      const existing = new Set(results.map(r => r.pilot_name));
      const toInsert = data.filter(p => !existing.has(p.name)).map(p => ({
        race_id: selRace, pilot_name: p.name, car_number: p.car_number,
        car: p.car, team_name: p.team_name, points: 0
      }));
      if (toInsert.length) {
        await window.sbClient.from('race_results').insert(toInsert);
        load();
      } else alert("Toți piloții din grilă sunt deja importați.");
    } else alert("Nu există piloți înscriși pentru această cursă.");
    setImporting(false);
  };

  const race = races.find(r => r.id === selRace);
  const lS = { fontSize: "11px", color: "var(--muted)", fontFamily: "var(--mono)", marginBottom: 4, display: "block", letterSpacing: "0.08em" };
  const iS = { width: "100%", padding: "7px 10px", background: "var(--bg2)", border: "1px solid var(--line)", color: "var(--text)", fontFamily: "var(--mono)", fontSize: 13, outline: "none", boxSizing: "border-box" };
  const thS = { padding: "8px 10px", textAlign: "left", fontFamily: "var(--mono)", fontSize: "10px", letterSpacing: "0.1em", color: "var(--muted)", fontWeight: 400, borderBottom: "1px solid var(--line)", whiteSpace: "nowrap" };
  const tdS = { padding: "9px 10px", verticalAlign: "middle", borderBottom: "1px solid rgba(255,255,255,0.04)", fontSize: 13 };

  return (
    <div style={{ display: "grid", gap: 20 }}>
      {/* Race selector */}
      <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
        <select style={{ ...iS, width: "auto", flex: 1 }} value={selRace} onChange={e => { setSelRace(e.target.value); setCsvOpen(false); setCsvRows([]); setCsvRaw(""); }}>
          {races.sort((a,b)=>a.round-b.round).map(r => (
            <option key={r.id} value={r.id}>RND {String(r.round).padStart(2,"0")} · {r.name}</option>
          ))}
        </select>
        <button className="btn sm ghost" onClick={importFromSignups} disabled={importing}>
          <span>{importing ? "Se importă..." : "⬇ Import din grilă"}</span>
        </button>
        <button className="btn sm ghost" onClick={() => { setCsvOpen(v => !v); setCsvRows([]); setCsvRaw(""); setCsvErr(""); }}
          style={csvOpen ? { borderColor: "var(--accent)", color: "var(--accent)" } : {}}>
          <span>{csvOpen ? "✕ Închide CSV" : "📂 Import CSV"}</span>
        </button>
      </div>

      {/* ── CSV Import Panel ── */}
      {csvOpen && (
        <div style={{ background: "var(--panel)", padding: 16, border: "1px solid var(--accent)", display: "grid", gap: 12 }}>
          <div style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--accent)", letterSpacing: "0.1em" }}>IMPORT CSV iRacing</div>
          <div style={{ fontSize: 12, color: "var(--muted)", lineHeight: 1.5 }}>
            iRacing → My Events → Recent Results → Export CSV. Paste CSV-ul mai jos (cu header).<br />
            Coloane recunoscute: <span style={{ fontFamily: "var(--mono)", color: "var(--text)" }}>Finish Pos, Car #, Driver, Car, Team, Out</span>
          </div>
          <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
            <label style={{ cursor: "pointer" }}>
              <input type="file" accept=".csv,text/csv" style={{ display: "none" }} onChange={e => {
                const file = e.target.files[0];
                if (!file) return;
                const reader = new FileReader();
                reader.onload = ev => {
                  const text = ev.target.result;
                  setCsvRaw(text);
                  setCsvRows([]); setCsvErr("");
                  try { const r = parseIRacingCSV(text); setCsvRows(r); setCsvErr(""); }
                  catch(err) { setCsvErr(err.message); }
                };
                reader.readAsText(file);
                e.target.value = "";
              }} />
              <span className="btn sm ghost" style={{ pointerEvents: "none" }}>📁 Alege fișier CSV</span>
            </label>
            <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--muted)" }}>sau paste mai jos</span>
          </div>
          <textarea
            value={csvRaw}
            onChange={e => { setCsvRaw(e.target.value); setCsvRows([]); setCsvErr(""); }}
            rows={4}
            placeholder={"Paste CSV aici sau alege fișierul de mai sus..."}
            style={{ width: "100%", background: "var(--bg2)", color: "var(--text)", border: "1px solid var(--line)", fontFamily: "var(--mono)", fontSize: 11, padding: 8, boxSizing: "border-box", resize: "vertical" }}
          />
          <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
            <button className="btn sm" onClick={() => {
              try { const r = parseIRacingCSV(csvRaw); setCsvRows(r); setCsvErr(""); }
              catch(e) { setCsvErr(e.message); setCsvRows([]); }
            }}>Parsează →</button>
            {csvErr && <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--accent)" }}>✕ {csvErr}</span>}
            {csvRows.length > 0 && !csvErr && <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "#3ecf8e" }}>✓ {csvRows.length} rânduri detectate</span>}
          </div>

          {csvRows.length > 0 && (
            <>
              <div style={{ fontSize: 11, color: "var(--muted)", fontFamily: "var(--mono)" }}>
                Verifică datele și marchează Fastest Lap / DNF / DSQ:
              </div>
              <div style={{ overflowX: "auto" }}>
                <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
                  <thead>
                    <tr>{["POS","#","PILOT","MAȘINĂ","ECHIPĂ","FL","DNF","DSQ"].map(h => (
                      <th key={h} style={{ padding: "6px 8px", textAlign: "left", fontFamily: "var(--mono)", fontSize: 9, color: "var(--muted)", borderBottom: "1px solid var(--line)", whiteSpace: "nowrap" }}>{h}</th>
                    ))}</tr>
                  </thead>
                  <tbody>
                    {csvRows.map((row, i) => {
                      const upd = (patch) => setCsvRows(p => p.map((r,j) => j===i ? {...r,...patch} : r));
                      const fi = { width: 40, background: "var(--bg2)", border: "1px solid var(--line)", color: "var(--text)", padding: "2px 4px", fontFamily: "var(--mono)", fontSize: 11 };
                      const fi2 = { ...fi, width: 100 };
                      return (
                        <tr key={i} style={{ borderBottom: "1px solid rgba(255,255,255,0.04)" }}>
                          <td style={{ padding: "5px 8px" }}>
                            <input type="number" value={row.position||""} onChange={e => upd({position: parseInt(e.target.value)||null})} style={fi} />
                          </td>
                          <td style={{ padding: "5px 8px" }}>
                            <input value={row.car_number} onChange={e => upd({car_number: e.target.value})} style={fi} />
                          </td>
                          <td style={{ padding: "5px 8px", fontWeight: 600, whiteSpace: "nowrap" }}>{row.pilot_name}</td>
                          <td style={{ padding: "5px 8px" }}>
                            <input value={row.car} onChange={e => upd({car: e.target.value})} style={{...fi2, width:130}} />
                          </td>
                          <td style={{ padding: "5px 8px" }}>
                            <input value={row.team_name} onChange={e => upd({team_name: e.target.value})} style={fi2} />
                          </td>
                          <td style={{ padding: "5px 8px", textAlign: "center" }}>
                            <input type="checkbox" checked={row.fastest_lap} onChange={e => upd({fastest_lap: e.target.checked})} style={{ accentColor: "#b44fff" }} />
                          </td>
                          <td style={{ padding: "5px 8px", textAlign: "center" }}>
                            <input type="checkbox" checked={row.dnf} onChange={e => upd({dnf: e.target.checked, position: e.target.checked ? null : row.position})} />
                          </td>
                          <td style={{ padding: "5px 8px", textAlign: "center" }}>
                            <input type="checkbox" checked={row.dsq} onChange={e => upd({dsq: e.target.checked})} />
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
              <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                <button className="btn" disabled={csvSaving} onClick={async () => {
                  setCsvSaving(true);
                  const toInsert = csvRows.map(row => ({
                    race_id: selRace,
                    position: (row.dnf||row.dsq) ? null : row.position,
                    pilot_name: row.pilot_name,
                    car_number: row.car_number || null,
                    car: row.car || null,
                    team_name: row.team_name || null,
                    fastest_lap: !!row.fastest_lap,
                    dnf: !!row.dnf, dsq: !!row.dsq,
                    points: calcPtsAdmin((row.dnf||row.dsq) ? null : row.position, row.fastest_lap, row.dnf, row.dsq)
                  }));
                  const { error } = await window.sbClient.from('race_results').insert(toInsert);
                  if (error) { alert("Eroare Supabase: " + error.message); }
                  else { setCsvOpen(false); setCsvRaw(""); setCsvRows([]); load(); }
                  setCsvSaving(false);
                }}>
                  <span>{csvSaving ? "Se salvează..." : `✓ Importă ${csvRows.length} piloți`}</span>
                </button>
                <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--muted)" }}>
                  Rezultatele existente pentru această cursă nu se șterg automat.
                </span>
              </div>
            </>
          )}
        </div>
      )}

      {/* Add result form */}
      <div style={{ background: "var(--panel)", padding: 16, border: "1px solid var(--line)" }}>
        <div style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--accent)", marginBottom: 12, letterSpacing: "0.1em" }}>ADAUGĂ REZULTAT</div>
        <div style={{ display: "grid", gridTemplateColumns: "60px 1fr 70px 1fr 1fr", gap: 8, marginBottom: 8 }}>
          <div><label style={lS}>POS</label><input style={iS} type="number" min="1" placeholder="1" value={form.position} onChange={e => setForm(s => ({...s, position: e.target.value}))} /></div>
          <div><label style={lS}>PILOT *</label><input style={iS} placeholder="Nume pilot" value={form.pilot_name} onChange={e => setForm(s => ({...s, pilot_name: e.target.value}))} /></div>
          <div><label style={lS}>#</label><input style={iS} placeholder="33" value={form.car_number} onChange={e => setForm(s => ({...s, car_number: e.target.value}))} /></div>
          <div><label style={lS}>MAȘINĂ</label><input style={iS} placeholder="Porsche 992 GT3 R" value={form.car} onChange={e => setForm(s => ({...s, car: e.target.value}))} /></div>
          <div><label style={lS}>ECHIPĂ</label><input style={iS} placeholder="Team name" value={form.team_name} onChange={e => setForm(s => ({...s, team_name: e.target.value}))} /></div>
        </div>
        <div style={{ display: "flex", gap: 16, alignItems: "center", flexWrap: "wrap" }}>
          <label style={{ display: "flex", alignItems: "center", gap: 6, cursor: "pointer", fontSize: 13 }}>
            <input type="checkbox" checked={form.fastest_lap} onChange={e => setForm(s => ({...s, fastest_lap: e.target.checked}))} />
            <span style={{ color: "#b44fff" }}>⬤ Fastest Lap (+1pt)</span>
          </label>
          <label style={{ display: "flex", alignItems: "center", gap: 6, cursor: "pointer", fontSize: 13 }}>
            <input type="checkbox" checked={form.dnf} onChange={e => setForm(s => ({...s, dnf: e.target.checked}))} />
            <span>DNF</span>
          </label>
          <label style={{ display: "flex", alignItems: "center", gap: 6, cursor: "pointer", fontSize: 13 }}>
            <input type="checkbox" checked={form.dsq} onChange={e => setForm(s => ({...s, dsq: e.target.checked}))} />
            <span>DSQ</span>
          </label>
          <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 10 }}>
            {form.position && !form.dnf && !form.dsq && (
              <span style={{ fontFamily: "var(--mono)", fontSize: 12, color: "var(--accent)" }}>
                {calcPtsAdmin(parseInt(form.position), form.fastest_lap, form.dnf, form.dsq)} puncte
              </span>
            )}
            <button className="btn sm" onClick={addResult} disabled={saving || !form.pilot_name.trim()}>
              <span>{saving ? "Se salvează..." : "+ Adaugă"}</span>
            </button>
          </div>
        </div>
      </div>

      {/* All results grouped by race */}
      {loading ? (
        <div style={{ padding: 40, textAlign: "center", fontFamily: "var(--mono)", color: "var(--muted)" }}>Se încarcă...</div>
      ) : allResults.length === 0 ? (
        <div style={{ padding: 40, textAlign: "center", fontFamily: "var(--mono)", color: "var(--muted)", background: "var(--panel)", border: "1px solid var(--line)" }}>
          Niciun rezultat în baza de date.
        </div>
      ) : (
        <div style={{ display: "grid", gap: 16 }}>
          {resultRaceIds.map(raceId => {
            const raceData = raceMap[raceId];
            const raceResults = allResults.filter(r => r.race_id === raceId).sort((a,b) => {
              if (a.dnf || a.dsq) return 1; if (b.dnf || b.dsq) return -1;
              return (a.position||99)-(b.position||99);
            });
            const label = raceData ? `RND ${String(raceData.round).padStart(2,"0")} · ${raceData.name.toUpperCase()}` : raceId;
            return (
              <div key={raceId} style={{ background: "var(--panel)", border: "1px solid var(--line)" }}>
                <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 8 }}>
                  <span style={{ fontFamily: "var(--display)", fontSize: 15, fontWeight: 700 }}>{label} · {raceResults.length} rezultate</span>
                  <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                    <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--muted)" }}>
                      Total: {raceResults.reduce((s,r) => s+(r.points||0), 0)} puncte
                    </span>
                    <button className="btn sm ghost" style={{ color: "var(--accent)", borderColor: "var(--accent)" }}
                      onClick={() => deleteAllForRace(raceId)}>
                      <span>🗑 Șterge toate</span>
                    </button>
                  </div>
                </div>
                <div style={{ overflowX: "auto" }}>
                  <table style={{ width: "100%", borderCollapse: "collapse" }}>
                    <thead>
                      <tr><th style={thS}>POS</th><th style={thS}>#</th><th style={thS}>PILOT</th><th style={thS}>MAȘINĂ</th><th style={thS}>ECHIPĂ</th><th style={{...thS,textAlign:"center"}}>FL</th><th style={{...thS,textAlign:"center"}}>DNF</th><th style={{...thS,textAlign:"right"}}>PTS</th><th style={thS}></th></tr>
                    </thead>
                    <tbody>
                      {raceResults.map(r => (
                        <tr key={r.id}>
                          <td style={tdS}><span style={{ fontFamily: "var(--display)", fontWeight: 700 }}>{r.dnf ? "DNF" : r.dsq ? "DSQ" : r.position ? `P${r.position}` : "—"}</span></td>
                          <td style={{...tdS, color:"var(--accent)", fontFamily:"var(--display)", fontWeight:700}}>{r.car_number ? `#${r.car_number}` : "—"}</td>
                          <td style={{...tdS, fontWeight:600}}>{r.pilot_name}</td>
                          <td style={{...tdS, color:"var(--muted)", fontSize:12}}>{r.car || "—"}</td>
                          <td style={{...tdS, color:"var(--muted)", fontSize:12}}>{r.team_name || "—"}</td>
                          <td style={{...tdS, textAlign:"center"}}>{r.fastest_lap && <span style={{color:"#b44fff"}}>⬤</span>}</td>
                          <td style={{...tdS, textAlign:"center"}}>{(r.dnf||r.dsq) && <span style={{color:"var(--accent)"}}>✕</span>}</td>
                          <td style={{...tdS, textAlign:"right", fontFamily:"var(--display)", fontWeight:700, fontSize:16, color:"var(--accent)"}}>{r.points || 0}</td>
                          <td style={{...tdS}}>
                            <button className="btn sm ghost" onClick={() => deleteResult(r.id)} style={{color:"var(--accent)",border:"1px solid var(--accent)",padding:"3px 8px"}}><span>✕</span></button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Points legend */}
      <div style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--faint)", padding: "8px 0" }}>
        Sistem puncte: P1=25 · P2=18 · P3=15 · P4=12 · P5=10 · P6=8 · P7=6 · P8=4 · P9=2 · P10=1 · Fastest Lap=+1
      </div>
    </div>
  );
}

function PilotiTab({ races }) {
  const [pilots, setPilots] = useAA([]);
  const [loading, setLoading] = useAA(true);
  const [error, setError] = useAA(null);
  const [expanded, setExpanded] = useAA(null);
  const [updating, setUpdating] = useAA(null);

  const load = async () => {
    if (!window.sbClient) { setError("Supabase nu e configurat."); setLoading(false); return; }
    setLoading(true); setError(null);
    try {
      const { data, error: err } = await window.sbClient
        .from('signups').select('*').order('created_at', { ascending: true });
      if (err) setError("Eroare Supabase: " + err.message);
      else setPilots(data || []);
    } catch(e) { setError("Eroare rețea: " + e.message); }
    setLoading(false);
  };

  useEA(() => { load(); }, []);

  const toggleAdded = async (pilot) => {
    if (updating) return;
    setUpdating(pilot.id);
    const newVal = !pilot.league_added;
    const { error: err } = await window.sbClient
      .from('signups').update({ league_added: newVal }).eq('id', pilot.id);
    if (!err) setPilots(prev => prev.map(p => p.id === pilot.id ? { ...p, league_added: newVal } : p));
    setUpdating(null);
  };

  const deletePilot = async (pilot) => {
    if (!window.confirm(`Ștergi pilotul "${pilot.name}"? Această acțiune nu poate fi anulată.`)) return;
    const { error: err, count } = await window.sbClient
      .from('signups').delete({ count: 'exact' }).eq('id', pilot.id);
    if (err) {
      alert("Eroare la ștergere: " + err.message);
    } else if (count === 0) {
      alert("Ștergerea a eșuat — adaugă politica DELETE în Supabase:\nCREATE POLICY \"Allow anon delete signups\" ON signups FOR DELETE USING (true);");
    } else {
      setPilots(prev => prev.filter(p => p.id !== pilot.id));
    }
  };

  const byRace = {};
  pilots.forEach(p => { if (!byRace[p.race_id]) byRace[p.race_id] = []; byRace[p.race_id].push(p); });

  const addedTotal = pilots.filter(p => p.league_added).length;

  const thS = { padding: "8px 12px", textAlign: "left", color: "var(--muted)", fontFamily: "var(--mono)", fontWeight: 400, fontSize: "11px", letterSpacing: "0.08em", whiteSpace: "nowrap" };
  const tdS = { padding: "10px 12px", verticalAlign: "middle" };

  const knownRaceIds = new Set(races.map(r => r.id));
  const unmatchedPilots = pilots.filter(p => !knownRaceIds.has(p.race_id));

  return (
    <div style={{ display: "grid", gap: "20px" }}>

      {/* Summary bar */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 10 }}>
        <div style={{ display: "flex", gap: 20 }}>
          <span style={{ fontFamily: "var(--mono)", fontSize: "13px", color: "var(--muted)" }}>
            Total înscriși: <b style={{ color: "var(--text)" }}>{pilots.length}</b>
          </span>
          <span style={{ fontFamily: "var(--mono)", fontSize: "13px", color: "var(--muted)" }}>
            Adăugați în ligă: <b style={{ color: "#3ecf8e" }}>{addedTotal}</b>
          </span>
          <span style={{ fontFamily: "var(--mono)", fontSize: "13px", color: "var(--muted)" }}>
            În așteptare: <b style={{ color: "var(--accent)" }}>{pilots.length - addedTotal}</b>
          </span>
        </div>
        <button className="btn sm ghost" onClick={load} disabled={loading}>
          <span>{loading ? "Se încarcă..." : "↻ Reîncarcă"}</span>
        </button>
      </div>

      {error && (
        <div style={{ padding: "12px 16px", background: "rgba(255,60,60,0.1)", border: "1px solid #ff3c3c", color: "#ff7070", fontFamily: "var(--mono)", fontSize: "13px" }}>
          {error}
          <div style={{ marginTop: 6, fontSize: "11px", opacity: 0.8 }}>
            Rulează în Supabase SQL Editor:<br />
            <code style={{ background: "rgba(0,0,0,0.3)", padding: "2px 6px", display: "inline-block", marginTop: 4 }}>
              alter table signups add column if not exists league_added boolean default false;
            </code>
          </div>
        </div>
      )}

      {loading && !pilots.length && (
        <div style={{ padding: "30px", textAlign: "center", color: "var(--muted)", fontFamily: "var(--mono)", fontSize: "13px" }}>
          Se încarcă piloții...
        </div>
      )}

      {/* Per-race groups */}
      {races.map(r => {
        const rp = byRace[r.id] || [];
        const addedInRace = rp.filter(p => p.league_added).length;
        return (
          <div key={r.id} style={{ background: "var(--panel)", border: "1px solid var(--line)" }}>
            {/* Race header */}
            <div style={{ padding: "14px 20px", borderBottom: rp.length > 0 ? "1px solid var(--line)" : "none", display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 8 }}>
              <h3 style={{ margin: 0, fontFamily: "var(--display)", fontSize: "17px" }}>
                RND {String(r.round).padStart(2,"0")} · {r.name}
              </h3>
              <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
                <span style={{ fontFamily: "var(--mono)", fontSize: "12px", color: "#3ecf8e" }}>{addedInRace} adăugați</span>
                <span style={{ fontFamily: "var(--mono)", fontSize: "13px", color: rp.length > 0 ? "var(--accent)" : "var(--muted)" }}>
                  {rp.length} / {r.gridTotal} înscriși
                </span>
              </div>
            </div>

            {rp.length === 0
              ? <div style={{ padding: "14px 20px", color: "var(--muted)", fontSize: "13px", fontFamily: "var(--mono)" }}>Niciun pilot înscris.</div>
              : <div style={{ overflowX: "auto" }}>
                  <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "13px" }}>
                    <thead>
                      <tr style={{ borderBottom: "1px solid var(--line)" }}>
                        {["", "#", "Pilot", "iRacing ID", "Nr. pref. / alt.", "Echipă", "Mașină", "Ajutor", "Acțiune"].map(h => (
                          <th key={h} style={thS}>{h}</th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {rp.map((p, i) => {
                        const isExpanded = expanded === p.id;
                        const isAdded = !!p.league_added;
                        const isUpdating = updating === p.id;
                        return (
                          <React.Fragment key={p.id || i}>
                            {/* Main row */}
                            <tr
                              style={{ borderBottom: isExpanded ? "none" : "1px solid rgba(255,255,255,0.04)", background: isAdded ? "rgba(62,207,142,0.04)" : "transparent", cursor: "pointer" }}
                              onClick={() => setExpanded(isExpanded ? null : p.id)}
                            >
                              {/* Expand toggle */}
                              <td style={{ ...tdS, paddingLeft: 16, color: "var(--faint)", fontSize: "10px", width: 24 }}>
                                {isExpanded ? "▼" : "▶"}
                              </td>
                              {/* Index */}
                              <td style={{ ...tdS, color: "var(--faint)", fontFamily: "var(--mono)", fontSize: "12px", width: 30 }}>{i + 1}</td>
                              {/* Name */}
                              <td style={{ ...tdS, fontWeight: 600, whiteSpace: "nowrap" }}>
                                {isAdded && <span style={{ display: "inline-block", width: 8, height: 8, borderRadius: "50%", background: "#3ecf8e", marginRight: 8 }} />}
                                {p.name}
                              </td>
                              {/* iRacing ID */}
                              <td style={{ ...tdS, fontFamily: "var(--mono)", color: "var(--muted)", fontSize: "12px" }}>{p.iracing_id}</td>
                              {/* Numbers */}
                              <td style={{ ...tdS, fontFamily: "var(--mono)", fontSize: "12px" }}>
                                {p.car_number ? <b style={{ color: "var(--text)" }}>#{p.car_number}</b> : <span style={{ color: "var(--faint)" }}>—</span>}
                                {p.car_number_2 && <span style={{ color: "var(--muted)", marginLeft: 6 }}>/ #{p.car_number_2}</span>}
                              </td>
                              {/* Team */}
                              <td style={{ ...tdS, color: "var(--muted)", fontSize: "12px" }}>{p.team_name || <span style={{ color: "var(--faint)" }}>—</span>}</td>
                              {/* Car */}
                              <td style={{ ...tdS, color: "var(--accent)", fontSize: "11px", maxWidth: 160, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.car}</td>
                              {/* Help interest */}
                              <td style={{ ...tdS, textAlign: "center" }}>
                                {p.help_interest
                                  ? <span style={{ color: "#3ecf8e", fontFamily: "var(--mono)", fontSize: "11px" }}>DA</span>
                                  : <span style={{ color: "var(--faint)", fontFamily: "var(--mono)", fontSize: "11px" }}>—</span>}
                              </td>
                              {/* Action buttons */}
                              <td style={{ ...tdS, paddingRight: 16 }} onClick={e => e.stopPropagation()}>
                                <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
                                  <button
                                    className={"btn sm" + (!isAdded ? "" : " ghost")}
                                    disabled={isUpdating}
                                    onClick={() => toggleAdded(p)}
                                    style={isAdded
                                      ? { background: "transparent", color: "#3ecf8e", border: "1px solid #3ecf8e", opacity: isUpdating ? 0.5 : 1 }
                                      : { opacity: isUpdating ? 0.5 : 1 }
                                    }
                                  >
                                    <span>{isUpdating ? "..." : isAdded ? "✓ În ligă" : "Adaugă în ligă"}</span>
                                  </button>
                                  <button
                                    className="btn sm ghost"
                                    onClick={() => deletePilot(p)}
                                    style={{ color: "var(--accent)", border: "1px solid var(--accent)", padding: "4px 8px" }}
                                    title="Șterge pilot"
                                  >
                                    <span>✕</span>
                                  </button>
                                </div>
                              </td>
                            </tr>

                            {/* Expanded detail row */}
                            {isExpanded && (
                              <tr style={{ borderBottom: "1px solid rgba(255,255,255,0.04)" }}>
                                <td colSpan={9} style={{ padding: "0 16px 16px 56px", background: "rgba(0,0,0,0.2)" }}>
                                  <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(180px, 1fr))", gap: "10px 20px", paddingTop: 12 }}>
                                    {[
                                      ["Țară", p.country],
                                      ["Discord", p.discord],
                                      ["Nivel", p.experience],
                                      ["Ajutor operațiuni", p.help_interest ? "Da" : "Nu"],
                                      ["Înscris la", p.created_at ? new Date(p.created_at).toLocaleString("ro-RO") : "—"],
                                    ].map(([k, v]) => v ? (
                                      <div key={k}>
                                        <div style={{ fontSize: "10px", color: "var(--faint)", fontFamily: "var(--mono)", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 2 }}>{k}</div>
                                        <div style={{ fontSize: "13px", color: "var(--text)" }}>{v}</div>
                                      </div>
                                    ) : null)}
                                  </div>
                                  {p.notes && (
                                    <div style={{ marginTop: 12, padding: "10px 14px", background: "var(--bg2)", border: "1px solid var(--line)" }}>
                                      <div style={{ fontSize: "10px", color: "var(--faint)", fontFamily: "var(--mono)", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 4 }}>Note pentru staff</div>
                                      <div style={{ fontSize: "13px", color: "var(--text)", lineHeight: 1.5 }}>{p.notes}</div>
                                    </div>
                                  )}
                                </td>
                              </tr>
                            )}
                          </React.Fragment>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
            }
          </div>
        );
      })}

      {/* Piloți cu race_id necunoscut — nu se pierd */}
      {unmatchedPilots.length > 0 && (
        <div style={{ background: "var(--panel)", border: "1px solid var(--accent)" }}>
          <div style={{ padding: "14px 20px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <h3 style={{ margin: 0, fontFamily: "var(--display)", fontSize: "17px", color: "var(--accent)" }}>
              ⚠ Piloți fără cursă asociată ({unmatchedPilots.length})
            </h3>
            <span style={{ fontFamily: "var(--mono)", fontSize: "12px", color: "var(--muted)" }}>race_id nu corespunde niciunei curse din admin</span>
          </div>
          <div style={{ overflowX: "auto" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "13px" }}>
              <thead>
                <tr style={{ borderBottom: "1px solid var(--line)" }}>
                  {["Pilot", "race_id", "Mașină", "iRacing ID", "Acțiune"].map(h => (
                    <th key={h} style={{ padding: "8px 12px", textAlign: "left", color: "var(--muted)", fontFamily: "var(--mono)", fontWeight: 400, fontSize: "11px" }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {unmatchedPilots.map((p, i) => (
                  <tr key={p.id || i} style={{ borderBottom: "1px solid rgba(255,255,255,0.04)" }}>
                    <td style={{ padding: "10px 12px", fontWeight: 600 }}>{p.name}</td>
                    <td style={{ padding: "10px 12px", fontFamily: "var(--mono)", fontSize: "12px", color: "var(--accent)" }}>{p.race_id}</td>
                    <td style={{ padding: "10px 12px" }}>{p.car}</td>
                    <td style={{ padding: "10px 12px", fontFamily: "var(--mono)", fontSize: "12px" }}>{p.iracing_id}</td>
                    <td style={{ padding: "10px 12px" }}>
                      <div style={{ display: "flex", gap: 6 }}>
                        <button className="btn sm ghost" onClick={() => toggleAdded(p)}
                          style={p.league_added ? { color: "#3ecf8e", border: "1px solid #3ecf8e" } : {}}>
                          <span>{p.league_added ? "✓ În ligă" : "Adaugă"}</span>
                        </button>
                        <button className="btn sm ghost" onClick={() => deletePilot(p)}
                          style={{ color: "var(--accent)", border: "1px solid var(--accent)", padding: "4px 8px" }}
                          title="Șterge pilot">
                          <span>✕</span>
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}

function ImageSyncBtn() {
  const [status, setStatus] = useAA(null);

  const syncToCloud = async () => {
    if (!window.sbClient) { setStatus("error"); return; }
    setStatus("saving");
    try {
      const raw = localStorage.getItem("igs-image-slots");
      const slots = raw ? JSON.parse(raw) : {};
      await window.sbClient.from("site_config")
        .upsert({ id: "images", value: slots, updated_at: new Date().toISOString() }, { onConflict: "id" });
      setStatus("ok");
    } catch(e) {
      setStatus("error");
    }
    setTimeout(() => setStatus(null), 3000);
  };

  return (
    <div style={{ background: "rgba(0,200,100,.07)", border: "1px solid rgba(0,200,100,.25)", borderRadius: "8px", padding: "16px", display: "flex", alignItems: "center", gap: "16px", flexWrap: "wrap" }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: "var(--mono)", fontSize: "11px", color: "var(--accent)", marginBottom: "4px" }}>SYNC IMAGINI ÎN CLOUD</div>
        <div style={{ fontSize: "13px", color: "var(--muted)" }}>Salvează toate imaginile încărcate în Supabase — vor apărea pe orice dispozitiv (inclusiv mobil).</div>
      </div>
      <button onClick={syncToCloud} style={{ background: "var(--accent)", color: "var(--bg)", border: "none", padding: "10px 20px", fontFamily: "var(--display)", fontSize: "13px", letterSpacing: "1px", cursor: "pointer", borderRadius: "4px", whiteSpace: "nowrap" }}>
        {status === "saving" ? "SE SALVEAZĂ..." : status === "ok" ? "✓ SALVAT ÎN CLOUD" : status === "error" ? "✗ EROARE" : "☁ SYNC ÎN CLOUD"}
      </button>
    </div>
  );
}

function VisualSaveBtn({ tw }) {
  const [status, setStatus] = useAA(null);
  const save = async () => {
    if (!window.sbClient) { setStatus("error"); return; }
    setStatus("saving");
    const { error } = await window.sbClient.from('site_config').upsert(
      { id: 'tweaks', value: { theme: tw.theme, accent: tw.accent, headFont: tw.headFont, ticker: tw.ticker, tower: tw.tower }, updated_at: new Date().toISOString() },
      { onConflict: 'id' }
    );
    if (error) {
      setStatus("error");
      console.error("Eroare salvare visual:", error);
    } else {
      setStatus("saved");
    }
    setTimeout(() => setStatus(null), 3000);
  };
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
      <button className="btn sm" onClick={save} disabled={status === "saving"}>
        <span>{status === "saving" ? "Se salvează..." : "☁ Salvează aspect în cloud"}</span>
      </button>
      {status === "saved" && <span style={{ fontFamily: "var(--mono)", fontSize: "12px", color: "#3ecf8e" }}>✓ Sincronizat — reîncarcă site-ul</span>}
      {status === "error" && <span style={{ fontFamily: "var(--mono)", fontSize: "12px", color: "var(--accent)" }}>✗ Eroare — verifică RLS în Supabase</span>}
    </div>
  );
}

function LinksSaveBtn({ tw }) {
  const [status, setStatus] = useAA(null);
  const save = async () => {
    setStatus("saving");
    await saveConfigToCloud('links', {
      discordUrl: tw.discordUrl || "",
      discordWebhook: tw.discordWebhook || "",
      coffeeUrl: tw.coffeeUrl || "",
      showCoffee: !!tw.showCoffee,
    });
    setStatus("saved");
    setTimeout(() => setStatus(null), 2500);
  };
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, paddingTop: 4 }}>
      <button className="btn sm" onClick={save} disabled={status === "saving"}>
        <span>{status === "saving" ? "Se salvează..." : "☁ Salvează link-uri în cloud"}</span>
      </button>
      {status === "saved" && (
        <span style={{ fontFamily: "var(--mono)", fontSize: "12px", color: "#3ecf8e" }}>✓ Sincronizat pe toate dispozitivele</span>
      )}
    </div>
  );
}

function AdminPanel({ onClose, tw = {}, setTweak = () => {}, asPage = false }) {
  const { t } = useT();
  const [pwd, setPwd] = useAA("");
  const [authed, setAuthed] = useAA(false);
  const [tab, setTab] = useAA("races");
  const [races, setRaces] = useAA(loadRaces);
  const [editing, setEditing] = useAA(null);
  const [form, setForm] = useAA({});
  const [annMsg, setAnnMsg] = useAA({});
  const [cloudSaveErr, setCloudSaveErr] = useAA(null);
  useEA(() => {
    window._adminSetSaveError = setCloudSaveErr;
    return () => { delete window._adminSetSaveError; };
  }, []);
  const [schedInfo, setSchedInfo] = useAA(() => {
    if (!window.loadSchedule) return {};
    const info = {};
    window.loadSchedule().forEach(s => { if (!s.fired) info[s.raceId] = (info[s.raceId] || 0) + 1; });
    return info;
  });

  const AdminPW = "Lasamasaintru30@";
  const handleAuth = (e) => {
    e.preventDefault();
    if (pwd === AdminPW) { setAuthed(true); setPwd(""); }
    else alert("Wrong password");
  };

  const startEdit = (r) => {
    setEditing(r.id);
    setForm({
      name: r.name, status: r.status,
      classes: r.classes || r.class || "GT3",
      imageUrl: r.imageUrl || "",
      gridFree: r.gridFree, gridTotal: r.gridTotal,
      laps: r.laps, durMin: r.durMin, password: r.password || "",
      dateD: r.date.d, dateMon: r.date.mon, dateY: r.date.y,
      time: r.time || "21:00", tz: roTimeToUtc(r.time||"21:00", r.date.y, r.date.mon, r.date.d).tz, utc: roTimeToUtc(r.time||"21:00", r.date.y, r.date.mon, r.date.d).utcStr || r.utc || "18:00 UTC",
      practiceMin: r.practiceMin != null ? r.practiceMin : FORMAT.practiceMin,
      qualiLaps: r.qualiLaps != null ? r.qualiLaps : FORMAT.qualiLaps,
      cond: r.cond ? [...r.cond] : [],
      wCloud: (r.weather && r.weather.cloudCover) || "Clear",
      wMoisture: (r.weather && r.weather.moisture) || "None",
      wTemp: (r.weather && r.weather.temp != null) ? r.weather.temp : 25,
      wWind: (r.weather && r.weather.windSpeed != null) ? r.weather.windSpeed : 0,
      wDir: (r.weather && r.weather.windDir) || "N",
      wHumidity: (r.weather && r.weather.humidity != null) ? r.weather.humidity : 45,
    });
  };

  const saveEdit = () => {
    const gFree = parseInt(form.gridFree) || 0;
    const gTotal = parseInt(form.gridTotal) || 30;
    const d = parseInt(form.dateD) || 1;
    const mon = parseInt(form.dateMon) || 1;
    const y = parseInt(form.dateY) || 2026;
    const dow = new Date(y, mon - 1, d).getDay();
    const autoStatus = form.status === "done" ? "done" : (gFree === 0 ? "full" : (form.status === "full" && gFree > 0 ? "open" : form.status));
    const updated = races.map(r =>
      r.id === editing
        ? { ...r, name: form.name, status: autoStatus, classes: form.classes || "GT3", imageUrl: form.imageUrl || "", gridFree: gFree, gridTotal: gTotal,
            laps: parseInt(form.laps) || 0, durMin: parseInt(form.durMin) || 0, password: form.password || "",
            practiceMin: parseInt(form.practiceMin) >= 0 ? parseInt(form.practiceMin) : FORMAT.practiceMin,
            qualiLaps: parseInt(form.qualiLaps) >= 0 ? parseInt(form.qualiLaps) : FORMAT.qualiLaps,
            date: { dow, d, mon, y }, time: form.time, tz: form.tz, utc: form.utc,
            cond: form.cond || [],
            weather: { cloudCover: form.wCloud, moisture: form.wMoisture, temp: parseInt(form.wTemp) || 25, windSpeed: parseInt(form.wWind) || 0, windDir: form.wDir, humidity: parseInt(form.wHumidity) || 45 } }
        : r
    );
    setRaces(updated);
    saveRaces(updated);
    setEditing(null);
  };

  const deleteRace = (id) => {
    if (confirm("Delete this race?")) {
      const updated = races.filter(r => r.id !== id);
      setRaces(updated);
      saveRaces(updated);
    }
  };

  const addRace = () => {
    const newId = "race-" + Date.now();
    const nextRound = races.length > 0 ? Math.max(...races.map(r => r.round || 0)) + 1 : 1;
    const lastRace = races.length > 0 ? races[races.length - 1] : null;
    const newRace = {
      id: newId, round: nextRound, name: "Etapă nouă", classes: "GT3",
      date: lastRace ? { ...lastRace.date } : { dow: 4, d: 1, mon: 6, y: 2026 },
      time: lastRace ? lastRace.time : "21:00",
      tz: lastRace ? lastRace.tz : "EEST",
      utc: lastRace ? lastRace.utc : "18:00 UTC",
      laps: lastRace ? lastRace.laps : 15,
      durMin: lastRace ? lastRace.durMin : 45,
      cond: ["day"], gridTotal: 30, gridFree: 30, status: "open", imageUrl: "",
    };
    const updated = [...races, newRace];
    setRaces(updated);
    saveRaces(updated);
  };

  if (!authed) {
    return (
      <div style={{ position: "fixed", inset: 0, zIndex: 9999, display: "flex", alignItems: "center", justifyContent: "center", background: "rgba(0,0,0,0.8)" }}>
        <div style={{ background: "var(--panel)", padding: "40px", borderRadius: "8px", maxWidth: "300px", textAlign: "center" }}>
          <h2 style={{ margin: "0 0 20px", fontFamily: "var(--display)", fontSize: "24px" }}>ADMIN</h2>
          <form onSubmit={handleAuth} style={{ display: "flex", flexDirection: "column", gap: "12px" }}>
            <input
              type="password"
              placeholder="Password"
              value={pwd}
              onChange={(e) => setPwd(e.target.value)}
              style={{ padding: "10px", background: "var(--bg2)", color: "var(--text)", border: "1px solid var(--line)", fontFamily: "var(--mono)" }}
            />
            <button type="submit" className="btn block"><span>Unlock</span></button>
            <button type="button" className="btn ghost block" onClick={onClose}><span>Close</span></button>
          </form>
        </div>
      </div>
    );
  }

  const iStyle = { width: "100%", padding: "8px", background: "var(--bg2)", color: "var(--text)", border: "1px solid var(--line)", boxSizing: "border-box" };
  const lStyle = { display: "block", fontSize: "12px", color: "var(--muted)", marginBottom: "4px" };
  const themeColors = { broadcast: "#ff2e3f", telemetry: "#18e3ff", carbon: "#c8ff2e" };

  const sendAnnouncement = async (r) => {
    const webhookUrl = tw.discordWebhook;
    if (!webhookUrl) { setAnnMsg({ [r.id]: { err: true, text: "Lipsă Webhook URL — adaugă în tab Aspect → Links" } }); return; }
    const pwd = r.password || "—";
    const color = parseInt((tw.accent || "#ff2e3f").replace('#',''), 16);
    const payload = {
      content: "@here",
      embeds: [{ title: `🏁 RACE STARTING — RND ${String(r.round).padStart(2,"0")} · ${r.name}`, description: "Intră în iRacing și join sesiunea!", color,
        fields: [
          { name: "🔑 Parolă iRacing", value: `\`${pwd}\``, inline: true },
          { name: "⏰ Start", value: `${r.time} ${r.tz}`, inline: true },
          { name: "🏎️ Format", value: `${r.laps} ture · ≈${r.durMin} min`, inline: true },
        ],
        footer: { text: "IRON GT SERIES · iRacing GT3 Championship" }
      }]
    };
    try {
      const res = await fetch(webhookUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
      if (res.ok || res.status === 204) {
        localStorage.setItem('igs-ann', JSON.stringify({ raceId: r.id, name: r.name, round: r.round, time: r.time, tz: r.tz, password: pwd, announcedAt: Date.now() }));
        setAnnMsg({ [r.id]: { err: false, text: "✓ Anunț trimis pe Discord! Bannerul e activ pe site." } });
      } else {
        setAnnMsg({ [r.id]: { err: true, text: `Eroare Discord: ${res.status}` } });
      }
    } catch(e) {
      setAnnMsg({ [r.id]: { err: true, text: "Eroare rețea: " + e.message } });
    }
  };

  const outerStyle = asPage
    ? { minHeight: "100vh", background: "var(--bg)", paddingBottom: "60px" }
    : { position: "fixed", inset: 0, zIndex: 9999, overflow: "auto", background: "rgba(0,0,0,0.95)" };

  return (
    <div style={outerStyle}>
      <div style={{ maxWidth: "900px", margin: "0 auto", padding: "40px 20px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "24px" }}>
          <h1 style={{ margin: 0, fontFamily: "var(--display)", fontSize: "36px" }}>Admin Panel</h1>
          <button className="btn ghost" onClick={onClose}><span>Close</span></button>
        </div>

        {cloudSaveErr && (
          <div style={{ background: "#7f1d1d", border: "1px solid #ef4444", borderRadius: "6px", padding: "12px 16px", marginBottom: "20px", fontFamily: "var(--mono)", fontSize: "13px", color: "#fca5a5" }}>
            <b style={{ color: "#ef4444" }}>⚠ Eroare Supabase — schimbările NU s-au salvat în cloud!</b><br />
            <span style={{ opacity: 0.85 }}>{cloudSaveErr}</span><br /><br />
            <b style={{ color: "#fbbf24" }}>Soluție: rulează în Supabase SQL Editor:</b>
            <pre style={{ background: "#1c0707", padding: "10px", borderRadius: "4px", marginTop: "8px", overflowX: "auto", fontSize: "12px", color: "#d1fae5" }}>{`CREATE POLICY "anon insert site_config" ON site_config FOR INSERT WITH CHECK (true);
CREATE POLICY "anon update site_config" ON site_config FOR UPDATE USING (true);
CREATE POLICY "anon read site_config" ON site_config FOR SELECT USING (true);`}</pre>
            <button onClick={() => setCloudSaveErr(null)} style={{ marginTop: "8px", background: "none", border: "1px solid #ef4444", color: "#ef4444", padding: "4px 10px", cursor: "pointer", borderRadius: "4px", fontSize: "12px" }}>Închide</button>
          </div>
        )}

        <div style={{ display: "flex", gap: "8px", marginBottom: "28px", borderBottom: "1px solid var(--line)", paddingBottom: "16px", flexWrap: "wrap" }}>
          {[["races", "Curse"], ["piloti", "Piloți"], ["rezultate", "Rezultate"], ["appearance", "Aspect"], ["imagini", "Imagini"], ["texte", "Texte"]].map(([id, label]) => (
            <button key={id} className={"btn sm" + (tab !== id ? " ghost" : "")} onClick={() => setTab(id)}><span>{label}</span></button>
          ))}
        </div>

        {tab === "races" && (
          <>
            <div style={{ marginBottom: "20px" }}>
              <button className="btn" onClick={addRace}><span>+ Adaugă cursă</span></button>
            </div>
            <div style={{ display: "grid", gap: "20px" }}>
              {races.map((r) => (
                <div key={r.id} style={{ background: "var(--panel)", padding: "20px", border: "1px solid var(--line)" }}>
                  {editing === r.id ? (
                    <div style={{ display: "grid", gap: "12px", gridTemplateColumns: "repeat(2,1fr)" }}>
                      <div><label style={lStyle}>Name</label><input value={form.name} onChange={(e) => setForm(s => ({ ...s, name: e.target.value }))} style={iStyle} /></div>
                      <div><label style={lStyle}>Clase pe pistă</label>
                        <select value={form.classes || "GT3"} onChange={(e) => setForm(s => ({ ...s, classes: e.target.value }))} style={iStyle}>
                          <option value="GT3">GT3</option>
                          <option value="GT4">GT4</option>
                          <option value="LMP2">LMP2</option>
                          <option value="GTP">GTP</option>
                          <option value="GT3 · LMP2">GT3 · LMP2</option>
                          <option value="GT3 · GTP">GT3 · GTP</option>
                          <option value="GT3 · GT4">GT3 · GT4</option>
                          <option value="Multi-class">Multi-class</option>
                          <option value="Porsche Cup">Porsche Cup</option>
                          <option value="Ferrari Challenge">Ferrari Challenge</option>
                        </select>
                      </div>
                      <div><label style={lStyle}>Status</label>
                        <select value={form.status} onChange={(e) => setForm(s => ({ ...s, status: e.target.value }))} style={iStyle}>
                          <option>open</option><option>filling</option><option>full</option><option>done</option>
                        </select>
                      </div>
                      <div><label style={lStyle}>Grid Free</label><input type="number" value={form.gridFree} onChange={(e) => setForm(s => ({ ...s, gridFree: e.target.value }))} style={iStyle} /></div>
                      <div><label style={lStyle}>Grid Total</label><input type="number" value={form.gridTotal} onChange={(e) => setForm(s => ({ ...s, gridTotal: e.target.value }))} style={iStyle} /></div>
                      <div><label style={lStyle}>Ture cursă</label><input type="number" value={form.laps} onChange={(e) => setForm(s => ({ ...s, laps: e.target.value }))} style={iStyle} /></div>
                      <div><label style={lStyle}>Durată estimată (min)</label><input type="number" value={form.durMin} onChange={(e) => setForm(s => ({ ...s, durMin: e.target.value }))} style={iStyle} /></div>
                      <div><label style={lStyle}>Practice (min) · 0 = fără</label><input type="number" min="0" value={form.practiceMin} onChange={(e) => setForm(s => ({ ...s, practiceMin: e.target.value }))} style={iStyle} /></div>
                      <div><label style={lStyle}>Calificare (ture) · 0 = fără</label><input type="number" min="0" value={form.qualiLaps} onChange={(e) => setForm(s => ({ ...s, qualiLaps: e.target.value }))} style={iStyle} /></div>
                      <div style={{ gridColumn: "1/-1" }}><label style={lStyle}>🔑 Parolă iRacing (pentru anunț)</label><input type="text" value={form.password} onChange={(e) => setForm(s => ({ ...s, password: e.target.value }))} style={iStyle} placeholder="ex. GT3race2026" /></div>
                      <div style={{ gridColumn: "1/-1" }}>
                        <label style={lStyle}>🖼 Poză cursă</label>
                        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                          <label style={{ cursor: "pointer", background: "var(--accent)", color: "var(--accent-ink)", padding: "7px 14px", borderRadius: 4, fontFamily: "var(--mono)", fontSize: 12, letterSpacing: "0.05em", whiteSpace: "nowrap", userSelect: "none" }}>
                            📁 Alege fișier
                            <input type="file" accept="image/*" style={{ display: "none" }} onChange={async (e) => {
                              const file = e.target.files[0];
                              if (!file) return;
                              const dataUrl = await resizeImage(file);
                              setForm(s => ({ ...s, imageUrl: dataUrl }));
                            }} />
                          </label>
                          {form.imageUrl && <button type="button" onClick={() => setForm(s => ({ ...s, imageUrl: "" }))} style={{ background: "none", border: "1px solid var(--line)", color: "var(--muted)", padding: "7px 10px", borderRadius: 4, cursor: "pointer", fontSize: 13 }}>✕ Șterge</button>}
                        </div>
                        {form.imageUrl && <img src={form.imageUrl} alt="" style={{ marginTop: 8, width: "100%", maxHeight: 130, objectFit: "cover", borderRadius: 4, border: "1px solid var(--line)" }} />}
                        {!form.imageUrl && <div style={{ marginTop: 6, fontSize: 11, color: "var(--muted)", fontFamily: "var(--mono)" }}>JPG / PNG / WEBP — se redimensionează automat la 900×560px</div>}
                      </div>
                      <div style={{ gridColumn: "1/-1", borderTop: "1px solid var(--line)", paddingTop: "12px" }}>
                        <div style={{ fontSize: "12px", color: "var(--muted)", fontFamily: "var(--mono)", marginBottom: "10px" }}>📅 Data și ora cursei</div>
                        {(() => {
                          const { tz: cTz, utcStr: cUtc } = roTimeToUtc(form.time, parseInt(form.dateY)||2026, parseInt(form.dateMon)||1, parseInt(form.dateD)||1);
                          const onDateChange = (key, val) => {
                            const next = { [key]: val };
                            const y = parseInt(key==="dateY"?val:form.dateY)||2026, mon = parseInt(key==="dateMon"?val:form.dateMon)||1, d = parseInt(key==="dateD"?val:form.dateD)||1;
                            const { tz, utcStr } = roTimeToUtc(form.time, y, mon, d);
                            if (utcStr) next.tz = tz, next.utc = utcStr;
                            setForm(s => ({ ...s, ...next }));
                          };
                          const onTimeChange = (e) => {
                            const time = e.target.value;
                            const { tz, utcStr } = roTimeToUtc(time, parseInt(form.dateY)||2026, parseInt(form.dateMon)||1, parseInt(form.dateD)||1);
                            setForm(s => ({ ...s, time, ...(utcStr ? { tz, utc: utcStr } : {}) }));
                          };
                          return (
                            <div style={{ display: "grid", gridTemplateColumns: "60px 1fr 80px 1fr", gap: "8px" }}>
                              <div><label style={lStyle}>Zi</label><input type="number" min="1" max="31" value={form.dateD} onChange={(e) => onDateChange("dateD", e.target.value)} style={iStyle} /></div>
                              <div><label style={lStyle}>Lună</label>
                                <select value={form.dateMon} onChange={(e) => onDateChange("dateMon", e.target.value)} style={iStyle}>
                                  {["Ian","Feb","Mar","Apr","Mai","Iun","Iul","Aug","Sep","Oct","Nov","Dec"].map((m, i) => <option key={i+1} value={i+1}>{m}</option>)}
                                </select>
                              </div>
                              <div><label style={lStyle}>An</label><input type="number" value={form.dateY} onChange={(e) => onDateChange("dateY", e.target.value)} style={iStyle} /></div>
                              <div>
                                <label style={lStyle}>Ora României 🇷🇴</label>
                                <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                                  <input type="text" value={form.time} onChange={onTimeChange} style={{ ...iStyle, width: "74px", flexShrink: 0 }} placeholder="21:00" />
                                  <div style={{ fontFamily: "var(--mono)", fontSize: "12px", lineHeight: 1.5 }}>
                                    <div>
                                      <span style={{ background: "var(--accent)", color: "var(--accent-ink)", padding: "1px 5px", borderRadius: "3px", fontWeight: 700, fontSize: "11px" }}>{cTz || form.tz}</span>
                                      {" → "}
                                      <b style={{ color: "var(--text)" }}>{cUtc || form.utc}</b>
                                    </div>
                                    <div style={{ fontSize: "10px", color: "var(--muted)" }}>Ora României · UTC automat</div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          );
                        })()}
                      </div>
                      <div style={{ gridColumn: "1/-1", borderTop: "1px solid var(--line)", paddingTop: "14px" }}>
                        <div style={{ fontSize: "12px", color: "var(--muted)", fontFamily: "var(--mono)", marginBottom: "14px" }}>🌤️ Condiții circuit iRacing</div>
                        {(() => {
                          const pill = (active) => ({ padding: "5px 13px", fontSize: "12px", fontFamily: "var(--mono)", cursor: "pointer", border: "1px solid", borderRadius: "4px", transition: "all .15s", background: active ? "var(--accent)" : "var(--bg2)", color: active ? "var(--accent-ink)" : "var(--text)", borderColor: active ? "var(--accent)" : "var(--line)" });
                          return (
                            <div style={{ display: "grid", gap: "14px" }}>
                              <div>
                                <div style={{ fontSize: "11px", color: "var(--muted)", fontFamily: "var(--mono)", marginBottom: "7px" }}>Cloud Cover</div>
                                <div style={{ display: "flex", flexWrap: "wrap", gap: "6px" }}>
                                  {["Clear","Partly Cloudy","Mostly Cloudy","Overcast"].map(v => (
                                    <button key={v} type="button" style={pill(form.wCloud === v)} onClick={() => setForm(s => ({ ...s, wCloud: v }))}>{v}</button>
                                  ))}
                                </div>
                              </div>
                              <div>
                                <div style={{ fontSize: "11px", color: "var(--muted)", fontFamily: "var(--mono)", marginBottom: "7px" }}>Track Moisture</div>
                                <div style={{ display: "flex", flexWrap: "wrap", gap: "6px" }}>
                                  {["None","Very Light","Light","Moderate","Heavy","Very Heavy"].map(v => (
                                    <button key={v} type="button" style={pill(form.wMoisture === v)} onClick={() => setForm(s => ({ ...s, wMoisture: v }))}>{v}</button>
                                  ))}
                                </div>
                              </div>
                              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "10px" }}>
                                <div>
                                  <label style={lStyle}>Temperature</label>
                                  <div style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                                    <input type="number" min="-20" max="60" value={form.wTemp} onChange={e => setForm(s => ({ ...s, wTemp: e.target.value }))} style={{ ...iStyle, width: "80px" }} />
                                    <span style={{ color: "var(--muted)", fontSize: "13px" }}>°C</span>
                                  </div>
                                </div>
                                <div>
                                  <label style={lStyle}>Humidity</label>
                                  <div style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                                    <input type="number" min="0" max="100" value={form.wHumidity} onChange={e => setForm(s => ({ ...s, wHumidity: e.target.value }))} style={{ ...iStyle, width: "80px" }} />
                                    <span style={{ color: "var(--muted)", fontSize: "13px" }}>%</span>
                                  </div>
                                </div>
                                <div>
                                  <label style={lStyle}>Wind Speed</label>
                                  <div style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                                    <input type="number" min="0" max="999" value={form.wWind} onChange={e => setForm(s => ({ ...s, wWind: e.target.value }))} style={{ ...iStyle, width: "80px" }} />
                                    <span style={{ color: "var(--muted)", fontSize: "13px" }}>kph</span>
                                  </div>
                                </div>
                              </div>
                              <div>
                                <div style={{ fontSize: "11px", color: "var(--muted)", fontFamily: "var(--mono)", marginBottom: "7px" }}>Wind Direction</div>
                                <div style={{ display: "flex", flexWrap: "wrap", gap: "6px" }}>
                                  {["N","NE","E","SE","S","SW","W","NW"].map(d => (
                                    <button key={d} type="button" style={pill(form.wDir === d)} onClick={() => setForm(s => ({ ...s, wDir: d }))}>{d}</button>
                                  ))}
                                </div>
                              </div>
                            </div>
                          );
                        })()}
                      </div>
                      <div style={{ gridColumn: "1/-1", display: "flex", gap: "10px" }}>
                        <button className="btn" onClick={saveEdit}><span>Save</span></button>
                        <button className="btn ghost" onClick={() => setEditing(null)}><span>Cancel</span></button>
                      </div>
                    </div>
                  ) : (
                    <div>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                        <div>
                          <h3 style={{ margin: "0 0 4px", fontFamily: "var(--display)" }}>RND {String(r.round).padStart(2, "0")} · {r.name}</h3>
                          <p style={{ margin: 0, fontSize: "13px", color: "var(--muted)" }}>
                            {r.status} · {r.gridTotal - r.gridFree}/{r.gridTotal} ocupat · {r.laps} tururi
                            {r.password && <span style={{ marginLeft: 8, color: "var(--accent)", fontFamily: "var(--mono)" }}>🔑 {r.password}</span>}
                          </p>
                        </div>
                        <div style={{ display: "flex", gap: "8px", flexWrap: "wrap", justifyContent: "flex-end" }}>
                          <button className="btn sm" style={{ background: "var(--accent)", color: "var(--accent-ink)", border: "none" }} onClick={() => sendAnnouncement(r)}><span>🏁 Anunță</span></button>
                          {schedInfo[r.id]
                            ? <button className="btn sm ghost" title={schedInfo[r.id] + " anunțuri programate"} onClick={() => { window.unscheduleRace && window.unscheduleRace(r.id); setSchedInfo(s => ({ ...s, [r.id]: 0 })); }}><span>📅 {schedInfo[r.id]} progr. ✕</span></button>
                            : <button className="btn sm ghost" onClick={() => { const n = window.scheduleRace && window.scheduleRace(r); setSchedInfo(s => ({ ...s, [r.id]: n || 0 })); }}><span>📅 Programează</span></button>
                          }
                          <button className="btn sm" onClick={() => startEdit(r)}><span>Edit</span></button>
                          <button className="btn sm ghost" onClick={() => deleteRace(r.id)}><span>Delete</span></button>
                        </div>
                      </div>
                      {annMsg[r.id] && (
                        <div style={{ marginTop: "10px", padding: "8px 12px", background: annMsg[r.id].err ? "rgba(255,60,60,0.12)" : "rgba(62,207,142,0.12)", border: `1px solid ${annMsg[r.id].err ? "#ff3c3c" : "#3ecf8e"}`, fontSize: "13px", fontFamily: "var(--mono)", color: annMsg[r.id].err ? "#ff7070" : "#3ecf8e" }}>
                          {annMsg[r.id].text}
                        </div>
                      )}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </>
        )}

        {tab === "imagini" && (
          <div style={{ display: "grid", gap: "20px" }}>

            {/* Cloud sync banner */}
            <ImageSyncBtn />

            <div style={{ background: "var(--panel)", padding: "20px", border: "1px solid var(--line)" }}>
              <h3 style={{ margin: "0 0 8px", fontFamily: "var(--display)", fontSize: "18px" }}>Hero (fundal principal)</h3>
              <ImageSlotAdmin id="hero-bg" height="260px" placeholder="HERO IMAGE · GT3 ON TRACK" />
              <div style={{ marginTop: "16px", paddingTop: "16px", borderTop: "1px solid var(--line)" }}>
                <div style={{ fontSize: "12px", color: "var(--muted)", marginBottom: "8px", fontFamily: "var(--mono)" }}>SAU video de fundal (MP4/WebM) — are prioritate față de imagine</div>
                <VideoUploadAdmin id="hero-video" />
              </div>
            </div>
            <div style={{ background: "var(--panel)", padding: "20px", border: "1px solid var(--line)" }}>
              <h3 style={{ margin: "0 0 8px", fontFamily: "var(--display)", fontSize: "18px" }}>Etapa vedetă — Spa-Francorchamps</h3>
              <ImageSlotAdmin id="feature-spa" height="200px" placeholder="PHOTO / MAP · SPA-FRANCORCHAMPS" />
            </div>
            <div style={{ background: "var(--panel)", padding: "20px", border: "1px solid var(--line)" }}>
              <h3 style={{ margin: "0 0 16px", fontFamily: "var(--display)", fontSize: "18px" }}>Hărți circuite</h3>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: "16px" }}>
                {races.map(r => (
                  <div key={r.id}>
                    <ImageSlotAdmin id={"map-" + r.id} label={`RND ${String(r.round).padStart(2,"0")} · ${r.name}`} height="130px" placeholder={"MAP · " + r.name.toUpperCase()} />
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {tab === "piloti" && <PilotiTab races={races} />}

        {tab === "rezultate" && <RezultateTab races={races} />}
        {tab === "texte" && <TexteTab />}

        {tab === "appearance" && (
          <div style={{ display: "grid", gap: "20px" }}>
            <div style={{ background: "var(--panel)", padding: "20px", border: "1px solid var(--line)" }}>
              <h3 style={{ margin: "0 0 16px", fontFamily: "var(--display)", fontSize: "18px" }}>Visual</h3>
              <div style={{ display: "grid", gap: "12px", gridTemplateColumns: "repeat(2,1fr)" }}>
                <div>
                  <label style={lStyle}>Temă</label>
                  <select style={iStyle} value={tw.theme || "broadcast"} onChange={e => setTweak({ theme: e.target.value, accent: themeColors[e.target.value] })}>
                    <option value="broadcast">Broadcast</option>
                    <option value="telemetry">Telemetry</option>
                    <option value="carbon">Carbon</option>
                  </select>
                </div>
                <div>
                  <label style={lStyle}>Culoare accent</label>
                  <input type="color" value={tw.accent || "#ff2e3f"} onChange={e => setTweak("accent", e.target.value)} style={{ ...iStyle, height: "38px", padding: "2px 4px" }} />
                </div>
                <div style={{ gridColumn: "1/-1" }}>
                  <label style={lStyle}>Font titluri</label>
                  <select style={iStyle} value={tw.headFont || "Saira Condensed"} onChange={e => setTweak("headFont", e.target.value)}>
                    {["Saira Condensed", "Oswald", "Archivo", "Saira"].map(f => <option key={f} value={f}>{f}</option>)}
                  </select>
                </div>
                <div style={{ gridColumn: "1/-1" }}>
                  <VisualSaveBtn tw={tw} />
                </div>
              </div>
            </div>

            <div style={{ background: "var(--panel)", padding: "20px", border: "1px solid var(--line)" }}>
              <h3 style={{ margin: "0 0 16px", fontFamily: "var(--display)", fontSize: "18px" }}>Overlays</h3>
              <div style={{ display: "grid", gap: "12px" }}>
                <label style={{ display: "flex", alignItems: "center", gap: "10px", cursor: "pointer" }}>
                  <input type="checkbox" checked={!!tw.ticker} onChange={e => setTweak("ticker", e.target.checked)} />
                  <span>Live ticker (jos)</span>
                </label>
                <label style={{ display: "flex", alignItems: "center", gap: "10px", cursor: "pointer" }}>
                  <input type="checkbox" checked={!!tw.tower} onChange={e => setTweak("tower", e.target.checked)} />
                  <span>Timing tower (hero)</span>
                </label>
              </div>
            </div>

            <div style={{ background: "var(--panel)", padding: "20px", border: "1px solid var(--line)" }}>
              <h3 style={{ margin: "0 0 16px", fontFamily: "var(--display)", fontSize: "18px" }}>Link-uri</h3>
              <div style={{ display: "grid", gap: "12px" }}>
                <div>
                  <label style={lStyle}>Discord invite URL</label>
                  <input style={iStyle} type="text" value={tw.discordUrl || ""} onChange={e => setTweak("discordUrl", e.target.value)} placeholder="https://discord.gg/..." />
                </div>
                <div>
                  <label style={lStyle}>Discord Webhook URL (pentru anunțuri curse)</label>
                  <input style={iStyle} type="text" value={tw.discordWebhook || ""} onChange={e => setTweak("discordWebhook", e.target.value)} placeholder="https://discord.com/api/webhooks/..." />
                  <div style={{ fontSize: "11px", color: "var(--muted)", marginTop: "4px", fontFamily: "var(--mono)" }}>Discord → Server Settings → Integrations → Webhooks → New Webhook → Copy URL</div>
                </div>
                <label style={{ display: "flex", alignItems: "center", gap: "10px", cursor: "pointer" }}>
                  <input type="checkbox" checked={!!tw.showCoffee} onChange={e => setTweak("showCoffee", e.target.checked)} />
                  <span>Arată Patreon</span>
                </label>
                <div>
                  <label style={lStyle}>Patreon URL</label>
                  <input style={iStyle} type="text" value={tw.coffeeUrl || ""} onChange={e => setTweak("coffeeUrl", e.target.value)} placeholder="https://www.patreon.com/..." />
                </div>
                <LinksSaveBtn tw={tw} />
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { AdminPanel, loadRaces, saveRaces, saveConfigToCloud });
