// BENTO — auto-panning carousel of feature cards

const features = [
{
  kicker: '01 · AI EXTRACTION',
  title: 'See what matters.',
  body: 'Scrub scans every email and surfaces only what needs you — payments, replies, deadlines, deliveries.',
  visual: 'extract'
},
{
  kicker: '02 · QUICK REPLIES',
  title: 'One-tap responses.',
  body: 'Smart, on-brand replies for the messages you owe people. Tap, send, move on.',
  visual: 'reply',
  featured: true
},
{
  kicker: '03 · ASK ANYTHING',
  title: 'Your inbox agent.',
  body: 'Ask the Chat Agent — never manually search your inbox again.',
  visual: 'agent'
},
{
  kicker: '04 · BULK CLEANUP',
  title: 'Clear the noise.',
  body: 'Bulk unsubscribe and clear promotional clutter. Your inbox shrinks 80% overnight.',
  visual: 'cleanup'
},
{
  kicker: '05 · AUTO-CATEGORIZED',
  title: 'Every email finds its place.',
  body: 'Bills, travel, receipts, parcels — auto-tagged as they arrive. No folders. No rules. No setup.',
  visual: 'categories'
}];


function MiniVisual({ kind }) {
  if (kind === 'extract') {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, alignItems: 'stretch', width: '100%' }}>
        <div style={{
          padding: '12px 14px', borderRadius: 10,
          background: 'rgba(232,112,90,0.10)',
          border: '1px solid rgba(232,112,90,0.3)',
          display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12
        }}>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.16em', color: 'var(--accent)' }}>PAYMENT</span>
          <span style={{ fontFamily: 'var(--serif)', fontSize: 18, color: 'var(--ink)' }}>₹4,820</span>
        </div>
        <div style={{
          padding: '12px 14px', borderRadius: 10,
          background: 'rgba(232,112,90,0.10)',
          border: '1px solid rgba(232,112,90,0.3)',
          display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12
        }}>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.16em', color: 'var(--accent)' }}>FLIGHT</span>
          <span style={{ fontFamily: 'var(--serif)', fontSize: 18, color: 'var(--ink)' }}>DEL → BLR</span>
        </div>
        <div style={{
          padding: '12px 14px', borderRadius: 10,
          background: 'rgba(238,240,248,0.04)',
          border: '1px solid var(--hair-dk)',
          display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12
        }}>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.16em', color: 'var(--ink-faint)' }}>DELIVERY</span>
          <span style={{ fontFamily: 'var(--serif)', fontSize: 16, color: 'var(--ink-mute)' }}>Wed</span>
        </div>
      </div>);

  }
  if (kind === 'reply') {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, width: '100%' }}>
        {['Sounds good — let\'s lock it in.'].map((t, i) =>
        <div key={i} style={{
          padding: '12px 14px', borderRadius: 12,
          background: 'rgba(232,112,90,0.14)',
          border: '1px solid rgba(232,112,90,0.35)',
          fontSize: 13, color: 'var(--ink)'
        }}>"{t}"</div>
        )}
      </div>);

  }
  if (kind === 'agent') {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, width: '100%' }}>
        <div style={{
          padding: '10px 12px', borderRadius: 10,
          background: 'rgba(238,240,248,0.04)',
          border: '1px solid var(--hair-dk)',
          fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-mute)',
          textAlign: 'left'
        }}>
          <span style={{ color: 'var(--accent)' }}>›</span> Amazon spend last month
          <span style={{ display: 'inline-block', width: 6, height: 11, background: 'var(--accent)', marginLeft: 4, animation: 'type-cursor 1s infinite', verticalAlign: 'middle' }} />
        </div>
        <div style={{
          padding: '12px 14px', borderRadius: 10,
          background: 'rgba(232,112,90,0.10)',
          border: '1px solid rgba(232,112,90,0.3)',
          textAlign: 'left',
          display: 'flex', flexDirection: 'column', gap: 4
        }}>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.18em', color: 'var(--accent)' }}>3 PARCELS · APR</span>
          <span style={{ fontFamily: 'var(--serif)', fontSize: 22, color: 'var(--ink)' }}>₹3,142</span>
        </div>
      </div>);

  }
  if (kind === 'cleanup') {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14, width: '100%' }}>
        {[
        { label: 'Promotions', pct: 92 },
        { label: 'Social', pct: 78 },
        { label: 'Newsletters', pct: 64 }].
        map((row, i) =>
        <div key={i}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
              <span style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.14em', color: 'var(--ink-mute)', textTransform: 'uppercase' }}>{row.label}</span>
              <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--accent)' }}>−{row.pct}%</span>
            </div>
            <div style={{ height: 4, background: 'rgba(238,240,248,0.06)', borderRadius: 2, overflow: 'hidden' }}>
              <div style={{
              width: `${row.pct}%`, height: '100%',
              background: 'linear-gradient(90deg, var(--accent-deep), var(--accent))',
              borderRadius: 2
            }} />
            </div>
          </div>
        )}
      </div>);

  }
  if (kind === 'categories') {
    const pills = [
    { t: 'Bills', n: 14, c: 'var(--accent)' },
    { t: 'Travel', n: 6, c: '#5567A8' },
    { t: 'Receipts', n: 142, c: 'var(--ink-mute)' },
    { t: 'Subscriptions', n: 14, c: '#8B6FA8' },
    { t: 'Parcels', n: 4, c: '#5C8A6F' },
    { t: 'Meetings', n: 11, c: '#7CA88B' },
    { t: 'Statements', n: 12, c: 'var(--ink-mute)' }];

    return (
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, justifyContent: 'center', width: '100%' }}>
        {pills.map((p, i) =>
        <div key={i} style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          padding: '7px 12px', borderRadius: 99,
          background: 'rgba(255,255,255,0.04)',
          border: `1px solid ${p.c}40`
        }}>
            <span style={{ fontFamily: 'var(--serif)', fontSize: 13, fontStyle: 'italic', color: p.c }}>{p.t}</span>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 9.5, color: 'var(--ink-faint)' }}>{p.n}</span>
          </div>
        )}
      </div>);

  }
  return null;
}

function FeatureCard({ f, hovered }) {
  const featured = f.featured;
  const lift = hovered ? -10 : 0;
  return (
    <div style={{
      width: 340,
      flex: '0 0 340px',
      minHeight: 540,
      background: hovered ?
      'linear-gradient(180deg, rgba(232,112,90,0.08), rgba(232,112,90,0.02))' :
      featured ?
      'linear-gradient(180deg, rgba(255,255,255,0.045), rgba(255,255,255,0.01))' :
      'rgba(255,255,255,0.015)',
      border: hovered ?
      '1px solid rgba(232,112,90,0.5)' :
      featured ? '1px solid rgba(232,112,90,0.18)' : '1px solid var(--hair-dk)',
      borderRadius: 22,
      padding: '40px 28px',
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      textAlign: 'center',
      position: 'relative',
      transform: `translateY(${lift}px)`,
      boxShadow: hovered ?
      '0 40px 100px -24px rgba(232,112,90,0.35), 0 0 0 1px rgba(232,112,90,0.18) inset' :
      featured ?
      '0 30px 80px -20px rgba(232,112,90,0.22), 0 0 0 1px rgba(232,112,90,0.08) inset' :
      '0 10px 40px -20px rgba(0,0,0,0.6)',
      transition: 'transform 0.5s cubic-bezier(.2,.7,.2,1), border-color 0.4s, background 0.4s, box-shadow 0.5s'
    }}>
      <div style={{
        fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.2em',
        color: 'var(--accent)', marginBottom: 22
      }}>{f.kicker}</div>

      <h3 style={{
        fontFamily: 'var(--serif)', fontWeight: 400,
        fontSize: 32,
        lineHeight: 1.05, letterSpacing: '-0.02em',
        margin: 0, marginBottom: 28,
        textWrap: 'balance'
      }}>{f.title}</h3>

      <div style={{
        flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
        width: '100%', marginBottom: 28, minHeight: 180
      }}>
        <MiniVisual kind={f.visual} />
      </div>

      <div style={{
        width: 24, height: 1, background: 'var(--hair-dk-strong)', marginBottom: 18
      }} />

      <p style={{
        fontSize: 13.5, lineHeight: 1.6, color: 'var(--ink-mute)',
        fontWeight: 300, margin: 0, maxWidth: 280, textWrap: 'pretty'
      }}>{f.body}</p>
    </div>);

}

function Carousel() {
  const trackRef = React.useRef(null);
  const containerRef = React.useRef(null);
  const offsetRef = React.useRef(0);
  const lastTRef = React.useRef(0);
  const pausedRef = React.useRef(false);
  const cycleWidthRef = React.useRef(0);
  const lastScrubRef = React.useRef(0);
  const [hoveredIdx, setHoveredIdx] = React.useState(-1);

  // Duplicate features for seamless loop
  const loop = [...features, ...features];

  React.useEffect(() => {
    // Measure one cycle (single set of features)
    const measure = () => {
      const track = trackRef.current;
      if (!track) return;
      const half = track.scrollWidth / 2;
      cycleWidthRef.current = half;
    };
    measure();
    window.addEventListener('resize', measure);

    const SCRUB_RECOVERY_MS = 600;

    let raf;
    const SPEED = 28; // px per second
    const tick = (t) => {
      if (!lastTRef.current) lastTRef.current = t;
      const dt = (t - lastTRef.current) / 1000;
      lastTRef.current = t;
      const sinceScrub = t - lastScrubRef.current;
      const scrubbing = lastScrubRef.current > 0 && sinceScrub < SCRUB_RECOVERY_MS;
      // Auto-flow runs unless paused (hover) or actively scrubbing (recent wheel input)
      if (!pausedRef.current && !scrubbing && cycleWidthRef.current > 0) {
        // Ease back in after a scrub finishes — ramp speed from 0 to SPEED across the recovery window
        let speed = SPEED;
        if (lastScrubRef.current > 0 && sinceScrub < SCRUB_RECOVERY_MS * 1.6) {
          const k = Math.min(1, (sinceScrub - SCRUB_RECOVERY_MS) / (SCRUB_RECOVERY_MS * 0.6));
          speed = SPEED * Math.max(0, k);
        }
        offsetRef.current += speed * dt;
      }
      // Wrap offset in both directions for seamless loop
      const w = cycleWidthRef.current;
      if (w > 0) {
        if (offsetRef.current >= w) offsetRef.current -= w;else
        if (offsetRef.current < 0) offsetRef.current += w;
      }
      if (trackRef.current) {
        trackRef.current.style.transform = `translate3d(${-offsetRef.current}px, 0, 0)`;
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);

    // Resume animation on scroll or cursor movement (resets dt spike)
    const wake = () => {lastTRef.current = 0;};
    window.addEventListener('scroll', wake, { passive: true });
    window.addEventListener('mousemove', wake, { passive: true });

    // Wheel scrubbing — let the user push cards either direction with trackpad/mouse wheel.
    // We only intercept clearly-horizontal intent so vertical page scroll keeps working.
    const onWheel = (e) => {
      // Prefer deltaX (trackpad horizontal swipe). If user is holding shift, treat
      // deltaY as horizontal too. Otherwise leave the event alone.
      let dx = e.deltaX;
      if (Math.abs(dx) < 1 && e.shiftKey) dx = e.deltaY;
      // If horizontal intent dominates, use it.
      if (Math.abs(dx) >= Math.abs(e.deltaY) && Math.abs(dx) > 1) {
        e.preventDefault();
        offsetRef.current += dx;
        lastScrubRef.current = performance.now();
      }
    };
    const el = containerRef.current;
    if (el) el.addEventListener('wheel', onWheel, { passive: false });

    // Drag-to-scrub for users without a horizontal trackpad — click-and-drag the carousel.
    let dragging = false;
    let dragStartX = 0;
    let dragStartOffset = 0;
    const onPointerDown = (e) => {
      // Only primary button, and ignore drags that start on a real interactive element
      if (e.button !== 0) return;
      dragging = true;
      dragStartX = e.clientX;
      dragStartOffset = offsetRef.current;
      lastScrubRef.current = performance.now();
      if (el) el.style.cursor = 'grabbing';
      e.preventDefault();
    };
    const onPointerMove = (e) => {
      if (!dragging) return;
      const dx = e.clientX - dragStartX;
      offsetRef.current = dragStartOffset - dx;
      lastScrubRef.current = performance.now();
    };
    const onPointerUp = () => {
      if (!dragging) return;
      dragging = false;
      lastScrubRef.current = performance.now(); // start the recovery window now
      if (el) el.style.cursor = 'grab';
    };
    if (el) {
      el.style.cursor = 'grab';
      el.addEventListener('pointerdown', onPointerDown);
    }
    window.addEventListener('pointermove', onPointerMove);
    window.addEventListener('pointerup', onPointerUp);
    window.addEventListener('pointercancel', onPointerUp);

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('resize', measure);
      window.removeEventListener('scroll', wake);
      window.removeEventListener('mousemove', wake);
      if (el) {
        el.removeEventListener('wheel', onWheel);
        el.removeEventListener('pointerdown', onPointerDown);
      }
      window.removeEventListener('pointermove', onPointerMove);
      window.removeEventListener('pointerup', onPointerUp);
      window.removeEventListener('pointercancel', onPointerUp);
    };
  }, []);

  const onCardEnter = (i) => {
    pausedRef.current = true;
    setHoveredIdx(i);
  };
  const onCardLeave = () => {
    pausedRef.current = false;
    lastTRef.current = 0; // reset so dt doesn't spike
    setHoveredIdx(-1);
  };

  return (
    <div ref={containerRef} style={{
      position: 'relative',
      width: '100%',
      overflow: 'hidden',
      paddingTop: 40, paddingBottom: 40,
      maskImage: 'linear-gradient(90deg, transparent 0%, #000 8%, #000 92%, transparent 100%)',
      WebkitMaskImage: 'linear-gradient(90deg, transparent 0%, #000 8%, #000 92%, transparent 100%)'
    }}>
      <div ref={trackRef} style={{
        display: 'flex',
        gap: 24,
        willChange: 'transform'
      }}>
        {loop.map((f, i) =>
        <div
          key={i}
          onMouseEnter={() => onCardEnter(i)}
          onMouseLeave={onCardLeave}
          style={{ flexShrink: 0 }}>
          
            <FeatureCard f={f} hovered={hoveredIdx === i} />
          </div>
        )}
      </div>
    </div>);

}

function Bento() {
  return (
    <section id="features" className="rs-section" style={{
      position: 'relative', padding: '120px 0 80px',
      background: 'var(--bg-deep)', overflow: 'hidden'
    }}>
      <div style={{
        position: 'absolute', top: '30%', left: '50%', transform: 'translateX(-50%)',
        width: 900, height: 600, borderRadius: '50%',
        background: 'radial-gradient(ellipse, rgba(232,112,90,0.05) 0%, transparent 60%)',
        pointerEvents: 'none'
      }} />

      <div style={{ position: 'relative', margin: '0 auto' }}>
        <div style={{ marginBottom: 40, maxWidth: 720, textAlign: 'center', marginLeft: 'auto', marginRight: 'auto', padding: '0 32px' }}>
          <Reveal><div style={{ display: 'flex', justifyContent: 'center' }}><SectionMark num="03" label="What's inside" /></div></Reveal>
          <Reveal delay={100}>
            <h2 style={{
              fontFamily: 'var(--serif)', fontWeight: 400,
              fontSize: 'clamp(2.2rem, 4.8vw, 4rem)', lineHeight: 1,
              letterSpacing: '-0.03em', margin: '24px 0 16px', textWrap: 'balance'
            }}>
              A small system,<br /><span className="italic" style={{ color: 'var(--accent)' }}>quietly</span> running.
            </h2>
          </Reveal>
          <Reveal delay={200}>
            <p style={{ fontSize: 16, lineHeight: 1.7, fontWeight: 300, color: 'var(--ink-mute)', margin: 0 }}>
              Connect once. Scrub does the rest in the background.
            </p>
          </Reveal>
        </div>

        <Carousel />
      </div>
    </section>);

}

window.Bento = Bento;