/* global React, ReactDOM, window */
// ════════════════════════════════════════════════════════════════
// Company pages (About, Careers) + the ?p=slug router/bootstrap.
// ════════════════════════════════════════════════════════════════
const { useState, useEffect, useRef } = React;
const { Check, TurnstileBox, ContactModal, SiteNav, SiteFooter, HOME } = window.SostratusChrome;
const { FeaturePage, CTABand, FEATURES } = window.SostratusPages;
const { Wordmark } = window;

function PageHero({ section, title, sub }) {
  return (
    <header className="grid-bg" style={{ position: "relative", overflow: "hidden", borderBottom: "1px solid var(--divider-2)" }}>
      <div className="noise-glow" style={{ position: "absolute", inset: 0, height: 560, pointerEvents: "none" }} />
      <div className="wrap" style={{ position: "relative", paddingTop: 64, paddingBottom: 60 }}>
        <div className="mono" style={{ fontSize: 12, color: "var(--tx-3)", marginBottom: 22 }}>
          <a href={HOME} style={{ color: "var(--accent)", textDecoration: "none" }}>Home</a> <span style={{ color: "var(--tx-4)" }}>/</span> Company <span style={{ color: "var(--tx-4)" }}>/</span> <span style={{ color: "var(--tx-2)" }}>{section}</span>
        </div>
        <div className="kicker" style={{ marginBottom: 16 }}>Company · {section}</div>
        <h1 className="disp" style={{ fontSize: 64, maxWidth: "15em" }}>{title}</h1>
        <p className="sub" style={{ marginTop: 22, maxWidth: "40em", fontSize: 20 }}>{sub}</p>
      </div>
    </header>
  );
}

// ───────── About ─────────
const BELIEFS = [
  { t: "One source of truth", b: "Discovery, inventory, topology, monitoring, and response should read from one model of the network, not five disconnected tools." },
  { t: "Multi-tenant from day one", b: "Isolation between tenants is not a feature you bolt on later. It is the shape of the product." },
  { t: "The network describes itself", b: "Devices already announce what they are. Software should listen, not ask an operator to maintain a spreadsheet." },
  { t: "Operators first", b: "We build for the people on call at 3am, which means density, speed, and keyboard-first workflows over decoration." },
];
const STORY = [
  "Sostratus started from a simple frustration: running a network means stitching together a discovery tool, an IPAM, a DCIM, a monitoring stack, and a pile of scripts, none of which agree with each other.",
  "We think the whole thing should be one platform with one model of the network, scoped cleanly per tenant, so a single operator or a managed-service provider running a hundred customers works the same way.",
  "Today the core is real: create a tenant (including MSP structures), deploy a NIMS agent, discover the network, and see it as a live map. Everything else on the platform builds out from that foundation.",
];

function AboutPage({ onContact }) {
  useEffect(() => { document.title = "Sostratus · About"; }, []);
  return (
    <div>
      <SiteNav onContact={onContact} />
      <PageHero section="About" title="We're building the control plane for network infrastructure." sub="One platform to discover, map, and run every network, scoped cleanly for one team or an entire managed-services fleet." />

      <section className="feat" style={{ background: "var(--bg)" }}>
        <div className="wrap" style={{ display: "grid", gridTemplateColumns: "0.8fr 1.2fr", gap: 48 }}>
          <div><div className="kicker" style={{ marginBottom: 10 }}>Our mission</div><h2 className="sec">Make running a network feel like one product, not ten.</h2></div>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            {STORY.map((p, i) => <p key={i} className="sub" style={{ fontSize: 18, color: i === 0 ? "var(--tx)" : "var(--tx-2)" }}>{p}</p>)}
          </div>
        </div>
      </section>

      <section className="feat" style={{ background: "var(--bg-deep)" }}>
        <div className="wrap">
          <div className="kicker" style={{ marginBottom: 10 }}>What we believe</div>
          <h2 className="sec">Four principles.</h2>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20, marginTop: 40 }}>
            {BELIEFS.map((c) => (
              <div key={c.t} style={{ padding: "24px 24px", background: "var(--card)", border: "1px solid var(--divider)", borderRadius: 14 }}>
                <div style={{ fontSize: 19, fontWeight: 600, color: "#fff", marginBottom: 8 }}>{c.t}</div>
                <div style={{ fontSize: 14.5, color: "var(--tx-2)", lineHeight: 1.55 }}>{c.b}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <CTABand onContact={onContact} />
      <SiteFooter onContact={onContact} />
    </div>
  );
}

// ───────── Careers ─────────
const VALUES = [
  { t: "Small team, large surface", b: "Everyone owns meaningful pieces of the product end to end. Title doesn't gate scope." },
  { t: "Operators in the loop", b: "We build with real network operators, so what we ship survives contact with a 3am page." },
  { t: "Ship and learn", b: "Tight loops over big-bang releases. The alpha is real software that real teams use." },
  { t: "Remote and async", b: "Distributed by default, with deep-work time protected and meetings kept rare." },
];
const APPLY_ACCEPT = ".pdf,.doc,.docx,.rtf,.txt";

const toB64 = (file) => new Promise((resolve, reject) => {
  const r = new FileReader();
  r.onload = () => resolve({ name: file.name, type: file.type || "application/octet-stream", b64: String(r.result).split(",")[1] });
  r.onerror = reject;
  r.readAsDataURL(file);
});

function UploadIcon() {
  return <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M12 16V5m0 0l-4 4m4-4l4 4M5 19h14" /></svg>;
}

function FileDrop({ label, optional, file, onFile }) {
  const ref = useRef(null);
  const [drag, setDrag] = useState(false);
  const pick = (f) => { if (f) onFile(f); };
  return (
    <div>
      <span className="mono" style={{ display: "block", fontSize: 10.5, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--tx-3)", marginBottom: 8 }}>{label}{optional ? " · optional" : ""}</span>
      <div role="button" tabIndex={0} onClick={() => ref.current && ref.current.click()}
        onDragOver={(e) => { e.preventDefault(); setDrag(true); }}
        onDragLeave={() => setDrag(false)}
        onDrop={(e) => { e.preventDefault(); setDrag(false); pick(e.dataTransfer.files[0]); }}
        style={{ display: "flex", alignItems: "center", gap: 13, padding: "15px 16px", borderRadius: 10, border: `1.5px dashed ${drag ? "var(--primary)" : file ? "rgba(52,211,153,0.5)" : "var(--hair)"}`, background: drag ? "rgba(145,128,212,0.08)" : "rgba(242,242,244,0.02)", cursor: "pointer", transition: "all .15s" }}>
        <span style={{ width: 38, height: 38, borderRadius: 9, flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center", background: file ? "rgba(52,211,153,0.14)" : "rgba(145,128,212,0.14)", color: file ? "#34d399" : "var(--primary)" }}>
          {file ? <Check /> : <UploadIcon />}
        </span>
        {file ? (
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ fontSize: 14, color: "var(--tx)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{file.name}</div>
            <div className="mono" style={{ fontSize: 11, color: "var(--tx-3)", marginTop: 2 }}>{(file.size / 1024).toFixed(0)} KB · click to replace</div>
          </div>
        ) : (
          <div>
            <div style={{ fontSize: 14, color: "var(--tx-2)" }}>Drag and drop, or <span style={{ color: "#bdb0f6", fontWeight: 600 }}>browse</span></div>
            <div className="mono" style={{ fontSize: 11, color: "var(--tx-4)", marginTop: 2 }}>PDF, DOC, or DOCX up to 3 MB</div>
          </div>
        )}
      </div>
      <input ref={ref} type="file" accept={APPLY_ACCEPT} style={{ display: "none" }} onChange={(e) => pick(e.target.files[0])} />
    </div>
  );
}

function CareersApply() {
  const [resume, setResume] = useState(null);
  const [cover, setCover] = useState(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const [sent, setSent] = useState(false);
  const [tsToken, setTsToken] = useState("");
  const submit = async (e) => {
    e.preventDefault();
    if (!resume) { setError("resume"); return; }
    const MAX = 3 * 1024 * 1024;
    if (resume.size > MAX || (cover && cover.size > MAX)) { setError("size"); return; }
    const fd = new FormData(e.currentTarget);
    setBusy(true); setError("");
    try {
      const payload = { name: fd.get("name"), email: fd.get("email"), interest: fd.get("interest"), resume: await toB64(resume) };
      if (cover) payload.cover = await toB64(cover);
      payload.turnstile_token = tsToken;
      const r = await fetch("/api/apply", {
        method: "POST", headers: { "content-type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!r.ok) { let m = ""; try { m = (await r.json()).error || ""; } catch (e2) {} throw new Error(m); }
      setSent(true);
    } catch (err) { setError(err && err.message ? err.message : "send"); } finally { setBusy(false); }
  };
  if (sent) return (
    <div style={{ padding: "36px 28px 40px", background: "var(--card)", border: "1px solid var(--divider)", borderRadius: 16, textAlign: "center" }}>
      <div style={{ width: 56, height: 56, borderRadius: 99, margin: "0 auto 18px", background: "rgba(52,211,153,0.14)", border: "1px solid rgba(52,211,153,0.4)", display: "flex", alignItems: "center", justifyContent: "center" }}>
        <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#34d399" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12.5l5 5L20 6.5" /></svg>
      </div>
      <div style={{ fontSize: 22, fontWeight: 600, color: "#fff" }}>Application received.</div>
      <p className="sub" style={{ fontSize: 15.5, margin: "10px auto 0", maxWidth: "28em" }}>Thanks for reaching out. We read every application and will be in touch if there's a fit.</p>
    </div>
  );
  return (
    <form onSubmit={submit} style={{ padding: "24px 24px 26px", background: "var(--card)", border: "1px solid var(--divider)", borderRadius: 16 }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <label style={{ display: "block" }}><span className="mono" style={{ display: "block", fontSize: 10.5, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--tx-3)", marginBottom: 7 }}>Full name</span><input className="cf-input" name="name" placeholder="Jordan Okafor" required /></label>
        <label style={{ display: "block" }}><span className="mono" style={{ display: "block", fontSize: 10.5, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--tx-3)", marginBottom: 7 }}>Email</span><input className="cf-input" name="email" type="email" placeholder="jordan@email.com" required /></label>
      </div>
      <label style={{ display: "block", marginTop: 16 }}><span className="mono" style={{ display: "block", fontSize: 10.5, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--tx-3)", marginBottom: 7 }}>What would you want to own?</span><input className="cf-input" name="interest" placeholder="e.g. discovery engine, frontend, design, field / MSP" /></label>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 18 }}>
        <FileDrop label="Resume / CV" file={resume} onFile={setResume} />
        <FileDrop label="Cover letter" optional file={cover} onFile={setCover} />
      </div>
      {error === "resume" && <p style={{ fontSize: 13, color: "#f0a060", margin: "14px 0 0" }}>Please attach your resume before sending.</p>}
      {error === "size" && <p style={{ fontSize: 13, color: "#f0a060", margin: "14px 0 0" }}>Each file must be 3 MB or smaller.</p>}
      {error && error !== "resume" && error !== "size" && <p style={{ fontSize: 13, color: "#f06080", margin: "14px 0 0" }}>{error === "send" ? "Something went wrong. Please try again, or email your application to careers@sostr.io." : error}</p>}
      <div style={{ marginTop: 18 }}><TurnstileBox onToken={setTsToken} /></div>
      <button type="submit" disabled={busy} className="btn btn-primary" style={{ width: "100%", justifyContent: "center", cursor: busy ? "default" : "pointer", marginTop: 8, opacity: busy ? 0.7 : 1 }}>{busy ? "Sending…" : "Send application →"}</button>
      <p className="mono" style={{ fontSize: 11, color: "var(--tx-4)", textAlign: "center", margin: "14px 0 0" }}>Prefer email? Send your resume and cover letter to careers@sostr.io</p>
    </form>
  );
}
const PERKS = ["Meaningful early equity", "Top-tier hardware and tools", "Health, dental, and vision", "Generous, tracked PTO with minimums", "Home-office and learning budget", "Yearly team gatherings"];

function CareersPage({ onContact }) {
  useEffect(() => { document.title = "Sostratus · Careers"; }, []);
  return (
    <div>
      <SiteNav onContact={onContact} />
      <PageHero section="Careers" title="Build the platform network teams wish they had." sub="We're a small, focused team turning a pile of disconnected network tools into one coherent control plane. Come help us." />

      <section className="feat" style={{ background: "var(--bg)" }}>
        <div className="wrap">
          <div className="kicker" style={{ marginBottom: 10 }}>How we work</div>
          <h2 className="sec">The way we operate.</h2>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20, marginTop: 40 }}>
            {VALUES.map((c) => (
              <div key={c.t} style={{ padding: "24px 24px", background: "var(--card)", border: "1px solid var(--divider)", borderRadius: 14 }}>
                <div style={{ fontSize: 19, fontWeight: 600, color: "#fff", marginBottom: 8 }}>{c.t}</div>
                <div style={{ fontSize: 14.5, color: "var(--tx-2)", lineHeight: 1.55 }}>{c.b}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="feat" style={{ background: "var(--bg-deep)" }}>
        <div className="wrap">
          <div className="kicker" style={{ marginBottom: 10 }}>Apply</div>
          <h2 className="sec">Introduce yourself.</h2>
          <p className="sub" style={{ marginTop: 16, maxWidth: "42em" }}>We don't keep a long list of open reqs. If building the control plane for network infrastructure sounds like your kind of problem, send your resume and a short cover letter telling us what you'd want to own. We read every one.</p>
          <div style={{ marginTop: 36, maxWidth: 680 }}>
            <CareersApply />
          </div>
        </div>
      </section>

      <section className="feat" style={{ background: "var(--bg)" }}>
        <div className="wrap" style={{ display: "grid", gridTemplateColumns: "0.8fr 1.2fr", gap: 48, alignItems: "start" }}>
          <div><div className="kicker" style={{ marginBottom: 10 }}>Perks</div><h2 className="sec">The basics, covered.</h2></div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "14px 24px" }}>
            {PERKS.map((p) => <div key={p} style={{ display: "flex", gap: 11, fontSize: 15, color: "var(--tx-2)", lineHeight: 1.4 }}><Check />{p}</div>)}
          </div>
        </div>
      </section>

      <CTABand onContact={onContact} />
      <SiteFooter onContact={onContact} />
    </div>
  );
}

function NotFound({ onContact }) {
  return (
    <div>
      <SiteNav onContact={onContact} />
      <div className="wrap" style={{ padding: "140px 48px", textAlign: "center" }}>
        <h1 className="disp" style={{ fontSize: 54 }}>Page not found.</h1>
        <p className="sub" style={{ margin: "18px auto 28px", maxWidth: "26em" }}>That page doesn't exist yet.</p>
        <a href={HOME} className="btn btn-primary">Back to overview →</a>
      </div>
      <SiteFooter onContact={onContact} />
    </div>
  );
}

function slugFromLocation() {
  const qp = new URLSearchParams(location.search).get("p");
  if (qp) return qp;
  const seg = location.pathname.replace(/\/+$/g, "").split("/").pop();
  if (seg && seg !== "page.html" && seg !== "index.html") return seg;
  return "about";
}

function Root() {
  const [contact, setContact] = useState(false);
  const open = () => setContact(true);
  const p = slugFromLocation();
  useEffect(() => {
    if (FEATURES[p]) {
      const f = FEATURES[p];
      document.title = "Sostratus · " + f.kicker.split("·").pop().trim();
    }
  }, [p]);
  let body;
  if (p === "about") body = <AboutPage onContact={open} />;
  else if (p === "careers") body = <CareersPage onContact={open} />;
  else if (FEATURES[p]) body = <FeaturePage slug={p} onContact={open} />;
  else body = <NotFound onContact={open} />;
  return <div>{body}<ContactModal open={contact} onClose={() => setContact(false)} /></div>;
}

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