/* TTS Careers — BAS community job board (live).
   Public browsing, sign-in to apply, employer self-serve posting with
   staff moderation. Backend bridge: window.TTS_BACKEND (see index.html). */
const { Logo, Button, Card } = window.TTSTechnicalTradeSchoolDesignSystem_281306;

/* Wait for the ES-module backend bridge (tts-client) to land. */
function useBackend() {
  const [be, setBe] = React.useState(window.TTS_BACKEND || null);
  React.useEffect(() => {
    if (be) return;
    const t = setInterval(() => { if (window.TTS_BACKEND) { setBe(window.TTS_BACKEND); clearInterval(t); } }, 60);
    return () => clearInterval(t);
  }, [be]);
  return be;
}

/* Session + profile (null when signed out). */
function useSession(be) {
  const [me, setMe] = React.useState(null);
  const [loaded, setLoaded] = React.useState(false);
  React.useEffect(() => {
    if (!be) return;
    const off = be.auth.onChange(async (session) => {
      if (!session) { setMe(null); setLoaded(true); return; }
      try { setMe(await be.auth.profile()); } catch (e) { setMe(null); }
      setLoaded(true);
    });
    return off;
  }, [be]);
  return { me, loaded };
}

/* ---------- Header ---------- */
function TalentHeader({ me, go, route, be, mobile }) {
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });
  const link = (label, r) => (
    <button onClick={() => go(r)} style={{
      border: "none", background: route === r ? "var(--color-ember-50)" : "transparent",
      color: route === r ? "var(--color-ember-700)" : "var(--text-secondary)",
      borderRadius: "var(--radius-md)", padding: "8px 12px", fontFamily: "var(--font-sans)",
      fontSize: 13.5, fontWeight: 700, cursor: "pointer" }}>{label}</button>
  );
  return (
    <header style={{ position: "sticky", top: 0, zIndex: 40, background: "rgba(250,248,243,0.92)", backdropFilter: "blur(10px)", borderBottom: "1px solid var(--color-line)" }}>
      <div style={{ maxWidth: 1180, margin: "0 auto", padding: "0 20px", height: 64, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
        <a href="../marketing/index.html" title="TTS home" style={{ display: "flex", alignItems: "center", gap: 12, textDecoration: "none" }}>
          <Logo size={30} assetBase="../../assets" />
          {!mobile && <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--color-ember-600)", borderLeft: "1px solid var(--color-line)", paddingLeft: 12 }}>Careers</span>}
        </a>
        <div style={{ display: "flex", alignItems: "center", gap: mobile ? 2 : 8, flexWrap: "wrap", justifyContent: "flex-end" }}>
          {link("Browse jobs", "board")}
          {link(mobile ? "Seekers" : "For job seekers", "seeker")}
          {link(mobile ? "Employers" : "For employers", "employer")}
          {me ? (
            <Button size="sm" variant="secondary" onClick={async () => { try { await be.auth.signOut(); } catch (e) {} go("board"); }}>Sign out</Button>
          ) : (
            <Button size="sm" variant="secondary" onClick={() => go("auth")}>Sign in</Button>
          )}
        </div>
      </div>
    </header>
  );
}

/* ---------- Hero ---------- */
function Hero({ mobile, jobsCount }) {
  return (
    <section className="tts-blueprint" style={{ background: "var(--color-ink)", color: "#fff" }}>
      <div style={{ maxWidth: 980, margin: "0 auto", padding: mobile ? "44px 20px 36px" : "64px 20px 48px", textAlign: "center" }}>
        <span className="tts-kicker" style={{ color: "var(--color-ember-400)", justifyContent: "center" }}>BAS community · Careers</span>
        <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: mobile ? 36 : 56, letterSpacing: "-0.03em", color: "#fff", margin: "18px 0 12px", lineHeight: 1.05 }}>
          Where the BAS community goes to work.
        </h1>
        <p style={{ fontFamily: "var(--font-sans)", fontSize: mobile ? 16 : 19, color: "var(--color-mist)", maxWidth: 640, margin: "0 auto", lineHeight: 1.55 }}>
          Find work, post jobs, ask questions, learn. Open to every building-automation
          professional — not just TTS graduates. {jobsCount > 0 ? `${jobsCount} open role${jobsCount === 1 ? "" : "s"} right now.` : ""}
        </p>
      </div>
    </section>
  );
}

/* ---------- Two doors: job seekers / employers ---------- */
function Doors({ go, mobile }) {
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });
  const bullets = (items, dark) => (
    <ul style={{ listStyle: "none", padding: 0, margin: "0 0 20px", display: "flex", flexDirection: "column", gap: 9 }}>
      {items.map((b) => (
        <li key={b} style={{ display: "flex", gap: 10, alignItems: "flex-start", fontFamily: "var(--font-sans)", fontSize: 14, color: dark ? "var(--color-stone-50)" : "var(--text-primary)", lineHeight: 1.45 }}>
          <TIcon name="check" size={17} color={dark ? "var(--color-ember-400)" : "var(--color-ember-500)"} /> <span>{b}</span>
        </li>
      ))}
    </ul>
  );
  const { Card, Button } = window.TTSTechnicalTradeSchoolDesignSystem_281306;
  return (
    <section style={{ maxWidth: 1180, margin: "0 auto", padding: mobile ? "0 20px" : "0 20px", marginTop: mobile ? -20 : -28 }}>
      <div style={{ display: "grid", gridTemplateColumns: mobile ? "1fr" : "1fr 1fr", gap: 18 }}>
        {/* Job seeker door */}
        <Card accent padding={mobile ? 22 : 28} style={{ display: "flex", flexDirection: "column" }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--color-ember-600)", marginBottom: 6 }}>Job seekers</div>
          <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: mobile ? 22 : 25, letterSpacing: "-0.02em", margin: "0 0 12px" }}>Find your next role</h2>
          {bullets(["Browse and apply below — any BAS professional", "Build a talent profile employers can see", "Track every application in one place"], false)}
          <div style={{ marginTop: "auto" }}>
            <Button onClick={() => go("seeker")} rightIcon={<TIcon name="arrow-right" size={17} />}>My seeker home</Button>
          </div>
        </Card>
        {/* Employer door */}
        <div className="tts-blueprint" style={{ background: "var(--color-ink)", borderRadius: "var(--radius-lg)", padding: mobile ? 22 : 28, display: "flex", flexDirection: "column", border: "1px solid var(--color-ink-soft)" }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--color-ember-400)", marginBottom: 6 }}>Employers</div>
          <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: mobile ? 22 : 25, letterSpacing: "-0.02em", margin: "0 0 12px", color: "#fff" }}>Find your next hire</h2>
          {bullets(["Register your company and post jobs — free", "Reach the whole BAS community, not one cohort", "Review applicants from your dashboard"], true)}
          <div style={{ marginTop: "auto" }}>
            <Button onClick={() => go("employer")} rightIcon={<TIcon name="arrow-right" size={17} />}>Post a job</Button>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Real sign-in / create account ---------- */
function AuthCard({ be, onDone, mobile, prompt }) {
  const [mode, setMode] = React.useState("signin");
  const [email, setEmail] = React.useState("");
  const [pw, setPw] = React.useState("");
  const [name, setName] = React.useState("");
  const [msg, setMsg] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });
  const { Input } = window.TTSTechnicalTradeSchoolDesignSystem_281306;

  async function submit() {
    setMsg(""); setBusy(true);
    try {
      if (mode === "signin") {
        await be.auth.signIn({ email: email.trim(), password: pw });
      } else {
        if (!name.trim()) throw new Error("Please enter your name.");
        await be.auth.signUp({ email: email.trim(), password: pw, fullName: name.trim() });
        try { await be.auth.signIn({ email: email.trim(), password: pw }); } catch (e) {
          setMsg("Account created. Check your email to confirm, then sign in."); setBusy(false); return;
        }
      }
      onDone();
    } catch (e) {
      const t = String(e && e.message || e);
      setMsg(/invalid login/i.test(t) ? "That email + password combination didn't match. Try again or create an account."
        : /already registered/i.test(t) ? "That email already has an account — sign in instead."
        : /at least 6/i.test(t) ? "Passwords need at least 6 characters."
        : t);
    }
    setBusy(false);
  }

  return (
    <div className="tts-blueprint-light" style={{ minHeight: "calc(100vh - 64px)", display: "flex", alignItems: "flex-start", justifyContent: "center", padding: mobile ? "36px 20px" : "64px 20px" }}>
      <Card padding={mobile ? 28 : 40} style={{ width: "100%", maxWidth: 430 }}>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--color-ember-600)", marginBottom: 6 }}>BAS community</div>
        <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 26, letterSpacing: "-0.02em", margin: "0 0 4px" }}>{mode === "signin" ? "Sign in" : "Create your account"}</h1>
        <p style={{ fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-secondary)", margin: "0 0 22px" }}>
          {prompt || "One account for jobs, the forum, and classes."}
        </p>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {mode === "create" && <Input label="Full name" placeholder="Alex Rivera" value={name} onChange={(e) => setName(e.target.value)} leftIcon={<TIcon name="user" size={18} />} />}
          <Input label="Email" type="email" placeholder="you@company.com" value={email} onChange={(e) => setEmail(e.target.value)} leftIcon={<TIcon name="mail" size={18} />} />
          <Input label="Password" type="password" placeholder="••••••••" value={pw} onChange={(e) => setPw(e.target.value)} leftIcon={<TIcon name="lock" size={18} />} />
          {msg && <div style={{ fontFamily: "var(--font-sans)", fontSize: 13.5, lineHeight: 1.45, padding: "10px 12px", borderRadius: 9, background: "#FCEEE6", border: "1px solid #F2B591", color: "var(--color-ember-700)" }}>{msg}</div>}
          <Button size="lg" fullWidth disabled={busy} onClick={submit}>{busy ? "One moment…" : mode === "signin" ? "Sign in" : "Create account & continue"}</Button>
        </div>
        <div style={{ textAlign: "center", marginTop: 18, fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-secondary)" }}>
          {mode === "signin" ? "New here? " : "Have an account? "}
          <a href="#" onClick={(e) => { e.preventDefault(); setMsg(""); setMode(mode === "signin" ? "create" : "signin"); }} style={{ color: "var(--text-link)", fontWeight: 600 }}>
            {mode === "signin" ? "Create an account" : "Sign in"}
          </a>
        </div>
        <div style={{ textAlign: "center", marginTop: 10, fontFamily: "var(--font-sans)", fontSize: 13 }}>
          <a href="../../backend/pages/reset-password.html" style={{ color: "var(--text-muted)" }}>Forgot password?</a>
        </div>
      </Card>
    </div>
  );
}

/* ---------- App shell ---------- */
function TalentApp() {
  const mobile = useTalentMobile();
  const be = useBackend();
  const { me } = useSession(be);
  const [route, setRoute] = React.useState("board");
  const [authNext, setAuthNext] = React.useState(null);   // route to land on after sign-in
  const [jobsCount, setJobsCount] = React.useState(0);
  const go = (r) => {
    if ((r === "seeker" || r === "employer") && !me) { setAuthNext(r); setRoute("auth"); }
    else setRoute(r);
    window.scrollTo(0, 0);
  };
  React.useEffect(() => { if (me && route === "auth") setRoute(authNext || "board"); }, [me]);

  if (!be) return (
    <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-sans)", color: "var(--text-secondary)" }}>Loading the job board…</div>
  );

  let view;
  if (route === "auth") view = <AuthCard be={be} mobile={mobile} onDone={() => go(authNext || "board")}
    prompt={authNext === "employer" ? "Sign in (or create a free account) to post jobs for your company." :
            authNext === "seeker" ? "Sign in to build your talent profile and track applications." :
            "Sign in to apply. Any BAS professional is welcome — you don't need to be a TTS student."} />;
  else if (route === "seeker") view = <SeekerHome be={be} me={me} mobile={mobile} go={go} />;
  else if (route === "employer") view = <EmployerDash be={be} me={me} mobile={mobile} go={go} />;
  else view = (
    <div>
      <Hero mobile={mobile} jobsCount={jobsCount} />
      <Doors go={go} mobile={mobile} />
      <main style={{ maxWidth: 1180, margin: "0 auto", padding: mobile ? "28px 20px 64px" : "36px 20px 80px" }}>
        <JobBoard be={be} me={me} mobile={mobile} go={(r) => { if (r === "auth") { setAuthNext("board"); setRoute("auth"); } else go(r); window.scrollTo(0, 0); }} onCount={setJobsCount} />
      </main>
    </div>
  );

  return (
    <div style={{ minHeight: "100vh", background: "var(--bg-page)" }}>
      <TalentHeader me={me} go={go} route={route} be={be} mobile={mobile} />
      {view}
    </div>
  );
}

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