/* TTS Marketing — app shell + lightweight client routing. */
const { Button, CourseCard, Input, Card, Logo, Tag, Badge } = window.TTSTechnicalTradeSchoolDesignSystem_281306;

function CatalogView({ go }) {
  const mobile = useIsMobile();
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });
  const statusTone = (s) => s === "Now enrolling" ? "ember" : "neutral";

  // Live access map (course_code → 'active'|'pending'|...) for the signed-in
  // student, so cards show open / pending / request states. Empty otherwise.
  const [access, setAccess] = React.useState({});
  React.useEffect(() => {
    if (window.TTS && window.TTS.isConfigured) {
      window.TTS.api.myAccess().then(setAccess).catch(() => {});
      window.TTS.auth.issueAccessCookie();   // pre-mint paywall cookie for deck opens
    }
  }, []);
  // What clicking a card does, given its access state.
  const openCourse = (c) => {
    const st = access[c.code];
    if ((st === "active" || st === "completed") && c.url) {
      if (window.TTS?.isConfigured) window.TTS.auth.issueAccessCookie();  // keep cookie fresh
      window.open(c.url, "_blank"); return;
    }
    if (st === "pending") { alert("Your enrollment is pending approval — you'll get access once an admin approves it."); return; }
    if (c.url && !window.TTS?.isConfigured) { window.open(c.url, "_blank"); return; }  // demo/preview
    go("enroll");
  };
  return (
    <div style={{ maxWidth: 1200, margin: "0 auto", padding: mobile ? "40px 20px 72px" : "64px 20px 88px" }}>
      <span className="tts-kicker">Course catalog</span>
      <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: mobile ? 34 : 48, letterSpacing: "-0.02em", margin: "16px 0 8px" }}>Five tracks. One trade.</h1>
      <p style={{ fontFamily: "var(--font-sans)", fontSize: 16, color: "var(--text-secondary)", maxWidth: 560 }}>From your first termination to the programmer's chair and the design desk — pick the role you're building toward.</p>
      <div style={{ marginTop: 18 }}>
        <Button variant="secondary" onClick={() => window.open("../../curriculum/Course-Catalog.html", "_blank")} rightIcon={<Icon name="external-link" size={16} />}>
          Open full course catalog · 61 courses
        </Button>
      </div>

      {window.TTS_DATA.tracks.map((t) => {
        const courses = window.TTS_DATA.courses.filter((c) => c.track === t.id);
        const iconMap = { technician: "chip", brand: "network", developer: "circuit", pm: "laptop", design: "brain", bootcamp: "circuit" };
        return (
          <section key={t.id} style={{ marginTop: 48 }}>
            <div style={{ borderTop: "2px solid var(--color-ink)", paddingTop: 16, marginBottom: 24, display: "flex", justifyContent: "space-between", alignItems: "flex-start", flexWrap: "wrap", gap: 12 }}>
              <div style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
                <span style={{ width: 46, height: 46, flex: "none", borderRadius: "var(--radius-md)", background: "var(--color-ember-50)", border: "1px solid var(--color-ember-100)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <img src={`../../assets/section-icons/${iconMap[t.id]}.svg`} width="28" height="28" alt="" />
                </span>
                <div>
                  <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: mobile ? 24 : 30, letterSpacing: "-0.02em", margin: "0 0 4px" }}>{t.label}</h2>
                  <p style={{ fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-secondary)", margin: 0, maxWidth: 560 }}>{t.blurb}</p>
                </div>
              </div>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-muted)" }}>{courses.length} courses</span>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: mobile ? "1fr" : "repeat(3,1fr)", gap: 20 }}>
              {courses.map((c) => (
                <CourseCard key={c.code}
                  code={c.code} title={c.title} description={c.description}
                  weeks={c.weeks} level={c.platform || c.level} standards={c.standards}
                  badge={{ tone: statusTone(c.status), children: c.status }}
                  onClick={() => openCourse(c)}
                  footer={(() => {
                    const st = access[c.code];
                    if (st === "active" || st === "completed")
                      return <Button fullWidth variant="primary" onClick={(e) => { e.stopPropagation(); openCourse(c); }}>Open course</Button>;
                    if (st === "pending")
                      return <Button fullWidth variant="secondary" disabled>Pending approval</Button>;
                    const enroll = <Button fullWidth variant="primary"
                      onClick={(e) => { e.stopPropagation(); go("enroll"); }}>Request enrollment</Button>;
                    if (c.price)
                      return (
                        <div>
                          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8 }}>
                            <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 20 }}>{"$" + c.price.toLocaleString()}</span>
                            <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-muted)" }}>{c.requires ? "requires " + c.requires : "individual purchase"}</span>
                          </div>
                          {enroll}
                        </div>
                      );
                    return enroll;
                  })()}
                />
              ))}
            </div>
          </section>
        );
      })}
    </div>
  );
}

function LoginView({ go }) {
  const mobile = useIsMobile();
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [err, setErr] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const signIn = async () => {
    setErr("");
    // No backend configured yet → keep the original mock behavior.
    if (!window.TTS || !window.TTS.isConfigured) { window.location.href = "../portal/index.html"; return; }
    setBusy(true);
    try {
      await window.TTS.auth.signIn({ email, password });
      window.location.href = "../portal/index.html";
    } catch (e) {
      setErr(e.message || "Could not sign in.");
      setBusy(false);
    }
  };
  return (
    <div className="tts-blueprint-light" style={{ minHeight: "calc(100vh - 68px)", display: "flex", alignItems: "flex-start", justifyContent: "center", padding: mobile ? "40px 20px" : "72px 20px" }}>
      <Card padding={mobile ? 28 : 40} style={{ width: "100%", maxWidth: 420 }}>
        <Logo size={36} assetBase="../../assets" style={{ marginBottom: 24 }} />
        <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 26, letterSpacing: "-0.02em", margin: "0 0 6px" }}>Welcome back</h1>
        <p style={{ fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-secondary)", margin: "0 0 24px" }}>Sign in to your student portal.</p>
        <form style={{ display: "flex", flexDirection: "column", gap: 16 }} onSubmit={(e) => { e.preventDefault(); signIn(); }}>
          <Input label="Email" type="email" placeholder="you@email.com" value={email} onChange={(e) => setEmail(e.target.value)} leftIcon={<Icon name="mail" size={18} />} />
          <Input label="Password" type="password" placeholder="••••••••" value={password} onChange={(e) => setPassword(e.target.value)} leftIcon={<Icon name="lock" size={18} />} />
          {err && <div style={{ fontFamily: "var(--font-sans)", fontSize: 13, color: "var(--color-danger)" }}>{err}</div>}
          <Button type="submit" variant="primary" size="lg" fullWidth disabled={busy}>{busy ? "Signing in…" : "Sign in"}</Button>
        </form>
        <div style={{ textAlign: "center", marginTop: 20, fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-secondary)" }}>
          New here? <a href="#" onClick={(e) => { e.preventDefault(); go("enroll"); }} style={{ color: "var(--text-link)", fontWeight: 600 }}>Enroll now</a>
        </div>
      </Card>
    </div>
  );
}

function AboutView({ go }) {
  const mobile = useIsMobile();
  return (
    <div style={{ maxWidth: 760, margin: "0 auto", padding: mobile ? "48px 20px" : "80px 20px" }}>
      <span className="tts-kicker">About TTS</span>
      <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: mobile ? 34 : 52, letterSpacing: "-0.025em", margin: "16px 0 24px", lineHeight: 1.05 }}>
        Built for people who build, fix, and run things.
      </h1>
      <p style={{ fontFamily: "var(--font-sans)", fontSize: 18, color: "var(--text-secondary)", lineHeight: 1.7 }}>
        TTS is an online technical trade school. We teach hands-on, standards-based skills that lead to real careers — starting with Building Automation Systems and expanding into HVAC, Electrical, and Plumbing.
      </p>
      <p style={{ fontFamily: "var(--font-sans)", fontSize: 18, color: "var(--text-secondary)", lineHeight: 1.7 }}>
        We're pursuing accreditation, and we offer need-based scholarships — partial or full — so cost is never the thing that stops you. Learn the trade. Get to work.
      </p>
      <Button variant="primary" size="lg" onClick={() => go("catalog")} style={{ marginTop: 16 }}>Browse the catalog</Button>
    </div>
  );
}

function App() {
  const ROUTES = ["home", "program", "catalog", "login", "about", "enroll"];
  const fromHash = () => { const h = (location.hash || "").replace(/^#/, ""); return ROUTES.includes(h) ? h : "home"; };
  const [route, setRoute] = React.useState(fromHash());
  // Sync route <-> URL hash so the browser Back/Forward buttons work.
  const go = (r) => { if ((location.hash || "").replace(/^#/, "") !== r) location.hash = r; setRoute(r); window.scrollTo(0, 0); };
  React.useEffect(() => {
    const on = () => { setRoute(fromHash()); window.scrollTo(0, 0); };
    window.addEventListener("hashchange", on);
    return () => window.removeEventListener("hashchange", on);
  }, []);

  let view;
  if (route === "program") view = <ProgramPage go={go} />;
  else if (route === "enroll") view = <EnrollPage go={go} />;
  else if (route === "catalog") view = <CatalogView go={go} />;
  else if (route === "login") view = <LoginView go={go} />;
  else if (route === "about") view = <AboutView go={go} />;
  else view = <HomePage go={go} />;

  const bare = route === "enroll" || route === "login";

  return (
    <div>
      <SiteHeader route={route} go={go} />
      {view}
      {!bare && <SiteFooter go={go} />}
    </div>
  );
}

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