// automations.jsx — AI Agents showcase section

const AGENTS = [
  {
    id: 'research-write',
    name: 'Research-then-Write',
    tag: 'Multi-agent · Content',
    tagline: 'Sourced long-form articles, zero human hours.',
    what: 'Orchestrator spins up three sub-agents: Researcher pulls 8–15 verified sources via Exa, Writer composes a structured long-form draft with inline citations, Editor checks facts and flow. Finished article lands in Notion as a Draft page.',
    model: 'claude-sonnet-4-6',
    trigger: 'Webhook / cron',
    tools: ['exa', 'notion'],
    phases: ['Researcher', 'Writer', 'Editor', 'Publish'],
    phaseIcons: ['⊠', '✦', '✓', '↗'],
    metric: { before: '6h manual research', after: '0h human time', delta: '−100%' },
    color: 'var(--ai)',
    log: [
      'Searching: "AI regulation 2025 policy"',
      '12 sources found · 3 deduped',
      'Research brief compiled: 1,840 words',
      'Writer phase started → target 1,500w',
      'Draft complete: 1,512 words, 9 citations',
      'Editor: 4 redundancies removed',
      'Notion page created: "Draft" status set',
    ],
  },
  {
    id: 'sales-triage',
    name: 'Sales Triage Squad',
    tag: 'Multi-agent · Sales',
    tagline: 'Raw leads → scored contacts → ready-to-send emails.',
    what: 'Three-agent squad runs every 30 minutes. Enrichment Agent pulls company + title data from Apollo and dedupes against HubSpot. Scoring Agent assigns a 0–100 ICP score. Outreach Agent drafts a personalized first-touch email for every WARM/HOT lead.',
    model: 'claude-sonnet-4-6',
    trigger: 'Cron / webhook (30min)',
    tools: ['apollo', 'hubspot', 'slack', 'agentmail'],
    phases: ['Enrich', 'Score', 'Draft', 'Notify'],
    phaseIcons: ['◉', '▤', '✦', '✓'],
    metric: { before: '45min manual triage', after: '30s per batch', delta: '−98%' },
    color: 'var(--success)',
    log: [
      '14 new leads received',
      'Apollo enrichment: 12 matched, 2 incomplete',
      'HubSpot dedupe: 3 SKIP (already qualified)',
      'Scoring: 4 HOT · 5 WARM · 2 COLD',
      '9 outreach drafts created in agentmail',
      'Slack summary posted → #sales-leads',
      'Batch complete in 28s',
    ],
  },
  {
    id: 'contract-intel',
    name: 'Contract Intelligence',
    tag: 'Single agent · Legal Ops',
    tagline: 'Every contract reviewed in under 90 seconds.',
    what: 'Upload a PDF or link a Drive file. The agent parses clauses, flags unusual terms (auto-renewal traps, liability caps, IP assignment), extracts key dates and parties, and writes a plain-English risk summary. Sends a Slack alert for any high-risk clause. Saves structured output to Notion.',
    model: 'claude-sonnet-4-6',
    trigger: 'Webhook (file upload)',
    tools: ['drive', 'notion', 'slack'],
    phases: ['Ingest', 'Parse', 'Risk Flag', 'Summarize'],
    phaseIcons: ['⊞', '◇', '◐', '▤'],
    metric: { before: '2h lawyer review', after: '90s AI review', delta: '−97%' },
    color: 'var(--accent)',
    log: [
      'Contract received: "MSA_ClientX_2025.pdf"',
      'Parsing 34 pages · 9,200 words',
      '3 clauses flagged as HIGH RISK',
      'Auto-renewal: 60-day window detected',
      'IP assignment: "work for hire" clause found',
      'Summary written: 280 words, plain English',
      'Slack alert sent · Notion page saved',
    ],
  },
  {
    id: 'newsletter-factory',
    name: 'AI Newsletter Factory',
    tag: 'Multi-agent · Content Ops',
    tagline: 'One brief → a ready-to-send newsletter in 8 minutes.',
    what: 'You drop a topic brief. Curator Agent searches Exa for the week\'s best sources. Writer Agent drafts an editorial newsletter in your brand voice. Formatter Agent structures it for Beehiiv/Ghost with proper headings and CTAs. Sends a preview to Slack for one-click approval before publishing.',
    model: 'claude-sonnet-4-6',
    trigger: 'Webhook / manual trigger',
    tools: ['exa', 'notion', 'slack', 'beehiiv'],
    phases: ['Curate', 'Write', 'Format', 'Approve'],
    phaseIcons: ['⊠', '✦', '◈', '✓'],
    metric: { before: '3h manual writing', after: '8min review only', delta: '−96%' },
    color: 'var(--ai)',
    log: [
      'Brief received: "AI tools for small teams"',
      'Curation: 18 sources scanned · 6 selected',
      'Writing draft: target 900 words',
      'Draft complete: 872 words, 3 sections',
      'Formatted for Beehiiv: header + CTA added',
      'Preview sent to Slack: #content-team',
      'Awaiting approval → 1 click to publish',
    ],
  },
  {
    id: 'code-review',
    name: 'Code Review Orchestrator',
    tag: 'Multi-agent · Engineering',
    tagline: 'PR analysis, security check, and doc review in 90s.',
    what: 'Triggered on every pull request. Analyzer Agent reviews logic, complexity, and patterns. Security Agent scans for common vulnerabilities (OWASP top 10, secrets in code). Doc Agent checks that public functions have accurate docstrings. A structured review comment is posted to the PR.',
    model: 'claude-sonnet-4-6',
    trigger: 'GitHub webhook (PR opened)',
    tools: ['github', 'linear', 'slack'],
    phases: ['Analyze', 'Security', 'Docs', 'Comment'],
    phaseIcons: ['◇', '◐', '▤', '↗'],
    metric: { before: '30–60min human review', after: '90s auto review', delta: '−97%' },
    color: 'var(--success)',
    log: [
      'PR #142 opened: "feat: add payment webhook"',
      'Analyzer: 3 files · +187 −42 lines',
      '1 high-complexity function flagged',
      'Security: no secrets detected ✓',
      '1 potential injection point flagged',
      'Docs: 2 public functions missing docstrings',
      'Review comment posted to PR #142',
    ],
  },
  {
    id: 'churn-predictor',
    name: 'Churn Predictor',
    tag: 'Single agent · Customer Success',
    tagline: 'Spot at-risk accounts 2 weeks before they leave.',
    what: 'Runs nightly. Pulls usage, billing, and support data from Stripe, Mixpanel, and HubSpot. Scores each account on a churn risk model (login frequency, feature adoption, support volume, payment history). Flags HIGH RISK accounts in HubSpot and sends a Slack digest with suggested retention actions.',
    model: 'claude-sonnet-4-6',
    trigger: 'Cron (nightly)',
    tools: ['stripe', 'mixpanel', 'hubspot', 'slack'],
    phases: ['Collect', 'Analyze', 'Score', 'Alert'],
    phaseIcons: ['⊞', '◉', '▤', '⚑'],
    metric: { before: 'Churn surprise', after: '14-day early warning', delta: '+14 days' },
    color: 'var(--danger)',
    log: [
      'Nightly run started: 284 accounts',
      'Stripe: payment + plan data pulled',
      'Mixpanel: 30-day usage trends loaded',
      '12 accounts flagged HIGH RISK',
      '3 accounts show payment decline pattern',
      'HubSpot: risk scores written to contacts',
      'Slack digest sent → #customer-success',
    ],
  },
  {
    id: 'agentmail',
    name: 'AgentMail Copilot',
    tag: 'Single agent · Email Ops',
    tagline: 'Send, read, and auto-reply — inbox runs itself.',
    what: 'Email operations copilot powered by AgentMail. Reads incoming messages, classifies intent, drafts contextual replies in your voice, and sends — all headlessly. Handles outbound campaigns, follow-up threads, and auto-reply rules without a human in the loop.',
    model: 'claude-sonnet-4-6',
    trigger: 'Webhook / polling',
    tools: ['agentmail'],
    phases: ['Read', 'Classify', 'Draft', 'Send'],
    phaseIcons: ['⊠', '◇', '✦', '↗'],
    metric: { before: '45min inbox/day', after: '0min inbox/day', delta: '−100%' },
    color: 'var(--accent)',
    log: [
      '8 new emails received',
      'Classified: 3 Inquiry · 2 Follow-up · 3 Auto',
      'Auto-archived: receipts + newsletters',
      'Drafting reply: "Re: proposal timeline"',
      'Reply sent — matched sender tone',
      'Follow-up scheduled: 48h if no reply',
      'Inbox zero achieved in 12s',
    ],
  },
  {
    id: 'browseruse',
    name: 'BrowserUse Extractor',
    tag: 'Single agent · Web Scraping',
    tagline: 'Structured data from any website — no API needed.',
    what: 'Point it at any URL. BrowserUse Cloud drives a real browser, navigates pagination, clicks through dynamic content, and extracts clean structured data — tables, product listings, job boards, pricing pages, directories. Returns JSON ready to pipe into your CRM, sheet, or database.',
    model: 'claude-sonnet-4-6',
    trigger: 'Webhook / on-demand',
    tools: ['browseruse'],
    phases: ['Navigate', 'Interact', 'Extract', 'Output'],
    phaseIcons: ['◉', '◈', '⊞', '↗'],
    metric: { before: '3h manual copy-paste', after: '2min automated', delta: '−96%' },
    color: 'var(--success)',
    log: [
      'Target: "G2 reviews page · 12 pages"',
      'Browser launched via BrowserUse Cloud',
      'Navigating paginated results...',
      'Page 1 of 12: 25 reviews extracted',
      'Handling dynamic load — scrolling',
      'All 12 pages complete: 284 records',
      'JSON output ready → piped to Notion',
    ],
  },
  {
    id: 'support-agent',
    name: 'Docs Support Agent',
    tag: 'Single agent · Support',
    tagline: 'Answers from llms.txt — escalates the rest via email.',
    what: 'Docs-powered support agent. Reads your llms.txt knowledge base and answers user questions directly. When confidence is low or the question is outside scope, it escalates automatically via Resend — sending a well-formatted email to your support team with full context. Zero tickets fall through the cracks.',
    model: 'claude-sonnet-4-6',
    trigger: 'Webhook (support form)',
    tools: ['resend', 'llms.txt'],
    phases: ['Receive', 'Search Docs', 'Answer', 'Escalate'],
    phaseIcons: ['⊠', '◐', '✦', '◷'],
    metric: { before: '4h avg response', after: '8s AI answer', delta: '−99%' },
    color: 'var(--ai)',
    log: [
      'Question: "How do I connect my CRM to Zapier?"',
      'Searching llms.txt knowledge base...',
      '3 relevant sections found (score > 0.82)',
      'Answer drafted: 4 steps, 2 code snippets',
      'Confidence: 0.91 → sending directly',
      'Reply sent in 8s via Resend',
      'Low-confidence fallback: escalate path ready',
    ],
  },
];

window.AGENTS = AGENTS;

// ─── Animated phase pipeline ────────────────────────────────────────────────
const AgentPhases = ({ phases, phaseIcons, color, active }) => (
  <div className="ag-phases">
    {phases.map((p, i) => (
      <React.Fragment key={i}>
        <div className={`ag-phase ${i === active ? 'ag-phase-on' : i < active ? 'ag-phase-done' : ''}`}
          style={i === active ? { '--ag-color': color } : {}}>
          <div className="ag-phase-icon">{phaseIcons[i]}</div>
          <div className="ag-phase-label">{p}</div>
        </div>
        {i < phases.length - 1 && (
          <div className={`ag-phase-arrow ${i < active ? 'ag-phase-arrow-done' : ''}`}>→</div>
        )}
      </React.Fragment>
    ))}
  </div>
);

// ─── Animated log stream ────────────────────────────────────────────────────
const AgentLog = ({ log, tick }) => {
  const visible = Math.min(tick + 1, log.length);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (ref.current) ref.current.scrollTop = ref.current.scrollHeight;
  }, [visible]);
  return (
    <div className="ag-log" ref={ref}>
      {log.slice(0, visible).map((line, i) => (
        <div key={i} className={`ag-log-line ${i === visible - 1 ? 'ag-log-new' : ''}`}>
          <span className="ag-log-idx">{String(i + 1).padStart(2, '0')}</span>
          <span>{line}</span>
        </div>
      ))}
      {visible < log.length && <div className="ag-log-cursor">▋</div>}
    </div>
  );
};

// ─── Single agent card (collapsed + expanded) ───────────────────────────────
const AgentCard = ({ agent, isOpen, onToggle }) => {
  const [tick, setTick] = React.useState(-1);
  const [running, setRunning] = React.useState(false);

  const activePhase = Math.min(
    Math.floor(tick / Math.ceil(agent.log.length / agent.phases.length)),
    agent.phases.length - 1
  );

  React.useEffect(() => {
    if (!isOpen) { setTick(-1); setRunning(false); return; }
    const delay = setTimeout(() => { setRunning(true); setTick(0); }, 400);
    return () => clearTimeout(delay);
  }, [isOpen]);

  React.useEffect(() => {
    if (!running) return;
    if (tick >= agent.log.length - 1) { setRunning(false); return; }
    const id = setTimeout(() => setTick(t => t + 1), 480 + Math.random() * 240);
    return () => clearTimeout(id);
  }, [running, tick]);

  const restart = (e) => {
    e.stopPropagation();
    setTick(-1);
    setRunning(false);
    setTimeout(() => { setRunning(true); setTick(0); }, 80);
  };

  return (
    <div className={`ag-card ${isOpen ? 'ag-card-open' : ''}`} onClick={onToggle}>
      {/* Card header — always visible */}
      <div className="ag-card-head">
        <div className="ag-card-left">
          <div className="ag-tag-pill">{agent.tag}</div>
          <div className="ag-card-name">{agent.name}</div>
          <div className="ag-card-tagline">{agent.tagline}</div>
        </div>
        <div className="ag-card-right">
          <div className="ag-tools-strip">
            {agent.tools.map(t => (
              <span key={t} className="ag-tool">{t}</span>
            ))}
          </div>
          <div className="ag-card-trigger">
            <span className="ag-trigger-dot" style={{ background: agent.color }} />
            <span className="ag-mono">{agent.trigger}</span>
          </div>
          <div className={`ag-chevron ${isOpen ? 'ag-chevron-open' : ''}`}>↓</div>
        </div>
      </div>

      {/* Expanded body */}
      {isOpen && (
        <div className="ag-card-body" onClick={e => e.stopPropagation()}>
          <div className="ag-body-split">
            {/* Left — details */}
            <div className="ag-detail">
              <p className="ag-what">{agent.what}</p>

              <div className="ag-row">
                <span className="ag-k">Model</span>
                <span className="ag-mono ag-v">{agent.model}</span>
              </div>
              <div className="ag-row">
                <span className="ag-k">MCP servers</span>
                <span className="ag-v ag-tools-inline">
                  {agent.tools.map(t => <span key={t} className="ag-tool ag-tool-lg">{t}</span>)}
                </span>
              </div>

              <div className="ag-metric">
                <div className="ag-m-col">
                  <div className="ag-m-l">Before</div>
                  <div className="ag-m-v ag-m-before">{agent.metric.before}</div>
                </div>
                <div className="ag-m-arr">→</div>
                <div className="ag-m-col">
                  <div className="ag-m-l">After</div>
                  <div className="ag-m-v ag-m-after">{agent.metric.after}</div>
                </div>
                <div className="ag-m-delta" style={{ color: agent.color }}>{agent.metric.delta}</div>
              </div>
            </div>

            {/* Right — live run visualization */}
            <div className="ag-viz">
              <div className="ag-viz-head">
                <span className="ag-viz-label">
                  <span className="ag-pulse" style={{ background: running ? agent.color : 'var(--muted)' }} />
                  {running ? 'running' : tick >= agent.log.length - 1 ? 'complete' : 'idle'}
                </span>
                <button className="ag-restart" onClick={restart} title="Re-run">↺ run again</button>
              </div>
              <AgentPhases
                phases={agent.phases}
                phaseIcons={agent.phaseIcons}
                color={agent.color}
                active={tick >= 0 ? activePhase : -1}
              />
              <AgentLog log={agent.log} tick={tick} />
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ─── Section ────────────────────────────────────────────────────────────────
const AgentShowcase = () => {
  const [openId, setOpenId] = React.useState(null);
  const [filter, setFilter] = React.useState('All');

  const cats = ['All', 'Sales', 'Content', 'Legal Ops', 'Content Ops', 'Engineering', 'Customer Success'];
  const catShort = {
    'All': 'All',
    'Sales': 'Sales',
    'Content': 'Content',
    'Legal Ops': 'Legal',
    'Content Ops': 'Content Ops',
    'Engineering': 'Eng',
    'Customer Success': 'CS',
  };

  const agentCat = (a) => a.tag.split(' · ')[1];
  const filtered = filter === 'All' ? AGENTS : AGENTS.filter(a => agentCat(a) === filter);

  const toggle = (id) => setOpenId(prev => prev === id ? null : id);

  return (
    <section className="section agents" id="agents">
      <Reveal><SectionLabel num="07" label="AI Agents" /></Reveal>
      <Reveal delay={80}>
        <h2 className="sec-h">Advanced automations — <em>multi-agent systems</em> running headless.</h2>
      </Reveal>
      <Reveal delay={140}>
        <p className="sec-sub">
          Beyond simple workflows — these are orchestrated AI pipelines using Anthropic Managed Agents and MCP servers.
          Click any card to watch the agent run live.
        </p>
      </Reveal>

      <Reveal delay={180} className="ag-filter-wrap">
        <div className="ag-filter">
          {['All', 'Sales', 'Content', 'Legal Ops', 'Content Ops', 'Engineering', 'Customer Success'].map(c => {
            const count = c === 'All' ? AGENTS.length : AGENTS.filter(a => agentCat(a) === c).length;
            if (count === 0) return null;
            return (
              <button
                key={c}
                className={`ag-filter-btn ${filter === c ? 'on' : ''}`}
                onClick={() => { setFilter(c); setOpenId(null); }}
              >
                {catShort[c]}
                <span className="ag-filter-count">{count}</span>
              </button>
            );
          })}
        </div>
      </Reveal>

      <div className="ag-stack">
        {filtered.map((agent, i) => (
          <Reveal key={agent.id} delay={i * 60} y={20}>
            <AgentCard
              agent={agent}
              isOpen={openId === agent.id}
              onToggle={() => toggle(agent.id)}
            />
          </Reveal>
        ))}
      </div>

      <Reveal delay={200} y={20}>
        <div className="ag-cta-strip">
          <div className="ag-cta-text">
            <div className="ag-cta-h">Want a custom agent built for your workflow?</div>
            <div className="ag-cta-sub">Every system above can be adapted, combined, or built from scratch around your stack.</div>
          </div>
          <a className="btn-primary" href="#contact">Book a free audit →</a>
        </div>
      </Reveal>
    </section>
  );
};

window.AgentShowcase = AgentShowcase;
