/*
  Bento — the main feature showcase, replacing the old stacked "cards over cards"
  grids (Moat + Features + Ecosystem). One asymmetric bento grid per PRODUCT MODE:

    studio   → the MIT engine (:18802): prompt → a real app, any domain.
    business → the paid layer (:18804): prompt → an AI-operated business.

  Varied tile spans (a large lead tile + 2x1 + 1x1) on a 6-col desktop grid;
  collapses to one column on mobile via the .bento-grid media rule in design.css.
  Uses the existing design tokens + I.* icons — cohesive with the rest of the site.
*/

// Each tile: { span:[cols,rows], icon, kicker, title, body, proof, feature? }
const BENTO = {
  studio: {
    label: 'HOW IT WORKS · THE ARCHITECT + AGENT TEAM',
    title: <>One Architect. A <Italic>whole software team</Italic>.</>,
    lede: 'It doesn’t autocomplete code — it runs the real pipeline, clarify to go-live, with a team of specialist agents. And everything a real system needs comes standard: a backend, workflows, accounts and roles, connectors, a design system and responsive screens.',
    tiles: [
      { span: [12, 1], feature: true, icon: 'sparkle', kicker: 'THE PIPELINE · CLARIFY → SHIP',
        title: 'The whole pipeline, start to finish',
        body: 'Nine stages, each a specialist agent doing real work — clarifying the ask, writing the PRD, modelling the system, composing, designing, building, reviewing, connecting, shipping. Click any step to see exactly what it produced.',
        pipeline: true },
      // Three that SHOW it — real Studio surfaces, not another icon card.
      { span: [3, 1], shot: 'studio-workflows', shotPos: '62% 26%', shotZoom: 1.75, kicker: 'WORKFLOWS',
        title: 'Cross-app automations',
        body: 'Event- and schedule-driven flows with AI-agent steps in the middle. The business logic, not just screens.' },
      { span: [3, 1], shot: 'studio-connectors', shotPos: '36% 26%', shotZoom: 1.75, kicker: 'CONNECTORS',
        title: 'Your tools, connected',
        body: 'Email, payments, calendars, EHRs — through a secure vault. Build against mocks, flip to live.' },
      { span: [3, 1], shot: 'studio-responsive', shotPos: '54% 34%', shotZoom: 1.6, kicker: 'RESPONSIVE',
        title: 'Every screen size',
        body: 'Phone, tablet and desktop from the first build — and you can check each one right in the Studio.' },
      { span: [3, 1], shot: 'studio-code', shotPos: '42% 30%', shotZoom: 1.55, kicker: 'THE CODE IS YOURS',
        title: 'Open it. Change it. Keep it.',
        body: 'Not a black box — real TypeScript in a real repo, editable line by line. Download it, self-host it, bring your own LLM. MIT.',
        chips: ['src/App.tsx', 'src/pages/', 'src/workflows/', 'src/connectors/', 'theme.css', '.github/workflows/ci.yml'] },

      // The rest as a spec sheet, with real numbers from the run above.
      { span: [12, 1], spec: true, icon: 'stack', kicker: 'STANDARD EQUIPMENT',
        title: 'What every app ships with',
        items: [
          { k: 'AI agent team',   v: 'PM · Modeler · Designer · Workflow Architect · Build Engineer · Reviewer' },
          { k: 'Accounts & roles', v: 'End-user sign-in with role-based access, built into every app' },
          { k: 'Database & jobs',  v: 'A real database, background workers and scheduled tasks' },
          { k: 'Design system',    v: 'A tokenised theme per app — colour, type and components' },
          { k: 'Plugins',          v: 'Extend the engine, and the apps it builds' },
          { k: 'Knowledge base',   v: 'Cited answers grounded in the workspace’s own documents' },
        ],
        evidence: ['11 entities', '5 workflows', '8 connectors', '158 files', '11 screens'] },
    ],
  },
  business: {
    label: 'THE ANATOMY · WHAT GETS FOUNDED',
    title: <>Everything a company <Italic>runs on</Italic>.</>,
    lede: 'A company is not one app. It is the software its staff and customers use, the people who run it, the routines that keep it moving, and the judgement about when to ask a human. All six are generated, then operated.',
    tiles: [
      { span: [8, 2], feature: true, icon: 'sparkle', kicker: 'THE DIFFERENTIATOR',
        title: 'An AI team that builds AND runs it',
        body: 'Not another app builder. Describe a business and it provisions the whole company — apps, an AI agent team, cross-app workflows, connectors — then the team executes the work: reachable across the channels customers already use, asking for approval on consequential actions, and evolving the apps over time.',
        proof: 'AI team · workflows · omni-channel gateway · HITL approvals · evolution' },
      { span: [4, 1], icon: 'stack', kicker: 'DOMAIN EXPERTISE',
        title: 'Vertical playbooks',
        body: 'Realty, commerce, healthcare — expertise shipped as data packs the composer matches, adapts, or ignores. A build starts from real knowledge.' },
      { span: [4, 1], icon: 'clock', kicker: 'THE PLAN',
        title: 'Backlog + Now / Next / Later',
        body: 'Every build opens a living roadmap. “Later” items become one-click evolutions. The plan stays the record of what shipped and what’s next.' },
      { span: [4, 1], icon: 'cpu', kicker: 'MULTI-TENANT',
        title: 'Golden catalog',
        body: 'Curated, reusable business + app bundles — installed, then re-forged per tenant so every business is its own, not a frozen clone.' },
      { span: [4, 1], icon: 'compass', kicker: 'OMNI-CHANNEL',
        title: 'One team, every channel',
        body: 'The AI team is @-addressable across the channels customers live on — one conversation, wherever it happens.' },
      { span: [4, 1], icon: 'shield', kicker: 'OPEN-CORE',
        title: 'On an engine you can own',
        body: 'The business layer is paid; the engine underneath is MIT and self-hostable. No black box beneath your company.' },
    ],
  },
};

/* The nine real pipeline stages. Each image is a frame of the ACTUAL recorded
   run (chapter labels are the run's own), so clicking a step shows exactly what
   that agent produced. */
const PIPELINE_STAGES = [
  { n: '01', label: 'Clarify',      img: 'stage-clarify',      caption: 'Clarifying the ask' },
  { n: '02', label: 'PRD',          img: 'stage-requirements', caption: 'Writing the PRD' },
  { n: '03', label: 'Model',        img: 'stage-model',        caption: 'Modelling the system' },
  { n: '04', label: 'Compose',      img: 'stage-compose',      caption: 'Composing the graph' },
  { n: '05', label: 'Design',       img: 'stage-design',       caption: 'Laying out the storyboard' },
  { n: '06', label: 'Build',        img: 'stage-build',        caption: 'Building the screens' },
  { n: '07', label: 'Review',       img: 'stage-review',       caption: 'Reviewing against the PRD' },
  { n: '08', label: 'Connect',      img: 'stage-connect',      caption: 'Connecting real data + automations' },
  { n: '09', label: 'Ship',         img: 'stage-ship',         caption: 'Built, reviewed & live' },
];

const PipelineStepper = () => {
  // Closed by default — an open screenshot here competes with the hero. The
  // steps read as one compact rail; clicking one reveals it (click again to close).
  const [i, setI] = React.useState(null);
  const s = i == null ? null : PIPELINE_STAGES[i];
  return (
    <div style={{ marginTop: 16 }}>
      {/* One row, always: cards flex to share the width; scrolls on narrow. */}
      <div className="pipeline-rail" style={{
        display: 'flex', flexWrap: 'nowrap', alignItems: 'stretch', gap: 4,
        overflowX: 'auto', paddingBottom: 2,
      }}>
        {PIPELINE_STAGES.map((st, k) => {
          const on = k === i;
          return (
            <React.Fragment key={st.img}>
              {k > 0 && <I.chevronRight size={11} style={{ color: 'var(--fg-4)', flexShrink: 0, alignSelf: 'center' }} />}
              <button type="button" onClick={() => setI(on ? null : k)}
                title={on ? 'Hide this stage' : st.caption}
                style={{
                  flex: '1 1 0', minWidth: 78,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                  padding: '9px 8px', borderRadius: 9, cursor: 'pointer', font: 'inherit',
                  background: on ? 'var(--accent-soft)' : 'var(--bg-2)',
                  border: `1px solid ${on ? 'var(--accent)' : 'var(--line-2)'}`,
                  transition: 'background 160ms, border-color 160ms',
                }}>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9.5, letterSpacing: '0.06em', color: on ? 'var(--accent-2)' : 'var(--fg-4)', flexShrink: 0 }}>{st.n}</span>
                <span style={{ fontSize: 12, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', color: on ? 'var(--fg-1)' : 'var(--fg-2)' }}>{st.label}</span>
              </button>
            </React.Fragment>
          );
        })}
      </div>

      {/* Revealed on click only. */}
      {s && (
        <div style={{ marginTop: 14, border: '1px solid var(--line-2)', borderRadius: 12, overflow: 'hidden', background: '#0a0a0f', animation: 'lb-fade 260ms ease-out' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', borderBottom: '1px solid var(--line-1)', background: 'var(--bg-2)' }}>
            <span className="mono-label" style={{ fontSize: 10, color: 'var(--accent-2)' }}>{s.n}</span>
            <span className="mono-label" style={{ fontSize: 10.5, color: 'var(--fg-3)' }}>{s.caption}</span>
            <button type="button" onClick={() => setI(null)} title="Close" aria-label="Close"
              style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', color: 'var(--fg-3)', background: 'transparent', border: 'none', cursor: 'pointer', padding: 2 }}>
              <I.close size={13} />
            </button>
          </div>
          <div style={{ aspectRatio: '16 / 9', overflow: 'hidden' }}>
            <img key={s.img} src={`/screenshots/generated/${s.img}.png`} alt={`Pipeline — ${s.caption}`}
              title="Click to enlarge"
              onClick={() => window.openLightbox(`/screenshots/generated/${s.img}.png`, `Pipeline ${s.n} · ${s.caption}`)}
              style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', cursor: 'zoom-in' }} />
          </div>
        </div>
      )}
    </div>
  );
};

/* Spec sheet — the remaining capabilities as a datasheet rather than nine
   identical cards, closed with real numbers from the run shown above. */
const SpecSheet = ({ items = [], evidence = [] }) => (
  <div style={{ marginTop: 4 }}>
    <div className="spec-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))', columnGap: 36 }}>
      {items.map((it) => (
        <div key={it.k} style={{ display: 'flex', gap: 14, alignItems: 'baseline', padding: '11px 0', borderTop: '1px solid var(--line-1)' }}>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.03em', color: 'var(--accent-2)', flex: '0 0 128px' }}>{it.k}</span>
          <span style={{ fontSize: 13.5, color: 'var(--fg-2)', lineHeight: 1.5 }}>{it.v}</span>
        </div>
      ))}
    </div>
    {evidence.length > 0 && (
      <div style={{ marginTop: 18, paddingTop: 15, borderTop: '1px solid var(--line-2)', display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--fg-4)', marginRight: 2 }}>Measured on the run above</span>
        {evidence.map((e) => (
          <span key={e} style={{ fontFamily: 'var(--font-mono)', fontSize: 11.5, color: 'var(--fg-1)', background: 'var(--bg-3)', border: '1px solid var(--line-2)', borderRadius: 7, padding: '4px 10px' }}>{e}</span>
        ))}
      </div>
    )}
  </div>
);

const BentoTile = ({ t }) => {
  const [h, setH] = React.useState(false);
  const Icn = I[t.icon] || I.sparkle;
  const pad = t.feature ? 28 : 20;
  return (
    <div
      className={`bento-tile bento-span-${t.span[0]}`}
      onMouseEnter={() => setH(true)}
      onMouseLeave={() => setH(false)}
      style={{
        gridColumn: `span ${t.span[0]}`,
        gridRow: `span ${t.span[1]}`,
        background: t.feature
          ? 'linear-gradient(150deg, var(--accent-soft), var(--bg-1) 65%)'
          : 'var(--bg-1)',
        border: `1px solid ${h ? 'var(--line-3)' : 'var(--line-2)'}`,
        borderRadius: 16,
        padding: 0,
        display: 'flex', flexDirection: 'column',
        position: 'relative', overflow: 'hidden',
        transition: 'border-color 160ms, transform 160ms',
        transform: h ? 'translateY(-2px)' : 'none',
        minHeight: t.feature ? 220 : 0,
      }}>
      {/* Show, don't tell: a real Studio surface heads the tile. */}
      {t.shot && (
        <div style={{ aspectRatio: '16 / 10', overflow: 'hidden', borderBottom: '1px solid var(--line-1)', background: 'var(--bg-2)' }}>
          <img src={`/screenshots/generated/${t.shot}.png`} alt={t.title} loading="lazy" title="Click to enlarge"
            onClick={() => window.openLightbox(`/screenshots/generated/${t.shot}.png`, `AutoArchitect Studio · ${t.title}`)}
            style={{
              width: '100%', height: '100%', objectFit: 'cover', display: 'block', cursor: 'zoom-in',
              objectPosition: t.shotPos || 'top center',
              transformOrigin: t.shotPos || 'top center',
              transform: `scale(${(t.shotZoom || 1) * (h ? 1.04 : 1)})`,
              transition: 'transform 320ms',
            }} />
        </div>
      )}
      <div style={{ padding: pad, display: 'flex', flexDirection: 'column', gap: t.feature ? 12 : 8, flex: 1 }}>
        {!t.shot && (
          <div style={{
            width: t.feature ? 44 : 34, height: t.feature ? 44 : 34,
            borderRadius: t.feature ? 12 : 9,
            background: 'var(--bg-3)', border: '1px solid var(--line-2)',
            display: 'grid', placeItems: 'center',
            color: 'var(--accent-2)', flexShrink: 0,
          }}>
            <Icn size={t.feature ? 22 : 17} />
          </div>
        )}
        <div style={{
          fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.16em',
          color: 'var(--fg-3)', textTransform: 'uppercase',
        }}>{t.kicker}</div>
        <div style={{
          fontFamily: 'var(--font-display)', fontWeight: 600,
          fontSize: t.feature ? 26 : 17, letterSpacing: '-0.02em',
          color: 'var(--fg-1)', lineHeight: 1.15,
        }}>{t.title}</div>
        {t.body && (
          <p style={{
            margin: 0, fontSize: t.feature ? 15 : 13, lineHeight: 1.55,
            color: 'var(--fg-2)', maxWidth: t.feature ? 760 : 'none',
          }}>{t.body}</p>
        )}
        {t.pipeline && <PipelineStepper />}
        {/* Real paths out of the generated workspace — proof it's an actual repo. */}
        {t.chips && (
          <div style={{ marginTop: 'auto', paddingTop: 12, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {t.chips.map((c) => (
              <span key={c} style={{
                fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--fg-2)',
                background: 'var(--bg-3)', border: '1px solid var(--line-2)',
                borderRadius: 6, padding: '3px 8px', whiteSpace: 'nowrap',
              }}>{c}</span>
            ))}
          </div>
        )}
        {t.spec && <SpecSheet items={t.items} evidence={t.evidence} />}
        {t.proof && (
          <div style={{
            marginTop: 'auto', paddingTop: 12,
            fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)',
            borderTop: '1px solid var(--line-1)',
          }}>{t.proof}</div>
        )}
      </div>
    </div>
  );
};

const BentoSection = ({ mode }) => {
  const b = BENTO[mode] || BENTO.studio;
  return (
    <Section>
      <Container wide>
        <div style={{ maxWidth: 720, marginBottom: 40 }}>
          <SectionLabel index={1} label={b.label} />
          <DisplayTitle size={52}>{b.title}</DisplayTitle>
          <p style={{ marginTop: 18, fontSize: 17, lineHeight: 1.55, color: 'var(--fg-2)', maxWidth: 640 }}>
            {b.lede}
          </p>
        </div>
        <div className="bento-grid" style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(12, 1fr)',
          gridAutoRows: 'minmax(120px, auto)',
          gap: 14,
        }}>
          {b.tiles.map((t, i) => <BentoTile key={i} t={t} />)}
        </div>
      </Container>
    </Section>
  );
};
