/* global React */
// reo-components.jsx — shared visual building blocks for the Reo landing page.
// Exported to window at the bottom so other babel scripts can use them.

const { useState, useRef, useEffect } = React;

/* ----------------------------------------------------------- Sheets sink
 * Form submissions are appended to a Google Sheet via an Apps Script Web
 * App. The script's doPost reads JSON from e.postData.contents and routes
 * by the `form` field ("waitlist" or "contact"). We send Content-Type
 * text/plain so the browser treats it as a simple request — no CORS
 * preflight, which Apps Script doesn't reliably handle.
 */
const SHEETS_ENDPOINT = "https://script.google.com/macros/s/AKfycbx44cZ-5Wv1zJbgpQtzbBthrlwSDx57h7tqEdKeGyQ0_Wxiow6xlsmsNXBUFmXG0JP6/exec";

function postToSheets(payload) {
  if (!SHEETS_ENDPOINT) return;
  fetch(SHEETS_ENDPOINT, {
    method: "POST",
    body: JSON.stringify(payload),
    headers: { "Content-Type": "text/plain;charset=utf-8" }
  }).catch((err) => { console.warn("Sheets sync failed:", err); });
}

/* ----------------------------------------------------------- Agent glyphs
 * Small monochrome SVG glyphs — no emoji, no stock icons. Each glyph reads
 * editorial at 16–24px. They use currentColor so callers can recolor.
 */
function Glyph({ name, size = 16, stroke = 1.25 }) {
  const c = "currentColor";
  const common = { width: size, height: size, viewBox: "0 0 24 24", fill: "none",
                   stroke: c, strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (name) {
    case "clock":
      return <svg {...common}><circle cx="12" cy="12" r="8.5"/><path d="M12 7.5V12l3 2"/></svg>;
    case "cross-arrows":
      return <svg {...common}><path d="M5 7h10l-2.5-2.5M5 7l2.5 2.5"/><path d="M19 17H9l2.5 2.5M19 17l-2.5-2.5"/></svg>;
    case "diverge":
      return <svg {...common}><path d="M4 6l8 6 8-6"/><path d="M4 18l8-6 8 6"/></svg>;
    case "wave":
      return <svg {...common}><path d="M3 14c2-4 4-4 6 0s4 4 6 0 4-4 6 0"/><circle cx="3" cy="14" r=".8" fill={c}/><circle cx="21" cy="14" r=".8" fill={c}/></svg>;
    case "log":
      return <svg {...common}><rect x="4.5" y="4.5" width="15" height="15" rx="1"/><path d="M8 9h8M8 13h8M8 17h5"/></svg>;
    case "shield":
      return <svg {...common}><path d="M12 3.5l7 2.5v5c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6l7-2.5z"/></svg>;
    case "eye-off":
      return <svg {...common}><path d="M3 12s3-6 9-6c2 0 3.6.6 5 1.5M21 12s-3 6-9 6c-2 0-3.6-.6-5-1.5"/><path d="M4 4l16 16"/></svg>;
    case "target":
      return <svg {...common}><circle cx="12" cy="12" r="8.5"/><circle cx="12" cy="12" r="4.5"/><circle cx="12" cy="12" r="1.2" fill={c}/></svg>;
    case "bell":
      return <svg {...common}><path d="M6 16V11a6 6 0 0 1 12 0v5l1.5 2H4.5L6 16z"/><path d="M10 20a2 2 0 0 0 4 0"/></svg>;
    case "link":
      return <svg {...common}><path d="M10 14a4 4 0 0 0 5.66 0l3-3a4 4 0 0 0-5.66-5.66L11.5 7"/><path d="M14 10a4 4 0 0 0-5.66 0l-3 3A4 4 0 0 0 11 18.66L12.5 17"/></svg>;
    case "calendar":
      return <svg {...common}><rect x="3.5" y="5.5" width="17" height="14" rx="1.5"/><path d="M3.5 10h17M8 3.5v4M16 3.5v4"/></svg>;
    case "chip":
      return <svg {...common}><rect x="6" y="6" width="12" height="12" rx="1.5"/><rect x="9" y="9" width="6" height="6" rx=".5" fill={c} opacity=".15"/><path d="M3 9h3M3 12h3M3 15h3M18 9h3M18 12h3M18 15h3M9 3v3M12 3v3M15 3v3M9 18v3M12 18v3M15 18v3"/></svg>;
    case "ear":
      return <svg {...common}><path d="M8 18c-2 0-3-1.5-3-3.5 0-1.5.5-2.5 1-3.5C5.5 9.5 6 8 6 6.5 6 4 8 2.5 11 2.5s5 1.5 5 4.5c0 1.5-1 2-2 3-1 1-1.5 1.5-1.5 2.5"/></svg>;
    case "thread":
      return <svg {...common}><circle cx="6" cy="6" r="2"/><circle cx="6" cy="18" r="2"/><circle cx="18" cy="12" r="2"/><path d="M6 8v8M8 6c4 0 8 2.5 8 6M8 18c4 0 8-2.5 8-6"/></svg>;
    case "at":
      return <svg {...common}><circle cx="12" cy="12" r="4"/><path d="M16 8v4.5a2 2 0 0 0 4 0V12a8 8 0 1 0-3.5 6.6"/></svg>;
    case "currency":
      return <svg {...common}><path d="M16 7H9.5a2.5 2.5 0 0 0 0 5h5a2.5 2.5 0 0 1 0 5H7M12 4.5v15"/></svg>;
    case "scale":
      return <svg {...common}><path d="M12 5v14M5 9h14M5 9l-1.5 4.5h3L5 9zM19 9l-1.5 4.5h3L19 9z"/><path d="M8 19h8"/></svg>;
    default:
      return <svg {...common}><rect x="6" y="6" width="12" height="12" rx="2"/></svg>;
  }
}

/* ----------------------------------------------------------- Brand wordmark
 * Three letters, lowercase, with a single deliberate dot to act as a logo
 * mark. Letterspacing tightened slightly. No mixed case.
 */
function ReoMark({ size = 22, color = "currentColor", clickable = false }) {
  const inner = (
    <>
      {/* Logo glyph — a 2×2 grid of dots, the bottom-right one is accent.
          Reads as: "patterns" with one signal worth surfacing. */}
      <span style={{
        width: size * 1.05, height: size * 1.05,
        border: "1px solid currentColor",
        borderRadius: 4, padding: 3,
        display: "inline-grid",
        gridTemplateColumns: "1fr 1fr",
        gridTemplateRows: "1fr 1fr",
        gap: 2,
        marginRight: size * 0.32,
        flexShrink: 0
      }}>
        {[0,1,2,3].map(i => (
          <span key={i} style={{
            width: "100%", height: "100%",
            background: i === 3 ? "var(--accent)" : "currentColor",
            opacity: i === 3 ? 1 : 0.55,
            borderRadius: 1
          }}/>
        ))}
      </span>
      <span>reo</span>
    </>
  );

  const style = {
    display: "inline-flex", alignItems: "center",
    fontFamily: "var(--font-sans)", fontWeight: 500,
    fontSize: size, letterSpacing: "-0.035em", color,
    lineHeight: 1,
    textDecoration: "none",
    cursor: clickable ? "pointer" : "default",
    userSelect: "none"
  };

  if (clickable) {
    const scrollTop = (e) => {
      e?.preventDefault();
      try { window.scrollTo({ top: 0, behavior: "smooth" }); } catch { window.scrollTo(0, 0); }
    };
    return <a href="#top" onClick={scrollTop} style={style} aria-label="Reo home">{inner}</a>;
  }
  return <span style={style}>{inner}</span>;
}

/* ----------------------------------------------------------- SourceChip
 * Monospace pill that signals a real verifiable source. Used inside digest
 * insight cards and "between the lines" hero visuals.
 */
function SourceChip({ children, tone = "accent" }) {
  const bg = tone === "muted" ? "var(--paper-2)" : "var(--accent-tint)";
  const fg = tone === "muted" ? "var(--ink-2)" : "var(--accent)";
  const bd = tone === "muted" ? "var(--rule-2)" : "var(--accent-tint-2)";
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      height: 22, padding: "0 8px",
      background: bg, color: fg,
      border: `1px solid ${bd}`,
      borderRadius: 4,
      fontFamily: "var(--font-mono)",
      fontSize: 11, letterSpacing: "0.01em",
      whiteSpace: "nowrap"
    }}>
      <Glyph name="link" size={11} stroke={1.3}/>
      {children}
    </span>
  );
}

/* ----------------------------------------------------------- AudienceTag
 * Tiny label that always shows who will see something. Required honesty.
 */
function AudienceTag({ to = "you only" }) {
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      padding: "3px 9px",
      background: "var(--accent-tint)",
      border: "1px solid var(--accent-tint-2)",
      borderRadius: 99,
      fontFamily: "var(--font-mono)",
      fontSize: 10.5, letterSpacing: "0.05em", textTransform: "uppercase",
      color: "var(--accent)", fontWeight: 600
    }}>
      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
        <circle cx="12" cy="9" r="3.5"/><path d="M5 20c1-3.5 4-5 7-5s6 1.5 7 5"/>
      </svg>
      Visible to: <span style={{ fontWeight: 700 }}>{to}</span>
    </span>
  );
}

/* ----------------------------------------------------------- InsightCard
 * The atomic Reo unit: one inference, with sources, audience, and a single
 * primary action. Used inside the digest still and as standalone hero art.
 */
function InsightCard({
  agent, agentGlyph, headline, body, sources = [], audience = "you only",
  primary = "Open thread", secondary = "Mark resolved",
  pinned = false, highlighted = false
}) {
  return (
    <article style={{
      background: "var(--paper)",
      border: `1px solid ${highlighted ? "var(--accent-tint-2)" : "var(--rule)"}`,
      borderRadius: 6,
      padding: "18px 20px",
      position: "relative",
      boxShadow: highlighted ? "0 0 0 4px var(--accent-tint)" : "none",
      transition: "box-shadow 160ms, border-color 160ms"
    }}>
      {/* agent label row */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
        <div style={{
          display: "inline-flex", alignItems: "center", gap: 8,
          fontFamily: "var(--font-mono)", fontSize: 11,
          letterSpacing: "0.04em", textTransform: "uppercase",
          color: "var(--ink-3)"
        }}>
          <span style={{
            width: 18, height: 18, borderRadius: 4,
            background: "var(--paper-3)", border: "1px solid var(--rule-2)",
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            color: "var(--ink-2)"
          }}>
            <Glyph name={agentGlyph || "clock"} size={11} stroke={1.4}/>
          </span>
          {agent}
        </div>
        {pinned && (
          <span style={{
            fontFamily: "var(--font-mono)", fontSize: 10,
            color: "var(--accent)", letterSpacing: "0.08em",
            textTransform: "uppercase"
          }}>
            ▲ Pinned this week
          </span>
        )}
      </div>

      {/* the inference itself */}
      <h3 style={{
        fontSize: 18, lineHeight: 1.4, margin: "0 0 10px 0",
        fontWeight: 500, letterSpacing: "-0.012em", color: "var(--ink)",
        textWrap: "pretty"
      }}>{headline}</h3>

      {body && (
        <p style={{
          fontSize: 16, lineHeight: 1.6, color: "var(--ink-2)",
          margin: "0 0 14px 0", textWrap: "pretty"
        }}>{body}</p>
      )}

      {/* sources row */}
      {sources.length > 0 && (
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 14 }}>
          {sources.map((s, i) => <SourceChip key={i}>{s}</SourceChip>)}
        </div>
      )}

      {/* footer: audience + actions */}
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        gap: 12, paddingTop: 12, borderTop: "1px dashed var(--rule)",
        flexWrap: "wrap"
      }}>
        <AudienceTag to={audience}/>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", justifyContent: "flex-end" }}>
          <button style={btnTertiary}>{secondary}</button>
          <button style={btnPrimary}>{primary}</button>
        </div>
      </div>
    </article>
  );
}

const btnPrimary = {
  height: 28, padding: "0 12px",
  background: "var(--ink)", color: "var(--paper)",
  border: "1px solid var(--ink)", borderRadius: 4,
  fontSize: 12, fontFamily: "var(--font-sans)", fontWeight: 500,
  cursor: "pointer", letterSpacing: "-0.005em",
  whiteSpace: "nowrap", flexShrink: 0
};
const btnTertiary = {
  height: 28, padding: "0 12px",
  background: "transparent", color: "var(--ink-2)",
  border: "1px solid var(--rule-2)", borderRadius: 4,
  fontSize: 12, fontFamily: "var(--font-sans)", fontWeight: 500,
  cursor: "pointer", letterSpacing: "-0.005em",
  whiteSpace: "nowrap", flexShrink: 0
};

/* ----------------------------------------------------------- SkillCard
 * Editorial card. The "agents as cards in a library" treatment — the user's
 * brief asked for this metaphor. Each card has a glyph, name, short
 * description, and a small toggle that flips between "Watching" / "Off".
 */
function SkillCard({ glyph, name, description, on = false, badge, onToggle, compact = false }) {
  const [enabled, setEnabled] = useState(on);
  const toggle = () => {
    setEnabled(v => !v);
    onToggle?.(!enabled);
  };
  return (
    <div
      onClick={toggle}
      style={{
        background: enabled ? "var(--paper)" : "var(--paper-2)",
        border: `1px solid ${enabled ? "var(--ink-2)" : "var(--rule)"}`,
        borderRadius: 6,
        padding: compact ? "14px 16px" : "18px 20px",
        cursor: "pointer",
        transition: "border-color 140ms, background 140ms, transform 140ms",
        position: "relative",
        display: "flex", flexDirection: "column", gap: 10,
        minHeight: compact ? 132 : 156
      }}
      onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-1px)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = "translateY(0)"; }}
    >
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <span style={{
          width: 30, height: 30, borderRadius: 5,
          background: enabled ? "var(--accent)" : "var(--paper-3)",
          color: enabled ? "var(--paper)" : "var(--ink-2)",
          border: `1px solid ${enabled ? "var(--accent)" : "var(--rule-2)"}`,
          display: "inline-flex", alignItems: "center", justifyContent: "center"
        }}>
          <Glyph name={glyph} size={16} stroke={1.3}/>
        </span>
        <span style={{
          fontFamily: "var(--font-mono)", fontSize: 10,
          letterSpacing: "0.06em", textTransform: "uppercase",
          color: enabled ? "var(--accent)" : "var(--ink-4)"
        }}>
          {enabled ? "● Watching" : "○ Off"}
        </span>
      </div>
      <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 4 }}>
        <h4 style={{
          fontSize: 16, fontWeight: 500, margin: 0,
          letterSpacing: "-0.012em", color: "var(--ink)",
          textWrap: "balance", lineHeight: 1.3
        }}>{name}</h4>
        <p style={{
          fontSize: 14.5, lineHeight: 1.55, margin: 0,
          color: "var(--ink-2)", textWrap: "pretty"
        }}>{description}</p>
      </div>
      {badge && (
        <span style={{
          position: "absolute", top: 10, right: 10,
          fontFamily: "var(--font-mono)", fontSize: 9,
          color: "var(--ink-4)", letterSpacing: "0.06em"
        }}>{badge}</span>
      )}
    </div>
  );
}

/* ----------------------------------------------------------- Annotation
 * Hand-drawn-looking pointer + label, used for the annotated hero variant.
 */
function Annotation({ letter, label, x, y, towards = "left", length = 80 }) {
  // towards = direction the pointer goes (toward the artifact)
  const isLeft = towards === "left";
  const isRight = towards === "right";
  const isUp = towards === "up";
  const isDown = towards === "down";
  return (
    <div style={{
      position: "absolute", left: x, top: y,
      display: "flex",
      flexDirection: isUp || isDown ? "column" : "row",
      alignItems: "center", gap: 8, pointerEvents: "none"
    }}>
      {(isLeft || isUp) && (
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 11,
          color: "var(--accent)", letterSpacing: "0.04em",
          background: "var(--paper)", padding: "2px 6px",
          border: "1px solid var(--accent-tint-2)", borderRadius: 3,
          whiteSpace: "nowrap"
        }}>
          <strong style={{ color: "var(--accent)" }}>({letter})</strong>&nbsp;{label}
        </span>
      )}
      <svg width={isUp||isDown ? 1 : length} height={isUp||isDown ? length : 1}
           style={{ overflow: "visible" }}>
        {isLeft && <line x1="0" y1="0.5" x2={length} y2="0.5" stroke="var(--accent)" strokeWidth="1" strokeDasharray="3 3"/>}
        {isRight && <line x1="0" y1="0.5" x2={length} y2="0.5" stroke="var(--accent)" strokeWidth="1" strokeDasharray="3 3"/>}
        {isUp && <line x1="0.5" y1="0" x2="0.5" y2={length} stroke="var(--accent)" strokeWidth="1" strokeDasharray="3 3"/>}
        {isDown && <line x1="0.5" y1="0" x2="0.5" y2={length} stroke="var(--accent)" strokeWidth="1" strokeDasharray="3 3"/>}
      </svg>
      {(isRight || isDown) && (
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 11,
          color: "var(--accent)", letterSpacing: "0.04em",
          background: "var(--paper)", padding: "2px 6px",
          border: "1px solid var(--accent-tint-2)", borderRadius: 3,
          whiteSpace: "nowrap"
        }}>
          <strong style={{ color: "var(--accent)" }}>({letter})</strong>&nbsp;{label}
        </span>
      )}
    </div>
  );
}

/* ----------------------------------------------------------- ChromeBar
 * Mac-style window chrome row used to frame product stills. Three dots, no
 * url bar. The dots are muted, not gummy candy.
 */
function ChromeBar({ title, right }) {
  return (
    <div style={{
      height: 30, display: "flex", alignItems: "center",
      padding: "0 12px", gap: 6,
      borderBottom: "1px solid var(--rule)",
      background: "var(--paper-2)"
    }}>
      {[0,1,2].map(i => (
        <span key={i} style={{
          width: 9, height: 9, borderRadius: 50,
          background: "var(--paper-inset)", border: "1px solid var(--rule-2)"
        }}/>
      ))}
      <span style={{
        flex: 1, textAlign: "center",
        fontFamily: "var(--font-mono)", fontSize: 11,
        color: "var(--ink-4)", letterSpacing: "0.02em"
      }}>{title}</span>
      <span style={{ width: 27, fontFamily: "var(--font-mono)", fontSize: 11,
        color: "var(--ink-4)", textAlign: "right" }}>{right}</span>
    </div>
  );
}

/* ----------------------------------------------------------- ComplianceBadge
 * Original badge — does NOT replicate AICPA / HIPAA / ISO / GDPR / CASA
 * trademarked logo art. Uses the framework name in a tasteful frame plus the
 * required visible "In progress" chip beneath. This is design honesty — and
 * also avoids reproducing branded marks.
 */
function ComplianceBadge({ framework, fullName, targetQuarter, status = "in-progress" }) {
  const statusLabel = status === "planned" ? "Planned" : "In progress";
  const isPlanned   = status === "planned";
  return (
    <div style={{
      display: "flex", flexDirection: "column", alignItems: "stretch",
      gap: 10, minWidth: 0,
      opacity: isPlanned ? 0.78 : 1
    }}>
      <div style={{
        height: 124,
        border: "1px solid var(--rule-2)",
        borderRadius: 6,
        padding: "16px 14px",
        background: "var(--paper)",
        display: "flex", flexDirection: "column", justifyContent: "space-between",
        position: "relative"
      }}>
        <div style={{
          fontFamily: "var(--font-mono)", fontSize: 10,
          color: "var(--ink-4)", letterSpacing: "0.08em",
          textTransform: "uppercase"
        }}>Framework</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
          <div style={{
            fontSize: 18, fontWeight: 500,
            letterSpacing: "-0.015em", color: "var(--ink)"
          }}>{framework}</div>
          <div style={{
            fontSize: 11.5, color: "var(--ink-3)",
            lineHeight: 1.35, textWrap: "balance"
          }}>{fullName}</div>
        </div>
        {/* corner ticks */}
        {["tl","tr","bl","br"].map(c => (
          <span key={c} style={{
            position: "absolute",
            top: c.includes("t") ? -1 : "auto",
            bottom: c.includes("b") ? -1 : "auto",
            left: c.includes("l") ? -1 : "auto",
            right: c.includes("r") ? -1 : "auto",
            width: 6, height: 6,
            borderTop: c.includes("t") ? "1px solid var(--ink-2)" : "none",
            borderBottom: c.includes("b") ? "1px solid var(--ink-2)" : "none",
            borderLeft: c.includes("l") ? "1px solid var(--ink-2)" : "none",
            borderRight: c.includes("r") ? "1px solid var(--ink-2)" : "none",
          }}/>
        ))}
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 6, alignItems: "flex-start" }}>
        {isPlanned ? (
          <span style={{
            display: "inline-flex", alignItems: "center", gap: 6,
            height: 22, padding: "0 8px",
            background: "transparent",
            border: "1px dashed var(--rule-strong)",
            borderRadius: 999,
            fontFamily: "var(--font-mono)", fontSize: 10,
            letterSpacing: "0.06em", color: "var(--ink-4)",
            textTransform: "uppercase", whiteSpace: "nowrap", lineHeight: 1
          }}>
            <span style={{
              width: 5, height: 5, borderRadius: 50,
              border: "1px solid var(--ink-5)", background: "transparent"
            }}/>
            Planned
          </span>
        ) : (
          <span className="chip-progress">
            <span className="dot"/>In progress
          </span>
        )}
        <span style={{
          fontFamily: "var(--font-mono)", fontSize: 10,
          color: "var(--ink-4)", letterSpacing: "0.04em"
        }}>
          Target: {targetQuarter}
        </span>
      </div>
    </div>
  );
}

/* ----------------------------------------------------------- FAQ
 * Accessible accordion with keyboard support.
 */
function FAQItem({ q, a, initialOpen = false }) {
  const [open, setOpen] = useState(initialOpen);
  return (
    <div style={{
      borderBottom: "1px solid var(--rule)",
      borderLeft: `2px solid ${open ? "var(--accent)" : "transparent"}`,
      paddingLeft: open ? 16 : 0,
      transition: "border-color 200ms, padding-left 200ms"
    }}>
      <button
        onClick={() => setOpen(o => !o)}
        aria-expanded={open}
        style={{
          width: "100%", textAlign: "left",
          padding: "22px 0", display: "flex", alignItems: "center",
          justifyContent: "space-between", gap: 24,
          background: "transparent", border: "none", cursor: "pointer",
          color: open ? "var(--accent)" : "var(--ink)", fontSize: 19,
          letterSpacing: "-0.014em", fontWeight: open ? 500 : 450,
          fontFamily: "var(--font-sans)",
          transition: "color 180ms"
        }}>
        <span style={{ textWrap: "balance" }}>{q}</span>
        <span style={{
          width: 26, height: 26, flexShrink: 0,
          border: `1px solid ${open ? "var(--accent)" : "var(--rule-2)"}`,
          borderRadius: 50,
          background: open ? "var(--accent-tint)" : "transparent",
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          color: open ? "var(--accent)" : "var(--ink-3)",
          transform: open ? "rotate(45deg)" : "none",
          transition: "transform 180ms, border-color 180ms, background 180ms, color 180ms"
        }}>
          <svg width="10" height="10" viewBox="0 0 10 10">
            <path d="M5 1v8M1 5h8" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
          </svg>
        </span>
      </button>
      <div style={{
        maxHeight: open ? 700 : 0,
        overflow: "hidden",
        transition: "max-height 320ms ease, opacity 240ms ease",
        opacity: open ? 1 : 0
      }}>
        <div style={{
          paddingBottom: 22,
          fontSize: 17, lineHeight: 1.7,
          color: "var(--ink-2)", maxWidth: 720,
          textWrap: "pretty"
        }}>{a}</div>
      </div>
    </div>
  );
}

/* ----------------------------------------------------------- DemoModal
 * Tasteful demo modal that mimics a 45-second walkthrough. The "video" is a
 * staged sequence of insight cards animating in — restrained motion only,
 * fade + slight rise. ESC closes.
 */
function DemoModal({ open, onClose }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  const [stage, setStage] = useState(0);
  useEffect(() => {
    if (!open) return;
    setStage(0);
    const t = [
      setTimeout(() => setStage(1), 600),
      setTimeout(() => setStage(2), 1400),
      setTimeout(() => setStage(3), 2200),
      setTimeout(() => setStage(4), 3200),
    ];
    return () => t.forEach(clearTimeout);
  }, [open]);

  if (!open) return null;

  return (
    <div role="dialog" aria-modal="true" onClick={onClose}
      style={{
        position: "fixed", inset: 0, zIndex: 100,
        background: "oklch(0.18 0.010 270 / 0.45)",
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: 32, backdropFilter: "blur(8px)"
      }}>
      <div onClick={(e) => e.stopPropagation()}
        style={{
          width: "min(960px, 100%)",
          background: "var(--paper)",
          border: "1px solid var(--rule-strong)",
          borderRadius: 8, padding: 0, overflow: "hidden",
          display: "flex", flexDirection: "column"
        }}>
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          padding: "14px 18px", borderBottom: "1px solid var(--rule)"
        }}>
          <span className="eyebrow">Reo · 45-second demo</span>
          <button onClick={onClose} style={{
            background: "transparent", border: "1px solid var(--rule-2)",
            borderRadius: 4, padding: "4px 10px", fontFamily: "var(--font-sans)",
            fontSize: 12, color: "var(--ink-2)", cursor: "pointer"
          }}>Close (Esc)</button>
        </div>
        <div style={{
          background: "var(--paper-2)", padding: "32px 32px 28px",
          minHeight: 460, display: "flex", flexDirection: "column", gap: 14
        }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div style={{
              fontFamily: "var(--font-mono)", fontSize: 11,
              color: "var(--ink-3)", letterSpacing: "0.04em"
            }}>
              ▸ Friday digest · 8:00 AM · 14 March 2026
            </div>
            <div style={{
              fontFamily: "var(--font-mono)", fontSize: 11,
              color: "var(--ink-4)"
            }}>
              {stage}/4
            </div>
          </div>
          {[
            { delay: 0, glyph: "clock", agent: "Customer commitments tracker",
              headline: "You promised Acme an export endpoint by end of Q3 — the work moved to Q4 last week.",
              sources: ["Acme · re: Q3 plans (Aug 12)", "Eng standup notes (Sep 4)"],
              audience: "you only" },
            { delay: 1, glyph: "cross-arrows", agent: "Cross-customer contradictions",
              headline: "Voro and Beam were told different launch dates for SSO — Aug 15 vs Sep 30.",
              sources: ["Voro · re: SSO timeline", "Beam · re: rollout"],
              audience: "you only" },
            { delay: 2, glyph: "wave", agent: "Cooling counterparty threads",
              headline: "Three threads with Pier have gone quiet since their renewal in February.",
              sources: ["Pier · re: Q1 expansion"],
              audience: "you only" },
            { delay: 3, glyph: "log", agent: "Decision audit log",
              headline: "On Tuesday you decided to defer the auth migration — captured here so it doesn't slip again.",
              sources: ["Team standup · Mar 11"],
              audience: "team · ENG" },
          ].map((c, i) => (
            <div key={i} style={{
              opacity: stage > i ? 1 : 0,
              transform: stage > i ? "translateY(0)" : "translateY(8px)",
              transition: "opacity 320ms ease, transform 320ms ease"
            }}>
              <InsightCard {...c} primary="Open thread" secondary="Mark resolved"/>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ----------------------------------------------------------- Build-your-own
 * Lightly interactive: user types or picks a preset, click "Generate Skill",
 * a card materializes. Resets on edit.
 */
function BuildYourOwn() {
  const presets = [
    "Flag any customer email that mentions our competitors by name.",
    "Surface when a customer asks the same question twice in 30 days.",
    "Notice when a vendor changes the price after we've signed off.",
    "Watch for any thread where the team disagrees silently through me."
  ];
  const [val, setVal] = useState(presets[0]);
  const [generated, setGenerated] = useState(null);
  const [thinking, setThinking] = useState(false);

  const generate = () => {
    if (!val.trim()) return;
    setThinking(true);
    setGenerated(null);
    setTimeout(() => {
      // derive a name + glyph from the prompt (light heuristic — not LLM)
      const name = deriveName(val);
      const glyph = deriveGlyph(val);
      setGenerated({ name, glyph, description: val.trim() });
      setThinking(false);
    }, 900);
  };

  function deriveName(t) {
    const s = t.toLowerCase();
    if (s.includes("competitor")) return "Competitor mention watch";
    if (s.includes("twice") || s.includes("repeat")) return "Repeated question tracker";
    if (s.includes("price")) return "Price change sentinel";
    if (s.includes("disagree")) return "Silent disagreement detector";
    if (s.includes("overdue") || s.includes("late")) return "Overdue commitment watch";
    return "Custom inference agent";
  }
  function deriveGlyph(t) {
    const s = t.toLowerCase();
    if (s.includes("competitor")) return "scale";
    if (s.includes("twice") || s.includes("repeat")) return "ear";
    if (s.includes("price")) return "currency";
    if (s.includes("disagree")) return "cross-arrows";
    return "target";
  }

  return (
    <div style={{
      background: "var(--paper)",
      border: "1px solid var(--rule-2)",
      borderRadius: 8,
      padding: 24,
      display: "grid",
      gridTemplateColumns: "1fr 280px",
      gap: 24
    }}>
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Build your own</div>
          <h3 style={{
            fontSize: 24, lineHeight: 1.2, margin: 0,
            letterSpacing: "-0.018em", fontWeight: 450,
            color: "var(--ink)", textWrap: "balance"
          }}>Or describe one in plain English.</h3>
        </div>

        <textarea
          value={val}
          onChange={(e) => { setVal(e.target.value); setGenerated(null); }}
          placeholder="Describe what you want Reo to watch for. Be specific."
          rows={3}
          style={{
            width: "100%", resize: "none",
            fontFamily: "var(--font-sans)", fontSize: 15,
            lineHeight: 1.5, color: "var(--ink)",
            background: "var(--paper-2)",
            border: "1px solid var(--rule-2)",
            borderRadius: 6, padding: "12px 14px",
            outline: "none"
          }}
          onFocus={(e) => e.target.style.borderColor = "var(--accent)"}
          onBlur={(e) => e.target.style.borderColor = "var(--rule-2)"}
        />

        <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
          <button onClick={generate} className="reo-cta accent" style={{ height: 36, padding: "0 16px", fontSize: 13 }}>
            Generate Skill <span className="arrow"/>
          </button>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-4)" }}>
            Try a preset:
          </span>
          {presets.slice(1).map((p, i) => (
            <button key={i} onClick={() => { setVal(p); setGenerated(null); }}
              style={{
                background: "transparent",
                border: "1px solid var(--rule-2)",
                borderRadius: 99, padding: "5px 10px",
                fontFamily: "var(--font-mono)", fontSize: 10.5,
                color: "var(--ink-3)", cursor: "pointer",
                letterSpacing: "0.02em", whiteSpace: "nowrap"
              }}>
              {p.length > 40 ? p.slice(0, 40) + "…" : p}
            </button>
          ))}
        </div>
      </div>

      {/* output slot */}
      <div style={{
        background: "var(--paper-2)",
        border: "1px dashed var(--rule-2)",
        borderRadius: 6, padding: 16,
        minHeight: 196,
        display: "flex", flexDirection: "column",
        justifyContent: "center", alignItems: "stretch",
        gap: 10
      }}>
        {thinking && (
          <div style={{
            display: "flex", flexDirection: "column", gap: 8,
            fontFamily: "var(--font-mono)", fontSize: 11,
            color: "var(--ink-3)", letterSpacing: "0.02em"
          }}>
            <span>▸ parsing intent…</span>
            <span>▸ matching template…</span>
            <span>▸ writing rules…</span>
          </div>
        )}
        {!thinking && !generated && (
          <div style={{
            fontFamily: "var(--font-mono)", fontSize: 11,
            color: "var(--ink-4)", letterSpacing: "0.04em",
            textTransform: "uppercase", textAlign: "center"
          }}>
            ◌ Generated Skill will appear here
          </div>
        )}
        {!thinking && generated && (
          <SkillCard
            glyph={generated.glyph}
            name={generated.name}
            description={generated.description}
            on={true}
            badge="NEW"
            compact={true}
          />
        )}
      </div>
    </div>
  );
}

/* ----------------------------------------------------------- exports */
/* ----------------------------------------------------------- Waitlist
 * Working email-capture modal + inline form. Persists submission to
 * localStorage so reload remembers the user is on the list.
 *
 * Brief-compliant copy: no "join thousands of users", no "in seconds",
 * no "awesome". Just: request access, we'll email when there's room.
 */
function useWaitlist() {
  const [submitted, setSubmitted] = useState(() => {
    try { return !!localStorage.getItem("reo_waitlist_email"); }
    catch { return false; }
  });
  const [savedEmail, setSavedEmail] = useState(() => {
    try { return localStorage.getItem("reo_waitlist_email") || ""; }
    catch { return ""; }
  });
  const submit = (formData) => {
    const isObject = formData && typeof formData === "object";
    const email = isObject ? (formData.email || "") : (formData || "");
    try { localStorage.setItem("reo_waitlist_email", email); } catch {}
    setSavedEmail(email);
    setSubmitted(true);
    if (isObject) {
      postToSheets({ form: "waitlist", ...formData });
    }
  };
  return { submitted, savedEmail, submit };
}

function WaitlistModal({ open, onClose }) {
  const { submitted, savedEmail, submit } = useWaitlist();
  const [form, setForm] = useState({
    name: "",
    email: "",
    company: "",
    role: "",
    provider: "",
    referrer: ""
  });
  const inputRef = useRef(null);

  useEffect(() => {
    if (!open) return;
    const t = setTimeout(() => inputRef.current?.focus(), 80);
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => { clearTimeout(t); document.removeEventListener("keydown", onKey); };
  }, [open, onClose]);

  if (!open) return null;

  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email);
  const valid = form.name.trim().length >= 2 && emailValid && form.provider;

  const labelStyle = {
    fontFamily: "var(--font-mono)", fontSize: 10.5,
    color: "var(--ink-4)", letterSpacing: "0.06em",
    textTransform: "uppercase",
    display: "flex", alignItems: "center", justifyContent: "space-between"
  };
  const inputStyle = {
    height: 42, padding: "0 14px",
    fontFamily: "var(--font-sans)", fontSize: 14.5,
    color: "var(--ink)",
    background: "var(--paper-2)",
    border: "1px solid var(--rule-2)",
    borderRadius: 5, outline: "none",
    width: "100%"
  };
  const optTag = (
    <span style={{ textTransform: "none", letterSpacing: "0.02em", color: "var(--ink-4)" }}>
      optional
    </span>
  );

  return (
    <div role="dialog" aria-modal="true" onClick={onClose}
      style={{
        position: "fixed", inset: 0, zIndex: 100,
        background: "oklch(0.18 0.010 270 / 0.45)",
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: 32, backdropFilter: "blur(8px)",
        overflowY: "auto"
      }}>
      <div onClick={(e) => e.stopPropagation()}
        style={{
          width: "min(560px, 100%)", margin: "auto",
          background: "var(--paper)",
          border: "1px solid var(--rule-strong)",
          borderRadius: 8, overflow: "hidden",
          display: "flex", flexDirection: "column",
          boxShadow: "0 20px 60px oklch(0 0 0 / 0.18)"
        }}>
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          padding: "14px 22px", borderBottom: "1px solid var(--rule)"
        }}>
          <span className="eyebrow">Reo · join the waitlist</span>
          <button onClick={onClose} style={{
            background: "transparent", border: "1px solid var(--rule-2)",
            borderRadius: 4, padding: "4px 10px", fontFamily: "var(--font-sans)",
            fontSize: 12, color: "var(--ink-2)", cursor: "pointer"
          }}>Close (Esc)</button>
        </div>

        {!submitted ? (
          <form onSubmit={(e) => { e.preventDefault(); if (valid) submit(form); }}
            style={{ padding: "26px 28px 24px", display: "flex", flexDirection: "column", gap: 16 }}>
            <div>
              <h3 style={{
                fontSize: 26, lineHeight: 1.15,
                letterSpacing: "-0.02em", fontWeight: 450,
                margin: "0 0 8px 0", color: "var(--ink)", textWrap: "balance"
              }}>
                Join the waitlist.
              </h3>
              <p style={{
                fontSize: 14, lineHeight: 1.55, color: "var(--ink-3)",
                margin: 0, textWrap: "pretty"
              }}>
                We invite people in small cohorts so we can support each one well. Six quick questions — they help us figure out where to start.
              </p>
            </div>

            {/* Name + Email row */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                <label style={labelStyle}>Name</label>
                <input
                  ref={inputRef}
                  type="text"
                  value={form.name}
                  onChange={(e) => update("name", e.target.value)}
                  placeholder="Maya Chen"
                  required
                  style={inputStyle}
                  onFocus={(e) => e.target.style.borderColor = "var(--accent)"}
                  onBlur={(e) => e.target.style.borderColor = "var(--rule-2)"}
                />
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                <label style={labelStyle}>Work email</label>
                <input
                  type="email"
                  value={form.email}
                  onChange={(e) => update("email", e.target.value)}
                  placeholder="maya@company.com"
                  required
                  style={inputStyle}
                  onFocus={(e) => e.target.style.borderColor = "var(--accent)"}
                  onBlur={(e) => e.target.style.borderColor = "var(--rule-2)"}
                />
              </div>
            </div>

            {/* Company + Role row */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                <label style={labelStyle}>Company {optTag}</label>
                <input
                  type="text"
                  value={form.company}
                  onChange={(e) => update("company", e.target.value)}
                  placeholder="Acme, Inc."
                  style={inputStyle}
                  onFocus={(e) => e.target.style.borderColor = "var(--accent)"}
                  onBlur={(e) => e.target.style.borderColor = "var(--rule-2)"}
                />
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                <label style={labelStyle}>Role {optTag}</label>
                <input
                  type="text"
                  value={form.role}
                  onChange={(e) => update("role", e.target.value)}
                  placeholder="e.g. Head of CS"
                  style={inputStyle}
                  onFocus={(e) => e.target.style.borderColor = "var(--accent)"}
                  onBlur={(e) => e.target.style.borderColor = "var(--rule-2)"}
                />
              </div>
            </div>

            {/* Email provider */}
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <label style={labelStyle}>
                <span>Which email do you use?</span>
                <span style={{ textTransform: "none", letterSpacing: "0.02em", color: "var(--ink-4)" }}>
                  helps us prioritize integrations
                </span>
              </label>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8 }}>
                {[
                  { id: "gmail",   label: "Gmail" },
                  { id: "outlook", label: "Outlook" },
                  { id: "other",   label: "Other" }
                ].map(o => {
                  const active = form.provider === o.id;
                  return (
                    <button type="button" key={o.id}
                      onClick={() => update("provider", o.id)}
                      style={{
                        height: 42,
                        background: active ? "var(--accent-tint)" : "var(--paper-2)",
                        border: `1px solid ${active ? "var(--accent)" : "var(--rule-2)"}`,
                        color: active ? "var(--accent)" : "var(--ink-2)",
                        borderRadius: 5,
                        fontFamily: "var(--font-sans)", fontSize: 14,
                        fontWeight: active ? 500 : 400,
                        cursor: "pointer",
                        display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6
                      }}>
                      {active && (
                        <svg width="13" height="13" viewBox="0 0 14 14" fill="none">
                          <path d="M2 7l3.5 3.5L12 4" stroke="currentColor" strokeWidth="1.6"
                                strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                      )}
                      {o.label}
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Referrer */}
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <label style={labelStyle}>
                <span>How did you hear about Reo?</span>
                {optTag}
              </label>
              <input
                type="text"
                value={form.referrer}
                onChange={(e) => update("referrer", e.target.value)}
                placeholder="A friend, a podcast, a tweet — be specific if you can"
                style={inputStyle}
                onFocus={(e) => e.target.style.borderColor = "var(--accent)"}
                onBlur={(e) => e.target.style.borderColor = "var(--rule-2)"}
              />
            </div>

            <button type="submit" disabled={!valid}
              className="reo-cta accent"
              style={{
                opacity: valid ? 1 : 0.45,
                cursor: valid ? "pointer" : "not-allowed",
                height: 46, justifyContent: "center"
              }}>
              Join the waitlist <span className="arrow"/>
            </button>

            <div style={{
              textAlign: "center", paddingTop: 6,
              fontSize: 12.5, color: "var(--ink-4)"
            }}>
              Have a question first? <a href="#contact" onClick={(e) => {
                e.preventDefault();
                onClose();
                window.dispatchEvent(new CustomEvent("reo:open-contact"));
              }} style={{
                color: "var(--ink-2)", textDecoration: "none",
                borderBottom: "1px solid var(--rule-strong)",
                paddingBottom: 1, cursor: "pointer"
              }}>Send us a message →</a>
            </div>
          </form>
        ) : (
          <div style={{ padding: "32px 28px 28px", display: "flex", flexDirection: "column", gap: 18 }}>
            <div style={{
              width: 44, height: 44, borderRadius: 50,
              background: "var(--accent-tint)",
              border: "1px solid var(--accent-tint-2)",
              color: "var(--accent)",
              display: "inline-flex", alignItems: "center", justifyContent: "center"
            }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
                <path d="M4 12l5 5L20 6" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>
            <h3 style={{
              fontSize: 26, lineHeight: 1.15,
              letterSpacing: "-0.02em", fontWeight: 450,
              margin: 0, color: "var(--ink)"
            }}>You're on the list.</h3>
            <p style={{
              fontSize: 14.5, lineHeight: 1.55, color: "var(--ink-3)",
              margin: 0, textWrap: "pretty"
            }}>
              We'll write to <span style={{ color: "var(--ink)", fontFamily: "var(--font-mono)", fontSize: 13 }}>{savedEmail}</span> as soon as there's room — usually within a couple of weeks. One email, from a real person on the team.
            </p>
          </div>
        )}
      </div>
    </div>
  );
}

function InlineWaitlist({ onSubmitted, onExpand }) {
  const { submitted, savedEmail } = useWaitlist();

  if (submitted) {
    return (
      <div style={{
        display: "flex", alignItems: "center", gap: 14,
        padding: "14px 18px",
        background: "var(--accent-tint)",
        border: "1px solid var(--accent-tint-2)",
        borderRadius: 6, maxWidth: 560
      }}>
        <span style={{
          width: 22, height: 22, borderRadius: 50,
          background: "var(--accent)", color: "var(--paper)",
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          flexShrink: 0
        }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4">
            <path d="M4 12l5 5L20 6" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </span>
        <div style={{ flex: 1, fontSize: 14, color: "var(--ink-2)", lineHeight: 1.4 }}>
          <strong style={{ color: "var(--ink)", fontWeight: 500 }}>You're on the list.</strong>{" "}
          We'll write to <span style={{ fontFamily: "var(--font-mono)", fontSize: 13 }}>{savedEmail}</span> within two weeks.
        </div>
      </div>
    );
  }

  return (
    <button type="button" onClick={onExpand}
      className="reo-cta accent"
      style={{
        height: 52, padding: "0 28px", fontSize: 15,
        alignSelf: "flex-start"
      }}>
      Join the waitlist <span className="arrow"/>
    </button>
  );
}

Object.assign(window, {
  Glyph, ReoMark, SourceChip, AudienceTag, InsightCard,
  SkillCard, Annotation, ChromeBar, ComplianceBadge,
  FAQItem, DemoModal, BuildYourOwn,
  useWaitlist, WaitlistModal, InlineWaitlist, ContactModal
});

/* ----------------------------------------------------------- ContactModal
 * For website visitors who have a question instead of (or before) joining
 * the waitlist. Three fields, sober copy, "real person reads this." */
function ContactModal({ open, onClose }) {
  const [form, setForm] = useState({ name: "", email: "", topic: "general", message: "" });
  const [sent, setSent] = useState(false);
  const inputRef = useRef(null);

  useEffect(() => {
    if (!open) return;
    const t = setTimeout(() => inputRef.current?.focus(), 80);
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => { clearTimeout(t); document.removeEventListener("keydown", onKey); };
  }, [open, onClose]);

  useEffect(() => { if (!open) setSent(false); }, [open]);

  if (!open) return null;

  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email);
  const valid = form.name.trim().length >= 2 && emailValid && form.message.trim().length >= 10;

  const topics = [
    { id: "general",     label: "General question" },
    { id: "privacy",     label: "Privacy / security" },
    { id: "enterprise",  label: "Enterprise / SSO" },
    { id: "partnership", label: "Partnership" }
  ];

  const labelStyle = {
    fontFamily: "var(--font-mono)", fontSize: 10.5,
    color: "var(--ink-4)", letterSpacing: "0.06em",
    textTransform: "uppercase"
  };
  const inputStyle = {
    height: 42, padding: "0 14px",
    fontFamily: "var(--font-sans)", fontSize: 14.5,
    color: "var(--ink)",
    background: "var(--paper-2)",
    border: "1px solid var(--rule-2)",
    borderRadius: 5, outline: "none",
    width: "100%"
  };

  return (
    <div role="dialog" aria-modal="true" onClick={onClose}
      style={{
        position: "fixed", inset: 0, zIndex: 100,
        background: "oklch(0.18 0.010 270 / 0.45)",
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: 32, backdropFilter: "blur(8px)", overflowY: "auto"
      }}>
      <div onClick={(e) => e.stopPropagation()}
        style={{
          width: "min(540px, 100%)", margin: "auto",
          background: "var(--paper)",
          border: "1px solid var(--rule-strong)",
          borderRadius: 8, overflow: "hidden",
          boxShadow: "0 20px 60px oklch(0 0 0 / 0.18)",
          display: "flex", flexDirection: "column"
        }}>
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          padding: "14px 22px", borderBottom: "1px solid var(--rule)"
        }}>
          <span className="eyebrow">Reo · ask us anything</span>
          <button onClick={onClose} style={{
            background: "transparent", border: "1px solid var(--rule-2)",
            borderRadius: 4, padding: "4px 10px", fontFamily: "var(--font-sans)",
            fontSize: 12, color: "var(--ink-2)", cursor: "pointer"
          }}>Close (Esc)</button>
        </div>

        {!sent ? (
          <form onSubmit={(e) => {
              e.preventDefault();
              if (!valid) return;
              postToSheets({ form: "contact", ...form });
              setSent(true);
            }}
            style={{ padding: "24px 28px 22px", display: "flex", flexDirection: "column", gap: 16 }}>
            <div>
              <h3 style={{
                fontSize: 26, lineHeight: 1.15,
                letterSpacing: "-0.02em", fontWeight: 450,
                margin: "0 0 8px 0", color: "var(--ink)", textWrap: "balance"
              }}>
                Ask us anything.
              </h3>
              <p style={{
                fontSize: 14, lineHeight: 1.55, color: "var(--ink-3)",
                margin: 0, textWrap: "pretty"
              }}>
                A real person on the team reads every message. Usually we reply within one business day.
              </p>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                <label style={labelStyle}>Name</label>
                <input ref={inputRef} type="text" value={form.name}
                  onChange={(e) => update("name", e.target.value)}
                  placeholder="Maya Chen" required style={inputStyle}
                  onFocus={(e) => e.target.style.borderColor = "var(--accent)"}
                  onBlur={(e) => e.target.style.borderColor = "var(--rule-2)"}/>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                <label style={labelStyle}>Email</label>
                <input type="email" value={form.email}
                  onChange={(e) => update("email", e.target.value)}
                  placeholder="maya@company.com" required style={inputStyle}
                  onFocus={(e) => e.target.style.borderColor = "var(--accent)"}
                  onBlur={(e) => e.target.style.borderColor = "var(--rule-2)"}/>
              </div>
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <label style={labelStyle}>Topic</label>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
                {topics.map(t => {
                  const active = form.topic === t.id;
                  return (
                    <button type="button" key={t.id}
                      onClick={() => update("topic", t.id)}
                      style={{
                        height: 36,
                        background: active ? "var(--accent-tint)" : "var(--paper-2)",
                        border: `1px solid ${active ? "var(--accent)" : "var(--rule-2)"}`,
                        color: active ? "var(--accent)" : "var(--ink-2)",
                        borderRadius: 4,
                        fontFamily: "var(--font-sans)", fontSize: 13,
                        fontWeight: active ? 500 : 400,
                        cursor: "pointer"
                      }}>{t.label}</button>
                  );
                })}
              </div>
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <label style={labelStyle}>Your question</label>
              <textarea value={form.message}
                onChange={(e) => update("message", e.target.value)}
                placeholder="What would you like to know? Be specific if you can."
                rows={4} required
                style={{
                  ...inputStyle, height: "auto", padding: "10px 14px",
                  resize: "vertical", fontFamily: "var(--font-sans)",
                  lineHeight: 1.5
                }}
                onFocus={(e) => e.target.style.borderColor = "var(--accent)"}
                onBlur={(e) => e.target.style.borderColor = "var(--rule-2)"}/>
            </div>

            <button type="submit" disabled={!valid}
              className="reo-cta accent"
              style={{
                opacity: valid ? 1 : 0.45,
                cursor: valid ? "pointer" : "not-allowed",
                height: 46, justifyContent: "center"
              }}>
              Send message <span className="arrow"/>
            </button>
          </form>
        ) : (
          <div style={{ padding: "32px 28px 28px", display: "flex", flexDirection: "column", gap: 18 }}>
            <div style={{
              width: 44, height: 44, borderRadius: 50,
              background: "var(--accent-tint)",
              border: "1px solid var(--accent-tint-2)",
              color: "var(--accent)",
              display: "inline-flex", alignItems: "center", justifyContent: "center"
            }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
                <path d="M4 12l5 5L20 6" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>
            <h3 style={{
              fontSize: 26, lineHeight: 1.15,
              letterSpacing: "-0.02em", fontWeight: 450,
              margin: 0, color: "var(--ink)"
            }}>Message sent.</h3>
            <p style={{
              fontSize: 14.5, lineHeight: 1.55, color: "var(--ink-3)",
              margin: 0, textWrap: "pretty"
            }}>
              We'll reply to <span style={{ color: "var(--ink)", fontFamily: "var(--font-mono)", fontSize: 13 }}>{form.email}</span> within one business day. From a real person on the team.
            </p>
            <button onClick={onClose} style={{
              alignSelf: "flex-start",
              background: "transparent",
              border: "1px solid var(--rule-2)",
              padding: "8px 14px", borderRadius: 4,
              fontFamily: "var(--font-sans)", fontSize: 13,
              color: "var(--ink-2)", cursor: "pointer"
            }}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
}
