// Valdebebas Life — App
function App() {
  const [page, setPage] = useStored("vr2_page", "home");
  const [svc, setSvc] = useState("all");
  const [bestFocus, setBestFocus] = useState(null);
  const [boardFilter, setBoardFilter] = useState("all");
  const [me] = useStored("vr_me", null);
  const [users] = useStored("vr_users", []);
  const [posts, setPosts] = useStored("vr3_posts", VB_POSTS_SEED);
  const [social, setSocial] = useStored("vr3_social", {});
  const [auth, setAuth] = useState(null);
  const [pending, setPending] = useState(null);
  const [publish, setPublish] = useState(false);
  const [postId, setPostId] = useState(null);
  const [contact, setContact] = useState(null);
  const [legal, setLegal] = useState(null);
  const [toast, setToast] = useState("");
  const [recOpen, setRecOpen] = useState(false);
  const [baro, setBaro] = useStored("vr3_baro", {});
  const [dir, setDir] = useStored("vr3_dir", []);
  window.__dir = dir; window.__dirV = dir.length + ":" + dir.filter(x => x.status === "activo").length;
  const [invite, setInvite] = useState(false);
  const [baroState, setBaroState] = useState(null);
  const [myBaro, setMyBaro] = useState(false);
  const [delOpen, setDelOpen] = useState(false);
  const afterBaro = useRef(null);

  const user = me || null;
  const isAdmin = user && user.role === "admin";
  const mine = (user && social[user.email]) || { recs: [], votes: {} };
  const setMine = m => setSocial({ ...social, [user.email]: { ...mine, ...m } });
  const flash = m => { setToast(m); clearTimeout(window.__vrT); window.__vrT = setTimeout(() => setToast(""), 2600); };
  const alive = posts.filter(p => (!p.expires || p.expires > Date.now()) && !p.hidden);

  if (page === "noticias") setTimeout(() => setPage("home"), 0);
  useSeo(page);
  window.__vrSess = () => sessRef.current;
  window.__vrUser = () => VBStore.get("vr_me");
  useEffect(() => { window.__vrFlash = flash; window.__vrRecovery = () => setAuth({ mode: "newpass" }); if (window.__vrRecoveryPending) { window.__vrRecoveryPending = false; setAuth({ mode: "newpass" }); } }, []);
  useEffect(() => {
    if (!user) return;
    if (user.needsTerms) { if (localStorage.getItem("vb_terms_ok")) { localStorage.removeItem("vb_terms_ok"); VBStore.acceptTerms().catch(() => setAuth({ mode: "terms" })); } else setAuth(s => s || { mode: "terms" }); return; }
    if (user.role === "admin") return;
    const k = "vb_baro_auto_" + user.id, b = baro[user.email];
    if ((!b || !b.entries.length) && !localStorage.getItem(k)) { localStorage.setItem(k, "1"); setTimeout(() => setBaroState(s => s || { kind: "inicio", email: user.email }), 700); }
  }, [user && user.id, user && user.needsTerms]);
  const go = p => { setPage(p); window.scrollTo({ top: 0 }); try { history.replaceState(null, "", p === "admin" ? "#/admin" : location.pathname + location.search); } catch (e) {} };
  useEffect(() => { const L = { "#privacidad": "privacidad", "#aviso-legal": "legal", "#cookies": "cookies", "#condiciones": "condiciones" }; const h = () => { if (location.hash === "#/admin") setPage("admin"); if (L[location.hash]) setLegal(L[location.hash]); }; h(); window.addEventListener("hashchange", h); return () => window.removeEventListener("hashchange", h); }, []);
  const goServ = c => { setSvc(c); go("servicios"); };
  const goBest = c => { setBestFocus(c); setPage("mejor"); if (!c) window.scrollTo({ top: 0 }); };
  const requireAuth = (reason, fn) => { if (user) fn(); else { setPending(() => fn); setAuth({ mode: "register", reason }); } };

  const onAuthed = (u, isNew) => {
    setAuth(null); if (!u) return;
    flash(u.role === "admin" ? "Hola, administrador" : "Bienvenido/a, " + u.name.split(" ")[0]);
    const fn = pending; setPending(null);
    if (isNew) { afterBaro.current = fn; localStorage.setItem("vb_baro_auto_" + u.id, "1"); setTimeout(() => setBaroState({ kind: "inicio", email: u.email }), 300); }
    else if (fn) setTimeout(fn, 0);
  };
  const closeBaro = () => { setBaroState(null); const fn = afterBaro.current; afterBaro.current = null; if (fn) setTimeout(fn, 0); };
  const startBaro = () => { if (!user) return; const b = baro[user.email]; setMyBaro(false); setBaroState({ kind: b && b.entries.length ? "seguimiento" : "inicio", email: user.email }); };
  const deleteAccount = async reason => {
    try { await VBStore.deleteAccount(reason !== null ? VB_EXIT[reason] : null); setDelOpen(false); go("home"); flash("Tu cuenta y tus datos se han borrado"); }
    catch (e) { flash("No se pudo borrar la cuenta. Escríbenos a " + VB_EMAIL); }
  };
  const showBaroBanner = user && user.role !== "admin" && baroDue(baro[user.email]) && !baroState;

  const onRec = p => requireAuth("Crea tu cuenta para recomendar a " + p.name + ".", () => {
    const m = (social[sessRef.current] || { recs: [], votes: {} });
    const has = m.recs.includes(p.id);
    setSocial(s => ({ ...s, [sessRef.current]: { ...m, recs: has ? m.recs.filter(x => x !== p.id) : [...m.recs, p.id] } }));
    if (!has) flash("Gracias por recomendar a " + p.name);
  });
  const onVote = (cat, id) => requireAuth("Crea tu cuenta para votar lo mejor del barrio.", () => {
    setSocial(s => { const m = s[sessRef.current] || { recs: [], votes: {} }; const v = { ...m.votes }; if (v[cat] === id) delete v[cat]; else v[cat] = id; return { ...s, [sessRef.current]: { ...m, votes: v } }; });
  });
  const sessRef = useRef(null);
  sessRef.current = user ? user.email : null;

  const openPublish = () => requireAuth("Crea tu cuenta para publicar en el tablón. Es gratis y tarda un minuto.", () => setPublish(true));
  const savePost = async f => {
    const u = VBStore.get("vr_me");
    const id = vbId();
    const files = f.files && f.files.length ? await VBStore.upload(id, f.files) : [];
    const p = { id, files, type: f.type, title: f.title.trim(), body: f.body.trim(), detail: f.detail.trim(), author: u.name, email: u.email, role: u.role === "admin" ? "admin" : "vecino", ts: Date.now(), expires: Date.now() + f.days * VB_DAY, replies: [] };
    setPosts(ps => [p, ...ps]); setPublish(false); setBoardFilter("all"); go("tablon"); flash("Anuncio publicado");
  };
  const upd = (id, fn) => setPosts(ps => ps.map(p => p.id === id ? fn(p) : p));
  const onReply = (p, text) => { const u = VBStore.get("vr_me"); upd(p.id, x => ({ ...x, replies: [...x.replies, { author: u.name, ts: Date.now(), text }] })); };
  const onResolve = p => { upd(p.id, x => ({ ...x, done: true })); flash("Marcado como resuelto"); };
  const onDeletePost = p => { if (confirm("¿Borrar este anuncio?")) { setPosts(ps => ps.filter(x => x.id !== p.id)); setPostId(null); flash("Anuncio borrado"); } };
  const onReport = p => { upd(p.id, x => { const r = (x.reports || 0) + 1; return { ...x, reports: r, hidden: x.hidden || r >= 3 }; }); setPostId(null); flash("Gracias. Revisaremos el anuncio."); };


  const post = postId && posts.find(p => p.id === postId);
  const lg = legal && VB_LEGAL[legal];

  return (
    <>
      <Header page={page} go={go} user={user} onLogin={() => setAuth({ mode: "login" })} onRegister={() => setAuth({ mode: "register" })} onLogout={() => { VBStore.signOut(); flash("Sesión cerrada"); }} onBaro={() => setMyBaro(true)} onDelete={() => setDelOpen(true)} onInvite={() => setInvite(true)} />
      <main id="contenido">
        {showBaroBanner && page === "home" && <BaroBanner first={!(baro[user.email] && baro[user.email].entries.length)} onStart={startBaro} />}
        {page === "home" && <Home go={go} goServ={goServ} goBest={goBest} openPro={setContact} posts={[...alive].sort((a, b) => b.ts - a.ts)} openPost={p => setPostId(p.id)} onPublish={openPublish} user={user} onRegister={() => setAuth({ mode: "register" })} />}
        {page === "servicios" && <Services cat={svc} setCat={setSvc} recs={mine.recs} onRec={onRec} onContact={setContact} onPublish={openPublish} onJoin={() => go("contacto")} onRecommend={() => setRecOpen(true)} go={go} />}
        {page === "admin" && <Admin isAdmin={isAdmin} onLogin={() => setAuth({ mode: "login" })} users={users} posts={posts} setPosts={setPosts} dir={dir} setDir={setDir} baro={baro} flash={flash} />}
        {page === "contacto" && <Contact user={user} onRegister={() => setAuth({ mode: "register" })} />}
        {page === "mejor" && <Best focus={bestFocus} setFocus={setBestFocus} votes={mine.votes} onVote={onVote} onRecommend={() => setRecOpen(true)} go={go} />}
        {page === "tablon" && <Board posts={alive} filter={boardFilter} setFilter={setBoardFilter} openPost={p => setPostId(p.id)} onPublish={openPublish} user={user} />}
        {page === "comunidad" && <Community user={user} requireAuth={requireAuth} flash={flash} onRegister={() => setAuth({ mode: "register" })} />}
      </main>
      {page !== "admin" && <Footer go={go} openLegal={setLegal} />}
      {page !== "admin" && <InstallBanner />}
      <MobileNav page={page} go={go} />

      <AuthModal state={auth} onClose={() => { setAuth(null); setPending(null); }} onAuthed={onAuthed} />
      <PublishModal open={publish} onClose={() => setPublish(false)} onSave={savePost} defType={boardFilter} />
      <PostDetail post={post} onClose={() => setPostId(null)} user={user} requireAuth={requireAuth} onReply={onReply} onResolve={onResolve} onDelete={onDeletePost} onReport={onReport} />
      <ContactModal pro={contact} onClose={() => setContact(null)} />
      <Modal open={!!lg} onClose={() => setLegal(null)} title={lg && lg.t}><p className="post-full">{lg && lg.b}</p></Modal>
      <RecommendModal open={recOpen} onClose={() => setRecOpen(false)} user={user} />
      <Barometer state={baroState} onClose={closeBaro} baro={baro} setBaro={setBaro} go={go} />
      <MyBarometer open={myBaro && !!user} onClose={() => setMyBaro(false)} email={user && user.email} baro={baro} setBaro={setBaro} onStart={startBaro} />
      <DeleteAccount open={delOpen} onClose={() => setDelOpen(false)} onConfirm={deleteAccount} />
      <InviteModal open={invite && !!user} onClose={() => setInvite(false)} user={user} users={users} flash={flash} />
      <Toast msg={toast} />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
if ("serviceWorker" in navigator && location.protocol === "https:" && window.top === window.self) navigator.serviceWorker.register("sw.js").catch(() => {});
