// PortalTable — brand layer: icon set, logo, sticky nav, waitlist modal, footer.
// Depends on React (global) + Stratum bundle (window.StratumDesignSystem_019e2e).

const { useState, useEffect, useRef } = React;
// The Stratum bundle assigns its components (Button, Card, Badge…) directly to window.
const DS = window;

/* -------------------------------------------------------------------------- */
/* Icon set — Lucide geometry, stroke 1.5, currentColor (matches Stratum vibe) */
/* -------------------------------------------------------------------------- */
const PD_ICONS = {
  arrowRight: "M5 12h14M13 6l6 6-6 6",
  arrowDown: "M12 5v14M6 13l6 6 6-6",
  check: "M20 6 9 17l-5-5",
  grid: "M4 4h16v16H4zM4 10h16M4 16h16M10 4v16M16 4v16",
  clock: "M12 7v5l3 2M12 21a9 9 0 1 1 0-18 9 9 0 0 1 0 18Z",
  coins: "M16 8h5v6M21 8l-8 8-4-4-7 7",
  palette: "M12 21a9 9 0 1 1 0-18 9 9 0 0 1 9 9c0 1.66-1.34 3-3 3h-1.6a1.5 1.5 0 0 0-1.06 2.56A1.5 1.5 0 0 1 12 21ZM7.5 11.5h.01M10.5 8.5h.01M14.5 8.5h.01",
  database: "M12 8c4.97 0 9-1.34 9-3s-4.03-3-9-3-9 1.34-9 3 4.03 3 9 3ZM3 5v7c0 1.66 4.03 3 9 3s9-1.34 9-3V5M3 12v7c0 1.66 4.03 3 9 3s9-1.34 9-3v-7",
  checklist: "m3 8 1.5 1.5L8 6M3 16l1.5 1.5L8 14M12 8h9M12 16h9",
  gauge: "M12 13l4-4M4.6 18a9 9 0 1 1 14.8 0",
  shield: "M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67 0C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.18 1.18 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",
  shieldCheck: "M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67 0C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.18 1.18 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1zM9 12l2 2 4-4",
  users: "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8ZM22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75",
  link: "M9 17H7A5 5 0 0 1 7 7h2M15 7h2a5 5 0 0 1 0 10h-2M8 12h8",
  history: "M3 4v5h5M3.5 13a9 9 0 1 0 2.5-7.4L3 9M12 7v5l4 2",
  globe: "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18ZM3 12h18M12 3a14 14 0 0 1 0 18 14 14 0 0 1 0-18Z",
  file: "M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6",
  upload: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 9l5-5 5 5M12 4v12",
  message: "M21 14a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",
  bell: "M10.268 21a2 2 0 0 0 3.464 0M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",
  card: "M3 7a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2zM3 10h18",
  sparkle: "M12 3l1.7 5.1a2 2 0 0 0 1.2 1.2L20 11l-5.1 1.7a2 2 0 0 0-1.2 1.2L12 19l-1.7-5.1a2 2 0 0 0-1.2-1.2L4 11l5.1-1.7a2 2 0 0 0 1.2-1.2z",
  external: "M15 3h6v6M10 14 21 3M21 14v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h5",
  menu: "M3 6h18M3 12h18M3 18h18",
  x: "M18 6 6 18M6 6l12 12",
  plus: "M12 5v14M5 12h14",
  chevronRight: "m9 6 6 6-6 6",
  chevronLeft: "m15 6-6 6 6 6",
  download: "M12 3v12M8 11l4 4 4-4M4 21h16",
  send: "M22 2 11 13M22 2l-7 20-4-9-9-4z",
  calendar: "M8 2v4M16 2v4M3 9h18M5 4h14a1 1 0 0 1 1 1v15a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1z",
  eye: "M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7zM12 14.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5z",
  folder: "M4 5h5l2 2.5h9a1 1 0 0 1 1 1V19a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1z",
  image: "M4 4h16a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1zM9 10a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM21 16l-5-5L5 21",
  dot: "",
};

function Ic({ name, size = 18, style = {}, strokeWidth = 1.6, className = "" }) {
  const d = PD_ICONS[name];
  if (d === undefined) return null;
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
      stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round"
      strokeLinejoin="round" style={{ flexShrink: 0, ...style }} className={className}>
      {d.split("M").filter(Boolean).map((seg, i) => <path key={i} d={"M" + seg} />)}
    </svg>
  );
}

/* -------------------------------------------------------------------------- */
/* Logo — 2×2 grid mark (one branded chartreuse cell) + wordmark               */
/* -------------------------------------------------------------------------- */
function Logo({ size = 26, showWord = true, wordColor = "var(--fg-1)" }) {
  const pos = [0, 17]; // 2 cells of 13 with a 4 gap → fills 30×30
  const cells = [];
  pos.forEach((x, ci) => pos.forEach((y, ri) => {
    const lit = ci === 0 && ri === 0;
    cells.push(<rect key={ci + "-" + ri} x={x} y={y} width="13" height="13" rx="3.4" fill={lit ? "var(--accent)" : wordColor} />);
  }));
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
      <svg width={size} height={size} viewBox="0 0 30 30" fill="none" aria-hidden="true" style={{ flexShrink: 0 }}>
        {cells}
      </svg>
      {showWord && (
        <span style={{ fontWeight: 600, fontSize: 17, color: wordColor, letterSpacing: "-0.02em" }}>
          PortalTable
        </span>
      )}
    </span>
  );
}

/* -------------------------------------------------------------------------- */
/* Waitlist — global open helper + modal                                       */
/* -------------------------------------------------------------------------- */
function openWaitlist() { window.dispatchEvent(new CustomEvent("pd-open-waitlist")); }
window.openWaitlist = openWaitlist;

function WaitlistModal() {
  const [open, setOpen] = useState(false);
  const [email, setEmail] = useState("");
  const [role, setRole] = useState("Agency / consultancy");
  const [status, setStatus] = useState("idle"); // idle | error | done
  const inputRef = useRef(null);

  useEffect(() => {
    const onOpen = () => { setOpen(true); setStatus("idle"); };
    window.addEventListener("pd-open-waitlist", onOpen);
    return () => window.removeEventListener("pd-open-waitlist", onOpen);
  }, []);

  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("keydown", onKey);
    const t = setTimeout(() => inputRef.current && inputRef.current.focus(), 60);
    return () => { window.removeEventListener("keydown", onKey); clearTimeout(t); };
  }, [open]);

  function submit(e) {
    e.preventDefault();
    const ok = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
    if (!ok) { setStatus("error"); return; }
    setStatus("done");
  }

  if (!open) return null;

  return (
    <div onMouseDown={() => setOpen(false)}
      style={{
        position: "fixed", inset: 0, zIndex: 100,
        background: "rgba(16,18,22,0.34)", backdropFilter: "blur(4px)",
        display: "flex", alignItems: "center", justifyContent: "center", padding: 24,
        animation: "pdFade 180ms var(--ease-out)",
      }}>
      <div onMouseDown={(e) => e.stopPropagation()}
        style={{
          width: "100%", maxWidth: 452, background: "var(--ink-900)",
          border: "1px solid var(--line-2)", borderRadius: 16,
          boxShadow: "var(--pd-shadow-lg)", padding: 28, position: "relative",
          animation: "pdPop 200ms var(--ease-out)",
        }}>
        <button onClick={() => setOpen(false)} aria-label="Close"
          style={{
            position: "absolute", top: 16, right: 16, width: 30, height: 30,
            display: "grid", placeItems: "center", borderRadius: 8,
            background: "transparent", border: "1px solid transparent", color: "var(--fg-3)", cursor: "pointer",
          }}
          onMouseEnter={(e) => { e.currentTarget.style.background = "var(--ink-800)"; e.currentTarget.style.color = "var(--fg-1)"; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--fg-3)"; }}>
          <Ic name="x" size={17} />
        </button>

        {status === "done" ? (
          <div style={{ textAlign: "center", padding: "16px 4px 6px" }}>
            <div style={{
              width: 52, height: 52, borderRadius: 14, margin: "0 auto 18px",
              display: "grid", placeItems: "center",
              background: "var(--accent)", color: "var(--fg-inverse)",
            }}>
              <Ic name="check" size={26} strokeWidth={2.2} />
            </div>
            <h3 style={{ fontSize: 22, color: "var(--fg-1)", letterSpacing: "-0.02em", margin: 0 }}>You're on the list</h3>
            <p style={{ fontSize: 14, color: "var(--fg-2)", marginTop: 10, lineHeight: 1.55 }}>
              We'll email <strong style={{ color: "var(--fg-1)", fontWeight: 600 }}>{email.trim()}</strong> when your workspace is ready. Early-access agencies get onboarding support and locked-in pricing.
            </p>
            <div style={{ marginTop: 22 }}>
              <DS.Button variant="secondary" size="lg" onClick={() => setOpen(false)}
                style={{ width: "100%", justifyContent: "center" }}>Done</DS.Button>
            </div>
          </div>
        ) : (
          <React.Fragment>
            <span className="pd-eyebrow">EARLY&nbsp;ACCESS</span>
            <h3 style={{ fontSize: 23, color: "var(--fg-1)", letterSpacing: "-0.02em", margin: "12px 0 6px" }}>
              Join the waitlist
            </h3>
            <p style={{ fontSize: 14, color: "var(--fg-2)", lineHeight: 1.55, margin: 0 }}>
              Launch a branded client portal from your workspace. We're onboarding agencies in small batches.
            </p>

            <form onSubmit={submit} style={{ marginTop: 22, display: "flex", flexDirection: "column", gap: 14 }}>
              <label style={{ display: "flex", flexDirection: "column", gap: 7 }}>
                <span style={{ fontSize: 12.5, color: "var(--fg-2)", fontWeight: 500 }}>Work email</span>
                <input ref={inputRef} type="email" value={email} placeholder="you@agency.com"
                  onChange={(e) => { setEmail(e.target.value); if (status === "error") setStatus("idle"); }}
                  style={{
                    height: 42, padding: "0 13px", borderRadius: 8, fontSize: 14,
                    background: "var(--ink-900)", color: "var(--fg-1)",
                    border: `1px solid ${status === "error" ? "var(--red)" : "var(--line-3)"}`,
                    outline: "none", transition: "border-color var(--dur-2) var(--ease-out)",
                  }}
                  onFocus={(e) => { if (status !== "error") e.target.style.borderColor = "var(--accent-press)"; }}
                  onBlur={(e) => { if (status !== "error") e.target.style.borderColor = "var(--line-3)"; }} />
                {status === "error" && (
                  <span style={{ fontSize: 12, color: "var(--red)" }}>Enter a valid email address.</span>
                )}
              </label>

              <label style={{ display: "flex", flexDirection: "column", gap: 7 }}>
                <span style={{ fontSize: 12.5, color: "var(--fg-2)", fontWeight: 500 }}>What describes you best?</span>
                <div style={{ position: "relative" }}>
                  <select value={role} onChange={(e) => setRole(e.target.value)}
                    style={{
                      width: "100%", height: 42, padding: "0 13px", borderRadius: 8, fontSize: 14,
                      background: "var(--ink-900)", color: "var(--fg-1)", border: "1px solid var(--line-3)",
                      outline: "none", appearance: "none", cursor: "pointer",
                    }}>
                    <option>Agency / consultancy</option>
                    <option>Independent consultant</option>
                    <option>In-house ops team</option>
                    <option>Freelancer / other</option>
                  </select>
                  <span style={{ position: "absolute", right: 12, top: 14, color: "var(--fg-3)", pointerEvents: "none" }}>
                    <Ic name="arrowDown" size={15} />
                  </span>
                </div>
              </label>

              <DS.Button variant="primary" size="lg" type="submit"
                style={{ width: "100%", justifyContent: "center", marginTop: 4 }}>
                Request access
              </DS.Button>
              <p style={{ fontSize: 11.5, color: "var(--fg-3)", textAlign: "center", margin: 0 }}>
                No spam. We email you once, when your slot opens.
              </p>
            </form>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

/* -------------------------------------------------------------------------- */
/* Top navigation — sticky, blurred                                            */
/* -------------------------------------------------------------------------- */
function TopNav() {
  const [scrolled, setScrolled] = useState(false);
  const [hovered, setHovered] = useState(null);
  const links = [
    { label: "Features", href: "#solution" },
    { label: "Pricing", href: "#pricing" },
    { label: "Security", href: "#security" },
    { label: "Resources", href: "#resources" },
  ];
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 50, height: 64,
      background: scrolled ? "rgba(246,247,248,0.72)" : "rgba(246,247,248,0)",
      backdropFilter: scrolled ? "blur(14px)" : "none",
      borderBottom: `1px solid ${scrolled ? "var(--line-2)" : "transparent"}`,
      transition: "background var(--dur-3) var(--ease-out), border-color var(--dur-3) var(--ease-out)",
    }}>
      <div className="pd-container" style={{ height: "100%", display: "flex", alignItems: "center" }}>
        <a href="#top" style={{ border: 0 }}><Logo /></a>
        <nav className="pd-navlinks" style={{ display: "flex", alignItems: "center", gap: 2, marginLeft: 36 }}>
          {links.map((l) => (
            <a key={l.label} href={l.href}
              onMouseEnter={() => setHovered(l.label)} onMouseLeave={() => setHovered(null)}
              style={{
                padding: "7px 12px", fontSize: 13.5, border: 0, borderRadius: 7,
                color: hovered === l.label ? "var(--fg-1)" : "var(--fg-2)",
                background: hovered === l.label ? "var(--ink-800)" : "transparent",
                transition: "color var(--dur-2) var(--ease-out), background var(--dur-2) var(--ease-out)",
              }}>{l.label}</a>
          ))}
        </nav>
        <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 8 }}>
          <a href="#" className="pd-signin" style={{
            fontSize: 13.5, color: "var(--fg-2)", padding: "8px 12px", border: 0, borderRadius: 7,
          }}>Sign in</a>
          <DS.Button variant="primary" size="md" onClick={openWaitlist}>Join waitlist</DS.Button>
        </div>
      </div>
    </header>
  );
}

/* -------------------------------------------------------------------------- */
/* Footer                                                                      */
/* -------------------------------------------------------------------------- */
function Footer() {
  const cols = [
    { title: "Product", items: ["Features", "Pricing", "Security", "Example portal", "Changelog"] },
    { title: "Resources", items: ["Documentation", "Setup guide", "Templates", "Support", "Status"] },
    { title: "Company", items: ["About", "Customers", "Partners", "Contact"] },
    { title: "Legal", items: ["Privacy", "Terms", "DPA", "Subprocessors"] },
  ];
  return (
    <footer id="resources" style={{ borderTop: "1px solid var(--line-2)", background: "var(--ink-900)", padding: "64px 0 32px" }}>
      <div className="pd-container">
        <div className="pd-foot-grid" style={{ display: "grid", gridTemplateColumns: "1.6fr repeat(4, 1fr)", gap: 40, marginBottom: 56 }}>
          <div>
            <Logo />
            <p style={{ fontSize: 13.5, color: "var(--fg-3)", maxWidth: 280, lineHeight: 1.6, marginTop: 16 }}>
              The client experience layer for agencies and freelancers. Your workspace stays the source of truth — your clients get software with your name on it.
            </p>
            <div style={{ marginTop: 18 }}>
              <DS.Badge tone="neutral">
                <span style={{ width: 6, height: 6, borderRadius: 99, background: "var(--green)" }} />
                Early access · onboarding now
              </DS.Badge>
            </div>
          </div>
          {cols.map((c) => (
            <div key={c.title}>
              <span className="pd-eyebrow" style={{ display: "block", marginBottom: 14, fontSize: 10.5 }}>{c.title}</span>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 9 }}>
                {c.items.map((it) => (
                  <li key={it}>
                    <a href="#" style={{
                      fontSize: 13.5, color: "var(--fg-2)", border: 0,
                      transition: "color var(--dur-2) var(--ease-out)",
                    }}
                      onMouseEnter={(e) => (e.currentTarget.style.color = "var(--fg-1)")}
                      onMouseLeave={(e) => (e.currentTarget.style.color = "var(--fg-2)")}>{it}</a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div style={{ paddingTop: 24, borderTop: "1px solid var(--line-2)", display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--fg-3)" }}>© 2026 PortalTable, Inc.</span>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--fg-4)" }}>Built for client work · portals with your name on it</span>
          <span style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 14 }}>
            <a href="#" style={{ fontSize: 12.5, color: "var(--fg-3)", border: 0 }}>X</a>
            <a href="#" style={{ fontSize: 12.5, color: "var(--fg-3)", border: 0 }}>LinkedIn</a>
            <a href="#" style={{ fontSize: 12.5, color: "var(--fg-3)", border: 0 }}>GitHub</a>
          </span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Ic, Logo, openWaitlist, WaitlistModal, TopNav, Footer });
