/* ARKHAM — app root: state, routing, idle timer, my list, tweaks */
const { useState: aS, useEffect: aE, useRef: aR, useCallback: aCb } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#e50914",
  "heroSpeed": 20,
  "showTop10": true
}/*EDITMODE-END*/;

function Footer() {
  const socials = [
    { label: "Instagram", icon: Icon.IG },
    { label: "YouTube", icon: Icon.YT },
    { label: "Facebook", icon: Icon.FB },
    { label: "TikTok", icon: Icon.TikTok }
  ];
  return (
    <footer className="foot">
      <div className="foot-social">
        {socials.map((s) => (
          <a key={s.label} href="#" className="foot-soc" aria-label={s.label} title={s.label}>
            <s.icon s={22} />
          </a>
        ))}
      </div>
      <div className="foot-brand"><img src="assets/arkham-projects-white.png" alt="ARKHAM PROJECTS" /></div>
      <div className="foot-links">
        <a href="#">Sobre el estudio</a><a href="#">Sobre ARKHAM Projects</a><a href="#">Contacto</a>
        <a href="#">Prensa</a><a href="#">Conferencias</a>
        <a href="#">Privacidad</a><a href="#">Términos</a>
      </div>
      <div>ARKHAM PROJECTS · una plataforma para conocer a gente chingona.</div>
    </footer>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  const [view, setView] = aS("home");
  const [genre, setGenre] = aS("Comercio");
  const [detailId, setDetailId] = aS(null);
  const [playingId, setPlayingId] = aS(null);
  const [registerType, setRegisterType] = aS(null);
  const [idle, setIdle] = aS(false);
  const [query, setQuery] = aS("");
  const [toastMsg, setToastMsg] = aS(null);
  const [myList, setMyList] = aS(() => {
    try { return JSON.parse(localStorage.getItem("arkham_mylist") || "[]"); } catch { return []; }
  });

  aE(() => { localStorage.setItem("arkham_mylist", JSON.stringify(myList)); }, [myList]);

  // apply accent + top10 visibility
  aE(() => {
    document.documentElement.style.setProperty("--red", t.accent);
    document.body.classList.toggle("no-top10", !t.showTop10);
  }, [t.accent, t.showTop10]);

  const toastTimer = aR(null);
  const toast = aCb((msg) => {
    setToastMsg(msg);
    clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToastMsg(null), 2400);
  }, []);

  const go = aCb((v, g) => {
    if (g) setGenre(g);
    setView(v);
    setDetailId(null);
    window.scrollTo({ top: 0, behavior: "auto" });
  }, []);

  const toggleList = aCb((id) => {
    setMyList((cur) => {
      if (cur.includes(id)) { toast("Eliminado de Mi lista"); return cur.filter((x) => x !== id); }
      toast("Agregado a Mi lista"); return [...cur, id];
    });
  }, [toast]);

  const isActive = aCb((cat) => {
    if (cat.view === "home") return view === "home";
    if (cat.view === "browse") return view === "browse" && genre === cat.genre;
    return view === cat.view;
  }, [view, genre]);

  const ctx = {
    myList, toggleList, query, setQuery, toast,
    go, isActive, view, genre, tweaks: t,
    openDetail: (id) => setDetailId(id),
    closeDetail: () => setDetailId(null),
    play: (id) => { setDetailId(null); setPlayingId(id); },
    stop: () => setPlayingId(null),
    triggerIdle: () => setIdle(true),
    exitIdle: () => setIdle(false),
    openRegister: (kind) => setRegisterType(kind),
    closeRegister: () => setRegisterType(null)
  };

  const showChrome = !playingId && !idle;

  return (
    <AppCtx.Provider value={ctx}>
      {showChrome && <Nav />}

      {showChrome && (
        <main>
          {view === "home" && (
            <>
              <Hero />
              <div className="rows-wrap">
                {window.ARKHAM.rows.map((r) => <Row key={r.title} title={r.title} ids={r.ids} explore />)}
              </div>
              <Footer />
            </>
          )}
          {view === "browse" && <><Browse genre={genre} /><Footer /></>}
          {view === "mylist" && <><MyList /><Footer /></>}
          {view === "premios" && <><PremiosScreen /><Footer /></>}
          {view === "tienda" && <><TiendaScreen /><Footer /></>}
          {view === "search" && <SearchView />}
        </main>
      )}

      {registerType && <RegisterScreen type={registerType} />}
      {detailId && !playingId && <DetailModal id={detailId} />}
      {playingId && (playingId === "reel" ? <Player id="reel" /> : <ProjectViewer id={playingId} />)}
      {idle && <IdleScreen />}
      {toastMsg && <div className="toast">{toastMsg}</div>}

      <TweaksPanel>
        <TweakSection label="Marca" />
        <TweakColor label="Color de acento" value={t.accent}
          options={["#e50914", "#f5b50a", "#2a6fdb", "#1f8a5b", "#b026ff"]}
          onChange={(v) => setTweak("accent", v)} />
        <TweakSection label="Inicio" />
        <TweakSlider label="Velocidad del hero" value={t.heroSpeed} min={10} max={40} step={1} unit="s"
          onChange={(v) => setTweak("heroSpeed", v)} />
        <TweakToggle label="Insignias TOP 10" value={t.showTop10}
          onChange={(v) => setTweak("showTop10", v)} />
        <TweakSection label="Tarjeta de fin" />
        <TweakButton label="Ver pantalla “¿Sigues ahí?”" onClick={() => setIdle(true)} />
      </TweaksPanel>
    </AppCtx.Provider>
  );
}

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