/* global React */
// Landing page sections - composed inside index.html

const { useEffect, useRef, useState } = React;

/* ===============================================================
   PROBLEM FRAMING
=============================================================== */
function ProblemSection() {
  return (
    <section className="section">
      <div className="problem">
        <div className="problem-left">
          <span className="t-eyebrow">The problem</span>
          <h2 className="t-display-md" style={{ marginTop: 12 }}>
            Coding agents are powerful. The terminal is the wrong control surface for them.
          </h2>
        </div>
        <div className="problem-right">
          <p className="t-body-lg">
            Coding agents can plan, write, and ship real work - but most of them ship it through a scrolling
            terminal that hides what they did, why they did it, and what they need from you next.
          </p>
          <p className="t-body-lg">
            Agent Studio gives autonomous engineering work a control plane: a local-first dashboard that exposes
            every plan, patch, test, and approval - without sending your repo anywhere.
          </p>
          <div className="problem-bullets">
            <div className="problem-bullet">
              <span className="dot dot--red"></span>
              <div>
                <div className="t-title-sm">Before</div>
                <div className="t-body-sm muted">Watch logs scroll past, hope the agent didn't drift, scrub history to find what changed.</div>
              </div>
            </div>
            <div className="problem-bullet">
              <span className="dot dot--green"></span>
              <div>
                <div className="t-title-sm">With Agent Studio</div>
                <div className="t-body-sm muted">Staged pipeline, isolated worktrees, approval gates, evidence-linked trace for every run.</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ===============================================================
   FEATURE GRID (tabbed)
=============================================================== */
const FEATURES = [
  {
    id: "visibility",
    eyebrow: "Live visibility",
    tabTitle: "Watch every run",
    title: "See what every agent is doing, while it does it.",
    body: "A live activity feed surfaces tool calls, file edits, and shell commands as they happen. Each run produces a structured trace - not a scrolling log.",
    bullets: [
      "Real-time streaming events from the local daemon",
      "Node-by-node run detail: plans, diffs, tests, reports",
      "Structured artifacts you can link, search, and re-open",
    ],
    preview: <VisibilityPreview />,
  },
  {
    id: "pipeline",
    eyebrow: "Studio pipeline",
    tabTitle: "Plan, run, review",
    title: "Plan, parallelize, review - in one staged workflow.",
    body: "Tasks flow through orchestrator → planner → up to 5 parallel workers → review → reporter. Each stage produces structured outputs the next stage can act on.",
    bullets: [
      "Workers run in isolated git worktrees, never on your branch",
      "Optional review stages and approval checkpoints",
      "Merge & apply happens only when you say so",
    ],
    preview: <PipelinePreview />,
  },
  {
    id: "context",
    eyebrow: "Context inventory",
    tabTitle: "Curated context",
    title: "Give agents the right material - and only that.",
    body: "Attach markdown docs, uploads, screenshots, URLs, and project directories per workspace. The context inventory is local, versioned, and reviewable.",
    bullets: [
      "Markdown docs from your repo, editable in Studio",
      "Uploaded files, screenshots, and saved URLs",
      "Scoped per task, never re-shared without permission",
    ],
    preview: <ContextPreview />,
  },
  {
    id: "providers",
    eyebrow: "Engines & providers",
    tabTitle: "Engines",
    title: "Run on the Studio Engine - or bring your own.",
    body: "Every install ships with the Studio Engine: a curated, ready-to-run model that works out of the box. On paid plans, plug in any external CLI agent or model provider you already use.",
    bullets: [
      "Studio Engine bundled - zero setup, included on every plan",
      "Bring your own CLI agent or API key (Pro and Max)",
      "Per-task, per-role engine selection with health checks",
    ],
    preview: <ProvidersPreview />,
  },
];

function FeaturesSection() {
  // active tab can be set via URL hash like #features-pipeline
  const initial = (() => {
    const m = (typeof window !== "undefined" ? window.location.hash : "").match(/^#features-(\w+)/);
    if (m && FEATURES.find((f) => f.id === m[1])) return m[1];
    return "visibility";
  })();
  const [active, setActive] = useState(initial);

  useEffect(() => {
    const onHash = () => {
      const m = window.location.hash.match(/^#features-(\w+)/);
      if (m && FEATURES.find((f) => f.id === m[1])) setActive(m[1]);
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const feat = FEATURES.find((f) => f.id === active);
  return (
    <section className="section" id="features">
      <div className="section-head">
        <span className="t-eyebrow">Features</span>
        <h2 className="t-display-md">Built like an instrument, not a chat window.</h2>
        <p className="t-body-lg muted">
          Every surface is designed around the four operator questions: what is running, what changed,
          what needs approval, and what evidence supports the result.
        </p>
      </div>

      <div className="feat-shell">
        <div className="feat-tabs" role="tablist">
          {FEATURES.map((f) => (
            <button
              key={f.id}
              role="tab"
              aria-selected={active === f.id}
              className={"feat-tab" + (active === f.id ? " is-active" : "")}
              onClick={() => setActive(f.id)}
            >
              <span className="feat-tab-eyebrow">{f.eyebrow}</span>
              <span className="feat-tab-title">{f.tabTitle}</span>
            </button>
          ))}
        </div>

        <div className="feat-body">
          <div className="feat-text">
            <span className="t-eyebrow">{feat.eyebrow}</span>
            <h3 className="t-display-md" style={{ fontSize: 26, marginTop: 8 }}>{feat.title}</h3>
            <p className="t-body-lg" style={{ marginTop: 12 }}>{feat.body}</p>
            <ul className="feat-bullets">
              {feat.bullets.map((b, i) => (
                <li key={i}>
                  <span className="feat-bullet-mark"></span>
                  <span>{b}</span>
                </li>
              ))}
            </ul>
          </div>
          <div className="feat-preview panel">
            {feat.preview}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---- feature previews ---- */
function VisibilityPreview() {
  return (
    <div>
      <div className="panel-header">
        <span>Live activity · task-2af469</span>
        <span className="ph-meta">streaming</span>
      </div>
      <div className="prev-log">
        <div className="prev-log-row"><span className="prev-log-time">13:42:01</span><span className="prev-log-tag prev-log-tag--info">tool</span><span>read_file src/components/Header.tsx</span></div>
        <div className="prev-log-row"><span className="prev-log-time">13:42:02</span><span className="prev-log-tag prev-log-tag--info">tool</span><span>list_dir src/components/sidebar</span></div>
        <div className="prev-log-row"><span className="prev-log-time">13:42:04</span><span className="prev-log-tag prev-log-tag--ok">edit</span><span>Header.tsx · +4 -1</span></div>
        <div className="prev-log-row"><span className="prev-log-time">13:42:09</span><span className="prev-log-tag prev-log-tag--info">shell</span><span>pnpm typecheck</span></div>
        <div className="prev-log-row"><span className="prev-log-time">13:42:21</span><span className="prev-log-tag prev-log-tag--ok">test</span><span>vitest run · 24 passed</span></div>
        <div className="prev-log-row"><span className="prev-log-time">13:42:31</span><span className="prev-log-tag prev-log-tag--warn">gate</span><span>Awaiting approval · merge changes</span></div>
      </div>
    </div>
  );
}

function PipelinePreview() {
  const stages = [
    { name: "Orchestrator", color: "var(--acp-lavender)", state: "done" },
    { name: "Planner",      color: "var(--acp-cyan)",      state: "done" },
    { name: "Workers ×3",   color: "var(--acp-orange)",   state: "active" },
    { name: "Review",       color: "var(--acp-yellow)",   state: "pending" },
    { name: "Reporter",     color: "var(--acp-green)",    state: "pending" },
  ];
  return (
    <div>
      <div className="panel-header">
        <span>Studio pipeline</span>
        <span className="ph-meta">stage 3 / 5</span>
      </div>
      <div className="prev-pipe">
        {stages.map((s, i) => (
          <div key={i} className={"prev-pipe-stage prev-pipe-" + s.state}>
            <div className="prev-pipe-icon" style={{ background: s.color }}></div>
            <div className="prev-pipe-name">{s.name}</div>
            <div className="prev-pipe-state">{s.state === "done" ? "✓ verified" : s.state === "active" ? "running" : "queued"}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ContextPreview() {
  const items = [
    { type: "md", name: "DESIGN.md", meta: "13h ago · 22k" },
    { type: "md", name: "DESIGN_AGENT_RULES.md", meta: "13h ago · 9k" },
    { type: "md", name: "DESIGN_COMPONENTS.md", meta: "13h ago · 11k" },
    { type: "up", name: "dashboard-v3.png", meta: "Uploaded · screenshot" },
    { type: "url", name: "github.com/agent-studio/spec", meta: "Saved URL" },
    { type: "dir", name: "packages/frontend/src", meta: "Project directory" },
  ];
  return (
    <div>
      <div className="panel-header">
        <span>Context · 26 items</span>
        <span className="ph-meta">scoped to this task</span>
      </div>
      <div className="prev-ctx">
        {items.map((it, i) => (
          <div key={i} className="prev-ctx-row">
            <span className={"prev-ctx-type prev-ctx-type--" + it.type}>{it.type}</span>
            <span className="prev-ctx-name">{it.name}</span>
            <span className="prev-ctx-meta">{it.meta}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function ProvidersPreview() {
  return (
    <div>
      <div className="panel-header">
        <span>Engine readiness</span>
        <span className="ph-meta">2 / 2 healthy</span>
      </div>
      <div className="prev-prov">
        <div className="prev-prov-row">
          <div>
            <div className="t-title-sm">Studio Engine <span className="chip chip--cyan" style={{ marginLeft: 6 }}>Included</span></div>
            <div className="t-mono-xs muted">studio-engine · v1.4 · ready</div>
          </div>
          <span className="chip chip--verified">Healthy</span>
        </div>
        <div className="prev-prov-row">
          <div>
            <div className="t-title-sm">Custom provider <span className="chip chip--idle" style={{ marginLeft: 6 }}>Pro</span></div>
            <div className="t-mono-xs muted">my-cli · v0.9 · byok configured</div>
          </div>
          <span className="chip chip--verified">Healthy</span>
        </div>
        <div className="prev-prov-fix">
          <span className="t-mono-xs">$ studio doctor</span>
          <span className="t-mono-xs muted"> - exit 0, all engines ready</span>
        </div>
      </div>
    </div>
  );
}

/* ===============================================================
   STUDIO PIPELINE VISUAL
=============================================================== */
function PipelineSection() {
  return (
    <section className="section" id="pipeline">
      <div className="section-head">
        <span className="t-eyebrow">Studio pipeline</span>
        <h2 className="t-display-md">One staged workflow. Six roles. Five workers in parallel.</h2>
        <p className="t-body-lg muted">
          Every task moves through the same staged pipeline. Plans before patches, parallel execution in
          worktrees, optional review stages, structured reports - and a clear handoff at every step.
        </p>
      </div>

      <div className="panel" style={{ padding: 0 }}>
        <div className="pipeline-flow" style={{ padding: 24 }}>
          {[
            { name: "Orchestrator", role: "decides the route",     color: "var(--acp-lavender)", evidence: "task-2af469" },
            { name: "Planner",      role: "writes the plan",       color: "var(--acp-cyan)",      evidence: "plan v1 · approved" },
            { name: "Workers",      role: "1–5 in worktrees",      color: "var(--acp-orange)",   evidence: "3 active · 1 done" },
            { name: "Worker review", role: "checks each patch",    color: "var(--acp-yellow)",   evidence: "queued" },
            { name: "Final review", role: "evaluates outcome",     color: "var(--acp-peach)",    evidence: "queued" },
            { name: "Reporter",     role: "summarizes & files",    color: "var(--acp-green)",    evidence: "queued" },
          ].map((s, i) => (
            <div key={i} className="pipeline-node">
              <div className="pipeline-node-head">
                <span className="pipeline-icon" style={{ background: s.color }}></span>
                <div>
                  <div className="pipeline-name">{s.name}</div>
                  <div className="pipeline-role">{s.role}</div>
                </div>
              </div>
              <div className="pipeline-evidence">{s.evidence}</div>
            </div>
          ))}
        </div>

        <div className="pipeline-detail">
          <div>
            <div className="pipeline-detail-head">
              <span className="t-label">Workers · stage 3</span>
              <span className="chip chip--running">Running</span>
            </div>
            <p className="t-body-sm muted" style={{ margin: 0, marginBottom: 10 }}>
              Up to five workers run in parallel, each in its own git worktree. Studio surfaces conflicts on
              integration - never silently overwrites your branch.
            </p>
            <dl className="kv">
              <dt>task-2af469.w1</dt><dd>worktree/feat-blue-btn-w1 · +24 -3</dd>
              <dt>task-2af469.w2</dt><dd>worktree/feat-blue-btn-w2 · +18 -2</dd>
              <dt>task-2af469.w3</dt><dd>worktree/feat-blue-btn-w3 · +9 -1</dd>
            </dl>
          </div>
          <div>
            <div className="pipeline-detail-head">
              <span className="t-label">Run trace</span>
              <span className="chip chip--idle">tool calls only</span>
            </div>
            <pre className="pipeline-log">
{`13:42:01  read_file  src/components/Header.tsx
13:42:02  list_dir   src/components/sidebar
13:42:04  apply      Header.tsx  `}<span className="log-ok">+4 -1</span>{`
13:42:09  shell      pnpm typecheck
13:42:18  shell      pnpm test
13:42:21  test       `}<span className="log-ok">24 passed</span>{`
13:42:31  gate       `}<span className="log-warn">awaiting approval</span>
            </pre>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ===============================================================
   TRUST / TRACEABILITY
=============================================================== */
function TrustSection() {
  const items = [
    { eyebrow: "Trace", title: "Every action has a trace.", body: "Tool calls, shell commands, file reads, and edits are streamed to a structured event log - not buried in scrollback." },
    { eyebrow: "Approval", title: "Every risky step has a gate.", body: "Dependency changes, migrations, merges, and credential-touching work all stop at an explicit approval with evidence." },
    { eyebrow: "Evidence", title: "Every patch ships with tests.", body: "Workers run typecheck, lint, and tests inside their worktree. Studio attaches the output to the run." },
    { eyebrow: "Local", title: "Every byte stays on your machine.", body: "The daemon, worktrees, and Studio state live under ~/.studio. Providers talk to your local CLI, not our servers." },
  ];
  return (
    <section className="section" id="trust">
      <div className="section-head">
        <span className="t-eyebrow">Why teams trust it</span>
        <h2 className="t-display-md">Autonomous engineering, with the audit trail intact.</h2>
        <p className="t-body-lg muted">
          The product promise is simple: agents may plan, code, and test - but every action is observable,
          every risky step is explicit, and every change is reversible.
        </p>
      </div>

      <div className="trust-grid">
        {items.map((it, i) => (
          <div key={i} className="panel trust-card">
            <div className="trust-card-head">
              <span className="t-eyebrow">{it.eyebrow}</span>
            </div>
            <div className="trust-card-body">
              <div className="t-title-lg" style={{ marginBottom: 8 }}>{it.title}</div>
              <p className="t-body-md muted" style={{ margin: 0 }}>{it.body}</p>
            </div>
          </div>
        ))}
      </div>

      <div className="trust-evidence panel">
        <div className="panel-header">
          <span>Evidence stream · last 90s</span>
          <span className="ph-meta">3 runs · 1 awaiting approval</span>
        </div>
        <div className="trust-evidence-body">
          <div className="te-row"><span className="te-time">13:41:32</span><span className="chip chip--verified">Verified</span><span className="te-msg"><span className="m-mono">2af469</span> · plan approved by operator</span></div>
          <div className="te-row"><span className="te-time">13:41:34</span><span className="chip chip--running">Running</span><span className="te-msg"><span className="m-mono">2af469.w1</span> · worktree created at feat-blue-btn-w1</span></div>
          <div className="te-row"><span className="te-time">13:42:09</span><span className="chip chip--idle">Info</span><span className="te-msg"><span className="m-mono">2af469.w1</span> · shell: pnpm typecheck ✓</span></div>
          <div className="te-row"><span className="te-time">13:42:21</span><span className="chip chip--verified">Tests</span><span className="te-msg"><span className="m-mono">2af469.w1</span> · vitest 24/24 passed in 11.2s</span></div>
          <div className="te-row"><span className="te-time">13:42:31</span><span className="chip chip--approval">Awaiting</span><span className="te-msg"><span className="m-mono">2af469.w1</span> · gate: merge patch into integration worktree</span></div>
        </div>
      </div>
    </section>
  );
}

/* ===============================================================
   APPROVAL GATES
=============================================================== */
function ApprovalSection() {
  return (
    <section className="section" id="approvals">
      <div className="approval-grid">
        <div>
          <span className="t-eyebrow">Human-in-the-loop</span>
          <h2 className="t-display-md" style={{ marginTop: 12 }}>Approval gates that tell you exactly what will happen.</h2>
          <p className="t-body-lg muted">
            Gates aren't a yes/no prompt. Each gate shows the requested action, the risk level, the agent
            asking, and the evidence supporting the request - so the decision is informed, not reflexive.
          </p>
          <ul className="approval-list">
            <li><span className="chip chip--risk">Risk</span> Dependency changes, migrations, credentials</li>
            <li><span className="chip chip--approval">Approval</span> Merge, apply-to-branch, open PR</li>
            <li><span className="chip chip--blocked">Blocked</span> Policy violations stop the run cold</li>
          </ul>
        </div>

        <div className="panel approval-gate">
          <div className="approval-gate-head">
            <span className="chip chip--approval">Approval required</span>
            <span className="t-mono-xs muted">gate-2af469-w1-merge</span>
          </div>
          <h3 className="t-title-lg" style={{ marginTop: 12 }}>Merge patch into integration worktree</h3>
          <div className="approval-evidence">
            <dl className="kv">
              <dt>Agent</dt><dd>worker.w1 (Studio Engine)</dd>
              <dt>Task</dt><dd>add blue test button to sidebar</dd>
              <dt>Worktree</dt><dd>feat-blue-btn-w1</dd>
              <dt>Diff</dt><dd>+24 -3 across 2 files</dd>
              <dt>Tests</dt><dd><span style={{ color: "var(--acp-green-dark)" }}>24/24 passed</span> · 11.2s</dd>
              <dt>Risk</dt><dd>Low · no deps, no migrations</dd>
            </dl>
          </div>
          <div className="approval-consequence">
            <span className="t-eyebrow" style={{ color: "var(--acp-muted)" }}>If approved</span>
            <p className="t-body-sm" style={{ margin: "6px 0 0 0" }}>
              Studio merges <span className="m-mono">feat-blue-btn-w1</span> into the integration worktree.
              No changes are pushed to your branch.
            </p>
          </div>
          <div className="approval-actions">
            <button className="btn btn--sm">Defer</button>
            <button className="btn btn--sm">Review diff</button>
            <button className="btn btn--sm" style={{ background: "var(--acp-green)", borderColor: "var(--acp-green-dark)" }}>Approve merge</button>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ===============================================================
   PRICING TEASER
=============================================================== */
function PricingTeaser() {
  return (
    <section className="section" id="pricing">
      <div className="section-head">
        <span className="t-eyebrow">Pricing</span>
        <h2 className="t-display-md">Free with the Studio Engine. Paid when you need more.</h2>
        <p className="t-body-lg muted">
          Every install includes the Studio Engine - no API key, no setup. Upgrade to Pro for higher token
          limits and your own engines, or to Max for unlimited usage.
        </p>
      </div>

      <div className="pricing-grid">
        <div className="panel pricing-card">
          <div className="pricing-head">
            <div>
              <div className="t-eyebrow">Free</div>
              <div className="t-display-md" style={{ fontSize: 26, marginTop: 6 }}>$0</div>
            </div>
            <span className="chip chip--approval">STARTER</span>
          </div>
          <p className="t-body-md muted">Local-first dashboard with the Studio Engine included.</p>
          <ul className="pricing-bullets">
            <li>Studio Engine - bundled, no API key</li>
            <li>Generous monthly token limit</li>
            <li>Up to 5 parallel workers</li>
            <li>Local task history under ~/.studio</li>
          </ul>
          <a className="btn" href="/pricing">Join alpha</a>
        </div>

        <div className="panel pricing-card pricing-card--featured">
          <div className="pricing-head">
            <div>
              <div className="t-eyebrow" style={{ color: "var(--acp-primary-dark)" }}>Pro</div>
              <div className="t-display-md" style={{ fontSize: 26, marginTop: 6 }}>$19<span className="muted t-body-md">/mo</span></div>
              <div className="pricing-price-note">with Alpha pricing</div>
            </div>
            <span className="chip chip--approval">RECOMMENDED</span>
          </div>
          <p className="t-body-md muted">Everything in Free, plus your own engines and advanced controls.</p>
          <ul className="pricing-bullets">
            <li>Increased token limit on Studio Engine</li>
            <li>Bring your own CLI agent (BYOC)</li>
            <li>Bring your own API key (BYOK)</li>
            <li>Per-role engine binding</li>
          </ul>
          <a className="btn btn--primary" href="/pricing">Join alpha</a>
        </div>

        <div className="panel pricing-card">
          <div className="pricing-head">
            <div>
              <div className="t-eyebrow">Max</div>
              <div className="t-display-md" style={{ fontSize: 26, marginTop: 6 }}>$149<span className="muted t-body-md">/mo</span></div>
              <div className="pricing-price-note">with Alpha pricing</div>
            </div>
            <span className="chip chip--approval">POWER USERS</span>
          </div>
          <p className="t-body-md muted">Unlimited token usage for heavy operators.</p>
          <ul className="pricing-bullets">
            <li>Unlimited Studio Engine tokens</li>
            <li>Everything in Pro</li>
            <li>Higher worker concurrency</li>
            <li>Priority engine routing</li>
          </ul>
          <a className="btn" href="/pricing">Join alpha</a>
        </div>
      </div>
    </section>
  );
}

/* ===============================================================
   CTA BAND
=============================================================== */
function CtaBand() {
  const embedRef = useRef(null);
  useEffect(() => {
    const host = embedRef.current;
    if (!host || host.dataset.waitlistMounted === 'true') return;
    host.dataset.waitlistMounted = 'true';
    const hostname = window.location.hostname;
    const isDev = hostname === 'localhost' || hostname === '127.0.0.1' || hostname.endsWith('.local');
    const script = document.createElement('script');
    script.src = isDev
      ? 'https://frugal-wildebeest-16.convex.site/embed.js'
      : 'https://optimistic-mockingbird-89.convex.site/embed.js';
    script.setAttribute('data-waitlist', isDev
      ? 'lmi_af0afdee99a07b425e708b22d07a98a0'
      : 'lmi_86bef0baa973a8603937f49108394e58');
    script.defer = true;
    host.appendChild(script);
  }, []);
  return (
    <section className="section cta-band-section">
      <div className="panel cta-band">
        <div>
          <span className="t-eyebrow">Request access</span>
          <h2 className="t-display-md" style={{ marginTop: 8 }}>Give your agents a control plane.</h2>
          <p className="t-body-lg muted" style={{ maxWidth: 540 }}>
            Agent Studio is in private alpha. Drop your email and we'll send you a build, a short setup guide,
            and a calendar link if you'd like a walkthrough.
          </p>
        </div>
        <div className="cta-form" ref={embedRef} />
      </div>
    </section>
  );
}

Object.assign(window, {
  ProblemSection,
  FeaturesSection,
  PipelineSection,
  TrustSection,
  ApprovalSection,
  PricingTeaser,
  CtaBand,
});
