// CabinetReplay — animated Cabinet conversation hero section

const CABINET_EXCHANGES = [
  {
    counselor: 'Epictetus', initial: 'E',
    messages: [
      { role: 'user',      text: 'What should I be focusing on right now?' },
      { role: 'assistant', text: 'That question can sometimes be a way of avoiding a simpler, harder one: why are you not doing what you already know you should? What is actually stopping you?' },
    ],
  },
  {
    counselor: 'Marcus Aurelius', initial: 'M',
    messages: [
      { role: 'user',      text: 'I lost my temper with my kid tonight. Over nothing. I hate myself for it.' },
      { role: 'assistant', text: 'Do not hate yourself. Examine yourself. There is a difference. What were you carrying into that moment that the child had no part in creating? The enemy was not them. The enemy arrived before they did.' },
    ],
  },
  {
    counselor: 'Theodore Roosevelt', initial: 'T',
    messages: [
      { role: 'user',      text: "If I were certain I wouldn't fail — I'd go all in on my own thing. But I keep waiting." },
      { role: 'assistant', text: "The gap between 'soon' and 'now' is where intention goes to die quietly. You are not waiting for the right moment. You are waiting to feel certain. That feeling never comes. The arena does not care how ready you feel. It only cares whether you showed up." },
    ],
  },
  {
    counselor: 'Marcus Aurelius', initial: 'M',
    messages: [
      { role: 'user',      text: "I was exhausted tonight. My kid pushed every button. I kept my mouth shut and said nothing. But I almost didn't." },
      { role: 'assistant', text: 'That is a victory. Small, unglamorous, invisible to everyone but you and the people you did not wound. The man you are becoming is not built in dramatic breakthroughs. He is built in exactly these moments.' },
    ],
  },
];

// Static constellation dots computed once
const REPLAY_DOTS = Array.from({ length: 60 }, (_, i) => ({
  cx: ((i * 137.508) % 100).toFixed(2) + '%',
  cy: ((i * 97.3)    % 100).toFixed(2) + '%',
  r:  i % 5 === 0 ? 1.5 : 1,
  opacity: +(0.08 + (i % 4) * 0.05).toFixed(2),
}));

function CabinetReplay() {
  const APP_URL = 'https://apps.apple.com/app/id6762371595';
  const [exchangeIdx, setExchangeIdx] = React.useState(0);
  const [visibleCount, setVisibleCount]   = React.useState(0);
  const [fading, setFading]               = React.useState(false);
  const timersRef = React.useRef([]);

  function clearTimers() {
    timersRef.current.forEach(clearTimeout);
    timersRef.current = [];
  }
  function schedule(fn, delay) {
    timersRef.current.push(setTimeout(fn, delay));
  }

  React.useEffect(() => {
    const exchange = CABINET_EXCHANGES[exchangeIdx];
    let elapsed = 0;

    exchange.messages.forEach((msg, i) => {
      elapsed += msg.role === 'user' ? 1000 : 3200;
      const t = elapsed;
      schedule(() => setVisibleCount(i + 1), t);
    });

    elapsed += 4500;
    schedule(() => setFading(true), elapsed);
    elapsed += 600;
    schedule(() => {
      setFading(false);
      setVisibleCount(0);
      setExchangeIdx(prev => (prev + 1) % CABINET_EXCHANGES.length);
    }, elapsed);

    return clearTimers;
  }, [exchangeIdx]);

  const exchange = CABINET_EXCHANGES[exchangeIdx];

  return (
    <section style={{
      position: 'relative',
      width: '100%',
      background: '#0a0a0f',
      padding: '72px 16px 80px',
      overflow: 'hidden',
    }}>

      {/* Constellation */}
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none' }} aria-hidden="true">
        {REPLAY_DOTS.map((d, i) => (
          <circle key={i} cx={d.cx} cy={d.cy} r={d.r} fill="white" opacity={d.opacity}/>
        ))}
      </svg>

      {/* Content */}
      <div style={{ position: 'relative', zIndex: 1, maxWidth: 640, margin: '0 auto' }}>

        {/* Eyebrow */}
        <p style={{
          textAlign: 'center',
          color: '#c9a84c',
          fontSize: 11,
          textTransform: 'uppercase',
          letterSpacing: '0.1em',
          fontFamily: "'JetBrains Mono', 'Courier New', monospace",
          marginBottom: 24,
        }}>
          Real conversations from the Cabinet
        </p>

        {/* Chat window */}
        <div style={{
          background: 'rgba(255,255,255,0.03)',
          border: '1px solid rgba(201,168,76,0.2)',
          borderRadius: 20,
          padding: '24px 20px',
          minHeight: 260,
          transition: 'opacity 400ms ease',
          opacity: fading ? 0 : 1,
        }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {exchange.messages.slice(0, visibleCount).map((msg, i) => (
              <ReplayBubble
                key={`${exchangeIdx}-${i}`}
                msg={msg}
                counselor={exchange.counselor}
                initial={exchange.initial}
                appUrl={APP_URL}
              />
            ))}
          </div>
        </div>

      </div>
    </section>
  );
}

function ReplayBubble({ msg, counselor, initial, appUrl }) {
  const isUser = msg.role === 'user';
  return (
    <div style={{
      display: 'flex',
      alignItems: 'flex-end',
      gap: 8,
      flexDirection: isUser ? 'row-reverse' : 'row',
      animation: 'cabinetBubbleIn 300ms ease forwards',
      opacity: 0,
    }}>
      {/* Initial badge (counselor only) */}
      {!isUser && (
        <div style={{
          flexShrink: 0,
          width: 28, height: 28,
          borderRadius: '50%',
          background: '#c9a84c',
          color: '#0a0a0f',
          fontSize: 11,
          fontWeight: 700,
          fontFamily: "'JetBrains Mono', monospace",
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          alignSelf: 'flex-end',
          marginBottom: 2,
        }}>
          {initial}
        </div>
      )}

      <div style={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: isUser ? 'flex-end' : 'flex-start',
        maxWidth: '78%',
        gap: 4,
      }}>
        {/* Counselor name */}
        {!isUser && (
          <span style={{
            color: '#c9a84c',
            fontSize: 12,
            fontFamily: "'JetBrains Mono', monospace",
            letterSpacing: '0.04em',
          }}>
            {counselor}
          </span>
        )}

        {/* Bubble */}
        <button
          onClick={() => window.open(appUrl, '_blank')}
          style={{
            display: 'block',
            width: '100%',
            background: isUser ? 'rgba(255,255,255,0.08)' : 'rgba(255,255,255,0.05)',
            border: '1px solid rgba(255,255,255,0.07)',
            borderRadius: isUser ? '18px 18px 4px 18px' : '18px 18px 18px 4px',
            padding: '10px 14px',
            color: '#e6eef8',
            fontSize: 14,
            lineHeight: 1.55,
            textAlign: 'left',
            cursor: 'pointer',
            fontFamily: "'Cormorant Garamond', Georgia, serif",
            transition: 'opacity 150ms',
          }}
          onMouseEnter={e => e.currentTarget.style.opacity = '0.75'}
          onMouseLeave={e => e.currentTarget.style.opacity = '1'}
        >
          {msg.text}
        </button>
      </div>
    </div>
  );
}

window.CabinetReplay = CabinetReplay;
