// ============ MODALS ============
// Two modals: Architect (build-an-agent), Sign in (auth).
// Shared overlay shell with backdrop click + ESC + focus trap.

const { useState: useMState, useEffect: useMEffect, useRef: useMRef } = React;
const CharacterAvatar = window.CharacterAvatar;

function Modal({ open, onClose, children, label }) {
  useMEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = prev;
    };
  }, [open, onClose]);

  if (!open) return null;
  return (
    <div className="modal-root" role="dialog" aria-modal="true" aria-label={label}>
      <div className="modal-backdrop" onClick={onClose} />
      <div className="modal-card">
        <button className="modal-close" onClick={onClose} aria-label="Close">
          <svg width="14" height="14" viewBox="0 0 14 14"><path d="M2 2 L 12 12 M 12 2 L 2 12" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" /></svg>
        </button>
        {children}
      </div>
    </div>
  );
}

// ============ ARCHITECT MODAL ============
const ARCH_PALETTES = [
  { skin: "#E85D1A", skinDark: "#B84410", accent: "#FFCA7D", visor: "#1A120B" },
  { skin: "#2DAF6B", skinDark: "#196C42", accent: "#A6E8C7", visor: "#0A1F14" },
  { skin: "#3B7CFF", skinDark: "#1F4FB5", accent: "#A6D8FF", visor: "#0E1A30" },
  { skin: "#B4488C", skinDark: "#742855", accent: "#F2C8E0", visor: "#1F0A18" },
  { skin: "#D9A23C", skinDark: "#8A5F18", accent: "#FFE0A1", visor: "#1F1608" },
];
const ARCH_GLYPHS = ["◍", "✺", "✦", "❖", "◆", "◐"];
const ARCH_NAMES = ["NOVA", "ATLAS", "SAGE", "ARIA", "JUNO", "REMI", "KAI", "PIPER", "ECHO", "WREN"];

// Tools the user can drag onto an agent. Order matches the chip palette.
const ARCH_AVAILABLE_TOOLS = [
  "WhatsApp", "Email", "Sheets", "Stripe", "Calendar", "QuickBooks",
  "Phone", "Slack", "DocuSign", "Drive", "CRM", "Web",
];
const ARCH_TOOL_COLORS = {
  WhatsApp: "#25D366", Email: "#EA4335", Sheets: "#0F9D58", Stripe: "#635BFF",
  Calendar: "#4285F4", QuickBooks: "#2CA01C", Phone: "#1A120B", Slack: "#4A154B",
  DocuSign: "#FFCC00", Drive: "#1FA463", CRM: "#FF7A59", Web: "#3B7CFF",
};
const ARCH_PERSONALITIES = [
  { id: "warm",     label: "Warm",     hint: "Friendly, patient, never rushed."     },
  { id: "direct",   label: "Direct",   hint: "Short, clear, no fluff."              },
  { id: "cautious", label: "Cautious", hint: "Asks twice, ships once. Loops you in." },
];

// ============ BEHAVIOR BLOCKS ============
// The agent's logic, expressed as drag-and-drop blocks the user assembles
// into a "WHEN / DO / IF YOU CAN'T" rule. Each block carries:
//   id        — stable key
//   icon      — emoji / glyph in the chip
//   label     — short text shown on the block
//   sentence  — the snippet inserted into the synthesized brief
//   tool      — optional tool name to seed onto the agent
const ARCH_TRIGGERS = [
  { id: "wa-msg",   icon: "💬", label: "Customer texts on WhatsApp",      sentence: "a customer texts on WhatsApp",       tool: "WhatsApp" },
  { id: "email-in", icon: "✉",  label: "Email arrives",                   sentence: "a new email arrives",                tool: "Email" },
  { id: "monday",   icon: "📅", label: "Every Monday at 9am",             sentence: "it's Monday at 9am",                 tool: null },
  { id: "forward",  icon: "↪",  label: "You forward something",           sentence: "you forward something to it",        tool: "Email" },
  { id: "review",   icon: "★",  label: "A review is posted",              sentence: "a new review is posted",             tool: "Web" },
  { id: "lead-new", icon: "✦",  label: "A new lead comes in",             sentence: "a new lead lands in the inbox",      tool: "CRM" },
  { id: "form-sub", icon: "▤",  label: "Someone fills the website form",  sentence: "someone fills out the website form", tool: "Web" },
  { id: "doc-up",   icon: "□",  label: "A document is uploaded",          sentence: "a document is uploaded",             tool: "Drive" },
];
const ARCH_ACTIONS = [
  { id: "answer",   icon: "✓", label: "Try to answer it",                sentence: "try to answer it from the FAQ",     tool: null },
  { id: "reply",    icon: "→", label: "Send a friendly reply",           sentence: "send a friendly reply",             tool: null },
  { id: "book",     icon: "📅", label: "Book a meeting",                  sentence: "book a meeting",                    tool: "Calendar" },
  { id: "lead",     icon: "✦", label: "Capture them as a lead",          sentence: "capture them as a lead",            tool: "Sheets" },
  { id: "summary",  icon: "▦", label: "Write a summary",                 sentence: "write me a short summary",          tool: null },
  { id: "draft",    icon: "✎", label: "Draft a response for me",         sentence: "draft a response for me",           tool: null },
  { id: "tag",      icon: "◇", label: "Tag the conversation",            sentence: "tag the conversation",              tool: "CRM" },
  { id: "log",      icon: "≡", label: "Log it in the spreadsheet",       sentence: "log it in the spreadsheet",         tool: "Sheets" },
];
const ARCH_FALLBACKS = [
  { id: "ping-phone", icon: "📞", label: "Ping me by phone",      sentence: "ping me by phone",                  tool: "Phone" },
  { id: "ping-email", icon: "✉",  label: "Email me",              sentence: "email me",                          tool: "Email" },
  { id: "ping-slack", icon: "#",  label: "Message me in Slack",   sentence: "message me in Slack",               tool: "Slack" },
  { id: "approval",   icon: "✓",  label: "Wait for my approval",  sentence: "wait for my approval before sending", tool: null },
  { id: "log-only",   icon: "▦",  label: "Just log it for me",    sentence: "just log it so I can review later",  tool: "Sheets" },
];

// Templates pre-fill the rule. One click and you have a working agent.
const ARCH_TEMPLATES = [
  { id: "wa-help",   label: "WhatsApp helper",     when: "wa-msg",   do: ["answer"],            fallback: "ping-phone" },
  { id: "lead-grab", label: "Lead grabber",        when: "form-sub", do: ["lead", "reply"],     fallback: "ping-email" },
  { id: "monday-rep",label: "Monday morning report", when: "monday",   do: ["summary"],         fallback: "ping-email" },
  { id: "contract",  label: "Contract reader",     when: "forward",  do: ["draft"],             fallback: "ping-email" },
];

const ARCH_BLOCKS_BY_ID = {};
[...ARCH_TRIGGERS, ...ARCH_ACTIONS, ...ARCH_FALLBACKS].forEach(b => { ARCH_BLOCKS_BY_ID[b.id] = b; });

function archBriefFromFlow(flow) {
  const w = flow.when ? ARCH_BLOCKS_BY_ID[flow.when] : null;
  const ds = flow.do.map(id => ARCH_BLOCKS_BY_ID[id]).filter(Boolean);
  const f = flow.fallback ? ARCH_BLOCKS_BY_ID[flow.fallback] : null;
  if (!w && ds.length === 0) return "";
  let s = "";
  if (w) s += "When " + w.sentence + ", ";
  if (ds.length === 0) s += "do something useful.";
  else if (ds.length === 1) s += ds[0].sentence + ".";
  else s += ds.slice(0, -1).map(d => d.sentence).join(", ") + ", and " + ds[ds.length - 1].sentence + ".";
  if (f) s += " If you can't, " + f.sentence + ".";
  return s.charAt(0).toUpperCase() + s.slice(1);
}
function archToolsFromFlow(flow) {
  const all = [
    flow.when ? ARCH_BLOCKS_BY_ID[flow.when]?.tool : null,
    ...flow.do.map(id => ARCH_BLOCKS_BY_ID[id]?.tool),
    flow.fallback ? ARCH_BLOCKS_BY_ID[flow.fallback]?.tool : null,
  ].filter(Boolean);
  // dedupe preserving order
  const seen = new Set();
  return all.filter((t) => seen.has(t) ? false : (seen.add(t), true)).slice(0, 4);
}

// Best-effort tool detection from the user's brief.
// Order matters — first match wins for overlapping concepts.
const ARCH_TOOL_RULES = [
  ["WhatsApp",   /\bwhatsapp\b/i],
  ["Email",      /\bemail\b|\bgmail\b|\binbox\b|\bnewsletter\b/i],
  ["Sheets",     /\bsheets?\b|\bspreadsheets?\b/i],
  ["Stripe",     /\bstripe\b|\brefunds?\b|\bcharges?\b|\bpayouts?\b/i],
  ["Calendar",   /\bcalendar\b|\bmeetings?\b|\bschedule\b|\bbook(?:ing)?s?\b/i],
  ["QuickBooks", /\bquickbooks\b|\baccounting\b|\bbooks?\b|\binvoices?\b/i],
  ["Phone",      /\bphone\b|\bsms\b|\bcall(?:s|ing)?\b/i],
  ["Slack",      /\bslack\b|\bstand[- ]?up\b/i],
  ["DocuSign",   /\bcontracts?\b|\bsigning?\b|\bdocusign\b|\bnda\b|\blegal\b/i],
  ["Drive",      /\bdrive\b|\bdocuments?\b|\bfiles?\b|\bone[- ]?drive\b/i],
  ["CRM",        /\bcrm\b|\bhubspot\b|\bsalesforce\b|\bleads?\b/i],
];
function archDetectTools(text) {
  const hits = ARCH_TOOL_RULES.filter(([, re]) => re.test(text)).map(([name]) => name);
  return hits.length ? hits.slice(0, 4) : ["Email"];
}

function ArchitectModal({ open, preset, onClose, onCreate, agents = [] }) {
  const [phase, setPhase] = useMState("mode"); // mode | behavior | equip | building | done
  const [agent, setAgent] = useMState(null);
  const [step, setStep] = useMState(0);

  // Creation mode state
  const [creationMode, setCreationMode] = useMState("new"); // new | copy | instantiate | inherit
  const [sourceAgentId, setSourceAgentId] = useMState(null);
  const [draftName, setDraftName] = useMState("");

  // Behavior-phase state — the rule the user assembles from blocks.
  const [flow, setFlow]       = useMState({ when: null, do: [], fallback: null });
  const [paletteTab, setTab]  = useMState("triggers"); // triggers | actions | fallbacks
  const [bSlot, setBSlot]     = useMState(null); // {kind, idx} for drag-over highlight
  const [bSnap, setBSnap]     = useMState(null); // recently-filled slot key for animation

  // Equip-phase state. Slots is a fixed-length 4 array of tool names or null.
  const [slots, setSlots]             = useMState([null, null, null, null]);
  const [pIdx, setPIdx]               = useMState(0);
  const [gIdx, setGIdx]               = useMState(0);
  const [name, setName]               = useMState("ATLAS");
  const [personality, setPersonality] = useMState("direct");
  const [approval, setApproval]       = useMState(true);
  const [dragOver, setDragOver]       = useMState(null); // slot index being hovered
  const [snap, setSnap]               = useMState(null); // slot index that just got filled (for animation)

  // Synthesized brief is the user-facing outcome of the block flow.
  const text = archBriefFromFlow(flow);

  // reset when re-opened — honor preset if one was passed (e.g. from a
  // recommendation card in Settings or the empty-state quick-starts).
  useMEffect(() => {
    if (open) {
      const seedFlow = preset && preset.flow
        ? { when: preset.flow.when || null, do: [...(preset.flow.do || [])], fallback: preset.flow.fallback || null }
        : { when: null, do: [], fallback: null };
      // If a preset is passed, skip mode selection and go straight to behavior
      setPhase(preset ? "behavior" : "mode");
      setAgent(null); setStep(0);
      setCreationMode("new"); setSourceAgentId(null); setDraftName("");
      setFlow(seedFlow);
      setTab("triggers"); setBSlot(null); setBSnap(null);
      setSlots([null, null, null, null]);
      setPIdx(0); setGIdx(0);
      setName((preset && preset.name) || ARCH_NAMES[Math.floor(Math.random() * ARCH_NAMES.length)]);
      setPersonality("direct"); setApproval(true);
      setDragOver(null); setSnap(null);
    }
  }, [open]);

  // build steps — short and snappy now since the user already did the equip work.
  useMEffect(() => {
    if (phase !== "building") return;
    const steps = [200, 500, 850];
    const timers = steps.map((ms, i) => setTimeout(() => setStep(i + 1), ms));
    const finish = setTimeout(() => {
      let fullAgent;

      if (creationMode !== "new" && sourceAgentId) {
        // Derived modes — construct agent locally from source data
        const src = agents.find((a) => a.id === sourceAgentId);
        if (!src) { setPhase("mode"); return; }
        const newId = `a${Date.now().toString(36).slice(-6)}`;
        const newName = (draftName.trim() || `${src.name}2`).toUpperCase().slice(0, 8);
        const base = {
          id: newId, name: newName,
          role: src.role, brief: src.brief, tools: [...(src.tools || [])],
          personality: src.personality, approvalGate: src.approvalGate,
          channels: {}, voice: src.voice, avoid: src.avoid, company: src.company,
          palette: { ...src.palette }, glyph: src.glyph,
          status: "live", rating: 0, runs: 0,
          spark: Array(12).fill(0), sparkLabel: "Tasks / day",
          metrics: { "Tasks done": "0", "Avg reply": "—", "Hours saved": "0" },
          accuracy: 0,
          version: "1.0.0", versionHistory: [],
          // tell the server which mode this is so it can handle knowledge copy etc.
          mode: creationMode, sourceId: src.id,
        };
        if (creationMode === "copy") {
          fullAgent = { ...base, learnings: JSON.parse(JSON.stringify(src.learnings || [])), learnedAt: src.learnedAt || null };
        } else if (creationMode === "inherit") {
          fullAgent = { ...base, learnings: JSON.parse(JSON.stringify(src.learnings || [])), learnedAt: src.learnedAt || null, parentId: src.id };
        } else {
          fullAgent = { ...base, learnings: [] }; // instantiate: fresh slate
        }
      } else {
        // Original "new" flow
        const palette  = ARCH_PALETTES[pIdx];
        const glyph    = ARCH_GLYPHS[gIdx];
        const roleGuess = text.split(/[.\n]/)[0].slice(0, 60).trim() || "your custom agent";
        const filledTools = slots.filter(Boolean);
        fullAgent = {
          id: `a${Date.now().toString(36).slice(-6)}`,
          name: (name || "AGENT").toUpperCase(),
          role: roleGuess,
          status: "training",
          rating: 0,
          palette,
          glyph,
          brief: text.trim(),
          tools: filledTools.length ? filledTools : archDetectTools(text),
          metrics: { "Tasks done": "0", "Avg reply": "—", "Hours saved": "0" },
          spark: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
          sparkLabel: "Tasks / day",
          accuracy: 0,
          runs: 0,
          personality,
          approvalGate: approval,
        };
      }

      setAgent(fullAgent);
      setPhase("done");
    }, 1200);
    return () => { timers.forEach(clearTimeout); clearTimeout(finish); };
  }, [phase, creationMode, sourceAgentId, draftName, agents, text, slots, pIdx, gIdx, name, personality, approval]);

  // Move from "behavior" → "equip", seeding slots from the flow's tools.
  const handleSubmit = (e) => {
    e?.preventDefault();
    if (!flow.when || flow.do.length === 0) return;
    const detected = archToolsFromFlow(flow);
    const seeded = [null, null, null, null];
    detected.forEach((t, i) => { if (i < 4) seeded[i] = t; });
    setSlots(seeded);
    setPIdx(Math.floor(Math.random() * ARCH_PALETTES.length));
    setGIdx(Math.floor(Math.random() * ARCH_GLYPHS.length));
    setPhase("equip");
  };

  // Behavior-phase block helpers
  const blockKey = (kind, idx) => kind + (idx === undefined ? "" : ":" + idx);
  const flashSnap = (kind, idx) => {
    const k = blockKey(kind, idx);
    setBSnap(k);
    setTimeout(() => setBSnap((cur) => cur === k ? null : cur), 380);
  };
  const placeBlock = (block) => {
    // Pick the "natural" target slot by category, prefer the empty next slot.
    const isTrigger  = ARCH_TRIGGERS.some(t => t.id === block.id);
    const isAction   = ARCH_ACTIONS.some(a => a.id === block.id);
    const isFallback = ARCH_FALLBACKS.some(f => f.id === block.id);
    if (isTrigger)        { setFlow((f) => ({ ...f, when: block.id })); flashSnap("when"); }
    else if (isFallback)  { setFlow((f) => ({ ...f, fallback: block.id })); flashSnap("fallback"); }
    else if (isAction) {
      setFlow((f) => {
        if (f.do.includes(block.id)) return f;
        if (f.do.length >= 3) return f;
        return { ...f, do: [...f.do, block.id] };
      });
      flashSnap("do", flow.do.length);
    }
  };
  const dropOnFlowSlot = (kind, idx, e) => {
    e.preventDefault();
    setBSlot(null);
    const id = e.dataTransfer.getData("text/plain");
    const block = ARCH_BLOCKS_BY_ID[id];
    if (!block) return;
    if (kind === "when" && ARCH_TRIGGERS.some(t => t.id === id))     { setFlow((f) => ({ ...f, when: id })); flashSnap("when"); }
    else if (kind === "fallback" && ARCH_FALLBACKS.some(t => t.id === id)) { setFlow((f) => ({ ...f, fallback: id })); flashSnap("fallback"); }
    else if (kind === "do" && ARCH_ACTIONS.some(t => t.id === id)) {
      setFlow((f) => {
        const without = f.do.filter((x) => x !== id);
        const next = [...without];
        // Replace the targeted slot, or append if past the end
        if (idx < next.length) next[idx] = id;
        else next.push(id);
        return { ...f, do: next.slice(0, 3) };
      });
      flashSnap("do", idx);
    } else {
      placeBlock(block); // wrong-zone drop — still try the natural place
    }
  };
  const removeFromFlow = (kind, idx) => {
    if (kind === "when")     setFlow((f) => ({ ...f, when: null }));
    else if (kind === "fallback") setFlow((f) => ({ ...f, fallback: null }));
    else if (kind === "do")  setFlow((f) => ({ ...f, do: f.do.filter((_, i) => i !== idx) }));
  };
  const applyTemplate = (tpl) => {
    setFlow({ when: tpl.when, do: [...tpl.do], fallback: tpl.fallback });
    flashSnap("template");
  };
  const blockInFlow = (id) => flow.when === id || flow.do.includes(id) || flow.fallback === id;
  const flowReady = !!flow.when && flow.do.length > 0;

  const hire = () => {
    setStep(0);
    setPhase("building");
  };

  // Derived palette/glyph — from source agent for non-new modes, from pIdx/gIdx for new.
  const srcAgent  = agents.find((a) => a.id === sourceAgentId);
  const palette   = creationMode !== "new" && srcAgent ? srcAgent.palette : ARCH_PALETTES[pIdx];
  const glyph     = creationMode !== "new" && srcAgent ? srcAgent.glyph  : ARCH_GLYPHS[gIdx];
  const roleGuess = (creationMode !== "new" && srcAgent)
    ? srcAgent.role
    : (text.split(/[.\n]/)[0].slice(0, 60).trim() || "your custom agent");

  // Drag handlers for tool chips → slots.
  const dropOnSlot = (idx, tool) => {
    if (!tool) return;
    setSlots((prev) => {
      const next = [...prev];
      // If the tool is already in another slot, clear it first (a tool can
      // only occupy one slot at a time).
      const existing = next.indexOf(tool);
      if (existing !== -1 && existing !== idx) next[existing] = null;
      next[idx] = tool;
      return next;
    });
    setSnap(idx);
    setTimeout(() => setSnap(null), 380);
  };
  const onDropSlot = (e, idx) => {
    e.preventDefault();
    setDragOver(null);
    const tool = e.dataTransfer.getData("text/plain");
    if (tool) dropOnSlot(idx, tool);
  };
  const removeFromSlot = (idx) => {
    setSlots((prev) => {
      const next = [...prev];
      next[idx] = null;
      return next;
    });
  };
  const addToFirstEmpty = (tool) => {
    if (slots.includes(tool)) return;
    const empty = slots.findIndex((s) => s === null);
    if (empty === -1) return;
    dropOnSlot(empty, tool);
  };

  const filledCount = slots.filter(Boolean).length;

  const palettes = {
    triggers:  { label: "Triggers",  blocks: ARCH_TRIGGERS,  hint: "Pick when this agent kicks in." },
    actions:   { label: "Actions",   blocks: ARCH_ACTIONS,   hint: "Pick what it does (up to 3)." },
    fallbacks: { label: "Fallbacks", blocks: ARCH_FALLBACKS, hint: "Pick what to do if it gets stuck." },
  };

  return (
    <Modal open={open} onClose={onClose} label="Build a custom agent">
      <div className={`arch ${phase === "behavior" || phase === "equip" ? "arch-wide" : ""}`}>
        <header className="arch-head">
          <span className="arch-tag">
            {phase === "mode"     ? "Choose how to start" :
             phase === "behavior" ? "Step 1 of 2 · Build the rules" :
             phase === "equip"    ? "Step 2 of 2 · Equip your agent" :
             phase === "building" ? "Hiring…" :
                                    "Architect · build your own"}
          </span>
          <h3 className="arch-title">
            {phase === "mode"     ? "Hire someone new." :
             phase === "behavior" ? "Teach it what to do." :
             phase === "equip"    ? "Now make it yours." :
             phase === "building" ? "Putting it together…" :
                                    "Meet your new agent."}
          </h3>
          <p className="arch-sub">
            {phase === "mode"     ? "Pick how this agent comes into the world." :
             phase === "behavior" ? "Drag blocks into the slots — like Lego." :
             phase === "equip"    ? "Drag tools onto its slots. Pick a vibe. Name it." :
             ""}
          </p>
        </header>

        {/* ---- MODE SELECTION ---- */}
        {phase === "mode" && (
          <div className="arch-mode">
            <div className="arch-mode-grid">
              {[
                { id: "new",         icon: "✦", title: "Build new",     desc: "Start from scratch with the rule builder.", soon: false },
                { id: "copy",        icon: "⊕", title: "Copy",          desc: "Full clone — same config, skills, and knowledge.",            soon: true },
                { id: "instantiate", icon: "◈", title: "Instantiate",   desc: "Same config, clean slate — no learnings or history.",        soon: true },
                { id: "inherit",     icon: "◎", title: "Inherit",       desc: "Born from a parent — carries their learnings but grows independently.", soon: true },
              ].map((m) => (
                <button
                  key={m.id}
                  type="button"
                  className={`arch-mode-card ${creationMode === m.id ? "is-on" : ""}${m.soon ? " arch-mode-card--soon" : ""}`}
                  onClick={() => { if (m.soon) return; setCreationMode(m.id); if (m.id === "new") setSourceAgentId(null); }}
                  disabled={m.soon}
                  title={m.soon ? "Coming soon" : undefined}
                >
                  <span className="arch-mode-icon">{m.icon}</span>
                  <span className="arch-mode-title">{m.title}{m.soon ? <span className="arch-mode-soon-badge">Soon</span> : null}</span>
                  <span className="arch-mode-desc">{m.desc}</span>
                </button>
              ))}
            </div>

            {creationMode !== "new" && (
              <div className="arch-mode-source">
                <div className="arch-mode-source-h">Pick a source agent</div>
                {agents.length === 0 ? (
                  <div className="arch-mode-source-empty">No agents yet — create one first with "Build new".</div>
                ) : (
                  <div className="arch-mode-source-list">
                    {agents.map((a) => (
                      <button
                        key={a.id}
                        type="button"
                        className={`arch-mode-agent ${sourceAgentId === a.id ? "is-on" : ""}`}
                        onClick={() => { setSourceAgentId(a.id); setDraftName(`${a.name}2`); }}
                        style={{ "--agent-skin": a.palette.skin, "--agent-accent": a.palette.accent }}
                      >
                        <span className="arch-mode-agent-glyph" style={{ background: `radial-gradient(circle at 30% 30%, ${a.palette.accent}, ${a.palette.skin})` }}>{a.glyph}</span>
                        <div className="arch-mode-agent-meta">
                          <div className="arch-mode-agent-name">{a.name}</div>
                          <div className="arch-mode-agent-role">{a.role}</div>
                        </div>
                        {a.version && <span className="arch-mode-agent-ver">v{a.version}</span>}
                      </button>
                    ))}
                  </div>
                )}
                {sourceAgentId && (
                  <div className="arch-mode-name-row">
                    <label className="arch-mode-name-lbl">New agent name</label>
                    <input
                      className="arch-equip-name arch-mode-name-input"
                      value={draftName}
                      onChange={(e) => setDraftName(e.target.value.replace(/[^a-zA-Z0-9 ]/g, "").toUpperCase().slice(0, 8))}
                      placeholder="NOVA"
                    />
                  </div>
                )}
              </div>
            )}

            <div className="arch-equip-foot">
              <span />
              <button
                type="button"
                className="btn btn-primary"
                onClick={() => {
                  if (creationMode === "new") {
                    setPhase("behavior");
                  } else if (sourceAgentId && draftName.trim()) {
                    setStep(0);
                    setPhase("building");
                  }
                }}
                disabled={creationMode !== "new" && (!sourceAgentId || !draftName.trim())}
              >
                {creationMode === "new"
                  ? "Build from scratch"
                  : `${creationMode.charAt(0).toUpperCase() + creationMode.slice(1)} this agent`}
                <svg width="14" height="14" viewBox="0 0 14 14"><path d="M1 7h11M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
              </button>
            </div>
          </div>
        )}

        {phase === "behavior" && (
          <div className="arch-behavior">
            <div className="arch-behavior-grid">
              {/* LEFT — the rule, with drop zones */}
              <div className="arch-rule">
                {/* WHEN */}
                <div className="arch-rule-block">
                  <div className="arch-rule-h"><span className="arch-rule-h-l">WHEN</span><span className="arch-rule-h-c">trigger · 1</span></div>
                  <div
                    className={`arch-rule-slot arch-rule-slot-when ${flow.when ? "is-filled" : ""} ${bSlot === "when" ? "is-over" : ""} ${bSnap === "when" ? "is-snap" : ""}`}
                    onDragOver={(e) => { e.preventDefault(); setBSlot("when"); }}
                    onDragLeave={() => setBSlot((s) => s === "when" ? null : s)}
                    onDrop={(e) => dropOnFlowSlot("when", 0, e)}
                    onClick={() => flow.when && removeFromFlow("when")}
                  >
                    {flow.when ? (
                      <div className="arch-block arch-block-trigger">
                        <span className="arch-block-icon">{ARCH_BLOCKS_BY_ID[flow.when].icon}</span>
                        <span className="arch-block-label">{ARCH_BLOCKS_BY_ID[flow.when].label}</span>
                        <span className="arch-block-x">×</span>
                      </div>
                    ) : (
                      <div className="arch-rule-empty"><span className="arch-rule-empty-plus">+</span> Drop a trigger</div>
                    )}
                  </div>
                </div>

                <div className="arch-rule-arrow">↓</div>

                {/* DO */}
                <div className="arch-rule-block">
                  <div className="arch-rule-h"><span className="arch-rule-h-l">DO</span><span className="arch-rule-h-c">{flow.do.length} / 3</span></div>
                  <div className="arch-rule-do-list">
                    {[0, 1, 2].map((i) => {
                      const id = flow.do[i];
                      const filled = !!id;
                      const overKey = "do:" + i;
                      const snapKey = "do:" + i;
                      return (
                        <div
                          key={i}
                          className={`arch-rule-slot arch-rule-slot-do ${filled ? "is-filled" : ""} ${bSlot === overKey ? "is-over" : ""} ${bSnap === snapKey ? "is-snap" : ""}`}
                          onDragOver={(e) => { e.preventDefault(); setBSlot(overKey); }}
                          onDragLeave={() => setBSlot((s) => s === overKey ? null : s)}
                          onDrop={(e) => dropOnFlowSlot("do", i, e)}
                          onClick={() => filled && removeFromFlow("do", i)}
                        >
                          {filled ? (
                            <div className="arch-block arch-block-action">
                              <span className="arch-block-icon">{ARCH_BLOCKS_BY_ID[id].icon}</span>
                              <span className="arch-block-label">{ARCH_BLOCKS_BY_ID[id].label}</span>
                              <span className="arch-block-x">×</span>
                            </div>
                          ) : (
                            <div className="arch-rule-empty"><span className="arch-rule-empty-plus">+</span> {i === 0 ? "Drop an action" : "Optional"}</div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </div>

                <div className="arch-rule-arrow">↓</div>

                {/* IF YOU CAN'T */}
                <div className="arch-rule-block">
                  <div className="arch-rule-h"><span className="arch-rule-h-l">IF YOU CAN'T</span><span className="arch-rule-h-c">optional</span></div>
                  <div
                    className={`arch-rule-slot arch-rule-slot-fallback ${flow.fallback ? "is-filled" : ""} ${bSlot === "fallback" ? "is-over" : ""} ${bSnap === "fallback" ? "is-snap" : ""}`}
                    onDragOver={(e) => { e.preventDefault(); setBSlot("fallback"); }}
                    onDragLeave={() => setBSlot((s) => s === "fallback" ? null : s)}
                    onDrop={(e) => dropOnFlowSlot("fallback", 0, e)}
                    onClick={() => flow.fallback && removeFromFlow("fallback")}
                  >
                    {flow.fallback ? (
                      <div className="arch-block arch-block-fallback">
                        <span className="arch-block-icon">{ARCH_BLOCKS_BY_ID[flow.fallback].icon}</span>
                        <span className="arch-block-label">{ARCH_BLOCKS_BY_ID[flow.fallback].label}</span>
                        <span className="arch-block-x">×</span>
                      </div>
                    ) : (
                      <div className="arch-rule-empty"><span className="arch-rule-empty-plus">+</span> Drop a fallback</div>
                    )}
                  </div>
                </div>

                {/* Live sentence preview */}
                <div className={`arch-sentence ${flowReady ? "is-on" : ""}`}>
                  <div className="arch-sentence-quote">"</div>
                  {text || <span className="arch-sentence-stub">Your agent's instructions will appear here as you build.</span>}
                </div>
              </div>

              {/* RIGHT — block palette */}
              <div className="arch-palette">
                <div className="arch-palette-tabs">
                  {Object.entries(palettes).map(([k, p]) => (
                    <button
                      key={k}
                      type="button"
                      className={`arch-palette-tab arch-palette-tab-${k} ${paletteTab === k ? "is-on" : ""}`}
                      onClick={() => setTab(k)}
                    >
                      {p.label}
                    </button>
                  ))}
                </div>
                <div className="arch-palette-hint">{palettes[paletteTab].hint}</div>
                <div className="arch-palette-list">
                  {palettes[paletteTab].blocks.map((b) => {
                    const inUse = blockInFlow(b.id);
                    return (
                      <button
                        key={b.id}
                        type="button"
                        className={`arch-block arch-block-${paletteTab.slice(0, -1)} arch-block-source ${inUse ? "is-used" : ""}`}
                        draggable={!inUse}
                        onDragStart={(e) => { if (inUse) { e.preventDefault(); return; } e.dataTransfer.setData("text/plain", b.id); e.dataTransfer.effectAllowed = "move"; }}
                        onClick={() => !inUse && placeBlock(b)}
                        disabled={inUse}
                        title={inUse ? "Already placed" : "Click or drag to place"}
                      >
                        <span className="arch-block-icon">{b.icon}</span>
                        <span className="arch-block-label">{b.label}</span>
                      </button>
                    );
                  })}
                </div>

                <div className="arch-templates">
                  <div className="arch-templates-h">Quick start</div>
                  <div className="arch-templates-list">
                    {ARCH_TEMPLATES.map((tpl) => (
                      <button
                        key={tpl.id}
                        type="button"
                        className="arch-template"
                        onClick={() => applyTemplate(tpl)}
                      >
                        {tpl.label}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            <div className="arch-equip-foot">
              <span className="arch-count">
                {flow.when ? "✓ trigger" : "○ trigger"} · {flow.do.length > 0 ? `✓ ${flow.do.length} action${flow.do.length === 1 ? "" : "s"}` : "○ action"} · {flow.fallback ? "✓ fallback" : "○ fallback"}
              </span>
              <button
                type="button"
                className="btn btn-primary arch-submit"
                onClick={handleSubmit}
                disabled={!flowReady}
              >
                Next: pick the gear
                <svg width="14" height="14" viewBox="0 0 14 14"><path d="M1 7h11M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
              </button>
            </div>
          </div>
        )}

        {phase === "equip" && (
          <div className="arch-equip">
            <div className="arch-equip-grid">
              {/* LEFT — live preview */}
              <div className="arch-equip-preview">
                <div
                  className={`arch-equip-avatar ${snap !== null ? "is-bumped" : ""}`}
                  style={{ background: `radial-gradient(circle at 30% 30%, ${palette.accent}, ${palette.skin} 60%, ${palette.skinDark})` }}
                >
                  <CharacterAvatar palette={palette} glyph={glyph} size="hero" />
                  {/* Floating tool chips around the avatar */}
                  {slots.map((tool, i) => tool ? (
                    <span
                      key={i}
                      className={`arch-orbit arch-orbit-${i} ${snap === i ? "is-snap" : ""}`}
                      style={{ background: ARCH_TOOL_COLORS[tool] || "#1A120B" }}
                      title={tool}
                    >
                      {tool[0]}
                    </span>
                  ) : null)}
                </div>
                <input
                  className="arch-equip-name"
                  value={name}
                  onChange={(e) => setName(e.target.value.replace(/[^a-zA-Z0-9 ]/g, "").toUpperCase().slice(0, 8))}
                  placeholder="ATLAS"
                  aria-label="Agent name"
                  spellCheck={false}
                />
                <div className="arch-equip-role">{roleGuess}</div>
              </div>

              {/* RIGHT — config */}
              <div className="arch-equip-config">
                <div className="arch-equip-section">
                  <div className="arch-equip-h">
                    <span>Tools</span>
                    <span className="arch-equip-count">{filledCount} / 4</span>
                  </div>
                  <div className="arch-equip-slots">
                    {slots.map((tool, i) => (
                      <div
                        key={i}
                        className={`arch-slot ${tool ? "is-filled" : ""} ${dragOver === i ? "is-over" : ""} ${snap === i ? "is-snap" : ""}`}
                        onDragOver={(e) => { e.preventDefault(); setDragOver(i); }}
                        onDragLeave={() => setDragOver((d) => d === i ? null : d)}
                        onDrop={(e) => onDropSlot(e, i)}
                        onClick={() => tool && removeFromSlot(i)}
                        title={tool ? `Remove ${tool}` : "Drop a tool here"}
                      >
                        {tool ? (
                          <span className="arch-slot-chip" style={{ background: ARCH_TOOL_COLORS[tool] || "#1A120B" }}>
                            <span className="arch-slot-chip-mark">{tool[0]}</span>
                            <span className="arch-slot-chip-l">{tool}</span>
                            <span className="arch-slot-x">×</span>
                          </span>
                        ) : (
                          <span className="arch-slot-empty">+</span>
                        )}
                      </div>
                    ))}
                  </div>
                  <div className="arch-equip-tray">
                    {ARCH_AVAILABLE_TOOLS.map((t) => {
                      const inUse = slots.includes(t);
                      return (
                        <button
                          key={t}
                          type="button"
                          className={`arch-tool-chip ${inUse ? "is-used" : ""}`}
                          style={{ "--chip": ARCH_TOOL_COLORS[t] || "#1A120B" }}
                          draggable={!inUse}
                          onDragStart={(e) => { if (inUse) { e.preventDefault(); return; } e.dataTransfer.setData("text/plain", t); e.dataTransfer.effectAllowed = "move"; }}
                          onClick={() => !inUse && addToFirstEmpty(t)}
                          disabled={inUse}
                          title={inUse ? `${t} is already on this agent` : `Add ${t}`}
                        >
                          <span className="arch-tool-chip-dot" />
                          {t}
                        </button>
                      );
                    })}
                  </div>
                </div>

                <div className="arch-equip-section arch-equip-row">
                  <div>
                    <div className="arch-equip-h">Look</div>
                    <div className="arch-equip-swatches">
                      {ARCH_PALETTES.map((p, i) => (
                        <button
                          key={i}
                          type="button"
                          className={`arch-swatch ${pIdx === i ? "is-on" : ""}`}
                          style={{ background: p.skin }}
                          onClick={() => setPIdx(i)}
                          aria-label={`Palette ${i + 1}`}
                        />
                      ))}
                    </div>
                    <div className="arch-equip-glyphs">
                      {ARCH_GLYPHS.map((g, i) => (
                        <button
                          key={g}
                          type="button"
                          className={`arch-glyph-btn ${gIdx === i ? "is-on" : ""}`}
                          onClick={() => setGIdx(i)}
                          aria-label={`Glyph ${g}`}
                        >{g}</button>
                      ))}
                    </div>
                  </div>
                  <div>
                    <div className="arch-equip-h">Personality</div>
                    <div className="arch-equip-personality">
                      {ARCH_PERSONALITIES.map((p) => (
                        <button
                          key={p.id}
                          type="button"
                          className={`arch-personality ${personality === p.id ? "is-on" : ""}`}
                          onClick={() => setPersonality(p.id)}
                          title={p.hint}
                        >{p.label}</button>
                      ))}
                    </div>
                    <button
                      type="button"
                      className="arch-equip-approval"
                      onClick={() => setApproval((v) => !v)}
                      aria-pressed={approval}
                    >
                      <span className={`arch-approval-toggle ${approval ? "is-on" : ""}`}><span /></span>
                      <span>Loop me in on big decisions</span>
                    </button>
                  </div>
                </div>
              </div>
            </div>

            <div className="arch-equip-foot">
              <button type="button" className="btn btn-ghost btn-sm" onClick={() => setPhase("behavior")}>← Edit rules</button>
              <button
                type="button"
                className="btn btn-primary"
                onClick={hire}
                disabled={filledCount === 0 || !name.trim()}
              >
                Hire {name || "it"}
                <svg width="14" height="14" viewBox="0 0 14 14"><path d="M1 7h11M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
              </button>
            </div>
          </div>
        )}

        {phase === "building" && (
          <div className="arch-build">
            <div className="arch-build-orb">
              <div className="arch-build-ring arch-build-ring-1" style={{ borderColor: palette.skin }} />
              <div className="arch-build-ring arch-build-ring-2" style={{ borderColor: palette.skin }} />
              <div className="arch-build-ring arch-build-ring-3" style={{ borderColor: palette.skin }} />
              <div className="arch-build-core" style={{ background: `radial-gradient(circle at 30% 30%, ${palette.accent}, ${palette.skin} 60%, ${palette.skinDark})` }}>
                <span>{glyph}</span>
              </div>
              <div className="arch-build-spark arch-build-spark-1" style={{ background: palette.skin }} />
              <div className="arch-build-spark arch-build-spark-2" style={{ background: palette.skin }} />
              <div className="arch-build-spark arch-build-spark-3" style={{ background: palette.skin }} />
              <div className="arch-build-spark arch-build-spark-4" style={{ background: palette.skin }} />
            </div>
            <ul className="arch-build-steps">
              {creationMode !== "new" && srcAgent ? [
                `${creationMode === "copy" ? "Cloning" : creationMode === "inherit" ? "Inheriting from" : "Seeding config from"} ${srcAgent.name}`,
                creationMode === "copy" ? "Copying knowledge assignments" :
                creationMode === "inherit" ? "Transferring " + (srcAgent.learnings?.length || 0) + " learnings" :
                "Starting with a clean slate",
                `Registering ${(draftName || "new agent").toUpperCase()}`,
              ].map((s, i) => (
                <li key={i} className={`arch-step ${step > i ? "is-done" : step === i ? "is-active" : ""}`}>
                  <span className="arch-step-dot">
                    {step > i ? "✓" : step === i ? <span className="arch-step-spin" /> : ""}
                  </span>
                  {s}
                </li>
              )) : [
                "Wiring " + slots.filter(Boolean).length + " " + (slots.filter(Boolean).length === 1 ? "tool" : "tools"),
                "Setting personality: " + personality,
                "Hiring " + (name || "the agent"),
              ].map((s, i) => (
                <li key={i} className={`arch-step ${step > i ? "is-done" : step === i ? "is-active" : ""}`}>
                  <span className="arch-step-dot">
                    {step > i ? "✓" : step === i ? <span className="arch-step-spin" /> : ""}
                  </span>
                  {s}
                </li>
              ))}
            </ul>
          </div>
        )}

        {phase === "done" && agent && (
          <div className="arch-done">
            <div
              className="arch-done-avatar"
              style={{ background: `radial-gradient(circle at 30% 30%, ${agent.palette.accent}, ${agent.palette.skin} 60%, ${agent.palette.skinDark})` }}
            >
              <CharacterAvatar palette={agent.palette} glyph={agent.glyph} size="hero" />
            </div>
            <div className="arch-done-name">{agent.name}</div>
            <div className="arch-done-role">{agent.role}</div>
            <blockquote className="arch-done-brief">"{text}"</blockquote>
            <div className="arch-done-meta">
              <div className="arch-done-pill"><span className="arch-done-pill-dot"/> on shift in 2 min</div>
              <div className="arch-done-pill"><span>⌘</span> approval gate set</div>
              <div className="arch-done-pill"><span>◇</span> {agent.tools.length} {agent.tools.length === 1 ? "tool" : "tools"}: {agent.tools.join(", ")}</div>
            </div>
            <div className="arch-done-cta">
              <button className="btn btn-ghost" onClick={() => setPhase("behavior")}>
                Edit the rules
              </button>
              {onCreate ? (
                <button className="btn btn-primary" type="button" onClick={() => { onCreate(agent); onClose(); }}>
                  Put it on shift
                  <svg width="14" height="14" viewBox="0 0 14 14"><path d="M1 7h11M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </button>
              ) : (
                <a className="btn btn-primary" href="#demo" onClick={onClose}>
                  Put it on shift
                  <svg width="14" height="14" viewBox="0 0 14 14"><path d="M1 7h11M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </a>
              )}
            </div>
          </div>
        )}
      </div>
    </Modal>
  );
}

// ============ SIGN-IN MODAL ============
// Sign-in ONLY. Citrus is sales-led — prospects request a call via
// LeadModal, which routes the conversation to master-admin as a lead.
// New tenants are provisioned by master-admin after the call, not
// self-served from the landing page.
function SignInModal({ open, onClose, onRequestLead }) {
  const [email, setEmail] = useMState("");
  const [pass, setPass] = useMState("");
  const [phase, setPhase] = useMState("idle"); // idle | submitting | done
  const [error, setError] = useMState("");

  // Same resolution order as dashboard's LoginScreen so the modal hits the
  // PRIMARY server (sandbox env overrides may have rewritten SERVER_URL).
  const cfg = (typeof window !== "undefined" && window.CITRUS_CONFIG) || {};
  const authBase = (typeof window !== "undefined" && window.__citrusPrimaryUrl) || cfg.SERVER_URL || "";
  const hasGoogle = !!cfg.GOOGLE_CLIENT_ID;

  useMEffect(() => {
    if (open) { setEmail(""); setPass(""); setPhase("idle"); setError(""); }
  }, [open]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!email || !pass) return;
    setError("");
    setPhase("submitting");
    try {
      const r = await fetch(`${authBase}/auth/login`, {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ email, password: pass }),
      });
      const j = await r.json().catch(() => ({}));
      if (!r.ok) {
        setError(j.error || "Invalid email or password");
        setPhase("idle");
        return;
      }
      // 2FA enrolled accounts need a TOTP step — the modal has no TOTP UI,
      // so kick them over to the full dashboard auth screen which handles it.
      if (j.requires2fa) {
        setError("This account uses 2FA. Continue sign-in from the dashboard.");
        setPhase("idle");
        setTimeout(() => { window.location.href = "/dashboard/"; }, 1200);
        return;
      }
      if (j.token) localStorage.setItem("citrus_auth_token", j.token);
      setPhase("done");
      setTimeout(() => { window.location.href = "/dashboard/"; }, 1400);
    } catch {
      setError("Could not reach server. Check your connection.");
      setPhase("idle");
    }
  };

  const signInWithGoogle = () => { window.location.href = `${authBase}/auth/google`; };

  return (
    <Modal open={open} onClose={onClose} label="Sign in">
      <div className="signin">
        <div className="signin-mark">◍</div>
        <h3 className="signin-title">Welcome back.</h3>
        <p className="signin-sub">Pick up where your agents left off.</p>

        {phase !== "done" && (
          <>
            {hasGoogle && (
              <>
                <div className="signin-social">
                  <button className="signin-social-btn" type="button" onClick={signInWithGoogle}>
                    <svg width="16" height="16" viewBox="0 0 24 24" aria-hidden="true">
                      <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.56c2.08-1.92 3.28-4.74 3.28-8.1z"/>
                      <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.56-2.77c-.99.66-2.25 1.06-3.72 1.06-2.86 0-5.29-1.93-6.16-4.53H2.17v2.84A11 11 0 0 0 12 23z"/>
                      <path fill="#FBBC05" d="M5.84 14.1A6.6 6.6 0 0 1 5.5 12c0-.73.13-1.44.34-2.1V7.06H2.17A11 11 0 0 0 1 12c0 1.78.43 3.46 1.17 4.94l3.67-2.84z"/>
                      <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1A11 11 0 0 0 2.17 7.06l3.67 2.84C6.71 7.31 9.14 5.38 12 5.38z"/>
                    </svg>
                    Continue with Google
                  </button>
                </div>
                <div className="signin-divider"><span>or</span></div>
              </>
            )}

            {error && <div className="signin-error" role="alert">{error}</div>}

            <form className="signin-form" onSubmit={handleSubmit}>
              <label className="signin-field">
                <span>Work email</span>
                <input
                  type="email"
                  placeholder="you@company.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  autoComplete="email"
                  required
                />
              </label>
              <label className="signin-field">
                <span>Password</span>
                <input
                  type="password"
                  placeholder="••••••••"
                  value={pass}
                  onChange={(e) => setPass(e.target.value)}
                  autoComplete="current-password"
                  required
                  minLength={6}
                />
              </label>
              <button
                type="submit"
                className="btn btn-primary signin-submit"
                disabled={phase === "submitting" || !email || !pass}
              >
                {phase === "submitting" ? (
                  <>
                    <span className="signin-spin" />
                    Signing in…
                  </>
                ) : (
                  <>
                    Sign in
                    <svg width="14" height="14" viewBox="0 0 14 14"><path d="M1 7h11M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  </>
                )}
              </button>
            </form>

            <div className="signin-switch">
              New to Citrus?{" "}
              <button type="button" onClick={() => { onClose(); if (onRequestLead) onRequestLead(); }}>
                Get in touch
              </button>
            </div>
            <div className="signin-fine">
              By continuing, you agree to our <a href="#">Terms</a> and <a href="#">Privacy</a>.
            </div>
          </>
        )}

        {phase === "done" && (
          <div className="signin-done">
            <div className="signin-done-check">
              <svg width="36" height="36" viewBox="0 0 36 36"><circle cx="18" cy="18" r="17" fill="none" stroke="currentColor" strokeWidth="2" className="signin-done-circle"/><path d="M11 18 L 16 23 L 25 13" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" className="signin-done-tick"/></svg>
            </div>
            <div className="signin-done-title">You're in.</div>
            <div className="signin-done-sub">Your agents are waiting.</div>
            <a className="btn btn-primary" href="/dashboard/" onClick={(e) => { onClose(); }}>
              Take me there
            </a>
          </div>
        )}
      </div>
    </Modal>
  );
}

// ============ LEAD MODAL ============
// Prospect contact form. Sales-led model: this is the ONLY way to start
// a new tenant — submissions land in master-admin's Leads view, the team
// books a call, and (after the call) master-admin provisions the business.
function LeadModal({ open, onClose }) {
  const [name, setName] = useMState("");
  const [email, setEmail] = useMState("");
  const [company, setCompany] = useMState("");
  const [phone, setPhone] = useMState("");
  const [message, setMessage] = useMState("");
  const [phase, setPhase] = useMState("idle"); // idle | submitting | done
  const [error, setError] = useMState("");

  const cfg = (typeof window !== "undefined" && window.CITRUS_CONFIG) || {};
  const apiBase = (typeof window !== "undefined" && window.__citrusPrimaryUrl) || cfg.SERVER_URL || "";

  useMEffect(() => {
    if (open) { setName(""); setEmail(""); setCompany(""); setPhone(""); setMessage(""); setPhase("idle"); setError(""); }
  }, [open]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!name.trim() || !email.trim()) return;
    setError("");
    setPhase("submitting");
    try {
      const r = await fetch(`${apiBase}/leads`, {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ name, email, company, phone, message, source: "landing" }),
      });
      const j = await r.json().catch(() => ({}));
      if (!r.ok) {
        setError(j.error || "Could not submit — please try again or email us directly.");
        setPhase("idle");
        return;
      }
      setPhase("done");
    } catch {
      setError("Could not reach server. Check your connection.");
      setPhase("idle");
    }
  };

  return (
    <Modal open={open} onClose={onClose} label="Get in touch">
      <div className="signin">
        <div className="signin-mark">◍</div>
        <h3 className="signin-title">Let's talk.</h3>
        <p className="signin-sub">Tell us about your business and we'll set up a call.</p>

        {phase !== "done" && (
          <>
            {error && <div className="signin-error" role="alert">{error}</div>}

            <form className="signin-form" onSubmit={handleSubmit}>
              <label className="signin-field">
                <span>Your name</span>
                <input type="text" placeholder="Alex Rivera" value={name}
                  onChange={(e) => setName(e.target.value)} autoComplete="name" required />
              </label>
              <label className="signin-field">
                <span>Work email</span>
                <input type="email" placeholder="you@company.com" value={email}
                  onChange={(e) => setEmail(e.target.value)} autoComplete="email" required />
              </label>
              <label className="signin-field">
                <span>Company</span>
                <input type="text" placeholder="Acme Co." value={company}
                  onChange={(e) => setCompany(e.target.value)} autoComplete="organization" />
              </label>
              <label className="signin-field">
                <span>Phone (WhatsApp)</span>
                <input type="tel" placeholder="+1 555 123 4567" value={phone}
                  onChange={(e) => setPhone(e.target.value)} autoComplete="tel" />
              </label>
              <label className="signin-field">
                <span>What are you trying to do?</span>
                <textarea rows={3} placeholder="A few words about your use case…" value={message}
                  onChange={(e) => setMessage(e.target.value)} />
              </label>
              <button
                type="submit"
                className="btn btn-primary signin-submit"
                disabled={phase === "submitting" || !name.trim() || !email.trim()}
              >
                {phase === "submitting" ? (
                  <><span className="signin-spin" />Sending…</>
                ) : (
                  <>Request a call<svg width="14" height="14" viewBox="0 0 14 14"><path d="M1 7h11M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg></>
                )}
              </button>
            </form>

            <div className="signin-fine">
              By submitting you agree to be contacted by the Citrus team.
            </div>
          </>
        )}

        {phase === "done" && (
          <div className="signin-done">
            <div className="signin-done-check">
              <svg width="36" height="36" viewBox="0 0 36 36"><circle cx="18" cy="18" r="17" fill="none" stroke="currentColor" strokeWidth="2" className="signin-done-circle"/><path d="M11 18 L 16 23 L 25 13" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" className="signin-done-tick"/></svg>
            </div>
            <div className="signin-done-title">Got it.</div>
            <div className="signin-done-sub">We'll be in touch within one business day.</div>
            <button className="btn btn-primary" type="button" onClick={onClose}>Close</button>
          </div>
        )}
      </div>
    </Modal>
  );
}

window.ArchitectModal = ArchitectModal;
window.SignInModal = SignInModal;
window.LeadModal = LeadModal;
