// resultados.jsx — Página dedicada de RESULTADOS OFICIALES (separada del index)
// Soporta deep-link desde el calendario:  resultados.html?race=<id>  o  resultados.html#<id>
const { useState, useEffect, useRef } = React;

// ----- Helpers (mismos que el index, copiados aquí para que la página sea autónoma) -----
const RES_PILOT_DIR = (typeof window !== "undefined" && window.CDG_PILOTS) ? window.CDG_PILOTS : {};
const _RES_PILOTS_NORM = Object.fromEntries(
  Object.entries(RES_PILOT_DIR).map(([k, v]) => [k.toLowerCase().trim(), v])
);
function pilotMeta(name) {
  if (!name) return {};
  return _RES_PILOTS_NORM[name.toLowerCase().trim()] || {};
}
function flagUrl(code) {
  if (!code || code.length !== 2) return "";
  return `https://flagcdn.com/${code.toLowerCase()}.svg`;
}
function availableYears() {
  const ys = new Set((window.CDG_RESULTS || []).map(r => r.year).filter(Boolean));
  const arr = [...ys].sort((a, b) => b - a);
  if (arr.length === 0) arr.push(new Date().getFullYear());
  return arr;
}
function pilotHref(name, year, cat) {
  return `piloto.html?name=${encodeURIComponent(name)}&year=${year}&cat=${encodeURIComponent(cat)}`;
}

// Icono Instagram reutilizable
function IgGlyph({ size = 13 }) {
  return (
    <svg className="ig-ico" viewBox="0 0 24 24" width={size} height={size} aria-hidden="true">
      <rect x="2.5" y="2.5" width="19" height="19" rx="5.5" fill="none" stroke="currentColor" strokeWidth="2"/>
      <circle cx="12" cy="12" r="4.2" fill="none" stroke="currentColor" strokeWidth="2"/>
      <circle cx="17.3" cy="6.7" r="1.4" fill="currentColor"/>
    </svg>
  );
}

// Avatar del piloto (foto recortada o iniciales)
function PilotAvatar({ name, size }) {
  const meta = pilotMeta(name);
  const s = size || 54;
  if (meta.photo) return <img className="pilot-avatar" src={meta.photo} alt={name} loading="lazy" style={{ width: s, height: s }} />;
  const initials = String(name || "?").split(/\s+/).map(w => w[0]).slice(0, 2).join("").toUpperCase();
  return <div className="pilot-avatar pa-fallback" style={{ width: s, height: s, fontSize: s * 0.36 }}>{initials}</div>;
}

// Podio visual (top 3) del resultado de la fecha
function ResultsPodium({ rows, tab, year, category }) {
  const top = rows.slice(0, 3);
  if (top.length < 3) return null;
  const order = [top[1], top[0], top[2]];
  const cat = category === "TINY" ? "tiny" : "five";
  return (
    <div className={`res-podium ${cat}`}>
      {order.map((r, idx) => {
        const place = idx === 1 ? 1 : (idx === 0 ? 2 : 3);
        const meta = pilotMeta(r.pilot);
        const flag = flagUrl(meta.country);
        const medal = place === 1 ? "ORO" : place === 2 ? "PLATA" : "BRONCE";
        const big = tab === "qualification" ? (r.time || "—") : `${r.points ?? 0} pts`;
        const sub = tab === "qualification" ? `${r.points ?? 0} pts` : "Bracket final";
        return (
          <a className={`rp-card place-${place}`} href={pilotHref(r.pilot, year, category)} key={r.pos} title={`Ver ficha de ${r.pilot}`}>
            <div className="rp-place">{place}<span className="rp-medal">{medal}</span></div>
            <div className="rp-ava"><PilotAvatar name={r.pilot} size={place === 1 ? 104 : 80} /></div>
            <div className="rp-name">{flag && <img className="rt-flag" src={flag} alt={meta.country} loading="lazy" />}{r.pilot}</div>
            <div className="rp-big">{big}</div>
            <div className="rp-sub">{sub}</div>
          </a>
        );
      })}
    </div>
  );
}

// Deep-link: ¿a qué carrera apuntamos al cargar?
function wantedRaceId() {
  const params = new URLSearchParams(location.search);
  const hash = decodeURIComponent((location.hash || "").replace(/^#/, ""));
  return params.get("race") || hash || null;
}

function Results() {
  const allData = window.CDG_RESULTS || [];
  const years = availableYears();
  const currentYear = new Date().getFullYear();

  // Resolver deep-link una sola vez
  const initial = useRef(null);
  if (initial.current === null) {
    const wid = wantedRaceId();
    const race = wid ? allData.find(r => r.id === wid) : null;
    initial.current = {
      year: race ? race.year : (years.includes(currentYear) ? currentYear : years[0]),
      id: race ? race.id : null,
      cat: "ALL"
    };
  }

  const [year, setYear] = useState(initial.current.year);
  const [catFilter, setCatFilter] = useState("ALL");
  const yearData = allData.filter(r => r.year === year);
  const data = yearData.filter(r => catFilter === "ALL" || r.category === catFilter);
  const [activeId, setActiveId] = useState(initial.current.id || data[0]?.id);
  const [tab, setTab] = useState("qualification");
  const mainRef = useRef(null);

  useEffect(() => {
    if (!data.find(r => r.id === activeId)) {
      setActiveId(data[0]?.id);
    }
  }, [year, catFilter]);

  // Si venimos de un deep-link, hacer scroll suave al panel una vez montado
  useEffect(() => {
    if (initial.current.id && mainRef.current) {
      const y = mainRef.current.getBoundingClientRect().top + window.scrollY - 90;
      window.scrollTo({ top: y, behavior: "smooth" });
    }
  }, []);

  if (allData.length === 0) {
    return (
      <section id="resultados" data-screen-label="Resultados">
        <div className="eyebrow">RESULTADOS OFICIALES <span className="num">/ TEMPORADA {year}</span></div>
        <h2 style={{ maxWidth: 900 }}>Resultados<br/>próximamente.</h2>
        <p className="lead" style={{ marginTop: 24 }}>Los resultados se publicarán después de cada fecha.</p>
      </section>
    );
  }

  const active = data.find(r => r.id === activeId) || data[0];
  const rows = (active && active[tab]) || [];
  const fmtCat = (c) => c === "TINY" ? "Tinywhoop" : "Open 5\"";
  const catClass = (c) => c === "TINY" ? "cat-tiny-pill" : "cat-five-pill";

  return (
    <section id="resultados" data-screen-label="Resultados">
      <div className="eyebrow">RESULTADOS OFICIALES · TEMPORADA {year}{year === currentYear ? " · ACTUAL" : ""} <span className="num">/ CDG</span></div>
      <div className="results-head">
        <h2>Resultados<br/>oficiales.</h2>
        <div className="ranking-year">
          <span className="ry-label">Temporada</span>
          <select value={year} onChange={e => setYear(Number(e.target.value))}>
            {years.map(y => (
              <option key={y} value={y}>{y}{y === currentYear ? " · actual" : ""}</option>
            ))}
          </select>
        </div>
      </div>
      <p className="lead" style={{ marginTop: -8, marginBottom: 36, maxWidth: 720 }}>
        Clasificación (tiempos) y bracket final de cada fecha de la temporada. Selecciona una fecha del calendario y caes directo aquí.
      </p>

      <div className="results-wrap" ref={mainRef}>
        <aside className="results-list">
          <div className="results-list-head">
            <span>FECHAS {year}</span>
            <span>{data.length}</span>
          </div>
          <div className="results-list-filter">
            {[
              { id: "ALL",  label: "Todas" },
              { id: "TINY", label: "Tiny" },
              { id: "5\"",  label: "5\"" }
            ].map(f => (
              <button
                key={f.id}
                className={`rlf-btn ${catFilter === f.id ? "active" : ""} ${f.id === "TINY" ? "tiny" : ""}`}
                onClick={() => setCatFilter(f.id)}
              >{f.label}</button>
            ))}
          </div>
          {data.length === 0 ? (
            <div className="rlf-empty">Sin fechas para este filtro.</div>
          ) : data.map(r => (
            <button
              key={r.id}
              className={`results-list-item ${activeId === r.id ? "active" : ""}`}
              onClick={() => setActiveId(r.id)}
            >
              <div className="rli-top">
                <span className="rli-round">{r.round}</span>
                <span className={`rli-cat ${catClass(r.category)}`}>{fmtCat(r.category)}</span>
              </div>
              <div className="rli-name">{r.name}</div>
              <div className="rli-meta">{r.date}{r.location ? ` · ${r.location}` : ""}</div>
            </button>
          ))}
        </aside>

        <div className="results-main">
          {!active ? (
            <div className="results-empty"><div className="re-icon">—</div><div className="re-text">Selecciona una fecha</div></div>
          ) : (<>
          <div className="results-main-head">
            <div>
              <div className="results-round">{active.round} · {active.date}</div>
              <h3 className="results-title">{active.name}</h3>
              <div className="results-meta">
                <span className={`rli-cat ${catClass(active.category)}`}>{fmtCat(active.category)}</span>
                {active.location && <span className="results-loc">📍 {active.location}</span>}
              </div>
              <div className="results-export">
                <button className="rx-btn" onClick={() => window.CDGShare && window.CDGShare.reel(active)} title="Imagen 1080×1920 para historia/reel de Instagram">
                  <svg viewBox="0 0 24 24" width="15" height="15" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="5" fill="none" stroke="currentColor" strokeWidth="2"/><path d="M3 9h18M9 3v18" fill="none" stroke="currentColor" strokeWidth="1.4" opacity=".5"/></svg>
                  Reel IG
                </button>
                <button className="rx-btn pdf" onClick={() => window.CDGShare && window.CDGShare.racePdf(active)} title="Reporte PDF de la fecha + estado del campeonato">
                  <svg viewBox="0 0 24 24" width="15" height="15" aria-hidden="true"><path d="M7 3h7l5 5v13H7z" fill="none" stroke="currentColor" strokeWidth="2" strokeLinejoin="round"/><path d="M14 3v5h5M10 13h5M10 17h5" fill="none" stroke="currentColor" strokeWidth="1.6"/></svg>
                  Reporte PDF
                </button>
              </div>
            </div>
            <div className="results-tabs">
              <button className={`results-tab ${tab === "qualification" ? "active" : ""}`} onClick={() => setTab("qualification")}>
                <span className="rt-label">Clasificación</span><span className="rt-sub">Tiempos</span>
              </button>
              <button className={`results-tab ${tab === "bracket" ? "active" : ""}`} onClick={() => setTab("bracket")}>
                <span className="rt-label">Bracket Final</span><span className="rt-sub">Posiciones</span>
              </button>
            </div>
          </div>

          {rows.length === 0 ? (
            <div className="results-empty">
              <div className="re-icon">—</div>
              <div className="re-text">Sin datos de {tab === "qualification" ? "clasificación" : "bracket final"} para esta fecha.</div>
            </div>
          ) : (<>
            <ResultsPodium rows={rows} tab={tab} year={year} category={active.category} />
            {(() => {
            // Si hay podio (3+ pilotos), no repetimos el top 3 en la lista de abajo
            const hasPodium = rows.length >= 3;
            const tableRows = hasPodium ? rows.slice(3) : rows;
            return tableRows.length === 0 ? (
              <div className="results-rest-empty">El podio completo lo tienes arriba. No hay más posiciones en esta fecha.</div>
            ) : (
            <table className="results-table">
              <thead>
                <tr>
                  <th style={{ width: 60 }}>Pos</th>
                  <th>Piloto</th>
                  <th>Handle</th>
                  {tab === "qualification" && <th style={{ width: 120, textAlign: "right" }}>Tiempo</th>}
                  <th style={{ width: 80, textAlign: "right" }}>Puntos</th>
                </tr>
              </thead>
              <tbody>
                {tableRows.map(r => {
                  const meta = pilotMeta(r.pilot);
                  return (
                  <tr key={r.pos} className={r.pos <= 3 ? `podium podium-${r.pos}` : ""}>
                    <td className="rt-pos">{String(r.pos).padStart(2, "0")}</td>
                    <td className="rt-name">
                      {flagUrl(meta.country) && <img className="rt-flag" src={flagUrl(meta.country)} alt={meta.country} title={meta.country} loading="lazy" />}
                      <a className="rt-name-link" href={pilotHref(r.pilot, year, active.category)}>{r.pilot}</a>
                    </td>
                    <td className="rt-handle">
                      {meta.ig
                        ? <a className="rt-ig" href={`https://instagram.com/${meta.ig}`} target="_blank" rel="noopener noreferrer" title="Ver Instagram"><IgGlyph />@{meta.ig}</a>
                        : (r.handle || "—")}
                    </td>
                    {tab === "qualification" && <td className="rt-time">{r.time || "—"}</td>}
                    <td className="rt-pts">{r.points ?? "—"}</td>
                  </tr>
                  );
                })}
              </tbody>
            </table>
            );
            })()}
          </>)}
          </>)}
        </div>
      </div>
    </section>
  );
}

ReactDOM.createRoot(document.getElementById("res-root")).render(<Results />);
