// OperatorFlow landing — sections + interactive LeadDemo.

const { useState: useStateL, useEffect: useEffectL, useRef: useRefL } = React;

// ─────────────────────────────────────────────────────────
// Scroll reveals — once
// ─────────────────────────────────────────────────────────
function useReveal(root) {
  useEffectL(() => {
    if (!root || !root.current) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.classList.add("in");
            io.unobserve(entry.target);
          }
        });
      },
      { threshold: 0.08, rootMargin: "0px 0px -40px 0px" }
    );
    root.current.querySelectorAll("[data-reveal]").forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, [root]);
}

// ─────────────────────────────────────────────────────────
// NavBar
// ─────────────────────────────────────────────────────────
function NavBar({ logoVariant, availability }) {
  return (
    <header className="of-nav">
      <div className="shell of-nav-row">
        <Logo variant={logoVariant} />
        <nav className="of-nav-links" aria-label="Primary">
          <a href="#workflows">Workflows</a>
          <a href="#sprint">AI Ops Sprint</a>
          <a href="#why">Why us</a>
          <a href="#contact">Contact</a>
        </nav>
        <div className="of-nav-right">
          <Pill variant={availability.variant}>{availability.label}</Pill>
          <CTA
            variant="ghost"
            href="mailto:hello@operatorflow.ai?subject=Workflow%20teardown"
            arrow={false}
          >
            Book a teardown
          </CTA>
        </div>
      </div>
    </header>
  );
}

// ─────────────────────────────────────────────────────────
// Hero — switches between three hero treatments
// ─────────────────────────────────────────────────────────
function Hero({ heroTreatment }) {
  let aside;
  if (heroTreatment === "runcard") {
    aside = (
      <RunCard
        name="lead-response"
        scope="run #4f2a"
        status="running"
        steps={[
          { ts: "09:14:02", title: "Inquiry captured", meta: <code>form-submission · {`{intent: "plumbing", urgency: "high"}`}</code>, ms: "84ms", status: "done" },
          { ts: "09:14:03", title: "AI drafts next action", meta: <code>claude-sonnet-4-6 · 142 tokens</code>, ms: "1.2s", status: "done" },
          { ts: "09:14:04", title: "CRM contact upserted", meta: <code>owner = arnab · stage = qualified</code>, ms: "0.3s", status: "done" },
          { ts: "09:14:05", title: "Awaiting human approval", meta: "queued in hello@operatorflow.ai", ms: "—", status: "run" },
        ]}
        foot={{ left: <span>step 4 / 5 · t+3s</span>, right: "approve →" }}
      />
    );
  } else if (heroTreatment === "terminal") {
    aside = <Terminal />;
  } else {
    aside = <Diagram />;
  }

  return (
    <section className="hero">
      <div className="of-ambient" aria-hidden="true" />
      <div className="shell hero-grid">
        <div data-reveal>
          <span className="eyebrow">
            <span className="accent">●</span>&nbsp;&nbsp;ai operations studio · est. 2026
          </span>
          <h1 className="display">
            Operations that don&rsquo;t drop the{" "}
            <span style={{ color: "var(--signal)" }}>thread</span>.
          </h1>
          <p className="lead">
            OperatorFlow ships practical AI-assisted systems for the workflows
            that slow your business down — leads, inboxes, docs, follow-ups,
            handoffs. Human approval where it matters. Real code, not prompt packs.
          </p>
          <div className="hero-actions">
            <CTA
              variant="primary"
              href="mailto:hello@operatorflow.ai?subject=Workflow%20teardown"
              caption="avg. first reply within a day"
            >
              Book a workflow teardown
            </CTA>
            <CTA variant="ghost" href="#sprint" caption="10 business days · fixed scope">
              See the sprint
            </CTA>
          </div>
          <div className="hero-meta">
            <div className="kv">
              <strong>2 workflows</strong>
              <span>shipped per sprint</span>
            </div>
            <div className="kv">
              <strong>10 days</strong>
              <span>build cycle, fixed</span>
            </div>
            <div className="kv">
              <strong>30 days</strong>
              <span>tune-up included</span>
            </div>
            <div className="kv">
              <strong>human-on-loop</strong>
              <span>approval gates by default</span>
            </div>
          </div>
        </div>
        <div data-reveal style={{ minWidth: 0 }}>{aside}</div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────
// Problem — three numbered steps, mono numbers as icons
// ─────────────────────────────────────────────────────────
function Problem() {
  return (
    <section>
      <div className="shell">
        <div className="section-head" data-reveal>
          <span className="eyebrow">/ the problem</span>
          <h2 className="title">Your business should not run on memory, tabs, and manual follow-up.</h2>
          <p className="lead">
            Most teams don&rsquo;t need a moonshot AI strategy. They need a few
            reliable systems around the work that repeats every week — and
            don&rsquo;t need to grow a new hire to operate.
          </p>
        </div>
        <div className="problem-list">
          <ProblemStep n={1} title="Leads age out before someone follows up.">
            Inquiries land in inboxes, forms, DMs, and missed calls. The response
            loop is slower than the customer expects — by the time you reply, the
            buying window has closed.
          </ProblemStep>
          <ProblemStep n={2} title="Answers exist, but nobody can find them in time.">
            Policies, SOPs, project notes, and prior threads are scattered across
            five tools. Teammates ask the founder. The founder is the operating system.
          </ProblemStep>
          <ProblemStep n={3} title="Admin steals operator time, every day.">
            Quotes, summaries, tasks, reminders, weekly reporting, customer
            handoffs. Each one is small. Together they are a second job.
          </ProblemStep>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────
// What we build — three RunCards
// ─────────────────────────────────────────────────────────
function WhatWeBuild() {
  return (
    <section id="workflows">
      <div className="shell">
        <div className="section-head" data-reveal>
          <span className="eyebrow">/ what we build</span>
          <h2 className="title">Small AI systems around high-friction workflows.</h2>
          <p className="lead">
            Each workflow ships with clear inputs, human review where it matters,
            measurable output, and handoff documentation your team can actually use.
          </p>
        </div>
        <div className="workflow-grid">
          <RunCard
            name="lead-response"
            scope="inbound · email + form"
            status="ready"
            steps={[
              { ts: "t+0",  title: "Capture",  meta: <code>form / email / call · normalized</code>, ms: "" },
              { ts: "t+0",  title: "Qualify",  meta: <code>intent · urgency · owner</code>, ms: "" },
              { ts: "t+1",  title: "Draft reply", meta: <code>your voice · booking link</code>, ms: "" },
              { ts: "t+48h", title: "Follow-up nudge", meta: "if no response, queue review", ms: "" },
            ]}
            foot={{ left: <span>shipped · 4 clients</span>, right: null }}
          />
          <RunCard
            name="doc-answers"
            scope="internal assistant"
            status="ready"
            steps={[
              { ts: "ingest", title: "Pull approved docs", meta: <code>drive / notion / slack-pinned</code>, ms: "" },
              { ts: "index",  title: "Embed & version", meta: <code>refreshes daily</code>, ms: "" },
              { ts: "ask",    title: "Answer w/ citations", meta: "links back to source paragraph", ms: "" },
              { ts: "review", title: "Flag uncertainty", meta: "low-confidence → human", ms: "" },
            ]}
            foot={{ left: <span>shipped · 2 clients</span>, right: null }}
          />
          <RunCard
            name="inbox-triage"
            scope="shared mailbox"
            status="ready"
            steps={[
              { ts: "00:01", title: "Classify intent", meta: <code>support · sales · invoice · noise</code>, ms: "" },
              { ts: "00:02", title: "Extract action items", meta: <code>{`{owner, due, task}`}</code>, ms: "" },
              { ts: "00:03", title: "Draft response", meta: "saved as gmail draft", ms: "" },
              { ts: "00:04", title: "Route to owner", meta: "linear / asana / inbox label", ms: "" },
            ]}
            foot={{ left: <span>shipped · 3 clients</span>, right: null }}
          />
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────
// LeadDemo — paste lead → claude drafts reply
// ─────────────────────────────────────────────────────────
const SAMPLE_LEADS = [
  {
    label: "plumbing emergency",
    text: "Hi! Our basement has standing water and the floor drain is bubbling. We're at 412 Oak St in Cabbagetown — can someone come today? Available after 2pm. — Priya",
    canned: {
      intent: "emergency dispatch · plumbing",
      urgency: "high",
      owner: "on-call technician",
      reply: "Hi Priya — sorry to hear this. Standing water plus a bubbling floor drain usually means a main line backup, which we'd want to look at today. I can have a technician at 412 Oak St between 2pm and 4pm. Could you reply with a phone number we can call on the way? Until then, please avoid using sinks, toilets, or anything that drains downstairs. — OperatorFlow",
    },
  },
  {
    label: "agency referral",
    text: "Hey, Mark from Westside Co. referred you. We run a 12-person studio and our lead inbox is a mess — would love to hear how the Sprint works and pricing. Calendly link? — Jordan",
    canned: {
      intent: "inbound · sprint inquiry · warm referral",
      urgency: "medium",
      owner: "founder",
      reply: "Hi Jordan — thanks, glad Mark sent you over. A 12-person studio with a messy lead inbox is exactly what the AI Ops Sprint is built for. Quick way to figure out fit: a free 20-min teardown where we look at your actual inbox flow and tell you whether a sprint would move the needle. Here's the link to grab a time: operatorflow.ai/teardown. Pricing is fixed-scope and we share it on that call. — OperatorFlow",
    },
  },
  {
    label: "tire kicker",
    text: "do you guys do AI? what's the cheapest package",
    canned: {
      intent: "low-intent inquiry · price-led",
      urgency: "low",
      owner: "auto-respond + archive",
      reply: "Hey — yes, we build practical AI systems for small teams, but we don't sell packages by price tier. Every engagement starts with a free 20-min workflow teardown where we figure out whether AI would actually help your specific operation. If you'd like to book one: operatorflow.ai/teardown. If you're just shopping by cost, we're probably not the right fit. — OperatorFlow",
    },
  },
];

// Heuristic stub for arbitrary input — keeps the demo honest without claiming
// to be a live model. Real Claude wiring is a follow-up task (see DEPLOY.md).
function stubClassify(text) {
  const t = text.toLowerCase();
  const urgency =
    /\b(today|asap|urgent|emergency|now|right away|right now|flooding|leaking|down|broken)\b/.test(t)
      ? "high"
      : /\b(this week|tomorrow|soon|by friday|by monday)\b/.test(t)
      ? "medium"
      : "low";
  const intent =
    /\b(price|pricing|cost|cheap|quote)\b/.test(t)
      ? "price inquiry"
      : /\b(refer|referral|sent me|recommended)\b/.test(t)
      ? "warm referral"
      : /\b(emergency|urgent|flood|leak|broken)\b/.test(t)
      ? "emergency / support"
      : "general inquiry";
  const owner = urgency === "high" ? "on-call" : intent === "price inquiry" ? "auto-respond" : "founder";
  return {
    intent,
    urgency,
    owner,
    reply: "Hi — thanks for reaching out. We read every inbound and reply within a business day. To make sure the right person handles this, we'd like to send back a quick teardown of what you described. Could you confirm: (1) the timing pressure on this, and (2) any constraints we should know up front? In the meantime, you can also grab a free 20-min workflow teardown at operatorflow.ai/teardown. — OperatorFlow\n\n[demo response · book a teardown to see it run on your real inbox]",
  };
}

function LeadDemo() {
  const [input, setInput] = useStateL("");
  const [draft, setDraft] = useStateL("");
  const [loading, setLoading] = useStateL(false);
  const [meta, setMeta] = useStateL(null);
  const [error, setError] = useStateL(null);

  const run = async (text, cannedFromSample) => {
    const lead = (text ?? input).trim();
    if (!lead || loading) return;
    setLoading(true);
    setDraft("");
    setError(null);
    setMeta(null);
    const t0 = performance.now();

    // Simulated latency to make the demo feel like a real workflow run.
    const latency = 700 + Math.floor(Math.random() * 600);
    await new Promise((r) => setTimeout(r, latency));

    const result = cannedFromSample || stubClassify(lead);
    const dur = Math.round(performance.now() - t0);
    setMeta({ intent: result.intent, urgency: result.urgency, owner: result.owner, dur });

    const reply = result.reply;
    const prefersReduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (prefersReduced) {
      setDraft(reply);
      setLoading(false);
    } else {
      let i = 0;
      const id = setInterval(() => {
        i += Math.max(2, Math.round(reply.length / 80));
        if (i >= reply.length) {
          setDraft(reply);
          clearInterval(id);
          setLoading(false);
        } else {
          setDraft(reply.slice(0, i));
        }
      }, 18);
    }
  };

  const loadSample = (s) => {
    setInput(s.text);
    setDraft("");
    setMeta(null);
    setError(null);
    run(s.text, s.canned);
  };

  return (
    <section id="demo">
      <div className="shell">
        <div className="section-head" data-reveal>
          <span className="eyebrow">/ try it · live</span>
          <h2 className="title">A lead just landed. Watch the workflow do the boring part.</h2>
          <p className="lead">
            Paste an inbound message — or use a sample — and the same kind of
            workflow we ship will classify it, suggest an owner, and draft a reply
            for human review. Nothing is sent. Your operator stays in control.
          </p>
        </div>
        <div className="lead-demo" data-reveal>
          <div className="lead-demo-head">
            <span>workflow.lead-response · interactive</span>
            <span>
              {loading ? (
                <span style={{ color: "var(--signal)" }}>● running…</span>
              ) : meta ? (
                <span>{meta.dur}ms · ready for review</span>
              ) : (
                <span>idle · waiting for input</span>
              )}
            </span>
          </div>
          <div className="lead-demo-body">
            <div className="lead-demo-pane">
              <div className="lead-demo-label">
                <span>inbound · raw</span>
                <span style={{ color: "var(--ink-dim)" }}>{input.length} chars</span>
              </div>
              <textarea
                rows={9}
                placeholder={"Paste an inbound message here — form submission, email, missed-call transcript…"}
                value={input}
                onChange={(e) => setInput(e.target.value)}
              />
            </div>
            <div className="lead-demo-divider" />
            <div className="lead-demo-pane">
              <div className="lead-demo-label">
                <span>ai draft · for human review</span>
                {meta && (
                  <span style={{ display: "flex", gap: 6, alignItems: "center" }}>
                    <Pill variant={meta.urgency === "high" ? "failed" : meta.urgency === "medium" ? "queued" : "done"} dot>{meta.urgency || "—"}</Pill>
                  </span>
                )}
              </div>
              <div className={`draft ${draft ? "" : "placeholder"}`}>
                {error
                  ? `error · ${error}`
                  : draft
                  ? <>{draft}<span className="cursor">▌</span></>
                  : loading
                  ? "thinking…"
                  : "↳ output appears here. classification, owner, urgency, and a draft reply in your voice."}
              </div>
              {meta && draft && (
                <div style={{
                  marginTop: 14, paddingTop: 12, borderTop: "1px solid var(--line)",
                  fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-dim)",
                  display: "flex", flexWrap: "wrap", gap: 14,
                }}>
                  <span>intent: <span style={{ color: "var(--ink-muted)" }}>{meta.intent}</span></span>
                  <span>owner: <span style={{ color: "var(--ink-muted)" }}>{meta.owner}</span></span>
                </div>
              )}
            </div>
          </div>
          <div className="lead-demo-foot">
            <div className="examples">
              <span style={{ alignSelf: "center", marginRight: 4 }}>try:</span>
              {SAMPLE_LEADS.map((s, i) => (
                <button key={i} onClick={() => loadSample(s)} disabled={loading}>{s.label}</button>
              ))}
            </div>
            <button className="run-btn" onClick={() => run()} disabled={loading || !input.trim()}>
              {loading ? "running…" : "run workflow →"}
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────
// Sprint — manifest + timeline
// ─────────────────────────────────────────────────────────
function Sprint({ availability }) {
  return (
    <section id="sprint">
      <div className="shell">
        <div className="section-head" data-reveal>
          <span className="eyebrow">/ first offer</span>
          <h2 className="title">AI Ops Sprint.</h2>
          <p className="lead">
            A fixed-scope engagement for teams that want a working system, not a
            strategy deck. Two workflows shipped, audited, and handed off in ten
            business days.
          </p>
        </div>
        <div className="sprint-grid">
          <div data-reveal>
            <Manifest
              title="sprint.yml · ai-ops-sprint"
              footer={<>v0.3 · <span style={{ color: "var(--signal)" }}>beta</span></>}
              entries={[
                { k: "duration",       v: "10 business days" },
                { k: "scope",          v: "2 shipped workflows", muted: "+ workflow audit + automation map" },
                { k: "review",         v: "human approval paths on every external action" },
                { k: "deliverables",   v: "running system · handoff docs · 30-day tune-up" },
                { k: "fits",           v: "small teams, agencies, indie founders, local ops" },
                { k: "price",          v: <>beta · <span className="muted">limited early engagements</span></> },
                { k: "availability",   v: <Pill variant={availability.variant}>{availability.label}</Pill> },
                { k: "next-step",      v: "20-min workflow teardown · free" },
              ]}
            />
          </div>
          <div className="sprint-timeline" data-reveal>
            <ProblemStep n={1} title="Map the work.">
              Two days. We sit with the workflow as it actually runs today — inputs,
              tools, owners, exception paths, failure modes — and produce an
              automation map you keep regardless of what we build.
            </ProblemStep>
            <ProblemStep n={2} title="Build the system.">
              Days 3–7. Real code: forms, inboxes, docs, models, queues, approval
              gates. Plausible mocks for anything you don&rsquo;t have yet. We pair with
              your operator daily.
            </ProblemStep>
            <ProblemStep n={3} title="Ship and hand off.">
              Days 8–10. You get the running workflow, the runbook, the keys, and
              a 30-day tune-up window. We don&rsquo;t become a dependency.
            </ProblemStep>
          </div>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────
// Why us — pulled quote left, manifest of credentials right
// ─────────────────────────────────────────────────────────
function Why() {
  return (
    <section id="why">
      <div className="shell why-grid">
        <div data-reveal>
          <span className="eyebrow">/ why us</span>
          <p className="why-quote" style={{ marginTop: 18 }}>
            Built by operators who think in systems, reliability, and the boring
            handoffs between humans and software.
          </p>
          <p className="why-quote-attr">
            arnab saha · founder · operatorflow<br />
            <span style={{ color: "var(--ink-muted)" }}>// shipping agent runtime tools at agentweave.dev</span>
          </p>
        </div>
        <div data-reveal>
          <Manifest
            title="credentials.yml"
            entries={[
              { k: "engineering",  v: "senior eng leadership · platform, data, cloud, AI systems" },
              { k: "portfolio",    v: <a href="https://arnabsaha.com" target="_blank" rel="noreferrer" style={{ color: "var(--signal)", textDecoration: "none", borderBottom: "1px solid var(--signal-dim)" }}>arnabsaha.com →</a> },
              { k: "public-build", v: <>agentweave · agent runtime observability <span className="muted">(MIT, OTel)</span></> },
              { k: "approach",     v: "practical over performative · ship the boring system that fixes the bleeding" },
              { k: "review-model", v: "human-on-loop by design · AI prepares, humans approve" },
              { k: "out-of-scope", v: "strategy decks · prompt packs · agentic moonshots · vendor lock-in" },
              { k: "location",     v: "Vancouver, BC · remote across NA/EU" },
            ]}
          />
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────
// Final CTA — single sentence, one button, mono caption
// ─────────────────────────────────────────────────────────
function FinalCTA({ availability }) {
  return (
    <section className="final-cta" id="contact">
      <div className="shell">
        <div className="final-cta-inner" data-reveal>
          <span className="eyebrow">/ start small</span>
          <h2>Send us the one workflow that keeps slipping.</h2>
          <p className="lead">
            We&rsquo;ll send back a practical teardown and a sprint plan within a
            business day. No deck, no NDA, no &ldquo;intro call.&rdquo;
          </p>
          <div className="actions">
            <CTA
              variant="primary"
              href="mailto:hello@operatorflow.ai?subject=Workflow%20teardown"
              caption="hello@operatorflow.ai · reply within 1 business day"
            >
              Get a workflow teardown
            </CTA>
            <Pill variant={availability.variant}>{availability.label}</Pill>
          </div>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────
// Footer
// ─────────────────────────────────────────────────────────
function Footer({ logoVariant }) {
  return (
    <footer className="of-footer">
      <div className="shell of-footer-row">
        <Logo variant={logoVariant} size={18} />
        <span className="links">
          <a href="mailto:hello@operatorflow.ai">hello@operatorflow.ai</a>
          <a href="https://agentweave.dev" target="_blank" rel="noreferrer">agentweave</a>
          <a href="#top">top ↑</a>
        </span>
        <span className="commit">commit a4f9c2 · 2026.05</span>
      </div>
    </footer>
  );
}

// ─────────────────────────────────────────────────────────
// Landing — composes the full site
// ─────────────────────────────────────────────────────────
function Landing({ accent = "green", logoVariant = "notch", heroTreatment = "diagram", density = "regular", availability }) {
  const rootRef = useRefL(null);
  useReveal(rootRef);

  return (
    <div
      ref={rootRef}
      className={`of-root of-accent-${accent} of-density-${density}`}
    >
      <NavBar logoVariant={logoVariant} availability={availability} />
      <main>
        <Hero heroTreatment={heroTreatment} />
        <Problem />
        <WhatWeBuild />
        <LeadDemo />
        <Sprint availability={availability} />
        <Why />
        <FinalCTA availability={availability} />
      </main>
      <Footer logoVariant={logoVariant} />
    </div>
  );
}

Object.assign(window, { Landing, NavBar, Hero, Problem, WhatWeBuild, LeadDemo, Sprint, Why, FinalCTA, Footer });
