/* App principal del juez — router por estado, sincronizado con history del navegador.
   - Login con secret_code (acepta ?code=xxx para autologin).
   - Home: lista de grupos.
   - Duel: comparación A/B (entra al pulsar una group-card).
   - Detail: ficha de un proyecto.
   - Profile: perfil del juez.

   Navegación:
   - Cada vista interna se empuja con history.pushState, así el botón "atrás"
     del navegador (y el swipe en móvil) navegan DENTRO de la app y no salen
     del dominio.
   - Los botones de flecha "atrás" internos disparan window.history.back()
     para que se comporten exactamente igual que el back del navegador.
   - El cambio de pestañas (home / me) también se trata como navegación,
     creando una entrada nueva.

   Nota: el ranking del mentor permanece **oculto** hasta que la organización
   lo valide. No hay tab visible ni botón en el duelo que lleven al ranking.
*/
const { useState: appUseState, useEffect: appUseEffect, useCallback: appUseCallback } = React;

const APP_STATE_KEY = "__upsteam_view";
const HOME_VIEW = { kind: "home" };

function readViewFromHistory() {
  try {
    const s = window.history.state;
    if (s && s[APP_STATE_KEY]) return s[APP_STATE_KEY];
  } catch {}
  return null;
}

function writeView(v, { replace } = {}) {
  const state = { ...(window.history.state || {}), [APP_STATE_KEY]: v };
  if (replace) window.history.replaceState(state, "");
  else window.history.pushState(state, "");
}

function App() {
  const [authState, setAuthState] = appUseState({ checking: true, judge: null });
  const [view, setView] = appUseState(() => readViewFromHistory() || HOME_VIEW);

  // ?code= autologin support
  const urlCode = React.useMemo(() => {
    try { return new URLSearchParams(window.location.search).get("code"); } catch { return null; }
  }, []);

  // Comprobar sesión al cargar
  appUseEffect(() => {
    window.API.me()
      .then((j) => setAuthState({ checking: false, judge: j }))
      .catch(() => setAuthState({ checking: false, judge: null }));
  }, []);

  // Sincronizar el history del navegador con la vista actual.
  // - Si no hay state en la primera entrada, lo "sembramos" con la home.
  // - Escuchamos popstate (back/forward del navegador, swipe móvil) para
  //   actualizar la vista a partir del state restaurado por el navegador.
  appUseEffect(() => {
    if (authState.checking) return;
    if (!authState.judge) return;

    if (!readViewFromHistory()) {
      writeView(HOME_VIEW, { replace: true });
    }

    function onPop() {
      const v = readViewFromHistory() || HOME_VIEW;
      setView(v);
    }
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, [authState.checking, authState.judge]);

  const pushView = appUseCallback((v) => {
    writeView(v);
    setView(v);
  }, []);

  const replaceView = appUseCallback((v) => {
    writeView(v, { replace: true });
    setView(v);
  }, []);

  const goBack = appUseCallback(() => {
    window.history.back();
  }, []);

  if (authState.checking) {
    return <div style={{padding:"60px 20px", textAlign:"center", color:"var(--ink-500)"}}>Cargando…</div>;
  }

  if (!authState.judge) {
    return <ScreenLogin
      prefilledCode={urlCode || ""}
      onLogin={(j) => {
        setAuthState({ checking: false, judge: j });
        // limpiar ?code= de la URL sin añadir entrada al historial
        try {
          const url = new URL(window.location.href);
          if (url.searchParams.has("code")) {
            url.searchParams.delete("code");
            window.history.replaceState(window.history.state || {}, "", url.toString());
          }
        } catch {}
        // tras login, la primera vista es home: la dejamos como entrada actual.
        writeView(HOME_VIEW, { replace: true });
        setView(HOME_VIEW);
      }}
    />;
  }

  function logout() {
    window.API.logout().finally(() => {
      setAuthState({ checking: false, judge: null });
      writeView(HOME_VIEW, { replace: true });
      setView(HOME_VIEW);
    });
  }

  let content;
  if (view.kind === "duel" && view.group) {
    content = <GavelDuel
      group={view.group}
      onOpenDetail={(id) => pushView({ kind: "detail", id, returnTo: "duel" })}
      onBack={goBack}
    />;
  } else if (view.kind === "detail") {
    content = <ScreenProjectDetail
      projectId={view.id}
      onBack={goBack}
    />;
  } else if (view.kind === "profile") {
    content = <ScreenProfile onBack={goBack} onLogout={logout}/>;
  } else {
    content = <ScreenHome
      judgeName={(authState.judge.name || "").split(" ")[0] || "Mentor"}
      onLogout={logout}
      onOpenGroup={(g) => pushView({ kind: "duel", group: g })}
    />;
  }

  // - TopBar (escritorio): siempre visible al estar logueado, igual que en admin.
  //   El indicador activo solo se muestra en pantallas top-level (home/perfil).
  // - TabBar (móvil): solo visible en home.
  // - Cambiar de pestaña empuja una entrada nueva en el historial.
  const topbarTab = view.kind === "profile" ? "me" : (view.kind === "home" ? "home" : null);
  const showTabbar = view.kind === "home";
  const handleNavChange = (t) => {
    if (t === "me") {
      if (view.kind !== "profile") pushView({ kind: "profile" });
    } else {
      if (view.kind !== "home") pushView(HOME_VIEW);
    }
  };

  return (
    <>
      <MentorTopBar active={topbarTab} onChange={handleNavChange} onLogout={logout}/>
      {content}
      {showTabbar && (
        <TabBar active="home" onChange={handleNavChange}/>
      )}
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
