// Bento — 2x2 grid where each hero visual is a LOOPED illustration of the agent at work.

function Bento() {
  return (
    <Section pad={120} id="bento" label="02 Bento">
      <SectionHeader
        eyebrow="What the agent does"
        headline="Get every show from"
        accent="confirmed to completed."
        subhead="Advancing is repetitive, stressful, and failure-prone. The agent reads every signal, chases every gap, and keeps the show packet truly current."
      />

      <div style={{
        display: 'grid',
        gridTemplateColumns: '1fr 1.5fr',
        gridAutoRows: 'minmax(420px, auto)',
        gap: 16,
      }}>
        <FlipZoomCard><BentoCard variant="cyan" style={{ padding: 32, display: 'flex', flexDirection: 'column', height: '100%' }}>
          <InboxTriageVisual />
          <div style={{ marginTop: 'auto' }}>
            <CardCopy
              icon="mail"
              title="Missing info chaser"
              body="Reads every promoter thread, detects what's missing — hotel, rider, timetable, deposit — and drafts the follow-up to the right person on the right channel."
              color="#fff"
              muted="rgba(255,255,255,0.78)"
            />
          </div>
        </BentoCard></FlipZoomCard>

        <FlipZoomCard><BentoCard variant="cyanSoft" style={{ padding: 32, display: 'flex', flexDirection: 'column' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 20 }}>
            <Icon name="chart" size={20} color="var(--accent)" />
            <span style={{ fontSize: 18, fontWeight: 600 }}>Readiness & risk radar</span>
          </div>
          <p style={{ fontSize: 14.5, lineHeight: 1.55, color: 'rgba(255,255,255,0.6)', maxWidth: 380, margin: 0 }}>
            Every show has a live readiness score. The agent flags risks before they become emergencies — missing hotel, unsigned contract, unpaid deposit, bad flight timing, missing passport.
          </p>
          <div style={{ marginTop: 'auto' }}>
            <ReadinessRadar />
          </div>
        </BentoCard></FlipZoomCard>

        <FlipZoomCard style={{ gridColumn: '1 / 2' }}><BentoCard variant="dark" style={{ padding: 32, display: 'flex', flexDirection: 'column', height: '100%' }}>
          <CardCopy
            icon="folder"
            title="Living show packet"
            body="One operational file per show: deal terms, contacts, logistics, travel, documents, payments, risks, notes. Auto-updated from email, contracts, and connected tools."
          />
          <div style={{ marginTop: 'auto' }}>
            <LivingPacket />
          </div>
        </BentoCard></FlipZoomCard>

        <FlipZoomCard><BentoCard variant="dark" style={{ padding: 32, display: 'flex', flexDirection: 'column', height: '100%' }}>
          <RosterCalendar />
          <div style={{ marginTop: 'auto' }}>
            <CardCopy
              icon="calendar"
              title="Show timeline"
              body="Every advance, hold, travel day, soundcheck, settlement — visualized across the roster. Conflicts surface automatically."
            />
          </div>
        </BentoCard></FlipZoomCard>
      </div>
    </Section>
  );
}

/* ───────── Inbox triage — emails arrive, top one slides out as drafted reply ───────── */
function InboxTriageVisual() {
  const reduced = window.PREFERS_REDUCED;
  const POOL = [
    { from: 'Marcus · Bowery',      subj: 'Brooklyn Steel — hotel block?',    tag: 'HOTEL',   priority: 'CHASE' },
    { from: 'Sara · Goldenvoice',   subj: 'Verandas Pickathon — rider?',      tag: 'RIDER',   priority: 'NOW'   },
    { from: 'Eli · Spaceland',      subj: 'Junot Fonda — deposit cleared',    tag: 'DEPOSIT', priority: 'OK'    },
    { from: 'Lena · Berghain',      subj: 'Sable Nov 02 — timetable?',        tag: 'TIME',    priority: 'CHASE' },
    { from: 'Tomi · Primavera',     subj: 'Lior — visa documents pending',    tag: 'VISA',    priority: 'HIGH'  },
    { from: 'Rae · MSG',            subj: 'Maya — settlement spreadsheet',    tag: 'SETTLE',  priority: 'OK'    },
  ];
  const [stack, setStack] = React.useState(POOL.slice(0, 3));
  const idxRef = React.useRef(3);
  const [phase, setPhase] = React.useState('settle');

  React.useEffect(() => {
    if (reduced) return;
    let t1, t2;
    const id = setInterval(() => {
      setPhase('reply');
      t1 = setTimeout(() => {
        setStack((s) => {
          const next = POOL[idxRef.current % POOL.length];
          idxRef.current += 1;
          return [...s.slice(1), next];
        });
        setPhase('arrive');
        t2 = setTimeout(() => setPhase('settle'), 600);
      }, 700);
    }, 3400);
    return () => { clearInterval(id); clearTimeout(t1); clearTimeout(t2); };
  }, [reduced]);

  return (
    <div style={{ position: 'relative', height: 220, marginBottom: 24 }}>
      {stack.map((m, i) => {
        const replying = phase === 'reply' && i === 0;
        const arriving = phase === 'arrive' && i === stack.length - 1;
        const offset = i * 14;
        return (
          <div key={`${i}-${m.from}-${idxRef.current}`} style={{
            position: 'absolute',
            left: offset, right: offset, top: i * 26,
            padding: '12px 16px', borderRadius: 12,
            background: i === 0 ? 'rgba(0,0,0,0.88)' : 'rgba(0,0,0,0.62)',
            border: '1px solid rgba(255,255,255,0.18)',
            display: 'flex', alignItems: 'center', gap: 12,
            backdropFilter: 'blur(8px)',
            boxShadow: '0 12px 40px rgba(0,0,0,0.4)',
            transform: replying
              ? 'translateX(-140%) rotate(-6deg)'
              : arriving
                ? `translateX(40%) scale(${1 - i * 0.04})`
                : `translateX(0) scale(${1 - i * 0.04})`,
            opacity: replying ? 0 : arriving ? 0.4 : 1,
            transformOrigin: 'top center',
            transition: 'transform 700ms cubic-bezier(.55,.05,.25,1), opacity 600ms ease',
            zIndex: 10 - i,
          }}>
            <div style={{
              fontSize: 9, fontWeight: 700, letterSpacing: '0.1em',
              padding: '3px 7px', borderRadius: 4,
              background: 'rgba(255,255,255,0.12)', color: '#fff',
              flexShrink: 0,
            }}>{m.tag}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: '#fff', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.from}</div>
              <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.6)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.subj}</div>
            </div>
            <div style={{
              fontSize: 9, fontWeight: 700, letterSpacing: '0.08em',
              padding: '3px 7px', borderRadius: 4,
              background: m.priority === 'NOW' ? '#ef4444' : m.priority === 'HIGH' ? '#fbbf24' : m.priority === 'OK' ? 'rgba(74,222,128,0.5)' : 'rgba(255,255,255,0.18)',
              color: '#fff',
              flexShrink: 0,
            }}>{m.priority}</div>
          </div>
        );
      })}

      {!reduced && phase === 'reply' && (
        <div style={{
          position: 'absolute', left: 8, top: 8,
          padding: '8px 14px', borderRadius: 999,
          background: '#000', color: 'var(--accent)',
          border: '1px solid var(--accent)',
          fontSize: 11, fontWeight: 600,
          display: 'flex', alignItems: 'center', gap: 6,
          animation: 'om-reply-fly 700ms cubic-bezier(.4,0,.2,1) forwards',
          boxShadow: '0 0 24px var(--accent-soft)',
          whiteSpace: 'nowrap',
          zIndex: 20,
        }}>
          <Icon name="sparkle" size={11} color="var(--accent)" />
          Drafted follow-up · sent
        </div>
      )}
    </div>
  );
}

/* ───────── Readiness radar — bars fill live, AT-RISK ring pulses ───────── */
function ReadinessRadar() {
  const reduced = window.PREFERS_REDUCED;
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    if (reduced) return;
    const id = setInterval(() => setTick((t) => t + 1), 2400);
    return () => clearInterval(id);
  }, [reduced]);

  const rows = [
    { name: 'Maya · Brooklyn Steel', sub: 'Oct 18 · hotel pending',    base: 78, jitter: 4, status: 'ok' },
    { name: 'Junot · Fonda LA',      sub: 'Oct 22 · ready for show',   base: 92, jitter: 2, status: 'ok' },
    { name: 'Verandas · Pickathon',  sub: 'Oct 25 · deposit unpaid',   base: 28, jitter: 0, status: 'risk' },
    { name: 'Sable · Berghain',      sub: 'Nov 02 · rider missing',    base: 64, jitter: 5, status: 'ok' },
  ];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {rows.map((r, i) => {
        const pct = r.status === 'risk'
          ? r.base
          : Math.min(98, r.base + ((tick + i) % 2 === 0 ? r.jitter : -r.jitter));
        return (
          <div key={i} style={{
            position: 'relative',
            padding: '10px 14px', borderRadius: 12,
            background: r.status === 'risk' ? 'rgba(239,68,68,0.06)' : 'rgba(0,0,0,0.4)',
            border: `1px solid ${r.status === 'risk' ? 'rgba(239,68,68,0.25)' : 'rgba(255,255,255,0.06)'}`,
            overflow: 'hidden',
          }}>
            <div style={{
              position: 'absolute', left: 0, top: 0, bottom: 0,
              width: `${pct}%`,
              background: r.status === 'risk'
                ? 'linear-gradient(90deg, rgba(239,68,68,0.18), rgba(239,68,68,0.05))'
                : 'linear-gradient(90deg, rgba(74,222,128,0.14), rgba(74,222,128,0.02))',
              transition: reduced ? 'none' : 'width 1800ms cubic-bezier(.4,0,.2,1)',
            }} />
            <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{
                width: 30, height: 30, borderRadius: 8,
                background: r.status === 'risk' ? 'rgba(239,68,68,0.18)' : 'var(--accent-soft)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: r.status === 'risk' ? '#ef4444' : 'var(--accent)', flexShrink: 0,
                position: 'relative',
              }}>
                <Icon name={r.status === 'risk' ? 'lock' : 'check'} size={14} />
                {!reduced && r.status === 'risk' && (
                  <span style={{
                    position: 'absolute', inset: -2, borderRadius: 10,
                    border: '1px solid #ef4444',
                    animation: 'om-ring 1.8s ease-out infinite',
                  }} />
                )}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5, fontWeight: 500, color: '#fff' }}>{r.name}</div>
                <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.4)' }}>{r.sub}</div>
              </div>
              <div style={{
                fontSize: 13, fontWeight: 600,
                color: r.status === 'risk' ? '#ef4444' : '#4ade80',
                fontVariantNumeric: 'tabular-nums',
                minWidth: 56, textAlign: 'right',
              }}>
                {r.status === 'risk' ? 'AT RISK' : `${pct}%`}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

/* ───────── Living packet — sync sweep travels down rows ───────── */
function LivingPacket() {
  const reduced = window.PREFERS_REDUCED;
  const items = [
    { stage: 'Deal',       label: 'Contract · countersigned',    value: '✓', dot: '#4ade80' },
    { stage: 'Logistics',  label: 'Hotel block · chasing',       value: '✓', dot: '#fbbf24' },
    { stage: 'Travel',     label: 'Flights · 3 options ranked',  value: '✓', dot: 'var(--accent)' },
    { stage: 'Production', label: 'Rider · unsigned',            value: '!', dot: '#ef4444' },
    { stage: 'Finance',    label: 'Deposit · cleared',           value: '✓', dot: '#4ade80' },
  ];
  const [active, setActive] = React.useState(-1);

  React.useEffect(() => {
    if (reduced) return;
    let i = 0;
    const id = setInterval(() => {
      setActive(i % (items.length + 2));
      i += 1;
    }, 900);
    return () => clearInterval(id);
  }, [reduced]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8, position: 'relative' }}>
      {items.map((d, i) => {
        const isActive = active === i;
        return (
          <div key={i} style={{
            position: 'relative',
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '10px 12px', borderRadius: 10,
            background: isActive ? 'rgba(56,189,248,0.06)' : 'rgba(255,255,255,0.03)',
            border: `1px solid ${isActive ? 'var(--accent-line)' : 'rgba(255,255,255,0.05)'}`,
            transition: 'background 320ms ease, border-color 320ms ease',
            overflow: 'hidden',
          }}>
            {!reduced && isActive && (
              <div style={{
                position: 'absolute', top: 0, bottom: 0, width: '40%',
                background: 'linear-gradient(90deg, transparent, var(--accent-soft), transparent)',
                animation: 'om-shimmer 900ms linear',
              }} />
            )}
            <div style={{
              width: 6, height: 6, borderRadius: 999, background: d.dot, flexShrink: 0,
              boxShadow: isActive ? `0 0 8px ${d.dot}` : 'none',
              transition: 'box-shadow 320ms ease',
              position: 'relative', zIndex: 1,
            }} />
            <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.45)', fontFamily: 'JetBrains Mono, monospace', width: 86, position: 'relative', zIndex: 1 }}>{d.stage}</div>
            <div style={{ flex: 1, fontSize: 13, color: '#fff', position: 'relative', zIndex: 1 }}>{d.label}</div>
            <div style={{ fontSize: 13, fontWeight: 600, color: '#fff', fontVariantNumeric: 'tabular-nums', position: 'relative', zIndex: 1 }}>{d.value}</div>
          </div>
        );
      })}
    </div>
  );
}

/* ───────── Roster calendar — "now" column sweeps, conflict callout pulses ───────── */
function RosterCalendar() {
  const reduced = window.PREFERS_REDUCED;
  const artists = [
    { name: 'Maya O.',  initials: 'MO', color: 'var(--accent-deep)' },
    { name: 'Lior H.',  initials: 'LH', color: '#7c3aed' },
    { name: 'Junot A.', initials: 'JA', color: '#ec4899' },
    { name: 'Sable Q.', initials: 'SQ', color: '#f59e0b' },
  ];
  const events = [
    [null, 'studio', null, 'press', null, 'show', null],
    ['mix', null, null, null, 'travel', null, null],
    [null, null, 'studio', 'studio', null, null, 'show'],
    [null, 'press', null, null, null, null, null],
  ];
  const eventColors = {
    studio: 'var(--accent)',
    press: '#fbbf24',
    show: '#ef4444',
    travel: 'rgba(255,255,255,0.4)',
    mix: '#7c3aed',
  };

  const [now, setNow] = React.useState(0);
  React.useEffect(() => {
    if (reduced) return;
    const id = setInterval(() => setNow((n) => (n + 1) % 7), 700);
    return () => clearInterval(id);
  }, [reduced]);

  return (
    <div style={{ marginBottom: 24, position: 'relative' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '60px repeat(7, 1fr)', gap: 4, marginBottom: 6 }}>
        <div></div>
        {['M', 'T', 'W', 'T', 'F', 'S', 'S'].map((d, i) => (
          <div key={i} style={{
            fontSize: 10,
            color: i === now ? 'var(--accent)' : 'rgba(255,255,255,0.4)',
            fontWeight: 600, textAlign: 'center', fontFamily: 'JetBrains Mono, monospace',
            transition: 'color 240ms ease',
          }}>{d}</div>
        ))}
      </div>
      {artists.map((a, ai) => (
        <div key={ai} style={{ display: 'grid', gridTemplateColumns: '60px repeat(7, 1fr)', gap: 4, marginBottom: 4 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <Avatar initials={a.initials} color={a.color} size={20} />
            <span style={{ fontSize: 11, color: 'rgba(255,255,255,0.7)' }}>{a.name.split(' ')[0]}</span>
          </div>
          {events[ai].map((e, j) => {
            const highlight = j === now;
            return (
              <div key={j} style={{
                position: 'relative',
                height: 24, borderRadius: 4,
                background: e ? eventColors[e] : 'rgba(255,255,255,0.04)',
                opacity: e ? 0.85 : 1,
                border: e ? 'none' : '1px solid rgba(255,255,255,0.04)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 9, fontWeight: 600, color: '#000',
                textTransform: 'uppercase', letterSpacing: '0.05em',
                outline: highlight ? '1px solid var(--accent)' : 'none',
                outlineOffset: highlight ? -1 : 0,
                transition: 'outline 240ms ease',
              }}>
                {e && e.slice(0, 3)}
              </div>
            );
          })}
        </div>
      ))}

      <div style={{
        position: 'absolute', top: 30, right: -8,
        padding: '4px 8px', borderRadius: 6,
        background: '#ef4444', color: '#fff',
        fontSize: 10, fontWeight: 600,
        boxShadow: '0 4px 12px rgba(239,68,68,0.4)',
        animation: reduced ? 'none' : 'om-callout 5.4s ease-in-out infinite',
      }}>
        ⚠ Hotel conflict resolved
      </div>
    </div>
  );
}

Object.assign(window, { Bento });
