// MomentIQ Home - V2: "Console" - light-themed IDE-feeling layout.
// Workflow rail (left) + form editor (center) + dark inspector (right).
// Below: API table, timeline viz (waveform + frame strip), flow-diagram use cases.

const v2Pad = 'calc(48px * var(--dens, 1))';
const v2PadY = 'calc(72px * var(--dens, 1))';
const momentLabHrefFor = (endpointId) => `#playground?endpoint=${encodeURIComponent(endpointId)}`;

const StartPathCard = ({ kicker, title, body, href, cta, accent, primary }) => (
  <a href={href} style={{
    textDecoration: 'none', color: 'inherit', cursor: 'pointer',
    background: primary ? 'var(--accent-soft)' : wf.cardAlt,
    border: `1px solid ${primary ? 'var(--accent)' : wf.line}`,
    borderRadius: 12, padding: 16,
    boxShadow: `inset 0 2px 0 ${accent || 'var(--accent)'}`,
    display: 'flex', flexDirection: 'column', gap: 8, minHeight: 144,
  }}>
    <div style={{ fontFamily: wf.mono, fontSize: 10.5, letterSpacing: 1, textTransform: 'uppercase', color: accent || 'var(--accent)' }}>{kicker}</div>
    <div style={{ fontFamily: wf.sans, fontSize: 17, fontWeight: 700, letterSpacing: -0.2 }}>{title}</div>
    <div style={{ fontFamily: wf.sans, fontSize: 13, color: wf.ink3, lineHeight: 1.5, flex: 1 }}>{body}</div>
    <div style={{ fontFamily: wf.sans, fontSize: 12.5, fontWeight: 700, color: accent || 'var(--accent)' }}>{cta}</div>
  </a>
);

const V2Hero = () =>
<div style={{
  background: wf.card, borderBottom: `1px solid ${wf.line}`,
  padding: `40px ${v2Pad} 56px`
}}>
    <div style={{ maxWidth: 1280, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 24, marginBottom: 24 }}>
        <div style={{ flex: '1 1 auto', minWidth: 0 }}>
          <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          padding: '4px 10px', borderRadius: 999,
          border: `1px solid ${wf.line}`, background: wf.cardAlt,
          fontFamily: wf.mono, fontSize: 11, color: wf.ink2, marginBottom: 18
        }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--accent)' }} />
            <span>MomentIQ.dev - live API lab</span>
          </div>
          <h1 style={{
          fontFamily: wf.sans, fontSize: 48, lineHeight: 1.08, fontWeight: 600,
          letterSpacing: -1, margin: 0, maxWidth: 980
        }}>
            Moment Lab: Find the moments that matter - <span style={{ color: 'var(--accent)' }}>without writing code first.</span>
          </h1>
          <p style={{ fontFamily: wf.sans, fontSize: 16, color: wf.ink3, margin: '14px 0 0', maxWidth: 760, lineHeight: 1.55, fontWeight: "500" }}>Try the API in 60 seconds with a real sample video, then upload your own media when you are ready. Production jobs run on MomentIQ workers, so the hosted processing estimate reflects compute you do not have to run on your own machine.</p>
          <a href="docs-setup.html" style={{ display:'inline-flex', marginTop: 12, fontFamily: wf.sans, fontSize: 13.5, fontWeight: 700, color: 'var(--accent)', textDecoration: 'none', cursor: 'pointer' }}>
            Not sure what to do first? Start here -&gt;
          </a>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 14, marginBottom: 24 }}>
        <StartPathCard
          kicker="No-code"
          title="I want to upload media."
          body="Use Moment Lab to try the tools, preview clips, download results, and see the cost before touching code."
          href="#playground"
          cta="Open Moment Lab"
          accent="var(--accent)"
          primary
        />
        <StartPathCard
          kicker="Developers"
          title="I am building an app."
          body="Create a key, call the API from your backend, upload files, create async jobs, and poll for results."
          href="docs-quickstart.html"
          cta="Read the quickstart"
          accent={GROUPS.video.color}
        />
        <StartPathCard
          kicker="AI agents"
          title="I want Claude or another agent to use it."
          body="First check whether your agent supports remote MCP. If it does, connect MomentIQ; if not, ask it to use the backend API/SDK."
          href="docs-ai-agents.html"
          cta="Open AI agent setup"
          accent={GROUPS.timeline.color}
        />
      </div>

      <div id="playground" style={{ scrollMarginTop: 96 }}>
        <Playground initialId="video/clip-window" defaultMinutes={18} />
      </div>

      <div style={{
      display: 'flex', alignItems: 'center', gap: 16, marginTop: 18, flexWrap: 'wrap',
      fontFamily: wf.mono, fontSize: 11, color: wf.ink3
    }}>
        <span style={{ color: wf.ink2 }}>Authorization: Bearer miq_live_....</span>
        <span style={{ flex: 1, height: 1, background: wf.line, minWidth: 40 }} />
        <span>same key - all endpoints</span>
        <span style={{ width: 4, height: 4, borderRadius: 999, background: wf.line }} />
        <span>hosted compute estimate</span>
        <span style={{ width: 4, height: 4, borderRadius: 999, background: wf.line }} />
        <span>hard caps</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 10, marginTop: 14 }}>
        {[
          ['1. Choose media', 'Use the demo video, paste a URL, or upload a file.'],
          ['2. Pick endpoint', 'Run clips, silence, energy, frames, or timelines.'],
          ['3. Get output', 'Preview clips, inspect JSON, copy cURL, or download results.'],
        ].map(([title, body]) => (
          <div key={title} style={{ background: wf.cardAlt, border: `1px solid ${wf.line}`, borderRadius: 10, padding: 12 }}>
            <div style={{ fontFamily: wf.sans, fontSize: 13, fontWeight: 700, color: wf.ink }}>{title}</div>
            <div style={{ fontFamily: wf.sans, fontSize: 12.5, color: wf.ink3, lineHeight: 1.45, marginTop: 3 }}>{body}</div>
          </div>
        ))}
      </div>
    </div>
  </div>;


// -- API groups (ported from V1's "Modular endpoints, mix freely" section) --
// Three group columns. Each group is color-coded via GROUPS[g].color - the
// kicker, the group dot, and every endpoint path use that color. Endpoint
// paths are real <a> tags that link to their docs-*.html page.

const V2ApiGroups = () => {
  const groups = Object.values(GROUPS).map(g => ({
    id:     g.id,
    title:  g.name,
    kicker: g.pathPrefix,
    color:  g.color,
    desc:   g.desc,
    items:  endpointIdsByGroup(g.id).map(id => {
      const ep    = ENDPOINTS[id];
      const price = g.id === 'timeline' ? 'low / req' : `$${priceFor(id).toFixed(2)}/min`;
      return { id, path: ep.path, desc: ep.short.replace(/\.$/, '').toLowerCase(), price };
    }),
  }));

  return (
    <div style={{ background: wf.bg, padding: `${v2PadY} ${v2Pad}` }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <SectionHead
          kicker="three groups - one key"
          title="Modular endpoints, mix freely."
          sub="Each call returns clean JSON ready to feed your model. Chain them through /v1/timeline/* for full media intelligence - same Authorization header for everything."
        />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 18 }}>
          {groups.map(g => (
            <div key={g.id} style={{
              background: wf.card, border: `1px solid ${wf.line}`, borderRadius: 12,
              padding: 22, display: 'flex', flexDirection: 'column',
              // a thin top accent rule in the group color so the column
              // reads as belonging to that group at a glance.
              boxShadow: `inset 0 2px 0 ${g.color}`,
            }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 6, gap: 10 }}>
                <h3 style={{ fontFamily: wf.sans, fontSize: 20, fontWeight: 600, margin: 0, letterSpacing: -0.2, display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ width: 8, height: 8, borderRadius: 999, background: g.color, display: 'inline-block' }} />
                  {g.title}
                </h3>
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
                  <a href={`docs.html#${g.id}`} style={{ fontFamily: wf.sans, fontSize: 12.5, color: g.color, textDecoration: 'none', fontWeight: 600, cursor: 'pointer' }}>View docs</a>
                  <span style={{ fontFamily: wf.mono, fontSize: 11, color: g.color, fontWeight: 500 }}>{g.kicker}</span>
                </div>
              </div>
              <p style={{ fontFamily: wf.sans, fontSize: 13.5, color: wf.ink3, margin: '0 0 14px', lineHeight: 1.55 }}>{g.desc}</p>
              <div style={{ display: 'flex', flexDirection: 'column' }}>
                {g.items.map((it, i) => (
                  <div
                    key={it.id}
                    style={{
                      display: 'grid', gridTemplateColumns: '1fr auto auto auto', gap: 8, alignItems: 'center',
                      padding: '10px 6px', margin: '0 -6px',
                      borderTop: i ? `1px solid ${wf.line2}` : 'none',
                      color: 'inherit', borderRadius: 6,
                      transition: 'background .12s',
                    }}
                    onMouseEnter={e => { e.currentTarget.style.background = `color-mix(in oklch, ${g.color} 7%, transparent)`; }}
                    onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; }}
                  >
                    <div style={{ minWidth: 0 }}>
                      <div style={{
                        fontFamily: wf.mono, fontSize: 12, color: g.color, fontWeight: 500,
                        overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                      }}>{it.path}</div>
                      <div style={{ fontFamily: wf.sans, fontSize: 12, color: wf.ink3, marginTop: 2 }}>{it.desc}</div>
                    </div>
                    <span style={{ fontFamily: wf.mono, fontSize: 11, color: wf.ink2, whiteSpace: 'nowrap' }}>{it.price}</span>
                    <a
                      href={momentLabHrefFor(it.id)}
                      title={`Open ${it.path} in Moment Lab`}
                      style={{
                        minWidth: 78, height: 26, borderRadius: 999, display: 'inline-flex',
                        alignItems: 'center', justifyContent: 'center',
                        border: `1px solid ${wf.line}`, background: wf.cardAlt,
                        color: g.color, textDecoration: 'none', fontFamily: wf.sans,
                        fontSize: 11, fontWeight: 700, cursor: 'pointer',
                      }}
                    >Try in Lab</a>
                    <a href={docsHrefFor(it.id)} title={`Open docs for ${it.path}`} style={{
                      fontFamily: wf.sans, fontSize: 12.5, color: wf.ink2,
                      textDecoration: 'none', fontWeight: 600, cursor: 'pointer',
                    }}>Docs</a>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// -- API table -------------------------------------------------------------

const V2ApiTable = () => {
  const [filter, setFilter] = React.useState('all');
  const [query, setQuery] = React.useState('');
  const allRows = endpointIds().map(id => {
    const ep = ENDPOINTS[id];
    const price = ep.group === 'timeline' ? 'low / req' : `$${priceFor(id).toFixed(2)} / ${ep.group} min`;
    return { id, group: ep.group, path: ep.path, desc: ep.short.replace(/\.$/, '').toLowerCase(), price };
  });
  const groupColor = Object.fromEntries(Object.values(GROUPS).map(g => [g.id, g.color]));
  const counts = {
    all: allRows.length,
    video: allRows.filter(r => r.group === 'video').length,
    audio: allRows.filter(r => r.group === 'audio').length,
    timeline: allRows.filter(r => r.group === 'timeline').length,
  };
  const queryText = query.trim().toLowerCase();
  const rows = allRows.filter(r => {
    if (filter !== 'all' && r.group !== filter) return false;
    if (!queryText) return true;
    return `${r.path} ${r.desc} ${r.group}`.toLowerCase().includes(queryText);
  });

  return (
    <div style={{ background: wf.bg, padding: `${v2PadY} ${v2Pad}` }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <SectionHead
          kicker="all endpoints - one key"
          title="The whole platform on one page."
          sub="Filter by group or search for what you need. Click an endpoint to open it in Moment Lab or read its docs." />
        
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
          {['all','video','audio','timeline'].map(g => (
            <Pill key={g} active={filter === g} onClick={() => setFilter(g)} style={g === 'all' ? null : { borderColor: groupColor[g], color: filter === g ? wf.card : groupColor[g] }}>
              {g === 'all' ? 'All' : GROUPS[g].name} <span style={{ marginLeft: 4, color: filter === g ? wf.card : wf.ink4 }}>{counts[g]}</span>
            </Pill>
          ))}
          <span style={{ flex: 1 }} />
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 10px',
            borderRadius: 7, border: `1px solid ${wf.line}`, background: wf.card,
            fontFamily: wf.sans, fontSize: 12.5, color: wf.ink3, minWidth: 240
          }}>
            <svg width="12" height="12" viewBox="0 0 12 12"><circle cx="5" cy="5" r="3.2" fill="none" stroke="currentColor" strokeWidth="1.4" /><line x1="7.5" y1="7.5" x2="10" y2="10" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" /></svg>
            <input
              value={query}
              onChange={e => setQuery(e.target.value)}
              placeholder="Search endpoints..."
              style={{ border: 0, outline: 0, background: 'transparent', flex: 1, fontFamily: wf.sans, fontSize: 12.5, color: wf.ink }}
            />
          </span>
        </div>

        <div style={{ background: wf.card, border: `1px solid ${wf.line}`, borderRadius: 12, overflow: 'hidden' }}>
          <div style={{
            display: 'grid', gridTemplateColumns: '90px 1.6fr 2fr 1fr 130px',
            padding: '10px 16px', background: wf.cardAlt, borderBottom: `1px solid ${wf.line}`,
            fontFamily: wf.mono, fontSize: 10.5, letterSpacing: 1, color: wf.ink3, textTransform: 'uppercase'
          }}>
            <span>Group</span><span>Endpoint</span><span>Description</span><span>Price</span><span style={{ textAlign: 'right' }}>Actions</span>
          </div>
          {rows.map((r, i) =>
          <div key={r.id} style={{
            display: 'grid', gridTemplateColumns: '90px 1.6fr 2fr 1fr 130px', alignItems: 'center',
            padding: '12px 16px',
            borderBottom: i < rows.length - 1 ? `1px solid ${wf.line2}` : 'none'
          }}>
              <span style={{
              fontFamily: wf.mono, fontSize: 10.5, letterSpacing: 1,
              color: groupColor[r.group], textTransform: 'uppercase', fontWeight: 500
            }}>{r.group}</span>
              <span style={{ fontFamily: wf.mono, fontSize: 12.5, color: wf.ink }}>{r.path}</span>
              <span style={{ fontFamily: wf.sans, fontSize: 13, color: wf.ink2 }}>{r.desc}</span>
              <span style={{ fontFamily: wf.mono, fontSize: 11.5, color: wf.ink2 }}>{r.price}</span>
              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 14 }}>
                <a href={momentLabHrefFor(r.id)} style={{ fontFamily: wf.sans, fontSize: 12.5, color: 'var(--accent)', textDecoration: 'none', cursor: 'pointer' }}>Try in Lab</a>
                <a href={docsHrefFor(r.id)} style={{ fontFamily: wf.sans, fontSize: 12.5, color: wf.ink3, textDecoration: 'none', cursor: 'pointer' }}>Docs</a>
              </div>
            </div>
          )}
          {!rows.length && (
            <div style={{ padding: '22px 16px', fontFamily: wf.sans, fontSize: 13, color: wf.ink3 }}>
              No endpoints match that search. Try "frames", "laughter", "clip", "speaker", or "timeline".
            </div>
          )}
        </div>
      </div>
    </div>);

};
// -- Timeline viz: waveform + frame strip ----------------------------------
//
// Color rule: every per-signal element is tinted by the group that *produces*
// the signal. silence/speakers/laughter come from /v1/audio so they pick up
// the audio color; cuts come from /v1/video; suggested clips comes from
// /v1/timeline. groupColorForStep() handles the lookup so adding a new lane
// just needs the right id/name and the color follows.

const groupColorForStep = (stepOrId) => {
  // Accepts 'video/best-frames', 'detect-laughter', or a bare lane name.
  if (!stepOrId) return GROUPS.timeline.color;
  const s = String(stepOrId).toLowerCase();
  if (window.ENDPOINTS[s]) return GROUPS[window.ENDPOINTS[s].group].color;
  // Try matching the bare suffix against any endpoint id (e.g. 'detect-laughter').
  const id = Object.keys(window.ENDPOINTS).find(k => k.endsWith('/' + s));
  if (id) return GROUPS[window.ENDPOINTS[id].group].color;
  // Lane-name fallbacks for visual labels that don't map 1:1 to an endpoint.
  if (/silence|speaker|laughter|music|energy|chunk|isolate/.test(s)) return GROUPS.audio.color;
  if (/clip|frame|cut|thumb/.test(s)) return GROUPS.video.color;
  return GROUPS.timeline.color;
};

// Returns the canonical docs href for a step or bare endpoint suffix. Falls
// back to the docs landing page if nothing matches.
const docsHrefForStep = (stepOrId) => {
  if (!stepOrId) return 'docs.html';
  const s = String(stepOrId).toLowerCase();
  if (window.ENDPOINTS[s]) return docsHrefFor(s);
  const id = Object.keys(window.ENDPOINTS).find(k => k.endsWith('/' + s));
  return id ? docsHrefFor(id) : 'docs.html';
};

// Soft tint at a fixed alpha so the saturated group colors don't clash when
// they sit next to each other on the same canvas.
const tint = (c, pct = 14) => `color-mix(in oklch, ${c} ${pct}%, transparent)`;

const V2TimelineViz = () => {
  const cVid = GROUPS.video.color;
  const cAud = GROUPS.audio.color;
  const cTl  = GROUPS.timeline.color;

  return (
  <div style={{ background: wf.card, borderTop: `1px solid ${wf.line}`, borderBottom: `1px solid ${wf.line}`, padding: `${v2PadY} ${v2Pad}` }}>
    <div style={{ maxWidth: 1280, margin: '0 auto' }}>
      <SectionHead
        kicker="merged timeline"
        title="One timeline. Many signals."
        sub="Detect laughter -> find silence before it -> score the nearby frame -> cut the clip. /v1/timeline/merge stitches video and audio results together."
      />

      <div style={{ background: wf.cardAlt, border: `1px solid ${wf.line}`, borderRadius: 12, padding: 22 }}>
        {/* legend so the color -> group mapping is unambiguous */}
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 14, marginBottom: 14, fontFamily: wf.mono, fontSize: 11, color: wf.ink3 }}>
          {[['video', cVid], ['audio', cAud], ['timeline', cTl]].map(([name, c]) => (
            <span key={name} style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 8, height: 8, borderRadius: 999, background: c }} />
              <span style={{ color: c, fontWeight: 500 }}>/v1/{name}/*</span>
            </span>
          ))}
        </div>

        {/* frame strip - video group */}
        <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', alignItems: 'center', gap: 14, marginBottom: 8 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontFamily: wf.sans, fontSize: 12.5, color: wf.ink2 }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: cVid }} />
            frames
          </span>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(16, 1fr)', gap: 4 }}>
            {Array.from({ length: 16 }).map((_, i) => <ImgPlace key={i} w="100%" h={56} rounded={4} />)}
          </div>
        </div>

        {/* waveform with laughter highlights - audio group */}
        <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', alignItems: 'center', gap: 14, marginBottom: 10 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontFamily: wf.sans, fontSize: 12.5, color: wf.ink2 }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: cAud }} />
            waveform - laughter
          </span>
          <div style={{ position: 'relative', height: 100, background: wf.card, border: `1px solid ${wf.line}`, borderRadius: 8 }}>
            <svg width="100%" height="100" preserveAspectRatio="none" viewBox="0 0 1000 100" style={{ position: 'absolute', inset: 0 }}>
              {Array.from({ length: 200 }).map((_, i) => {
                const h = 6 + Math.abs(Math.sin(i * 0.21) + Math.sin(i * 0.07) * 0.6) * 32;
                return (
                  <g key={i}>
                    <rect x={i * 5} y={50 - h} width="2.6" height={h} fill={wf.ink2} opacity="0.85" />
                    <rect x={i * 5} y={50} width="2.6" height={h * 0.7} fill={wf.ink3} opacity="0.55" />
                  </g>
                );
              })}
              <rect x="180" y="6" width="46" height="88" fill={tint(cAud)} stroke={cAud} strokeWidth="1.5" />
              <rect x="540" y="6" width="32" height="88" fill={tint(cAud)} stroke={cAud} strokeWidth="1.5" />
              <rect x="760" y="6" width="58" height="88" fill={tint(cAud)} stroke={cAud} strokeWidth="1.5" />
            </svg>
            {[18, 54, 76].map((p, i) => (
              <div key={i} style={{
                position: 'absolute', left: `${p}%`, top: 6,
                fontFamily: wf.mono, fontSize: 10.5, color: cAud, fontWeight: 500,
                padding: '1px 6px', borderRadius: 4, background: wf.card, border: `1px solid ${cAud}`,
                transform: 'translateY(-50%)'
              }}>laughter</div>
            ))}
          </div>
        </div>

        {/* signal lanes - group color encoded per lane */}
        {[
          { name: 'silence', endpoint: 'audio/detect-silence', color: cAud, kind: 'bars',  ranges: [[0.04, 0.07], [0.20, 0.25], [0.43, 0.46], [0.62, 0.66], [0.79, 0.82]] },
          { name: 'speakers', endpoint: 'audio/detect-speakers', color: cAud, kind: 'speak' },
          { name: 'cuts', endpoint: 'video/detect-cuts', color: cVid, kind: 'ticks', marks: [0.12, 0.34, 0.51, 0.68, 0.82] },
          { name: 'suggested clips', endpoint: 'timeline/suggest-ranges', color: cTl, kind: 'range', ranges: [[0.16, 0.28], [0.52, 0.62], [0.74, 0.84]] }
        ].map((ln, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '120px 1fr', alignItems: 'center', gap: 14, padding: '7px 0' }}>
            <a href={docsHrefFor(ln.endpoint)} title={`Open docs for /v1/${ln.endpoint}`} style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              fontFamily: wf.sans, fontSize: 12.5, color: wf.ink2, textDecoration: 'none',
            }}>
              <span style={{ width: 6, height: 6, borderRadius: 999, background: ln.color }} />
              {ln.name}
            </a>
            <div style={{ position: 'relative', height: 22, background: wf.card, border: `1px solid ${wf.line2}`, borderRadius: 4, overflow: 'hidden' }}>
              {ln.kind === 'speak' && (
                <div style={{ position: 'absolute', inset: 2, display: 'flex', gap: 2 }}>
                  {[[0.18, 'A'], [0.16, 'B'], [0.10, 'A'], [0.22, 'C'], [0.14, 'A'], [0.20, 'B']].map(([w, s], k) => {
                    // 3 speakers, all from /v1/audio - tints of the audio color
                    // keep them distinguishable without breaking the group palette.
                    const bg = s === 'A' ? tint(cAud, 22) : s === 'B' ? tint(cAud, 34) : tint(cAud, 50);
                    return <div key={k} style={{ flex: w, fontSize: 9.5, color: cAud, display: 'grid', placeItems: 'center', background: bg, borderRadius: 2, fontFamily: wf.mono, fontWeight: 500 }}>{s}</div>;
                  })}
                </div>
              )}
              {ln.kind === 'range' && ln.ranges.map(([a, b], k) => (
                <div key={k} style={{
                  position: 'absolute', left: `${a * 100}%`, width: `${(b - a) * 100}%`, top: 2, bottom: 2,
                  background: tint(ln.color, 18), border: `1.5px solid ${ln.color}`, borderRadius: 3,
                  display: 'grid', placeItems: 'center',
                  fontFamily: wf.mono, fontSize: 9.5, color: ln.color, fontWeight: 500
                }}>clip {k + 1}</div>
              ))}
              {ln.kind === 'bars' && ln.ranges.map(([a, b], k) => (
                <div key={k} style={{ position: 'absolute', left: `${a * 100}%`, width: `${(b - a) * 100}%`, top: 4, bottom: 4, background: tint(ln.color, 38), borderRadius: 2 }} />
              ))}
              {ln.kind === 'ticks' && ln.marks.map((m, k) => (
                <div key={k} style={{ position: 'absolute', left: `${m * 100}%`, top: 2, bottom: 2, width: 2, background: ln.color, transform: 'translateX(-1px)' }} />
              ))}
            </div>
          </div>
        ))}

        <div style={{ marginTop: 16, paddingTop: 14, borderTop: `1px solid ${wf.line}`, display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 8, fontFamily: wf.sans, fontSize: 13, color: wf.ink2 }}>
          <a href={docsHrefFor('timeline/merge')} style={{ textDecoration: 'none' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 8px', borderRadius: 6, background: tint(cTl, 12), border: `1px solid ${cTl}`, color: cTl, fontFamily: wf.mono, fontSize: 12, fontWeight: 500 }}>
              POST /v1/timeline/merge
            </span>
          </a>
          <span>+</span>
          <a href={docsHrefFor('timeline/suggest-ranges')} style={{ textDecoration: 'none' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 8px', borderRadius: 6, background: tint(cTl, 12), border: `1px solid ${cTl}`, color: cTl, fontFamily: wf.mono, fontSize: 12, fontWeight: 500 }}>
              POST /v1/timeline/suggest-ranges
            </span>
          </a>
          <span style={{ color: wf.ink3 }}>-> 3 podcast clips ready to render.</span>
        </div>
      </div>
    </div>
  </div>
  );
};


// -- Use cases: flow diagram -----------------------------------------------

const V2UseCases = () => {
  const flows = [
  { name: 'Podcast clip engine',
    steps: ['detect-laughter', 'detect-silence', 'suggest-ranges', 'clip-window', 'thumbnail-score'],
    out: 'short-form clips + cover frames' },
  { name: 'AI meeting memory',
    steps: ['detect-speakers', 'semantic-chunks', 'text-frames', 'timeline/merge'],
    out: 'searchable, speaker-tagged minutes' },
  { name: 'Lecture study tool',
    steps: ['text-frames', 'detect-cuts', 'semantic-chunks', 'timeline/merge'],
    out: 'slide-aligned notes + jumps' }];

  return (
    <div style={{ background: wf.bg, padding: `${v2PadY} ${v2Pad}` }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <SectionHead
          kicker="endpoint chains"
          title="Build whole apps from two or three calls."
          sub="Each card is a real flow. Boxes are endpoints, arrows are how the data moves. Copy any chain into your project." />

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {flows.map((f) => (
          <div key={f.name} style={{
            background: wf.card, border: `1px solid ${wf.line}`, borderRadius: 12, padding: 18
          }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 14 }}>
                <div style={{ fontFamily: wf.sans, fontSize: 16, fontWeight: 600 }}>{f.name}</div>
                <span style={{ fontFamily: wf.mono, fontSize: 11, color: wf.ink3 }}>example workflow</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: 0 }}>
                {f.steps.map((s, i) => {
                  // Each step box is colored by which group its endpoint
                  // belongs to (video / audio / timeline) so the chain reads
                  // as "audio -> audio -> timeline -> video -> video" at a glance.
                  const c = groupColorForStep(s);
                  return (
                  <React.Fragment key={s}>
                    <a href={docsHrefForStep(s)} title={`Open docs for ${s}`} style={{
                      textDecoration: 'none', color: 'inherit',
                      padding: '8px 12px', borderRadius: 8,
                      border: `1px solid ${c}`, background: tint(c, 10),
                      minWidth: 130, display: 'block',
                    }}>
                      <div style={{ fontFamily: wf.mono, fontSize: 11.5, color: c, fontWeight: 500 }}>{s}</div>
                      <div style={{ fontFamily: wf.sans, fontSize: 10.5, color: wf.ink3, marginTop: 2 }}>step {i + 1}</div>
                    </a>
                    {i < f.steps.length - 1 &&
                      <svg width="22" height="14" viewBox="0 0 22 14" style={{ margin: '0 4px' }}><path d="M1 7 H17 M14 3 L18 7 L14 11" fill="none" stroke={wf.ink3} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" /></svg>
                    }
                  </React.Fragment>
                  );
                })}
                <svg width="28" height="14" viewBox="0 0 28 14" style={{ margin: '0 6px' }}><path d="M1 7 H22 M19 3 L24 7 L19 11" fill="none" stroke={wf.ink3} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" /></svg>
                <div style={{
                padding: '8px 14px', borderRadius: 8,
                background: wf.cardAlt, border: `1px solid ${wf.line}`
              }}>
                  <div style={{ fontFamily: wf.sans, fontSize: 13.5, fontWeight: 600, color: wf.ink }}>{f.out}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>);

};

// -- Docs preview + pricing + CTA ------------------------------------------

const V2Bottom = () =>
<>
    <div style={{ background: wf.card, borderTop: `1px solid ${wf.line}`, padding: `${v2PadY} ${v2Pad}` }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <SectionHead
        kicker="built for AI agents too"
        title="Docs Claude, Cursor, and Replit can read."
        sub="Use Moment Lab when you want to test by hand. Use the agent setup page when you want Claude, ChatGPT, Cursor, Replit, or Lovable to build against MomentIQ safely." />
      
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          <CodeBlock
          filename="POST /v1/audio/detect-laughter"
          lang="cURL"
          lines={[
          'curl https://api.momentiq.dev/v1/audio/detect-laughter \\',
          '  -H "Authorization: Bearer $MIQ_KEY" \\',
          '  -H "Content-Type: application/json" \\',
          '  -d \'{',
          '    "media_url": "https://cdn.../ep-42.mp4",',
          '    "sensitivity": 0.62,',
          '    "min_duration": 0.4',
          '  }\'']
          } />
        
          <CodeBlock
          filename="POST /v1/timeline/suggest-ranges"
          lang="JavaScript"
          lines={[
          'const r = await fetch(BASE + "/v1/timeline/suggest-ranges", {',
          '  method: "POST",',
          '  headers: { Authorization: "Bearer " + KEY },',
          '  body: JSON.stringify({',
          '    signals: ["laughter", "silence", "speaker_change"],',
          '    min_clip: 8,',
          '    max_clip: 60',
          '  })',
          '});',
          'const { ranges } = await r.json();']
          } />
        
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 16, flexWrap: 'wrap' }}>
          <a href="docs-ai-agents.html" style={{ textDecoration: 'none' }}><Btn primary size={14}>AI agent setup</Btn></a>
          <a href="docs-quickstart.html" style={{ textDecoration: 'none' }}><Btn size={14}>Developer quickstart</Btn></a>
        </div>
      </div>
    </div>

    <div style={{ background: wf.bg, padding: `${v2PadY} ${v2Pad}` }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <SectionHead kicker="usage-only" title="No subscription. No surprise bills." />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14 }}>
          {[
        ['Video', 'best frames - cuts - text frames', '$0.012-0.060', '/ video min', GROUPS.video.color],
        ['Audio', 'silence - laughter - speakers', '$0.006-0.045', '/ audio min', GROUPS.audio.color],
        ['Timeline', 'merge - nearest - suggest', '$0.002-0.005', '/ request', GROUPS.timeline.color]].
        map(([cat, ex, price, unit, color]) =>
        <a key={cat} href="pricing.html#table" style={{
          background: wf.card, border: `1px solid ${color}`, borderRadius: 12, padding: 18,
          boxShadow: `inset 0 2px 0 ${color}`, textDecoration: 'none', color: 'inherit',
          cursor: 'pointer',
        }}>
              <div style={{ fontFamily: wf.sans, fontSize: 13.5, color, fontWeight: 700 }}>{cat}</div>
              <div style={{ fontFamily: wf.sans, fontSize: 12, color: wf.ink3, marginTop: 4, minHeight: 32, lineHeight: 1.45 }}>{ex}</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 12 }}>
                <span style={{ fontFamily: wf.sans, fontSize: 20, fontWeight: 600, letterSpacing: -0.3 }}>{price}</span>
                <span style={{ fontFamily: wf.mono, fontSize: 11, color: wf.ink3 }}>{unit}</span>
              </div>
            </a>
        )}
        </div>
      </div>
    </div>

  </>;


const HomeV2 = () =>
<div data-screen-label="V2 Home" style={{
  width: '100%', minHeight: '100%', background: wf.bg,
  fontFamily: wf.sans, color: wf.ink
}}>
    <NavBar />
    <V2Hero />
    <V2ApiGroups />
    <V2TimelineViz />
    <V2UseCases />
    <V2Bottom />
  </div>;


window.HomeV2 = HomeV2;
