// Deportes del Norte — ATL shared helpers
// Loaded by every ATL page via:
//   <script type="text/babel" src="/atl/_atl-shared.jsx" data-presets="react"></script>
// placed AFTER /media/shared.jsx and BEFORE the page's own inline script.
//
// Centralizes:
//   - useATLFetch(endpoint)  → { data, status: "loading"|"live"|"error", error }
//   - <ATLLoading>           → uniform skeleton block
//   - <ATLErrorState>        → loud failure card (per project rule: no silent fallback)
//   - <ATLEmptyState>        → uniform "nothing yet" card with optional CTA
//   - ATL_ENDPOINTS          → single source of truth for the data agent to wire
//
// All five ATL pages (hub, tournaments, rankings, players, player profile) read
// through these helpers — endpoint changes are one-file changes.

window.ATL_ENDPOINTS = {
  // GET /api/atl/season → see /atl/index.html header comment for payload shape.
  season:      "/api/atl/season",
  // GET /api/atl/tournaments → { tournaments: [{ id, name, dates, status, location, drawSize, logoUrl?, winnerId?, winnerName? }] }
  tournaments: "/api/atl/tournaments",
  // GET /api/atl/tournaments?id=<id> → { tournament: { ...meta, logoUrl?, draw, matches: [...] } }
  tournament:  function (id) { return "/api/atl/tournaments?id=" + encodeURIComponent(id); },
  // GET /api/atl/rankings → { asOf, rankings: [{ playerId, name, rank, rating, wins, losses, matchesPlayed }] }
  rankings:    "/api/atl/rankings",
  // GET /api/atl/players → { players: [{ playerId, name, rank, rating, matchesPlayed, club, country, hand }] }
  players:     "/api/atl/players",
  // GET /api/atl/players?id=<id> → { player: { ...meta, rank, rating, stats, gameLog: [...] } }
  player:      function (id) { return "/api/atl/players?id=" + encodeURIComponent(id); },
};

function useATLFetch(endpoint) {
  const [state, setState] = React.useState({ data: null, status: "loading", error: null });
  React.useEffect(() => {
    if (!endpoint) {
      setState({ data: null, status: "error", error: "Missing endpoint" });
      return;
    }
    let cancelled = false;
    setState({ data: null, status: "loading", error: null });
    fetch(endpoint)
      .then(r => r.ok ? r.json() : Promise.reject("HTTP " + r.status))
      .then(payload => { if (!cancelled) setState({ data: payload, status: "live", error: null }); })
      .catch(err => { if (!cancelled) setState({ data: null, status: "error", error: String(err) }); });
    return () => { cancelled = true; };
  }, [endpoint]);
  return state;
}

function ATLLoading({ height = 120, label = "Cargando" }) {
  return (
    <div
      className="rounded-2xl border border-white/10 bg-neutral-900/60 flex items-center justify-center text-[11px] uppercase tracking-widest text-neutral-500 animate-pulse"
      style={{ minHeight: height }}
    >
      {label}…
    </div>
  );
}

function ATLErrorState({ endpoint }) {
  // Surface the failing endpoint to devs via console only — public users see a friendly message.
  React.useEffect(() => {
    if (endpoint && typeof console !== "undefined") {
      console.warn("[ATL] data fetch failed:", endpoint);
    }
  }, [endpoint]);
  return (
    <div className="rounded-2xl border border-white/10 bg-neutral-900 p-5 sm:p-6 text-center">
      <h3 className="text-base sm:text-lg font-black uppercase tracking-tight text-white">No se pudo cargar la información</h3>
      <p className="mt-2 text-xs sm:text-sm text-neutral-400">Intenta de nuevo en unos momentos.</p>
    </div>
  );
}

function ATLEmptyState({ title, body, ctaHref, ctaLabel }) {
  return (
    <div className="rounded-2xl border border-white/10 bg-neutral-900 p-5 sm:p-6">
      <div className="text-[10px] sm:text-xs uppercase tracking-[0.3em] font-bold text-neutral-400">Sin datos</div>
      <h3 className="mt-1 text-base sm:text-lg font-black uppercase tracking-tight text-white">{title}</h3>
      {body && <p className="mt-2 text-xs sm:text-sm text-neutral-400">{body}</p>}
      {ctaHref && ctaLabel && (
        <a href={ctaHref} className="mt-4 inline-flex items-center gap-2 rounded-full bg-white/5 hover:bg-white/10 border border-white/10 px-4 py-2 text-[11px] font-bold uppercase tracking-widest text-neutral-200 transition">
          {ctaLabel}
          <span className="text-base">→</span>
        </a>
      )}
    </div>
  );
}

// Shared sub-tab nav block (used by every non-hub ATL page).
function ATLTabs({ activeTab }) {
  const tabs = [
    { id: "hub",         label: "ATL",       href: "/atl/" },
    { id: "tournaments", label: "Torneos",   href: "/atl/tournaments/" },
    { id: "rankings",    label: "Rankings",  href: "/atl/rankings/" },
    { id: "players",     label: "Jugadores", href: "/atl/players/" },
  ];
  return (
    <nav className="mt-5 sm:mt-6 flex flex-wrap gap-2 text-xs uppercase tracking-widest font-bold">
      {tabs.map(tab => (
        tab.id === activeTab ? (
          <span key={tab.id} className="rounded-full bg-lime-500 px-4 py-2 text-black">{tab.label}</span>
        ) : (
          <a key={tab.id} href={tab.href} className="rounded-full bg-white/5 hover:bg-white/10 border border-white/10 hover:border-white/20 px-4 py-2 text-neutral-300 hover:text-white transition">{tab.label}</a>
        )
      ))}
    </nav>
  );
}

// Standard ATL page hero — used by sub-pages so the wordmark + sub-tabs are consistent.
function ATLPageHero({ activeTab, subtitle }) {
  return (
    <div className="bg-neutral-950 border-b border-white/10 relative overflow-hidden">
      <div className="absolute inset-0 bg-gradient-to-br from-lime-900/30 via-transparent to-transparent pointer-events-none"></div>
      <div className="relative mx-auto max-w-7xl px-4 sm:px-6 py-6 sm:py-10">
        <div className="flex items-center gap-4 sm:gap-6">
          <a href="/atl/" className="flex-shrink-0">
            <img
              src="/media/atl/logo.png"
              alt="Los Alamos Tennis League"
              className="h-16 sm:h-24 md:h-28 w-auto drop-shadow-2xl"
            />
          </a>
          <div className="min-w-0">
            <div className="text-[10px] sm:text-xs uppercase tracking-[0.4em] text-lime-400 font-bold">ATL</div>
            <div className="mt-1 text-xl sm:text-2xl md:text-3xl font-black uppercase tracking-tight leading-tight">
              Los Alamos Tennis League
            </div>
            {subtitle && (
              <div className="mt-2 text-xs sm:text-sm text-neutral-400 uppercase tracking-widest">{subtitle}</div>
            )}
          </div>
        </div>
        <ATLTabs activeTab={activeTab} />
      </div>
    </div>
  );
}

window.useATLFetch = useATLFetch;
window.ATLLoading = ATLLoading;
window.ATLErrorState = ATLErrorState;
window.ATLEmptyState = ATLEmptyState;
window.ATLTabs = ATLTabs;
window.ATLPageHero = ATLPageHero;
