// ─── APP SHELL ────────────────────────────────────────────────────

const { useState: useAppState, useEffect: useAppEffect, useRef: useAppRef } = React;

function App() {
  const [tab, setTab] = useAppState("dashboard");
  const [kidId, setKidId] = useAppState("porter");
  const [checked, setChecked] = useAppState({});
  const [statuses, setStatuses] = useAppState({});
  const [notes, setNotes] = useAppState({});
  const [homework, setHomework] = useAppState({});

  const mainRef = useAppRef(null);

  // Persist
  useAppEffect(() => {
    try {
      const c = localStorage.getItem("kgp_checks");      if (c) setChecked(JSON.parse(c));
      const s = localStorage.getItem("kgp_statuses");    if (s) setStatuses(JSON.parse(s));
      const n = localStorage.getItem("kgp_notes");       if (n) setNotes(JSON.parse(n));
      const h = localStorage.getItem("kgp_homework");    if (h) setHomework(JSON.parse(h));
      const k = localStorage.getItem("kgp_kid");         if (k) setKidId(k);
    } catch (e) {}
  }, []);
  useAppEffect(() => { try { localStorage.setItem("kgp_checks",   JSON.stringify(checked));   } catch(e){} }, [checked]);
  useAppEffect(() => { try { localStorage.setItem("kgp_statuses", JSON.stringify(statuses)); } catch(e){} }, [statuses]);
  useAppEffect(() => { try { localStorage.setItem("kgp_notes",    JSON.stringify(notes));    } catch(e){} }, [notes]);
  useAppEffect(() => { try { localStorage.setItem("kgp_homework", JSON.stringify(homework)); } catch(e){} }, [homework]);
  useAppEffect(() => { try { localStorage.setItem("kgp_kid", kidId); } catch(e){} }, [kidId]);

  const toggle = id => setChecked(c => ({ ...c, [id]: !c[id] }));

  // Quiz progress for dashboard
  const quizProgress = (() => {
    const tot = PORTER_PROMPTS.length, ctot = CRITERIA.length, stot = STORY_PROMPTS.length;
    const filled = (obj) => Object.values(obj || {}).filter(v => typeof v === "string" ? v.trim() : v != null).length;
    const porterFill = (PORTER_PROMPTS.length * 3); // jamie/tom/together
    const tateFill   = (PORTER_PROMPTS.length * 3);
    const pq = (homework.kidQuiz || {}).porter || {};
    const tq = (homework.kidQuiz || {}).tate || {};
    const porter = Math.round(100 * (filled(pq.jamie) + filled(pq.tom) + filled(pq.together)) / porterFill);
    const tate   = Math.round(100 * (filled(tq.jamie) + filled(tq.tom) + filled(tq.together)) / tateFill);
    const cq = homework.criteria || {};
    const criteria = Math.round(100 * (filled(cq.jamie) + filled(cq.tom)) / (ctot * 2));
    const scores = homework.scores || {};
    const scoredCount = SHORTLIST.filter(s => {
      const sc = scores[s.name] || {};
      return CRITERIA.some(c => sc[c.id]?.jamie != null || sc[c.id]?.tom != null);
    }).length;
    const scoring = Math.round(100 * scoredCount / SHORTLIST.length);

    let next = "";
    if (porter < 100) next = "Finish the About Porter quiz";
    else if (criteria < 100) next = "Set your criteria weights";
    else if (tate < 100) next = "Start the About Tate quiz";
    else if (scoring < 100) next = "Score the schools you've toured";
    else next = "View your weighted profile";
    return { porter, tate, criteria, scoring, next };
  })();

  const TABS = [
    { id: "dashboard", label: "Today" },
    { id: "boys",      label: "Our boys" },
    { id: "shortlist", label: "Shortlist" },
    { id: "field",     label: "Wider field" },
    { id: "calendar",  label: "Calendar" },
    { id: "homework",  label: "Homework" },
    { id: "plan",      label: "Timeline" },
    { id: "questions", label: "Tour guide" },
  ];

  const onJumpToCalendar = () => setTab("calendar");
  const onJumpToHomework = () => setTab("homework");
  const onJumpToTour = () => setTab("questions");
  const onJumpToSchool = (name) => { setTab("shortlist"); /* could scroll */ };

  // Show hero ONLY on dashboard
  const showHero = tab === "dashboard";

  return (
    <div>
      {/* ── HERO — only on dashboard ── */}
      {showHero && (
        <header style={{
          position: "relative",
          height: 480,
          overflow: "hidden",
          background: "var(--forest-deep)",
        }}>
          <div style={{
            position: "absolute", inset: 0,
            backgroundImage: `url(${IMG.hero})`,
            backgroundSize: "cover",
            backgroundPosition: "center 60%",
            filter: "saturate(0.95) contrast(1.02)",
          }} />
          <div style={{
            position: "absolute", inset: 0,
            background: "linear-gradient(to bottom, rgba(26,38,32,0.20) 0%, rgba(26,38,32,0.10) 30%, rgba(26,38,32,0.70) 80%, rgba(26,38,32,0.92) 100%)",
          }} />
          <div style={{
            position: "absolute", top: 28, left: 20, right: 20,
            display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12,
          }}>
            <Eyebrow tone="cream">Wagon Wheel · Class of 2027 & 2030</Eyebrow>
            <Ornament size={11} color="rgba(245,239,230,0.7)" />
          </div>
          <div style={{
            position: "absolute", left: 20, right: 20, bottom: 36, color: "var(--cream)",
          }}>
            <h1 className="serif" style={{
              margin: 0, fontSize: 54, fontWeight: 300, lineHeight: 0.95,
              letterSpacing: "-0.025em", color: "var(--cream)",
            }}>
              LA Kindergarten<br/>
              <em style={{ fontStyle: "italic", fontWeight: 400 }}>Admissions Planner</em>
            </h1>
            <p style={{
              margin: "20px 0 0", fontSize: 13, lineHeight: 1.6,
              color: "rgba(245,239,230,0.75)", maxWidth: 460, letterSpacing: "0.01em",
            }}>
              Private independent · Los Angeles<br/>
              For Porter (Fall 2027) and Tate (Fall 2030).
            </p>
          </div>
        </header>
      )}

      {/* ── TAB NAV ── */}
      <nav style={{
        display: "flex", gap: 0,
        padding: "0 8px",
        borderBottom: "1px solid var(--line)",
        position: "sticky", top: 0, height: 56,
        background: "var(--cream)", zIndex: 10,
        overflowX: "auto", scrollbarWidth: "none",
      }}>
        {TABS.map(t => {
          const active = tab === t.id;
          return (
            <button key={t.id}
              onClick={() => setTab(t.id)}
              style={{
                flex: "0 0 auto",
                background: "transparent", border: "none",
                padding: "20px 14px 18px",
                cursor: "pointer",
                fontFamily: "var(--sans)", fontSize: 9.5, fontWeight: 500,
                letterSpacing: "0.16em", textTransform: "uppercase",
                color: active ? "var(--forest)" : "var(--ink-3)",
                borderBottom: `1px solid ${active ? "var(--forest)" : "transparent"}`,
                marginBottom: -1, whiteSpace: "nowrap",
                transition: "color 0.15s ease",
              }}>{t.label}</button>
          );
        })}
      </nav>

      {/* ── COMING UP BAR — sticky below tabs, on every tab except dashboard ── */}
      {tab !== "dashboard" && tab !== "calendar" && (
        <ComingUpBar
          onJumpToCalendar={onJumpToCalendar}
          onJumpToSchool={onJumpToSchool}
        />
      )}

      {/* ── TAB CONTENT ── */}
      <main ref={mainRef} style={{ padding: "0 0 80px" }}>
        {tab === "dashboard" && <DashboardTab
          onJumpToCalendar={onJumpToCalendar}
          onJumpToSchool={onJumpToSchool}
          onJumpToHomework={onJumpToHomework}
          onJumpToTour={onJumpToTour}
          quizProgress={quizProgress}
        />}
        {tab === "boys"      && <BoysTab kidId={kidId} setKidId={setKidId} />}
        {tab === "shortlist" && <ShortlistTab statuses={statuses} setStatuses={setStatuses} notes={notes} setNotes={setNotes} />}
        {tab === "field"     && <FieldTab />}
        {tab === "calendar"  && <CalendarTab onJumpToSchool={onJumpToSchool} />}
        {tab === "homework"  && <HomeworkTab homework={homework} setHomework={setHomework} onJumpToSchool={onJumpToSchool} />}
        {tab === "plan"      && <TimelineTab checked={checked} toggle={toggle} />}
        {tab === "questions" && <TourTab checked={checked} toggle={toggle} />}
      </main>

      {/* Footer */}
      <footer style={{
        padding: "32px 20px 48px",
        borderTop: "1px solid var(--line)",
        textAlign: "center",
      }}>
        <Ornament size={12} color="var(--gold)" style={{ marginBottom: 14, opacity: 0.7 }} />
        <Eyebrow tone="default">BATES · MMXXVI</Eyebrow>
      </footer>
    </div>
  );
}

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