// ============ CITRUS LANDING ============
// Plainspoken, creation-flow-first. Sections: Hero (typing demo) →
// Three steps → Agent roster → Effect (before/after with live counter) →
// Security → CTA → Footer.

const { useState, useEffect, useRef, useMemo } = React;

// ============ NAV ============
function Nav() {
  return (
    <nav className="nav" data-screen-label="00 Nav">
      <a className="nav-brand-a" href="#">
        <span className="brand-mark">◍</span>
        <span className="brand-word">citrus</span>
      </a>
      <div className="nav-links">
        <a href="#how">How it works</a>
        <a href="#agents">Agents</a>
        <a href="#effect">The effect</a>
        <a href="#security">Security</a>
      </div>
      <div className="nav-right">
        <button className="btn btn-ghost btn-sm" onClick={() => window.dispatchEvent(new CustomEvent('citrus:open-signin'))}>Sign in</button>
        <a href="#demo" className="btn btn-primary btn-sm">Get a demo</a>
      </div>
    </nav>
  );
}

// ============ HERO ============
function Hero() {
  const CitrusHero = window.CitrusHero;
  return (
    <section className="hero" data-screen-label="01 Hero">
      <div className="hero-grid">
        <div className="hero-copy">
          <div className="eyebrow">
            <span className="eyebrow-dot" />
            AI agents · ready to hire
          </div>
          <h1 className="hero-title">
            Tell it what to do.<br />
            <span className="title-accent">It does it<em className="amp-em">.</em></span>
          </h1>
          <p className="hero-sub">
            "I want someone to answer customers on WhatsApp."
            "I want a financial analyst." Type it like you'd text a friend.
            Citrus turns it into an AI employee that shows up Monday.
          </p>
          <div className="hero-ctas">
            <a className="btn btn-primary" href="#demo">
              Try it free
              <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>
            <a className="btn btn-ghost" href="#how">See how it works</a>
          </div>
          <div className="hero-meta">
            <div className="meta-col">
              <div className="meta-num">3 min</div>
              <div className="meta-lbl">to your first<br/>agent on shift</div>
            </div>
            <div className="meta-div" />
            <div className="meta-col">
              <div className="meta-num">No code</div>
              <div className="meta-lbl">type it like you'd<br/>brief a teammate</div>
            </div>
            <div className="meta-div" />
            <div className="meta-col">
              <div className="meta-num">You decide</div>
              <div className="meta-lbl">approve, edit, or<br/>let it run</div>
            </div>
          </div>
        </div>

        <div className="hero-visual">
          <CitrusHero />
        </div>
      </div>

      <div className="hero-marquee">
        <div className="marquee-track">
          {Array.from({ length: 2 }).map((_, k) => (
            <div key={k} className="marquee-group">
              {["Nile Bank","Cairo Logistics","Pharos Health","Sphinx Retail","Ramses Insurance","Luxor Media","Anubis & Co.","Karnak Mining"].map((n, i) => (
                <span key={i} className="marquee-item">
                  <span className="mk-bullet">✺</span>{n}
                </span>
              ))}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============ THREE STEPS ============
function ThreeSteps() {
  const steps = [
    {
      k: "01",
      title: "Write the job",
      body: "A few sentences, like you'd brief a new hire. \"Chase late invoices. Be polite. Loop me in over $10k.\"",
      mock: <StepMockWrite />,
    },
    {
      k: "02",
      title: "Pick what it can touch",
      body: "Click the tools it should use — Gmail, Stripe, Slack, your CRM. Set a budget. Set who approves what.",
      mock: <StepMockTools />,
    },
    {
      k: "03",
      title: "Put it on shift",
      body: "It starts working. You see every move it makes, in plain English. Edit, approve, or let it run.",
      mock: <StepMockShift />,
    },
  ];
  return (
    <section id="how" className="three" data-screen-label="02 Three steps">
      <div className="section-head">
        <div className="kicker">Three steps</div>
        <h2 className="section-title">
          From idea to <span className="title-accent">agent on shift</span><br/>in about three minutes.
        </h2>
      </div>
      <div className="three-grid">
        {steps.map((s, i) => (
          <div key={i} className="three-card">
            <div className="three-num">{s.k}</div>
            <div className="three-mock">{s.mock}</div>
            <h3 className="three-title">{s.title}</h3>
            <p className="three-body">{s.body}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

function StepMockWrite() {
  return (
    <div className="sm sm-write">
      <div className="sm-line">I want someone to answer</div>
      <div className="sm-line">customers on WhatsApp.</div>
      <div className="sm-line sm-line-faded">Send me the leads to my phone<span className="sm-caret" /></div>
    </div>
  );
}
function StepMockTools() {
  const tools = [
    { n: "Gmail", on: true },
    { n: "Stripe", on: true },
    { n: "QuickBooks", on: true },
    { n: "Slack", on: false },
    { n: "Salesforce", on: false },
  ];
  return (
    <div className="sm sm-tools">
      {tools.map((t, i) => (
        <div key={i} className={`sm-tool ${t.on ? "is-on" : ""}`}>
          <span className="sm-check">{t.on ? "✓" : ""}</span>
          {t.n}
        </div>
      ))}
      <div className="sm-budget">
        <span>Budget cap</span>
        <span className="sm-budget-v">$10,000 / mo</span>
      </div>
    </div>
  );
}
function StepMockShift() {
  const events = [
    { t: "9:02", e: "Sent reminder to Anubis & Co.", k: "ok" },
    { t: "9:04", e: "Drafted reply for Cairo Logistics", k: "ok" },
    { t: "9:07", e: "Flagged $14k invoice for review", k: "wait" },
    { t: "9:09", e: "Marked 3 paid", k: "ok" },
  ];
  return (
    <div className="sm sm-shift">
      {events.map((ev, i) => (
        <div key={i} className={`sm-evt sm-evt-${ev.k}`}>
          <span className="sm-evt-t">{ev.t}</span>
          <span className="sm-evt-e">{ev.e}</span>
          <span className="sm-evt-k">{ev.k === "ok" ? "✓" : "⌘"}</span>
        </div>
      ))}
    </div>
  );
}

// ============ AGENT ROSTER ============
// Four named characters — written like a text to a friend.
const ROSTER = [
  {
    id: "ori",
    charName: "ORI",
    name: "Customer support",
    role: "Answers customers on WhatsApp and email",
    palette: { skin: "#E85D1A", skinDark: "#B84410", accent: "#FFCA7D", visor: "#1A120B" },
    tone: "#E85D1A",
    glyph: "◍",
    one: "\"I want someone to answer customers on WhatsApp, send me the leads, and tell me when something's off.\"",
    does: ["Replies on WhatsApp and email", "Sends qualified leads to your phone", "Answers from your FAQ", "Pings you when it's stuck"],
    effect: { v: "24/7", l: "always answering" },
    bestFor: "Sales, customer ops",
  },
  {
    id: "sol",
    charName: "SOL",
    name: "Financial analyst",
    role: "Tells you how the business is really doing",
    palette: { skin: "#2DAF6B", skinDark: "#196C42", accent: "#A6E8C7", visor: "#0A1F14" },
    tone: "#2DAF6B",
    glyph: "✺",
    one: "\"I want a financial analyst to look at my numbers every Monday and tell me what changed and why.\"",
    does: ["Reads your books each Monday", "Calls out what changed", "Spots cash issues early", "Drafts the investor update"],
    effect: { v: "Mondays", l: "you get a real report" },
    bestFor: "Founders, finance",
  },
  {
    id: "vex",
    charName: "VEX",
    name: "Sales follow-up",
    role: "Follows up so you don't have to remember",
    palette: { skin: "#3B7CFF", skinDark: "#1F4FB5", accent: "#A6D8FF", visor: "#0E1A30" },
    tone: "#3B7CFF",
    glyph: "✦",
    one: "\"I want someone to follow up with every lead, three times, polite, and stop the moment they reply.\"",
    does: ["Follows up on the schedule you set", "Stops the second they reply", "Tells you when one is hot", "Books the call for you"],
    effect: { v: "0", l: "leads dropped" },
    bestFor: "Sales, founders",
  },
  {
    id: "ink",
    charName: "INK",
    name: "Contract reader",
    role: "Reads the fine print so you don't have to",
    palette: { skin: "#B4488C", skinDark: "#742855", accent: "#F2C8E0", visor: "#1F0A18" },
    tone: "#B4488C",
    glyph: "❖",
    one: "\"I want someone to read every contract before I sign and tell me, in plain English, where the weird stuff is.\"",
    does: ["Reads contracts as they land", "Highlights the weird clauses", "Tells you in plain English", "Pings legal on the unusual stuff"],
    effect: { v: "5 min", l: "to know if it's safe" },
    bestFor: "Founders, legal, ops",
  },
];

function AgentRoster() {
  const agents = ROSTER;

  const [open, setOpen] = useState(0);

  return (
    <section id="agents" className="roster" data-screen-label="03 Agents">
      <div className="section-head">
        <div className="kicker">Hire one in a click</div>
        <h2 className="section-title">
          Pre-built agents,<br/>
          <span className="title-accent">ready Monday morning</span>.
        </h2>
        <p className="section-lede">Each one comes with a sensible default brief, the right tools, and human approval gates. Tweak any of it. Or write your own from scratch.</p>
      </div>

      <div className="roster-grid">
        {agents.map((a, i) => (
          <article
            key={a.id}
            className={`roster-card ${open === i ? "is-open" : ""}`}
            onMouseEnter={() => setOpen(i)}
          >
            <header className="roster-head">
              <div className="roster-avatar-wrap" style={{ background: `radial-gradient(circle at 30% 30%, ${a.palette.accent}, ${a.palette.skin} 60%, ${a.palette.skinDark})` }}>
                <CharacterAvatar palette={a.palette} glyph={a.glyph} size="card" />
              </div>
              <div>
                <div className="roster-charname">{a.charName}</div>
                <div className="roster-name">{a.name}</div>
                <div className="roster-role">{a.role}</div>
              </div>
              <div className="roster-effect">
                <div className="roster-effect-v" style={{ color: a.tone }}>{a.effect.v}</div>
                <div className="roster-effect-l">{a.effect.l}</div>
              </div>
            </header>
            <blockquote className="roster-brief">{a.one}</blockquote>
            <ul className="roster-does">
              {a.does.map((d, j) => (
                <li key={j}><span className="roster-tick">→</span>{d}</li>
              ))}
            </ul>
            <footer className="roster-foot">
              <span className="roster-best">Best for · {a.bestFor}</span>
              <button className="roster-hire">
                Hire this one
                <svg width="12" height="12" 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>
            </footer>
          </article>
        ))}
      </div>

      <div className="roster-byo">
        <div>
          <div className="kicker">Or build your own</div>
          <h3 className="byo-title">Don't see your role? <span className="title-accent">Write the brief</span>, we'll do the rest.</h3>
        </div>
        <button className="btn btn-ghost" onClick={() => window.dispatchEvent(new CustomEvent('citrus:open-architect'))}>Open the architect →</button>
      </div>
    </section>
  );
}

// ============ EFFECT (before/after + live counter) ============
function Effect() {
  const start = 0;
  const targets = useMemo(() => ({ tickets: 6420, hours: 412, drafts: 1208, dollars: 184500 }), []);
  const [vals, setVals] = useState({ tickets: start, hours: start, drafts: start, dollars: start });

  useEffect(() => {
    const dur = 1800;
    const t0 = performance.now();
    let raf;
    const loop = (t) => {
      const p = Math.min(1, (t - t0) / dur);
      const e = 1 - Math.pow(1 - p, 3);
      setVals({
        tickets: Math.round(targets.tickets * e),
        hours: Math.round(targets.hours * e),
        drafts: Math.round(targets.drafts * e),
        dollars: Math.round(targets.dollars * e),
      });
      if (p < 1) raf = requestAnimationFrame(loop);
    };
    // start when section in view
    const el = document.getElementById("effect");
    let started = false;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(en => {
        if (en.isIntersecting && !started) { started = true; raf = requestAnimationFrame(loop); }
      });
    }, { threshold: 0.3 });
    if (el) io.observe(el);
    return () => { cancelAnimationFrame(raf); io.disconnect(); };
  }, [targets]);

  // ticking "in the last hour" counter
  const [live, setLive] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setLive(v => v + Math.floor(Math.random() * 3) + 1), 900);
    return () => clearInterval(id);
  }, []);

  const beforeQueue = ["Refund request · 4d", "PO mismatch · 2d", "Lead from form · 3d", "Vendor late · 5d", "Question from new hire", "Late invoice · 11d"];
  const afterQueue = [{ e: "Refund handled", k: "✓" }, { e: "PO reconciled", k: "✓" }, { e: "Lead routed", k: "✓" }, { e: "Vendor chased", k: "✓" }, { e: "Answered from SOP", k: "✓" }, { e: "Reminder sent", k: "✓" }];

  return (
    <section id="effect" className="effect" data-screen-label="04 Effect">
      <div className="section-head">
        <div className="kicker kicker-light">What changes</div>
        <h2 className="section-title section-title-light">
          The queue empties.<br/>
          <span className="title-accent-light">The team breathes.</span>
        </h2>
      </div>

      <div className="ba-frame">
        <div className="ba-side ba-before">
          <div className="ba-head">
            <span className="ba-tag">Before · Monday 9:14am</span>
            <span className="ba-num ba-num-red">{beforeQueue.length} stuck</span>
          </div>
          <ul className="ba-list">
            {beforeQueue.map((q, i) => (
              <li key={i} className="ba-item ba-item-stuck">
                <span className="ba-bul">●</span>{q}
              </li>
            ))}
          </ul>
          <div className="ba-foot ba-foot-red">someone has to do all this</div>
        </div>

        <div className="ba-arrow">
          <svg width="60" height="40" viewBox="0 0 60 40"><path d="M2 20 H 54 M44 8 L 56 20 L 44 32" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
          <span className="ba-arrow-l">Citrus</span>
        </div>

        <div className="ba-side ba-after">
          <div className="ba-head">
            <span className="ba-tag">After · Monday 9:18am</span>
            <span className="ba-num ba-num-green">all clear</span>
          </div>
          <ul className="ba-list">
            {afterQueue.map((q, i) => (
              <li key={i} className="ba-item ba-item-done" style={{ animationDelay: `${i * 0.1}s` }}>
                <span className="ba-bul ba-bul-done">{q.k}</span>{q.e}
              </li>
            ))}
          </ul>
          <div className="ba-foot ba-foot-green">your team did the other work</div>
        </div>
      </div>

      <div className="effect-stats">
        <div className="es-card">
          <div className="es-v">{vals.tickets.toLocaleString()}</div>
          <div className="es-l">tickets resolved last 30 days</div>
        </div>
        <div className="es-card">
          <div className="es-v">{vals.hours.toLocaleString()}</div>
          <div className="es-l">team hours given back this month</div>
        </div>
        <div className="es-card">
          <div className="es-v">{vals.drafts.toLocaleString()}</div>
          <div className="es-l">replies drafted, ready to send</div>
        </div>
        <div className="es-card es-card-live">
          <div className="es-live-tag">live · last hour</div>
          <div className="es-v es-v-accent">+{live}</div>
          <div className="es-l">things just done across Citrus</div>
        </div>
      </div>

      <figure className="pullquote">
        <blockquote>"We didn't replace anyone. We replaced the 600 tickets a week nobody wanted to touch. The team is doing the work they were hired for again — and the queue is empty by 4pm."</blockquote>
        <figcaption>
          <span className="fc-avatar">DR</span>
          <div>
            <div className="fc-name">Dana Reyes</div>
            <div className="fc-role">VP Operations · Pharos Health</div>
          </div>
        </figcaption>
      </figure>
    </section>
  );
}

// ============ SECURITY ============
function Security() {
  const items = [
    { k: "You stay in charge", d: "Set what it can touch, who it asks before doing big things, and when to stop and check in." },
    { k: "Your data stays yours", d: "We never train on your stuff. Your logs, your prompts, your outputs — all yours." },
    { k: "Receipts for everything", d: "Every action it takes is logged in plain English. Replay any decision. See why." },
    { k: "Bring your own model", d: "OpenAI, Anthropic, your own private model. Whatever your CISO is comfortable with." },
    { k: "SOC 2, HIPAA-ready", d: "Audited annually. BAA available. Built for regulated, audited businesses." },
    { k: "SAML / SCIM", d: "Standard SSO. Per-agent and per-tool permissions. Off-board with one click." },
  ];
  return (
    <section id="security" className="security" data-screen-label="05 Security">
      <div className="sec-grid">
        <div className="sec-head">
          <div className="kicker">Boring on purpose</div>
          <h2 className="section-title">
            Your CISO won't<br/>
            <span className="title-accent">need a slide for it</span>.
          </h2>
          <p className="section-lede">Citrus runs inside regulated, audited businesses. Your data stays yours. Your policies stay enforced. Every move it makes is reviewable down to the token.</p>
        </div>
        <div className="sec-list">
          {items.map((it, i) => (
            <div key={i} className="sec-item">
              <div className="sec-k"><span className="sec-bullet">◍</span>{it.k}</div>
              <div className="sec-d">{it.d}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============ CTA ============
function CTA() {
  return (
    <section id="demo" className="cta" data-screen-label="06 CTA">
      <div className="cta-inner">
        <div className="cta-mark">◍</div>
        <h2 className="cta-title">
          Stop hiring for<br/>
          <span className="title-accent">the work nobody wants</span>.
        </h2>
        <p className="cta-sub">30 minutes. We'll build one agent for your business, live, on the call. You decide if it's worth a second meeting.</p>
        <form className="cta-form" onSubmit={(e) => e.preventDefault()}>
          <input className="cta-input" placeholder="work email" type="email" />
          <input className="cta-input" placeholder="company" />
          <button className="btn btn-primary btn-cta" type="submit">
            Book the 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="cta-fine">No decks. No 14-page MSA on the first call.</div>
      </div>
    </section>
  );
}

// ============ FOOTER ============
function Footer() {
  return (
    <footer className="footer" data-screen-label="07 Footer">
      <div className="footer-top">
        <div className="footer-brand">
          <div className="brand-big">◍ citrus</div>
          <p>AI agents that show up, do the work, and keep you in the loop.</p>
        </div>
        <div className="footer-cols">
          <div><h5>Product</h5><a href="#">How it works</a><a href="#">Agents</a><a href="#">Integrations</a><a href="#">Changelog</a></div>
          <div><h5>For</h5><a href="#">Finance</a><a href="#">Operations</a><a href="#">Construction</a><a href="#">HR & people</a></div>
          <div><h5>Company</h5><a href="#">About</a><a href="#">Careers</a><a href="#">Press</a><a href="#">Contact</a></div>
          <div><h5>Trust</h5><a href="#">Security</a><a href="#">Privacy</a><a href="#">SOC 2</a><a href="#">Status</a></div>
        </div>
      </div>
      <div className="footer-bot">
        <div>© 2026 Citrus Labs, Inc.</div>
        <div>Made in Brooklyn · Oakland · Lisbon</div>
      </div>
    </footer>
  );
}

// ============ APP ============
const DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#E85D1A",
  "dark": false,
  "density": "roomy"
}/*EDITMODE-END*/;

function App() {
  const ArchitectModal = window.ArchitectModal;
  const SignInModal = window.SignInModal;
  const LeadModal = window.LeadModal;
  const [tweaks, setTweaks] = useTweaks(DEFAULTS);
  const [editMode, setEditMode] = useState(false);
  const [archOpen, setArchOpen] = useState(false);
  const [signInOpen, setSignInOpen] = useState(false);
  const [leadOpen, setLeadOpen] = useState(false);

  useEffect(() => {
    const onArch = () => setArchOpen(true);
    const onSign = () => setSignInOpen(true);
    const onLead = () => setLeadOpen(true);
    window.addEventListener('citrus:open-architect', onArch);
    window.addEventListener('citrus:open-signin', onSign);
    window.addEventListener('citrus:open-lead', onLead);
    return () => {
      window.removeEventListener('citrus:open-architect', onArch);
      window.removeEventListener('citrus:open-signin', onSign);
      window.removeEventListener('citrus:open-lead', onLead);
    };
  }, []);

  useEffect(() => {
    const h = (e) => {
      if (e.data?.type === '__activate_edit_mode') setEditMode(true);
      if (e.data?.type === '__deactivate_edit_mode') setEditMode(false);
    };
    window.addEventListener('message', h);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', h);
  }, []);

  const rootStyle = {
    "--accent": tweaks.accent,
    "--ink": tweaks.dark ? "#F7EFE2" : "#1A120B",
    "--paper": tweaks.dark ? "#0E0B07" : "#F7EFE2",
    "--paper-2": tweaks.dark ? "#1A140D" : "#EFE4D0",
    "--ink-2": tweaks.dark ? "#C9B79A" : "#4A392A",
    "--border": tweaks.dark ? "rgba(247,239,226,0.12)" : "rgba(26,18,11,0.14)",
  };

  return (
    <div className={`citrus-root ${tweaks.dark ? "is-dark" : ""} density-${tweaks.density}`} style={rootStyle}>
      <Nav />
      <Hero />
      <ThreeSteps />
      <AgentRoster />
      <Effect />
      <Security />
      <CTA />
      <Footer />

      <ArchitectModal open={archOpen} onClose={() => setArchOpen(false)} />
      <SignInModal open={signInOpen} onClose={() => setSignInOpen(false)} onRequestLead={() => setLeadOpen(true)} />
      <LeadModal open={leadOpen} onClose={() => setLeadOpen(false)} />

      {editMode && (
        <TweaksPanel title="Tweaks" onClose={() => setEditMode(false)}>
          <TweakSection title="Color">
            <TweakColor label="Accent" value={tweaks.accent} onChange={(v) => setTweaks({ accent: v })} />
            <TweakToggle label="Dark mode" value={tweaks.dark} onChange={(v) => setTweaks({ dark: v })} />
          </TweakSection>
          <TweakSection title="Layout">
            <TweakRadio label="Density" value={tweaks.density}
              options={[{value:"roomy",label:"Roomy"},{value:"compact",label:"Compact"}]}
              onChange={(v) => setTweaks({ density: v })} />
          </TweakSection>
        </TweaksPanel>
      )}
    </div>
  );
}

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