/* TTS Careers — community job board views (live data via community-jobs.sql).
   JobBoard (public browse + apply), MyApplications, EmployerDash
   (register company → post jobs → review applicants). */
const { Card, Badge, Tag, Button, Avatar, Input, Select } = window.TTSTechnicalTradeSchoolDesignSystem_281306;

function useTalentMobile(bp = 860) {
  const [m, setM] = React.useState(typeof window !== "undefined" && window.innerWidth < bp);
  React.useEffect(() => {
    const on = () => setM(window.innerWidth < bp);
    window.addEventListener("resize", on);
    return () => window.removeEventListener("resize", on);
  }, [bp]);
  return m;
}
function TIcon({ name, size = 18, color }) { return <i data-lucide={name} style={{ width: size, height: size, color }} />; }

const TRACKS = (window.TTS_TALENT && window.TTS_TALENT.tracks) || ["Technician", "Developer", "Project Manager", "Design", "Brand"];
const fmtDate = (v) => v ? new Date(v).toLocaleDateString([], { month: "short", day: "numeric" }) : "";
const errText = (e) => String((e && e.message) || e || "Something went wrong.");

function Note({ tone, children }) {
  const c = tone === "ok" ? { bg: "#E7F3EC", bd: "#BFE3CE", fg: "#1F6E43" } : { bg: "#FCEEE6", bd: "#F2B591", fg: "var(--color-ember-700)" };
  return <div style={{ fontFamily: "var(--font-sans)", fontSize: 13.5, lineHeight: 1.45, padding: "10px 12px", borderRadius: 9, background: c.bg, border: `1px solid ${c.bd}`, color: c.fg }}>{children}</div>;
}
function TextArea({ label, value, onChange, placeholder, rows = 4 }) {
  return (
    <label style={{ display: "block" }}>
      {label && <div style={{ fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 700, marginBottom: 6 }}>{label}</div>}
      <textarea value={value} onChange={onChange} placeholder={placeholder} rows={rows} style={{
        width: "100%", boxSizing: "border-box", resize: "vertical", padding: "11px 13px",
        border: "1px solid var(--color-line)", borderRadius: "var(--radius-md)",
        fontFamily: "var(--font-sans)", fontSize: 14, lineHeight: 1.5, background: "var(--bg-surface)" }} />
    </label>
  );
}

/* ================= Message thread (seeker ↔ employer, per application) ================= */
function MsgThread({ be, appId }) {
  const [msgs, setMsgs] = React.useState(null);
  const [draft, setDraft] = React.useState("");
  const [err, setErr] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const endRef = React.useRef(null);

  const load = React.useCallback(() => {
    be.supabase.rpc("application_thread", { p_application: appId })
      .then(({ data, error }) => setMsgs(error ? [] : (data || [])))
      .catch(() => setMsgs([]));
  }, [be, appId]);
  React.useEffect(() => { load(); const t = setInterval(load, 20000); return () => clearInterval(t); }, [load]);
  React.useEffect(() => { endRef.current && endRef.current.scrollIntoView({ block: "nearest" }); }, [msgs]);

  async function send() {
    const body = draft.trim();
    if (!body) return;
    setBusy(true); setErr("");
    try {
      const { data, error } = await be.supabase.rpc("send_application_message", { p_application: appId, p_body: body });
      if (error) throw error;
      setMsgs([...(msgs || []), { ...data, mine: true, sender_name: "You" }]);
      setDraft("");
    } catch (e) { setErr(errText(e)); }
    setBusy(false);
  }

  return (
    <div style={{ marginTop: 10, border: "1px solid var(--color-line)", borderRadius: "var(--radius-md)", background: "var(--bg-surface, #fff)" }}>
      <div style={{ maxHeight: 240, overflowY: "auto", padding: "12px 14px", display: "flex", flexDirection: "column", gap: 8 }}>
        {msgs === null && <div style={{ fontFamily: "var(--font-sans)", fontSize: 13, color: "var(--text-secondary)" }}>Loading messages…</div>}
        {msgs && msgs.length === 0 && <div style={{ fontFamily: "var(--font-sans)", fontSize: 13, color: "var(--text-secondary)" }}>No messages yet — say hello and share your interest.</div>}
        {(msgs || []).map((m) => (
          <div key={m.id} style={{ alignSelf: m.mine ? "flex-end" : "flex-start", maxWidth: "82%" }}>
            <div style={{
              padding: "8px 12px", borderRadius: 12, fontFamily: "var(--font-sans)", fontSize: 13.5, lineHeight: 1.45, whiteSpace: "pre-wrap",
              background: m.mine ? "var(--color-ember-50, #FBE9E1)" : "var(--bg-subtle, #F4F4F2)",
              border: "1px solid " + (m.mine ? "var(--color-ember-100, #F2C9AE)" : "var(--color-line)"),
            }}>{m.body}</div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--text-muted)", marginTop: 3, textAlign: m.mine ? "right" : "left" }}>
              {m.mine ? "You" : m.sender_name} · {new Date(m.created_at).toLocaleString([], { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })}
            </div>
          </div>
        ))}
        <div ref={endRef} />
      </div>
      {err && <div style={{ padding: "0 14px 8px" }}><Note>{err}</Note></div>}
      <div style={{ display: "flex", gap: 8, padding: "10px 12px", borderTop: "1px solid var(--color-line)" }}>
        <input value={draft} onChange={(e) => setDraft(e.target.value)}
          onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); } }}
          placeholder="Write a message…" aria-label="Message"
          style={{ flex: 1, padding: "9px 12px", border: "1px solid var(--color-line)", borderRadius: "var(--radius-md)", fontFamily: "var(--font-sans)", fontSize: 13.5 }} />
        <Button size="sm" disabled={busy || !draft.trim()} onClick={send}>{busy ? "…" : "Send"}</Button>
      </div>
    </div>
  );
}

/* ================= Job board (public) ================= */
function JobBoard({ be, me, mobile, go, onCount }) {
  const [jobs, setJobs] = React.useState(null);
  const [q, setQ] = React.useState("");
  const [track, setTrack] = React.useState("All tracks");
  const [applyJob, setApplyJob] = React.useState(null);   // job being applied to
  const [note, setNote] = React.useState("");
  const [mine, setMine] = React.useState({});             // job_id -> true (already applied)
  const [msg, setMsg] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });

  const load = React.useCallback(async () => {
    try {
      const { data, error } = await be.supabase.rpc("list_open_jobs", {
        p_q: q || null, p_track: track === "All tracks" ? null : track,
      });
      if (error) throw error;
      setJobs(data || []);
      if (onCount && !q && track === "All tracks") onCount((data || []).length);
    } catch (e) { setJobs([]); setMsg(errText(e)); }
  }, [be, q, track]);
  React.useEffect(() => { load(); }, [load]);
  React.useEffect(() => {
    if (!me) { setMine({}); return; }
    be.supabase.rpc("my_applications").then(({ data }) => {
      const m = {}; (data || []).forEach((a) => { m[a.job_id] = true; }); setMine(m);
    }).catch(() => {});
  }, [be, me]);

  async function submitApplication() {
    setBusy(true); setMsg("");
    try {
      const { error } = await be.supabase.rpc("apply_to_job", { p_job: applyJob.id, p_note: note || null });
      if (error) throw error;
      be.notifyStaff && be.notifyStaff("application", `${applyJob.title} @ ${applyJob.employer_name}`);
      setMine({ ...mine, [applyJob.id]: true });
      setApplyJob(null); setNote("");
    } catch (e) { setMsg(errText(e)); }
    setBusy(false);
  }

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, marginBottom: 18, flexWrap: "wrap" }}>
        <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 22, margin: 0 }}>
          Open roles{jobs ? ` · ${jobs.length}` : ""}
        </h2>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
          <div style={{ width: mobile ? "100%" : 240 }}>
            <Input placeholder="Search title, company, city…" value={q} onChange={(e) => setQ(e.target.value)} leftIcon={<TIcon name="search" size={16} />} aria-label="Search jobs" />
          </div>
          <div style={{ width: mobile ? "100%" : 190 }}>
            <Select options={["All tracks"].concat(TRACKS)} value={track} onChange={(e) => setTrack(e.target.value)} aria-label="Filter by track" />
          </div>
        </div>
      </div>

      {msg && <div style={{ marginBottom: 14 }}><Note>{msg}</Note></div>}
      {jobs === null && <Card padding={28}><div style={{ textAlign: "center", color: "var(--text-secondary)", fontFamily: "var(--font-sans)", fontSize: 14 }}>Loading open roles…</div></Card>}
      {jobs && jobs.length === 0 && (
        <Card padding={28}>
          <div style={{ textAlign: "center", color: "var(--text-secondary)", fontFamily: "var(--font-sans)", fontSize: 14, lineHeight: 1.6 }}>
            No open roles match{q || track !== "All tracks" ? " your filters" : " yet"}.<br />
            Hiring? <a href="#" onClick={(e) => { e.preventDefault(); go("employer"); }} style={{ color: "var(--text-link)", fontWeight: 600 }}>Post a job</a> — it's free for the BAS community.
          </div>
        </Card>
      )}

      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {(jobs || []).map((j) => (
          <Card key={j.id} padding={20} style={{ display: "flex", gap: 16, alignItems: "flex-start", flexWrap: "wrap" }}>
            <Avatar name={j.employer_name || "?"} size={44} />
            <div style={{ flex: 1, minWidth: 200 }}>
              <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 17, margin: "0 0 3px" }}>{j.title}</h3>
              <div style={{ fontFamily: "var(--font-sans)", fontSize: 13.5, color: "var(--text-secondary)" }}>
                {j.employer_name}
                {j.employer_website && <span> · <a href={/^https?:/i.test(j.employer_website) ? j.employer_website : "https://" + j.employer_website} target="_blank" rel="noopener noreferrer" style={{ color: "var(--text-link)" }}>website</a></span>}
              </div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 14, marginTop: 10, fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-secondary)" }}>
                {(j.location || j.employer_location) && <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><TIcon name="map-pin" size={13} />{j.location || j.employer_location}</span>}
                {j.track && <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><TIcon name="briefcase" size={13} />{j.track}</span>}
                <span>Posted {fmtDate(j.created_at)}</span>
              </div>
              {j.description && <p style={{ fontFamily: "var(--font-sans)", fontSize: 13.5, color: "var(--text-secondary)", lineHeight: 1.55, margin: "10px 0 0", whiteSpace: "pre-wrap" }}>{j.description}</p>}
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8, alignItems: "flex-end" }}>
              {mine[j.id]
                ? <Badge tone="success" variant="soft" dot>Applied</Badge>
                : <Button size="sm" onClick={() => { if (!me) { go("auth"); return; } setApplyJob(j); setNote(""); setMsg(""); }}>Apply</Button>}
            </div>
          </Card>
        ))}
      </div>

      {/* Apply modal */}
      {applyJob && (
        <div role="dialog" aria-modal="true" style={{ position: "fixed", inset: 0, zIndex: 60, background: "rgba(24,25,27,.5)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}
             onClick={(e) => { if (e.target === e.currentTarget) setApplyJob(null); }}>
          <Card padding={26} style={{ width: "100%", maxWidth: 480 }}>
            <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 20, margin: "0 0 4px" }}>Apply — {applyJob.title}</h3>
            <p style={{ fontFamily: "var(--font-sans)", fontSize: 13.5, color: "var(--text-secondary)", margin: "0 0 16px" }}>
              {applyJob.employer_name} sees your name, email, and this note.
            </p>
            <TextArea label="Note to the employer (optional)" value={note} onChange={(e) => setNote(e.target.value)}
              placeholder="A sentence or two: your experience, platforms you know, when you can start…" />
            {msg && <div style={{ marginTop: 12 }}><Note>{msg}</Note></div>}
            <div style={{ display: "flex", gap: 10, marginTop: 16, justifyContent: "flex-end" }}>
              <Button variant="secondary" onClick={() => setApplyJob(null)}>Cancel</Button>
              <Button disabled={busy} onClick={submitApplication}>{busy ? "Sending…" : "Send application"}</Button>
            </div>
          </Card>
        </div>
      )}
    </div>
  );
}

/* ================= Job seeker home: talent profile + applications ================= */
function SeekerHome({ be, me, mobile, go }) {
  const [prof, setProf] = React.useState(null);      // talent_profiles row (or defaults)
  const [rows, setRows] = React.useState(null);      // my applications
  const [msg, setMsg] = React.useState("");
  const [ok, setOk] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [openMsg, setOpenMsg] = React.useState({});
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });

  React.useEffect(() => {
    be.supabase.from("talent_profiles").select("*").maybeSingle()
      .then(({ data }) => setProf(data || { available: true, track: "", location: "", headline: "", _new: true }))
      .catch(() => setProf({ available: true, track: "", location: "", headline: "", _new: true }));
    be.supabase.rpc("my_applications").then(({ data, error }) => setRows(error ? [] : (data || []))).catch(() => setRows([]));
  }, [be]);

  async function save(next) {
    const p = next || prof;
    setBusy(true); setMsg(""); setOk("");
    try {
      const { data, error } = await be.supabase.rpc("set_talent_availability", {
        p_available: !!p.available, p_track: p.track || null,
        p_location: p.location || null, p_headline: p.headline || null,
      });
      if (error) throw error;
      setProf(data);
      setOk("Profile saved — employers reviewing your applications see it.");
    } catch (e) { setMsg(errText(e)); }
    setBusy(false);
  }

  const tone = { new: "neutral", viewed: "info", contacted: "success", declined: "neutral" };
  const label = { new: "Sent", viewed: "Viewed", contacted: "Contacted", declined: "Closed" };
  const P = (k) => ({ value: (prof && prof[k]) || "", onChange: (e) => setProf({ ...prof, [k]: e.target.value }) });

  return (
    <main style={{ maxWidth: 1080, margin: "0 auto", padding: mobile ? "28px 20px 64px" : "40px 20px 80px" }}>
      <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 28, margin: "0 0 4px" }}>Job seeker home</h1>
      <p style={{ fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-secondary)", margin: "0 0 18px" }}>
        Your talent profile travels with every application. {me && me.full_name ? `Signed in as ${me.full_name}.` : ""}
      </p>
      {ok && <div style={{ marginBottom: 14 }}><Note tone="ok">{ok}</Note></div>}
      {msg && <div style={{ marginBottom: 14 }}><Note>{msg}</Note></div>}
      <div style={{ display: "grid", gridTemplateColumns: mobile ? "1fr" : "340px 1fr", gap: 24, alignItems: "start" }}>
        {/* Talent profile */}
        <Card accent padding={22}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-muted)", marginBottom: 12 }}>Talent profile</div>
          {prof === null ? <div style={{ fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-secondary)" }}>Loading…</div> : (
            <div style={{ display: "flex", flexDirection: "column", gap: 13 }}>
              <button onClick={() => { const n = { ...prof, available: !prof.available }; setProf(n); save(n); }} style={{
                width: "100%", display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
                border: "1px solid var(--color-line)", background: prof.available ? "var(--color-success-soft, #E7F3EC)" : "var(--bg-subtle, #F4F4F2)",
                color: prof.available ? "var(--color-success, #1F6E43)" : "var(--text-secondary)", borderRadius: "var(--radius-md)",
                padding: "10px", fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 700, cursor: "pointer" }}>
                <TIcon name={prof.available ? "circle-check" : "circle"} size={16} color="currentColor" />
                {prof.available ? "Available for hire" : "Not currently looking"}
              </button>
              <Input label="Headline" placeholder="Niagara N4 tech, 5 yrs — service & retrofits" {...P("headline")} />
              <label style={{ display: "block" }}>
                <div style={{ fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 700, marginBottom: 6 }}>Track</div>
                <Select options={["—"].concat(TRACKS)} value={prof.track || "—"} onChange={(e) => setProf({ ...prof, track: e.target.value === "—" ? "" : e.target.value })} />
              </label>
              <Input label="Location" placeholder="Denver, CO" {...P("location")} leftIcon={<TIcon name="map-pin" size={16} />} />
              <Button fullWidth disabled={busy} onClick={() => save()}>{busy ? "Saving…" : "Save profile"}</Button>
            </div>
          )}
        </Card>

        {/* Applications */}
        <div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, marginBottom: 12, flexWrap: "wrap" }}>
            <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 20, margin: 0 }}>My applications{rows ? ` · ${rows.length}` : ""}</h2>
            <Button size="sm" variant="secondary" onClick={() => go("board")} rightIcon={<TIcon name="arrow-right" size={15} />}>Browse open roles</Button>
          </div>
          {rows === null && <Card padding={22}><div style={{ color: "var(--text-secondary)", fontFamily: "var(--font-sans)", fontSize: 14 }}>Loading…</div></Card>}
          {rows && rows.length === 0 && (
            <Card padding={26}>
              <div style={{ textAlign: "center", color: "var(--text-secondary)", fontFamily: "var(--font-sans)", fontSize: 14 }}>
                You haven't applied to anything yet. <a href="#" onClick={(e) => { e.preventDefault(); go("board"); }} style={{ color: "var(--text-link)", fontWeight: 600 }}>Browse open roles</a>.
              </div>
            </Card>
          )}
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {(rows || []).map((a) => (
              <Card key={a.id} padding={18}>
                <div style={{ display: "flex", gap: 14, alignItems: "center", flexWrap: "wrap" }}>
                  <div style={{ flex: 1, minWidth: 200 }}>
                    <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16 }}>{a.job_title}</div>
                    <div style={{ fontFamily: "var(--font-sans)", fontSize: 13, color: "var(--text-secondary)" }}>{a.employer_name} · applied {fmtDate(a.created_at)}</div>
                  </div>
                  <Badge tone={tone[a.status] || "neutral"} variant="soft">{label[a.status] || a.status}</Badge>
                  <Button size="sm" variant="ghost" leftIcon={<TIcon name="message-circle" size={15} />}
                    onClick={() => setOpenMsg({ ...openMsg, [a.id]: !openMsg[a.id] })}>
                    {openMsg[a.id] ? "Hide messages" : "Messages"}
                  </Button>
                </div>
                {openMsg[a.id] && <MsgThread be={be} appId={a.id} />}
              </Card>
            ))}
          </div>
        </div>
      </div>
    </main>
  );
}

/* ================= Employer dashboard ================= */
function EmployerDash({ be, me, mobile, go }) {
  const [companies, setCompanies] = React.useState(null);
  const [posts, setPosts] = React.useState([]);
  const [apps, setApps] = React.useState([]);
  const [view, setView] = React.useState("dash");         // dash | register | post
  const [form, setForm] = React.useState({});
  const [msg, setMsg] = React.useState("");
  const [ok, setOk] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [openApps, setOpenApps] = React.useState({});     // job_id -> expanded
  const [openMsg, setOpenMsg] = React.useState({});       // application_id -> thread open
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });

  const load = React.useCallback(async () => {
    try {
      const [c, p, a] = await Promise.all([
        be.supabase.rpc("my_employers"),
        be.supabase.rpc("my_job_posts"),
        be.supabase.rpc("employer_applications", { p_job: null }),
      ]);
      setCompanies(c.data || []);
      setPosts(p.data || []);
      setApps(a.data || []);
      if ((c.data || []).length === 0) setView("register");
    } catch (e) { setCompanies([]); setMsg(errText(e)); }
  }, [be]);
  React.useEffect(() => { load(); }, [load]);

  const F = (k) => ({ value: form[k] || "", onChange: (e) => setForm({ ...form, [k]: e.target.value }) });

  async function registerCompany() {
    setBusy(true); setMsg("");
    try {
      const { data, error } = await be.supabase.rpc("register_employer", {
        p_name: form.name || "", p_contact_name: (me && me.full_name) || null,
        p_contact_email: (me && me.email) || null, p_phone: form.phone || null,
        p_location: form.location || null, p_website: form.website || null,
      });
      if (error) throw error;
      setOk(`${data.name} is registered. Now post your first job.`);
      setForm({}); await load(); setView("post");
    } catch (e) { setMsg(errText(e)); }
    setBusy(false);
  }

  async function submitJob() {
    setBusy(true); setMsg("");
    try {
      const empId = form.employer_id || (companies[0] && companies[0].id);
      if (!empId) throw new Error("Register your company first.");
      const { error } = await be.supabase.rpc("post_job", {
        p_employer: empId, p_title: form.title || "", p_track: form.track || null,
        p_location: form.job_location || null, p_description: form.description || null,
      });
      if (error) throw error;
      be.notifyStaff && be.notifyStaff("job_post", form.title || "");
      setOk("Job submitted. TTS staff review every post before it goes live — usually within one business day.");
      setForm({}); await load(); setView("dash");
    } catch (e) { setMsg(errText(e)); }
    setBusy(false);
  }

  async function setAppStatus(id, status) {
    try {
      const { error } = await be.supabase.rpc("set_application_status", { p_id: id, p_status: status });
      if (error) throw error;
      setApps(apps.map((a) => a.id === id ? { ...a, status } : a));
    } catch (e) { setMsg(errText(e)); }
  }

  if (companies === null) return (
    <main style={{ maxWidth: 980, margin: "0 auto", padding: "40px 20px" }}>
      <Card padding={24}><div style={{ color: "var(--text-secondary)", fontFamily: "var(--font-sans)", fontSize: 14 }}>Loading…</div></Card>
    </main>
  );

  const appsByJob = {};
  apps.forEach((a) => { (appsByJob[a.job_id] = appsByJob[a.job_id] || []).push(a); });
  const aTone = { new: "info", viewed: "neutral", contacted: "success", declined: "neutral" };

  return (
    <main style={{ maxWidth: 980, margin: "0 auto", padding: mobile ? "28px 20px 64px" : "40px 20px 80px" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, marginBottom: 6, flexWrap: "wrap" }}>
        <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 28, margin: 0 }}>Employer dashboard</h1>
        {companies.length > 0 && view === "dash" && (
          <div style={{ display: "flex", gap: 10 }}>
            <Button variant="secondary" size="sm" onClick={() => { setView("register"); setMsg(""); setOk(""); }}>Add company</Button>
            <Button size="sm" leftIcon={<TIcon name="plus" size={16} />} onClick={() => { setView("post"); setMsg(""); setOk(""); }}>Post a job</Button>
          </div>
        )}
      </div>
      <p style={{ fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-secondary)", margin: "0 0 18px" }}>
        Post roles to the BAS community — free while we grow the board. Posts go live after a quick staff review.
      </p>
      {ok && <div style={{ marginBottom: 14 }}><Note tone="ok">{ok}</Note></div>}
      {msg && <div style={{ marginBottom: 14 }}><Note>{msg}</Note></div>}

      {view === "register" && (
        <Card padding={26} style={{ maxWidth: 520 }}>
          <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 20, margin: "0 0 14px" }}>{companies.length ? "Add a company" : "Register your company"}</h2>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <Input label="Company name" placeholder="Meridian Controls" {...F("name")} leftIcon={<TIcon name="building-2" size={18} />} />
            <Input label="Location" placeholder="Denver, CO" {...F("location")} leftIcon={<TIcon name="map-pin" size={18} />} />
            <Input label="Website (optional)" placeholder="meridiancontrols.com" {...F("website")} leftIcon={<TIcon name="globe" size={18} />} />
            <Input label="Phone (optional)" placeholder="(303) 555-0100" {...F("phone")} leftIcon={<TIcon name="phone" size={18} />} />
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}>
              {companies.length > 0 && <Button variant="secondary" onClick={() => setView("dash")}>Cancel</Button>}
              <Button disabled={busy} onClick={registerCompany}>{busy ? "Saving…" : "Register company"}</Button>
            </div>
          </div>
        </Card>
      )}

      {view === "post" && (
        <Card padding={26} style={{ maxWidth: 560 }}>
          <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 20, margin: "0 0 14px" }}>Post a job</h2>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {companies.length > 1 && (
              <label style={{ display: "block" }}>
                <div style={{ fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 700, marginBottom: 6 }}>Company</div>
                <Select options={companies.map((c) => c.name)}
                  value={(companies.find((c) => c.id === form.employer_id) || companies[0]).name}
                  onChange={(e) => { const c = companies.find((x) => x.name === e.target.value); setForm({ ...form, employer_id: c && c.id }); }} />
              </label>
            )}
            <Input label="Job title" placeholder="BAS Service Technician" {...F("title")} leftIcon={<TIcon name="briefcase" size={18} />} />
            <label style={{ display: "block" }}>
              <div style={{ fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 700, marginBottom: 6 }}>Track (optional)</div>
              <Select options={["—"].concat(TRACKS)} value={form.track || "—"} onChange={(e) => setForm({ ...form, track: e.target.value === "—" ? "" : e.target.value })} />
            </label>
            <Input label="Location" placeholder="Denver, CO · on-site" {...F("job_location")} leftIcon={<TIcon name="map-pin" size={18} />} />
            <TextArea label="Description" rows={6} {...F("description")}
              placeholder="What the role does, required experience (platforms, certs), pay range if you can share it, and how to reach you." />
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}>
              <Button variant="secondary" onClick={() => setView("dash")}>Cancel</Button>
              <Button disabled={busy} onClick={submitJob}>{busy ? "Submitting…" : "Submit for review"}</Button>
            </div>
          </div>
        </Card>
      )}

      {view === "dash" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {posts.length === 0 && (
            <Card padding={28}>
              <div style={{ textAlign: "center", color: "var(--text-secondary)", fontFamily: "var(--font-sans)", fontSize: 14 }}>
                No jobs posted yet. <a href="#" onClick={(e) => { e.preventDefault(); setView("post"); }} style={{ color: "var(--text-link)", fontWeight: 600 }}>Post your first role</a>.
              </div>
            </Card>
          )}
          {posts.map((j) => (
            <Card key={j.id} padding={20}>
              <div style={{ display: "flex", gap: 14, alignItems: "flex-start", flexWrap: "wrap" }}>
                <div style={{ flex: 1, minWidth: 200 }}>
                  <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 17, margin: "0 0 3px" }}>{j.title}</h3>
                  <div style={{ fontFamily: "var(--font-sans)", fontSize: 13, color: "var(--text-secondary)" }}>
                    {j.employer_name}{j.location ? ` · ${j.location}` : ""} · posted {fmtDate(j.created_at)}
                  </div>
                </div>
                <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
                  {j.approved
                    ? (j.status === "open" ? <Badge tone="success" variant="soft" dot>Live</Badge> : <Badge tone="neutral" variant="outline">{j.status}</Badge>)
                    : <Badge tone="warning" variant="soft" dot>Awaiting review</Badge>}
                  <Badge tone="neutral" variant="outline">{j.applicants} applicant{j.applicants === 1 ? "" : "s"}</Badge>
                  {j.status === "open" && (
                    <Button size="sm" variant="secondary" onClick={async () => {
                      const { error } = await be.supabase.rpc("update_job", { p_id: j.id, p_title: j.title, p_track: j.track, p_location: j.location, p_description: j.description, p_status: "filled" });
                      if (!error) load(); else setMsg(errText(error));
                    }}>Mark filled</Button>
                  )}
                  {(appsByJob[j.id] || []).length > 0 && (
                    <Button size="sm" variant="ghost" onClick={() => setOpenApps({ ...openApps, [j.id]: !openApps[j.id] })}>
                      {openApps[j.id] ? "Hide applicants" : "View applicants"}
                    </Button>
                  )}
                </div>
              </div>
              {openApps[j.id] && (appsByJob[j.id] || []).map((a) => (
                <div key={a.id} style={{ marginTop: 12, padding: "12px 14px", background: "var(--bg-subtle, #FCFBF8)", border: "1px solid var(--color-line)", borderRadius: "var(--radius-md)" }}>
                  <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
                    <Avatar name={a.applicant_name || a.applicant_email} size={36} shape="circle" />
                    <div style={{ flex: 1, minWidth: 160 }}>
                      <div style={{ fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 14 }}>{a.applicant_name || a.applicant_email}</div>
                      <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-secondary)" }}>
                        <a href={`mailto:${a.applicant_email}`} style={{ color: "var(--text-link)" }}>{a.applicant_email}</a>
                        {a.track ? ` · ${a.track}` : ""}{a.location ? ` · ${a.location}` : ""} · {fmtDate(a.created_at)}
                      </div>
                    </div>
                    <Badge tone={aTone[a.status] || "neutral"} variant="soft">{a.status}</Badge>
                    <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                      <Button size="sm" variant="ghost" leftIcon={<TIcon name="message-circle" size={15} />}
                        onClick={() => setOpenMsg({ ...openMsg, [a.id]: !openMsg[a.id] })}>
                        {openMsg[a.id] ? "Hide" : "Message"}
                      </Button>
                      {a.status !== "contacted" && <Button size="sm" variant="secondary" onClick={() => setAppStatus(a.id, "contacted")}>Mark contacted</Button>}
                      {a.status !== "declined" && <Button size="sm" variant="ghost" onClick={() => setAppStatus(a.id, "declined")}>Decline</Button>}
                    </div>
                  </div>
                  {(a.headline || a.note) && (
                    <p style={{ fontFamily: "var(--font-sans)", fontSize: 13.5, color: "var(--text-secondary)", lineHeight: 1.5, margin: "8px 0 0", whiteSpace: "pre-wrap" }}>
                      {a.headline && <em>{a.headline}{a.note ? " — " : ""}</em>}{a.note}
                    </p>
                  )}
                  {openMsg[a.id] && <MsgThread be={be} appId={a.id} />}
                </div>
              ))}
            </Card>
          ))}
        </div>
      )}
    </main>
  );
}

Object.assign(window, { useTalentMobile, TIcon, JobBoard, SeekerHome, EmployerDash });
