// SIGNAL — Find a Job page

const { useState, useEffect, useMemo, useCallback, useRef } = React;

const NAV = [
  { label: "Expertise", href: "index.html#expertise", panel: "expertise" },
  { label: "Services",  href: "index.html#services",  panel: "services" },
  { label: "Resources", href: "index.html#resources", panel: "resources" },
  { label: "Find a Job", href: "jobs.html", panel: null, noUnderline: true, current: true },
  { label: "About",     href: "index.html#about",     panel: null, noUnderline: true },
];

// realistic-looking job dataset
const JOBS = [
  { id: "FT-0481", title: "Staff Software Engineer, Platform", company: "Series C Health-Tech", loc: "Seattle, WA",   remote: "Hybrid",   type: "Direct Hire", area: "Tech & Engineering", level: "Staff",      sal: [220, 280], stage: "Series C",  posted: "2d", featured: true, isNew: true,
    desc: "Lead platform infrastructure for a profitable health-tech scale-up moving 30M patient interactions per month. Own service mesh, internal developer platform, and Kubernetes migration.",
    must: ["7+ yrs distributed systems", "Go or Rust", "Kubernetes at scale", "Strong written communication"], nice: ["Healthcare data experience", "Prior platform-team leadership"] },
  { id: "FT-0479", title: "Senior Product Designer, Growth",   company: "Stealth AI Startup",       loc: "Remote",      remote: "Remote",   type: "Direct Hire", area: "Design & UX Research", level: "Senior",   sal: [180, 230], stage: "Series A",  posted: "3d", featured: false, isNew: true,
    desc: "Shape the product surface for an AI-native productivity tool used by 50k+ developers. Own onboarding, conversion, and core workflow.",
    must: ["6+ yrs product design", "Strong portfolio of shipped work", "Comfort with ambiguity"], nice: ["AI/ML tooling background", "Motion design"] },
  { id: "FT-0476", title: "Senior Product Designer",            company: "AI Health Startup",        loc: "Remote (US)", remote: "Remote",   type: "Direct Hire", area: "Design & UX Research", level: "Senior",   sal: [170, 215], stage: "Series B",  posted: "3d", featured: false, isNew: true,
    desc: "Design the patient experience for a connected-health platform. Work with clinicians, PMs, and a small in-house design team to ship across iOS, Android, and web.",
    must: ["5+ yrs product design", "End-to-end mobile shipped", "Research literate"], nice: ["Healthcare", "Accessibility expertise"] },
  { id: "FT-0470", title: "Director of Product, Growth",        company: "Consumer Marketplace",     loc: "Bellevue, WA", remote: "Onsite",   type: "Direct Hire", area: "Product",              level: "Director", sal: [240, 310], stage: "Series C+", posted: "5d", featured: true,  isNew: false,
    desc: "Own the growth surface for a profitable consumer marketplace doing $400M GMV. Lead a team of 6 PMs across acquisition, activation, and retention.",
    must: ["10+ yrs product, 3+ leading PMs", "Marketplace or consumer experience", "Quant-fluent"], nice: ["Two-sided marketplaces", "International growth"] },
  { id: "FT-0468", title: "Principal Machine Learning Engineer", company: "Series B DevTools",      loc: "Remote",      remote: "Remote",   type: "Direct Hire", area: "Tech & Engineering",  level: "Principal", sal: [280, 360], stage: "Series B",  posted: "6d", featured: false, isNew: false,
    desc: "Own model architecture and training pipeline for a code-generation product shipping to 200k+ developers. Direct path to founding-engineer scope.",
    must: ["Strong CS fundamentals", "Production ML systems at scale", "PyTorch or JAX"], nice: ["LLM training experience", "Open-source contributions"] },
  { id: "FT-0463", title: "Head of Recruiting",                 company: "Climate Tech Scale-up",     loc: "Seattle, WA", remote: "Onsite",  type: "Direct Hire", area: "HR & Operations",     level: "Director", sal: [195, 245], stage: "Series B",  posted: "1w", featured: false, isNew: false,
    desc: "Build the recruiting org for a Series B climate-tech company scaling from 80 → 220 in 18 months. Own talent strategy, brand, and hiring systems.",
    must: ["5+ yrs in-house recruiting leadership", "Built recruiting teams from scratch", "Strong systems thinking"], nice: ["Climate or hardware industry", "DEI program design"] },
  { id: "FT-0461", title: "Chief Financial Officer",             company: "Vertical SaaS · Stealth",  loc: "Bellevue, WA", remote: "Hybrid", type: "Direct Hire", area: "Finance & Accounting", level: "C-Suite", sal: [320, 420], stage: "Series C",  posted: "1w", featured: false, isNew: false,
    desc: "First CFO for a $40M ARR vertical SaaS preparing for a 2027 growth round. Own FP&A, treasury, investor relations.",
    must: ["10+ yrs senior finance, 3+ as CFO", "SaaS finance fluency", "Audit-ready"], nice: ["IPO preparation", "Vertical SaaS experience"] },
  { id: "FT-0457", title: "Chief of Staff to CEO",               company: "Series C AI",              loc: "Seattle, WA", remote: "Onsite",   type: "Direct Hire", area: "Admin & Lifestyle",   level: "Senior",   sal: [180, 235], stage: "Series C",  posted: "2w", featured: false, isNew: false,
    desc: "Right-hand to a technical founder leading a 220-person AI company. Own operating cadence, board prep, and special projects.",
    must: ["MBA or equivalent operational experience", "Top-tier writing", "Boardroom-ready"], nice: ["Ex-consulting", "Founder-adjacent experience"] },
  { id: "FT-0455", title: "VP of Engineering",                   company: "FinTech · Series B",       loc: "Seattle, WA", remote: "Hybrid",  type: "Direct Hire", area: "C-Suite",             level: "VP",       sal: [280, 380], stage: "Series B",  posted: "2w", featured: true,  isNew: false,
    desc: "Lead a 60-person engineering org through 3× headcount growth. Own architecture, hiring, and engineering culture at a regulated FinTech.",
    must: ["10+ yrs eng leadership", "Built teams from 20 → 100+", "Regulated industry experience"], nice: ["FinTech or banking", "Public-cloud cost optimization"] },
  { id: "FT-0449", title: "Lead Brand Designer",                 company: "DTC Consumer Brand",       loc: "Seattle, WA", remote: "Hybrid",  type: "Contract",    area: "Design & UX Research", level: "Senior",   sal: [140, 180], stage: "Series A",  posted: "2w", featured: false, isNew: false,
    desc: "Refresh the brand system, packaging, and digital expression for a consumer brand entering its second growth phase. 6-month contract with intent to convert.",
    must: ["7+ yrs brand design", "Built brand systems end-to-end", "Print + packaging fluency"], nice: ["Sustainability or wellness brands"] },
  { id: "FT-0447", title: "Senior Product Manager, AI",          company: "Enterprise SaaS",          loc: "Remote (US)", remote: "Remote",  type: "Direct Hire", area: "Product",              level: "Senior",   sal: [200, 260], stage: "Series C+", posted: "3w", featured: false, isNew: false,
    desc: "Define and ship AI features inside a mature enterprise product used by 100k+ business users. Partner with ML and design.",
    must: ["7+ yrs PM, shipped AI features", "Comfortable with enterprise sales motion", "Strong written communication"], nice: ["MLOps awareness", "Prior B2B SaaS"] },
  { id: "FT-0445", title: "Executive Assistant to CTO",          company: "Series D SaaS",            loc: "Bellevue, WA", remote: "Hybrid", type: "Direct Hire", area: "Admin & Lifestyle",   level: "Mid",      sal: [110, 145], stage: "Series C+", posted: "3w", featured: false, isNew: false,
    desc: "Support a CTO of a 600-person SaaS company. Calendar, communications, special projects. High-trust, high-confidentiality role.",
    must: ["5+ yrs supporting C-level execs", "Calendar tetris champion", "Discreet"], nice: ["Tech-industry exposure", "Project-management fluency"] },
];

const AREAS = ["Tech & Engineering", "Design & UX Research", "Product", "Marketing", "C-Suite", "HR & Operations", "Finance & Accounting", "Admin & Lifestyle"];
const STAGES = ["Seed", "Series A", "Series B", "Series C", "Series C+", "Private Office"];
const REMOTE = ["Onsite", "Hybrid", "Remote"];
const TYPES = ["Direct Hire", "Contract", "Contract-to-hire"];

function useToggleSet(initial = []) {
  const [set, setSet] = useState(new Set(initial));
  const toggle = useCallback((v) => {
    setSet((s) => { const n = new Set(s); n.has(v) ? n.delete(v) : n.add(v); return n; });
  }, []);
  return [set, toggle, setSet];
}

function TopNav() {
  const [open, setOpen] = useState(null);
  const closeT = useRef(null);
  const enter = (key) => { clearTimeout(closeT.current); setOpen(key); };
  const leave = () => { closeT.current = setTimeout(() => setOpen(null), 120); };

  return (
    <header className="topnav" onMouseLeave={leave}>
      <div className="container nav-inner">
        <a className="logo" href="index.html" aria-label="Fuel Talent">
          <img src="logo.png" alt="Fuel Talent" className="logo-img" />
        </a>
        <nav className="nav-links">
          {NAV.map((n) => (
            <a key={n.label} href={n.href}
               className={`nav-link ${open && open === n.panel ? "is-open" : ""} ${n.noUnderline ? "no-underline" : ""} ${n.current ? "current" : ""}`}
               onMouseEnter={() => enter(n.panel)}>
              {n.label}
            </a>
          ))}
        </nav>
        <a className="nav-pill" href="#upload">Upload Resume <span>→</span></a>
      </div>
      <MegaMenu open={open} onMouseEnter={() => clearTimeout(closeT.current)} onMouseLeave={leave} />
    </header>
  );
}

function MegaMenu({ open, onMouseEnter, onMouseLeave }) {
  const panels = {
    expertise: {
      eyebrow: "Expertise · 8 practices",
      cols: [
        { head: "Build", items: ["Tech & Engineering", "Product", "Design & UX Research"] },
        { head: "Operate", items: ["HR & Operations", "Finance & Accounting", "Admin & Lifestyle"] },
        { head: "Lead", items: ["C-Suite", "Marketing"] },
        { head: "Featured", items: ["Browse all expertise →", "Submit a role"] },
      ],
    },
    services: {
      eyebrow: "Services · 3 modes",
      cols: [
        { head: "01 — Recruiting & Staffing", items: ["Permanent placement", "Contract & contingent", "Embedded recruiting"] },
        { head: "02 — Professional & Managed", items: ["Specialist teams", "Operational coverage", "Project execution"] },
        { head: "03 — Digital Workers",     items: ["AI agent design", "Workflow automation", "Human + agent hybrids"] },
        { head: "Not sure?", items: ["Talk to a strategist →"] },
      ],
    },
    resources: {
      eyebrow: "Fuel for Thought",
      cols: [
        { head: "Field Notes", items: ["Hiring playbooks", "Career guides", "Salary trends 2026"] },
        { head: "Case Studies", items: ["Provider case · Providence", "Scale-up case · Pacagen"] },
        { head: "Podcast", items: ["Make Them Lose Sleep", "Browse all episodes →"] },
        { head: "Subscribe", items: ["Monthly newsletter"] },
      ],
    },
  };
  const p = open && panels[open];
  return (
    <div className="megamenu" style={{
      maxHeight: p ? 320 : 0,
      opacity: p ? 1 : 0,
      pointerEvents: p ? "auto" : "none",
    }} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}>
      {p && (
        <div className="container" style={{ padding: "32px var(--pad)", display: "grid", gridTemplateColumns: "180px repeat(4, 1fr)", gap: 36 }}>
          <div className="mono" style={{ color: "var(--muted)" }}>{p.eyebrow}</div>
          {p.cols.map((c) => (
            <div key={c.head}>
              <div className="mono" style={{ color: "var(--muted)", marginBottom: 12 }}>{c.head}</div>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 8 }}>
                {c.items.map((it) => (
                  <li key={it}><a href="#" style={{ borderBottom: "1px solid transparent", paddingBottom: 1 }}
                    onMouseEnter={(e) => e.target.style.borderBottomColor = "currentColor"}
                    onMouseLeave={(e) => e.target.style.borderBottomColor = "transparent"}>
                    {it}
                  </a></li>
                ))}
              </ul>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function FilterGroup({ title, options, selected, toggle, withCounts }) {
  return (
    <div className="filter-group">
      <h4>{title}</h4>
      {options.map((o) => {
        const on = selected.has(o);
        const count = withCounts ? JOBS.filter((j) => j.area === o || j.remote === o || j.stage === o || j.type === o || j.level === o).length : null;
        return (
          <div key={o} className={`filter-opt ${on ? "on" : ""}`} onClick={() => toggle(o)}>
            <span className="check"></span>
            <span>{o}</span>
            {count !== null && <span className="count">{count}</span>}
          </div>
        );
      })}
    </div>
  );
}

function App() {
  const [q, setQ] = useState("");
  const [loc, setLoc] = useState("");
  const [stage, setStage] = useState("any");
  const [areaSet, areaToggle] = useToggleSet();
  const [remoteSet, remoteToggle] = useToggleSet();
  const [typeSet, typeToggle] = useToggleSet();
  const [sort, setSort] = useState("recent");
  const [active, setActive] = useState(null);
  const [page, setPage] = useState(1);
  const perPage = 8;

  const filtered = useMemo(() => {
    const ql = q.toLowerCase(), ll = loc.toLowerCase();
    let out = JOBS.filter((j) =>
      (!ql || j.title.toLowerCase().includes(ql) || j.company.toLowerCase().includes(ql) || j.area.toLowerCase().includes(ql)) &&
      (!ll || j.loc.toLowerCase().includes(ll)) &&
      (stage === "any" || j.stage === stage) &&
      (areaSet.size === 0 || areaSet.has(j.area)) &&
      (remoteSet.size === 0 || remoteSet.has(j.remote)) &&
      (typeSet.size === 0 || typeSet.has(j.type))
    );
    if (sort === "salary") out = out.sort((a, b) => b.sal[1] - a.sal[1]);
    else if (sort === "recent") out = out.sort((a, b) => parseInt(a.id.slice(3)) < parseInt(b.id.slice(3)) ? 1 : -1);
    return out;
  }, [q, loc, stage, areaSet, remoteSet, typeSet, sort]);

  const pageCount = Math.max(1, Math.ceil(filtered.length / perPage));
  const visible = filtered.slice((page - 1) * perPage, page * perPage);

  useEffect(() => { setPage(1); }, [q, loc, stage, areaSet, remoteSet, typeSet]);
  useEffect(() => {
    if (!active) return;
    const onKey = (e) => { if (e.key === "Escape") setActive(null); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [active]);

  return (
    <>
      <TopNav />
      <section className="pageheader">
        <div className="container">
          <div className="breadcrumb">
            <a href="index.html">Home</a>
            <span className="sep">/</span>
            <span className="now">Find a Job</span>
            <span className="sep">·</span>
            <span className="mono">§ JOB BOARD · LIVE</span>
          </div>
          <h1 className="pagetitle">Where careers <em>get fueled.</em></h1>
          <div className="header-meta">
            <p className="lead">
              We work with venture-backed startups, scale-ups, and innovation-led enterprises across Seattle and beyond. Every role here has been calibrated with the hiring manager — no recycled boards, no surprises.
            </p>
            <div className="stats">
              <div className="stat"><div className="n"><em>{JOBS.length}</em></div><div className="l">live roles</div></div>
              <div className="stat"><div className="n">18<span style={{ fontSize: 22, color: "var(--muted)", fontFamily: "var(--font-mono)", letterSpacing: 0 }}>d</span></div><div className="l">avg time-to-offer</div></div>
              <div className="stat"><div className="n">91<span style={{ fontSize: 22, color: "var(--muted)", fontFamily: "var(--font-mono)", letterSpacing: 0 }}>%</span></div><div className="l">accept rate</div></div>
            </div>
          </div>
        </div>
      </section>

      <section className="searchpanel">
        <div className="container">
          <div className="searchgrid">
            <label className="searchfield">
              <span>Title, company, practice</span>
              <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="e.g. Staff Engineer, Pacagen, Designer..." />
            </label>
            <label className="searchfield">
              <span>Location</span>
              <input value={loc} onChange={(e) => setLoc(e.target.value)} placeholder="Seattle, Bellevue, Remote..." />
            </label>
            <label className="searchfield">
              <span>Company stage</span>
              <select value={stage} onChange={(e) => setStage(e.target.value)}>
                <option value="any">Any stage</option>
                {STAGES.map((s) => <option key={s} value={s}>{s}</option>)}
              </select>
            </label>
            <button className="searchgo">Search →</button>
          </div>
        </div>
      </section>

      <section>
        <div className="container">
          <div className="results-layout">
            <aside className="filters">
              <FilterGroup title="Practice"     options={AREAS}  selected={areaSet}   toggle={areaToggle}   withCounts />
              <FilterGroup title="Work setting" options={REMOTE} selected={remoteSet} toggle={remoteToggle} withCounts />
              <FilterGroup title="Job type"     options={TYPES}  selected={typeSet}   toggle={typeToggle}   withCounts />
              <div className="filter-group">
                <h4>Want a custom match?</h4>
                <a className="btn" href="#upload" style={{ marginTop: 4 }}>Upload resume<span>→</span></a>
              </div>
            </aside>

            <div>
              <div className="results-header">
                <div className="count">
                  <em>{filtered.length}</em> {filtered.length === 1 ? "role" : "roles"} matched
                </div>
                <div className="sort">
                  <span className="lbl">Sort</span>
                  <button onClick={() => setSort("recent")}  className={`sort-btn ${sort === "recent"  ? "on" : ""}`}>Most recent</button>
                  <button onClick={() => setSort("salary")}  className={`sort-btn ${sort === "salary"  ? "on" : ""}`}>Compensation</button>
                </div>
              </div>

              <div className="job-list">
                {visible.length === 0 && (
                  <div style={{ padding: 64, textAlign: "center", color: "var(--muted)", fontFamily: "var(--font-mono)" }}>
                    No roles matched. Try clearing some filters — or <a href="#upload" style={{ color: "var(--accent)", textDecoration: "underline" }}>upload your resume</a> and we'll reach out as new roles open.
                  </div>
                )}
                {visible.map((j) => (
                  <div key={j.id} className="job-card" onClick={() => setActive(j)}>
                    <div className="id">{j.id}</div>
                    <div className="body">
                      <div className="tagrow">
                        {j.featured && <span className="tag featured">Featured</span>}
                        {j.isNew && <span className="tag new">New this week</span>}
                        <span className="tag">{j.area}</span>
                        <span className={`tag ${j.remote === "Remote" ? "remote" : ""}`}>{j.remote}</span>
                        <span className="tag">{j.stage}</span>
                      </div>
                      <h3>{j.title}</h3>
                      <div className="meta">
                        <span><b>Company</b> · {j.company}</span>
                        <span><b>Location</b> · {j.loc}</span>
                        <span><b>Level</b> · {j.level}</span>
                        <span><b>Posted</b> · {j.posted} ago</span>
                      </div>
                      <p className="desc">{j.desc}</p>
                    </div>
                    <div className="right">
                      <div className="salary">${j.sal[0]}–{j.sal[1]}<span>K</span></div>
                      <span className="arr">View role →</span>
                    </div>
                  </div>
                ))}
              </div>

              {filtered.length > perPage && (
                <div className="pagination">
                  <span className="mono">Showing {(page - 1) * perPage + 1}–{Math.min(page * perPage, filtered.length)} of {filtered.length}</span>
                  <div className="pages">
                    <button onClick={() => setPage(Math.max(1, page - 1))}>‹</button>
                    {Array.from({ length: pageCount }).map((_, i) => (
                      <button key={i} onClick={() => setPage(i + 1)} className={page === i + 1 ? "on" : ""}>{i + 1}</button>
                    ))}
                    <button onClick={() => setPage(Math.min(pageCount, page + 1))}>›</button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </section>

      <footer>
        <div className="container footrow">
          <span>© 2026 FUEL TALENT, LLC · ALL RIGHTS RESERVED</span>
          <span>500 108TH AVE NE, BELLEVUE WA · <a href="mailto:info@fueltalent.com">INFO@FUELTALENT.COM</a></span>
          <span><a href="index.html">BACK TO HOMEPAGE →</a></span>
        </div>
      </footer>

      {/* job detail panel */}
      <div className={`detail-backdrop ${active ? "open" : ""}`} onClick={() => setActive(null)} />
      <aside className={`detail ${active ? "open" : ""}`}>
        {active && (
          <>
            <div className="detail-head">
              <div>
                <div className="detail-id">{active.id} · {active.posted} ago</div>
                <h1>{active.title} <em>·</em></h1>
                <div className="mono" style={{ marginTop: 8, color: "var(--ink-2)", textTransform: "none", letterSpacing: "0.02em", fontSize: 13 }}>
                  {active.company} · {active.loc} · {active.remote}
                </div>
              </div>
              <button className="detail-close" onClick={() => setActive(null)}>✕</button>
            </div>
            <div className="detail-body">
              <div className="keys">
                <div><div className="l">Compensation</div><div className="v">${active.sal[0]}–{active.sal[1]}K base</div></div>
                <div><div className="l">Level</div><div className="v">{active.level}</div></div>
                <div><div className="l">Stage</div><div className="v">{active.stage}</div></div>
                <div><div className="l">Practice</div><div className="v">{active.area}</div></div>
              </div>

              <h3>About the role</h3>
              <p>{active.desc}</p>

              <h3>Must-haves</h3>
              <ul>
                {active.must.map((m) => <li key={m}>{m}</li>)}
              </ul>

              <h3>Nice-to-haves</h3>
              <ul>
                {active.nice.map((m) => <li key={m}>{m}</li>)}
              </ul>

              <h3>How we work this search</h3>
              <p>
                We've calibrated this role directly with the hiring manager — so when you apply, your materials go to a real human consultant who can answer questions, share context the JD doesn't capture, and make introductions if it isn't quite the right fit but something else might be.
              </p>

              <div className="btn-row">
                <a className="btn btn-accent" href="#">Apply for this role <span>→</span></a>
                <a className="btn" href="#">Share with a friend</a>
              </div>

              <div style={{ marginTop: 28, padding: 18, border: "1px solid var(--line)", background: "var(--paper)", fontSize: 13, color: "var(--ink-2)" }}>
                <span className="mono" style={{ color: "var(--accent)" }}>FAIR-PAY COMMITMENT</span><br/>
                <span style={{ marginTop: 6, display: "block" }}>Salary ranges are real — written into the role, not a recruiter-fluffed estimate. WA law requires it and we'd do it anyway.</span>
              </div>
            </div>
          </>
        )}
      </aside>
    </>
  );
}

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