/* global React, ReactDOM */
// ════════════════════════════════════════════════════════════════
// Sostratus secondary pages — shared chrome + detail-page template +
// content map. page.html reads ?p=<slug> and renders the matching
// page. Mocks come from the shared window globals (shell/appmocks/
// topology/mocks-infra/mocks-opsec/mocks-extra).
// ════════════════════════════════════════════════════════════════
const { useState, useEffect, useRef } = React;
const { Wordmark, Icon } = window;
const HOME = "/";

function Check() {
  return <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12.5l5 5L20 6.5" /></svg>;
}

const TURNSTILE_SITEKEY = "0x4AAAAAADbRUaxS3j7INQ6B";
function TurnstileBox({ onToken }) {
  const ref = useRef(null);
  const wid = useRef(null);
  useEffect(() => {
    let stop = false;
    (function go() {
      if (stop) return;
      if (window.turnstile && ref.current && wid.current === null) {
        try {
          wid.current = window.turnstile.render(ref.current, {
            sitekey: TURNSTILE_SITEKEY, theme: "dark", size: "flexible",
            callback: (t) => onToken(t),
            "error-callback": () => onToken(""),
            "expired-callback": () => onToken(""),
          });
        } catch (e) {}
      } else if (!window.turnstile) { setTimeout(go, 200); }
    })();
    return () => { stop = true; if (window.turnstile && wid.current !== null) { try { window.turnstile.remove(wid.current); } catch (e) {} wid.current = null; } };
  }, []);
  return <div ref={ref} style={{ marginBottom: 14, minHeight: 65 }} />;
}

// ---------- contact modal (shared) ----------
const TIMEZONES = ["Eastern Time (ET)", "Central Time (CT)", "Mountain Time (MT)", "Pacific Time (PT)", "Alaska Time (AKT)", "Hawaii Time (HT)", "UTC / GMT", "UK (GMT/BST)", "Central European (CET)", "India (IST)", "Singapore / HK (SGT)", "Japan (JST)", "Australia Eastern (AET)"];
const TZ_DEFAULT = (() => {
  try {
    const z = (Intl.DateTimeFormat().resolvedOptions().timeZone) || "";
    const map = [[/New_York|Toronto|Montreal/, "Eastern Time (ET)"], [/Chicago|Winnipeg|Mexico_City/, "Central Time (CT)"], [/Denver|Edmonton|Phoenix/, "Mountain Time (MT)"], [/Los_Angeles|Vancouver|Tijuana/, "Pacific Time (PT)"], [/Anchorage/, "Alaska Time (AKT)"], [/Honolulu/, "Hawaii Time (HT)"], [/London|Dublin|Lisbon/, "UK (GMT/BST)"], [/Paris|Berlin|Madrid|Rome|Amsterdam|Brussels|Zurich/, "Central European (CET)"], [/Kolkata|Calcutta/, "India (IST)"], [/Singapore|Hong_Kong/, "Singapore / HK (SGT)"], [/Tokyo|Seoul/, "Japan (JST)"], [/Sydney|Melbourne|Brisbane/, "Australia Eastern (AET)"]];
    for (const [re, label] of map) if (re.test(z)) return label;
  } catch (e) {}
  return "UTC / GMT";
})();

function CustomSelect({ options, name, defaultValue }) {
  const [open, setOpen] = useState(false);
  const [val, setVal] = useState(defaultValue || options[0]);
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);
  return (
    <div ref={ref} style={{ position: "relative" }}><input type="hidden" name={name} value={val} />
      <button type="button" className="cf-select-trigger" style={{ borderRadius: open ? "8px 8px 0 0" : 8 }} onClick={() => setOpen((o) => !o)}>
        <span>{val}</span>
        <span style={{ display: "flex", color: "var(--tx-3)", transition: "transform .15s", transform: open ? "rotate(180deg)" : "none" }}><Icon name="caret-down" size={16} /></span>
      </button>
      {open && (
        <div className="cf-menu">
          {options.map((o) => (
            <div key={o} className="cf-opt" onMouseDown={() => { setVal(o); setOpen(false); }} style={{ color: o === val ? "#fff" : "var(--tx-2)" }}>
              {o}{o === val && <span style={{ marginLeft: "auto", width: 6, height: 6, borderRadius: 99, background: "var(--accent)" }} />}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function ContactModal({ open, onClose, initialRole }) {
  const [role, setRole] = useState(initialRole || "Customer");
  const [sent, setSent] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(false);
  const [tsToken, setTsToken] = useState("");
  useEffect(() => {
    const h = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [onClose]);
  useEffect(() => { if (open) { setSent(false); setRole(initialRole || "Customer"); setTsToken(""); } }, [open, initialRole]);
  if (!open) return null;
  const Field = ({ label, children }) => (
    <label style={{ display: "block", marginBottom: 15 }}>
      <span className="mono" style={{ display: "block", fontSize: 10.5, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--tx-3)", marginBottom: 7 }}>{label}</span>
      {children}
    </label>
  );
  const secondary = role === "Customer"
    ? { label: "Approx. devices under management", el: <CustomSelect name="detail" options={["Under 500", "500 to 5,000", "5,000 to 50,000", "50,000+"]} /> }
    : role === "Investor"
      ? { label: "Firm / fund", el: <input className="cf-input" name="detail" placeholder="Acme Ventures" /> }
      : { label: "Partnership type", el: <CustomSelect name="detail" options={["Reseller / MSP", "Technology / integration", "Referral"]} /> };
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 100, background: "rgba(0,0,0,0.62)", backdropFilter: "blur(6px)", display: "flex", alignItems: "flex-start", justifyContent: "center", padding: "44px 20px", overflowY: "auto" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "100%", maxWidth: 500, background: "var(--paper)", border: "1px solid var(--hair)", borderRadius: 18, boxShadow: "0 40px 110px rgba(0,0,0,0.6)", overflow: "hidden" }}>
        <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", padding: "22px 24px 0" }}>
          <Wordmark size={24} />
          <button onClick={onClose} aria-label="Close" style={{ background: "transparent", border: "1px solid var(--divider)", color: "var(--tx-2)", width: 30, height: 30, borderRadius: 8, cursor: "pointer", fontSize: 15, lineHeight: 1 }}>✕</button>
        </div>
        {sent ? (
          <div style={{ padding: "30px 24px 40px", textAlign: "center" }}>
            <div style={{ width: 56, height: 56, borderRadius: 99, margin: "8px 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" }}>Thanks, we'll be in touch.</div>
            <p className="sub" style={{ fontSize: 15.5, margin: "10px auto 24px", maxWidth: "26em" }}>Someone from the team will reach out within a day or two to set up a walkthrough.</p>
            <button onClick={onClose} className="btn btn-ghost" style={{ cursor: "pointer" }}>Close</button>
          </div>
        ) : (
          <form onSubmit={async (e) => { e.preventDefault(); const fd = new FormData(e.currentTarget); if (fd.get("company_url")) { setSent(true); return; } setBusy(true); setError(false); try { const r = await fetch("/api/contact", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ role: role, name: fd.get("name"), email: fd.get("email"), company: fd.get("company"), phone: fd.get("phone"), contact_time: fd.get("contact_time"), timezone: fd.get("timezone"), detail: fd.get("detail"), message: fd.get("message"), turnstile_token: tsToken }) }); if (!r.ok) throw new Error(); setSent(true); } catch (err) { setError(true); } finally { setBusy(false); } }} style={{ padding: "18px 24px 26px" }}>
            <input type="text" name="company_url" tabIndex={-1} autoComplete="off" aria-hidden="true" style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }} />
            <h3 style={{ fontSize: 23, fontWeight: 600, color: "#fff", margin: "6px 0 4px", letterSpacing: "-0.02em" }}>Talk to the team</h3>
            <p style={{ fontSize: 14.5, color: "var(--tx-2)", margin: "0 0 20px", lineHeight: 1.5 }}>Tell us a little about you and we'll set up a walkthrough.</p>
            <Field label="I'm a">
              <div className="cf-seg">
                {["Customer", "Investor", "Partner"].map((r) => (
                  <button type="button" key={r} className={role === r ? "on" : ""} onClick={() => setRole(r)}>{r}</button>
                ))}
              </div>
            </Field>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
              <Field label="Full name"><input className="cf-input" name="name" placeholder="Jordan Okafor" required /></Field>
              <Field label="Work email"><input className="cf-input" name="email" type="email" placeholder="jordan@company.com" required /></Field>
            </div>
            <Field label="Company / organization"><input className="cf-input" name="company" placeholder="Northwind Trading" required /></Field>
            <Field label={secondary.label}>{secondary.el}</Field>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
              <Field label="Phone number"><input className="cf-input" name="phone" type="tel" placeholder="+1 555 123 4567" /></Field>
              <Field label="Preferred contact time"><input className="cf-input" name="contact_time" type="datetime-local" style={{ colorScheme: "dark" }} /></Field>
            </div>
            <Field label="Time zone"><CustomSelect name="timezone" defaultValue={TZ_DEFAULT} options={TIMEZONES} /></Field>
            <Field label="Anything we should know?"><textarea name="message" className="cf-textarea" placeholder="What you're hoping to manage, current tools, timeline…" /></Field>
            <div style={{ marginTop: 16 }}><TurnstileBox onToken={setTsToken} /></div>
            {error && <p style={{ fontSize: 13, color: "#f06080", textAlign: "center", margin: "0 0 12px" }}>Something went wrong. Please try again, or email hello@sostr.io.</p>}
            <button type="submit" disabled={busy} className="btn btn-primary" style={{ width: "100%", justifyContent: "center", cursor: busy ? "default" : "pointer", marginTop: 4, opacity: busy ? 0.7 : 1 }}>{busy ? "Sending…" : "Request a walkthrough →"}</button>
            <p className="mono" style={{ fontSize: 11, color: "var(--tx-4)", textAlign: "center", margin: "14px 0 0" }}>We'll only use this to get in touch. No spam.</p>
          </form>
        )}
      </div>
    </div>
  );
}

// ---------- shared nav + footer ----------
function SiteNav({ onContact }) {
  return (
    <div className="topnav">
      <div className="topnav-inner">
        <a href={HOME} style={{ textDecoration: "none" }}><Wordmark size={26} sub="network control plane" /></a>
        <div className="topnav-links">
          <a href={HOME + "#platform"}>Platform</a><a href="/topology">Topology</a><a href="/siem">Security</a><a href="/about">Company</a>
          <button onClick={onContact} className="btn btn-ghost" style={{ padding: "9px 16px", fontSize: 14, cursor: "pointer" }}>Request access</button>
        </div>
      </div>
    </div>
  );
}

function SiteFooter({ onContact }) {
  const cols = [
    ["Platform", [["NIMS discovery", "nims"], ["Devices", "devices"], ["Topology", "topology"], ["IPAM", "ipam"], ["DCIM", "dcim"]]],
    ["Operations", [["Monitoring", "monitoring"], ["Chaos engineering", "chaos"], ["Automation", "automation"]]],
    ["Security", [["SIEM", "siem"], ["SOAR", "soar"], ["XDR", "xdr"]]],
    ["Company", [["About", "about"], ["Careers", "careers"], ["Contact", "contact"]]],
  ];
  const itemSx = { display: "block", fontSize: 14, color: "var(--tx-2)", marginBottom: 9, cursor: "pointer", textDecoration: "none", background: "none", border: "none", padding: 0, fontFamily: "var(--sans)", textAlign: "left" };
  const hov = { onMouseEnter: (e) => e.currentTarget.style.color = "#fff", onMouseLeave: (e) => e.currentTarget.style.color = "var(--tx-2)" };
  return (
    <footer style={{ background: "var(--bg-deep)", borderTop: "1px solid var(--divider)", padding: "64px 0 40px" }}>
      <div className="wrap" style={{ display: "grid", gridTemplateColumns: "1.4fr repeat(4, 1fr)", gap: 40 }}>
        <div>
          <a href={HOME} style={{ textDecoration: "none" }}><Wordmark size={26} sub="network control plane" /></a>
          <p style={{ fontSize: 13.5, color: "var(--tx-3)", marginTop: 16, maxWidth: "20em", lineHeight: 1.6 }}>The multi-tenant control plane for network infrastructure, discovery to detection &amp; response.</p>
        </div>
        {cols.map(([h, items]) => (
          <div key={h}>
            <div className="mono" style={{ fontSize: 10.5, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--tx-3)", marginBottom: 14 }}>{h}</div>
            {items.map(([label, slug]) => slug === "contact"
              ? <button key={label} type="button" onClick={onContact} style={itemSx} {...hov}>{label}</button>
              : <a key={label} href={"/" + slug} style={itemSx} {...hov}>{label}</a>
            )}
          </div>
        ))}
      </div>
      <div className="wrap" style={{ marginTop: 48, paddingTop: 22, borderTop: "1px solid var(--divider)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <span className="mono" style={{ fontSize: 12, color: "var(--tx-4)" }}>© 2026 Sostratus</span>
        <span className="mono" style={{ fontSize: 12, color: "var(--tx-4)" }}>sostr.io</span>
      </div>
    </footer>
  );
}

window.SostratusChrome = { Check, TurnstileBox, ContactModal, SiteNav, SiteFooter, HOME };
