// waiting-screen.jsx — shown to non-active teams while others pick/order/play
// During 'play': shows big live timer + card status strip
// During 'pick'/'order': shows dancing pixel character
// On blast: character explodes into pieces + blast SFX
// Exports: WaitingScreen

function WaitingScreen({ phase, activeTeam, timeLeft, cardStates, bufferWord, activeCardIndex }) {
  const { useState, useEffect, useRef } = React;
  const [exploding, setExploding] = useState(false);
  const prevStatusesRef = useRef(null);
  const prevTimeRef = useRef(null);
  const prevBufferGuessedRef = useRef(false);

  const urgent = phase === 'play' && timeLeft != null && timeLeft <= 4;
  const isPlaying = phase === 'play';
  const inBuffer = isPlaying && !!bufferWord;
  const bufferWasGuessed = inBuffer && cardStates != null && activeCardIndex != null
    && cardStates[activeCardIndex]?.status === 'guessed';

  // Detect card blast → sfx + explosion animation
  useEffect(() => {
    if (!cardStates) { prevStatusesRef.current = null; return; }
    const statuses = cardStates.map(s => s.status);
    const prev = prevStatusesRef.current;
    prevStatusesRef.current = statuses;
    if (!prev) return;
    const newBlast = statuses.some((s, i) => prev[i] !== 'blasted' && s === 'blasted');
    if (newBlast) {
      window.sfx && window.sfx.blast();
      setExploding(true);
      setTimeout(() => setExploding(false), 900);
    }
  }, [cardStates]);

  // Success SFX when a guessed-card buffer starts — whole room hears it
  useEffect(() => {
    const wasGuessedBuf = prevBufferGuessedRef.current;
    prevBufferGuessedRef.current = bufferWasGuessed;
    if (bufferWasGuessed && !wasGuessedBuf) {
      window.sfx && window.sfx.cheer();
    }
  }, [bufferWasGuessed]);

  // Tick / urgent SFX for waiting devices too — whole room hears it
  useEffect(() => {
    if (!isPlaying || inBuffer) return;
    const prev = prevTimeRef.current;
    prevTimeRef.current = timeLeft;
    if (prev === null || timeLeft >= prev || timeLeft <= 0) return;
    if (timeLeft <= 4) window.sfx && window.sfx.urgent();
    else window.sfx && window.sfx.tick();
  }, [timeLeft, isPlaying, inBuffer]);

  // 8 particle pieces for the explosion — each has a unique color + direction
  const particles = [
    { color: 'var(--accent)',   size: 11, anim: 'particleFly0' },
    { color: 'var(--accent-2)', size: 9,  anim: 'particleFly1' },
    { color: 'var(--bad)',      size: 12, anim: 'particleFly2' },
    { color: 'var(--accent)',   size: 8,  anim: 'particleFly3' },
    { color: 'var(--accent-2)', size: 10, anim: 'particleFly4' },
    { color: 'var(--fg)',       size: 8,  anim: 'particleFly5' },
    { color: 'var(--bad)',      size: 11, anim: 'particleFly6' },
    { color: 'var(--accent)',   size: 9,  anim: 'particleFly7' },
  ];

  function renderSprite(happy) {
    return (
      <div className={happy ? 'sprite-wrap happy' : 'sprite-wrap'}>
        <div className="sprite-head">
          <div className={happy ? 'sprite-eye happy' : 'sprite-eye'} />
          <div className={happy ? 'sprite-eye happy' : 'sprite-eye'} />
        </div>
        <div className="sprite-body-row">
          <div className="sprite-arm sprite-arm-l" />
          <div className="sprite-body" />
          <div className="sprite-arm sprite-arm-r" />
        </div>
        <div className="sprite-legs">
          <div className="sprite-leg sprite-leg-l" />
          <div className="sprite-leg sprite-leg-r" />
        </div>
        <div className="sprite-shadow" />
      </div>
    );
  }

  // Explosion plays when card blasts; happy sprite during guessed buffer; hidden during blast buffer
  const spriteOrExplosion = exploding ? (
    <div className="sprite-explosion">
      {particles.map((p, i) => (
        <div key={i} style={{
          position: 'absolute',
          width: p.size,
          height: p.size,
          borderRadius: 2,
          background: p.color,
          border: '1.5px solid var(--fg)',
          animationName: p.anim,
          animationDuration: '0.75s',
          animationFillMode: 'forwards',
          animationTimingFunction: 'cubic-bezier(0.15, 0.8, 0.3, 1)',
        }} />
      ))}
    </div>
  ) : bufferWasGuessed ? renderSprite(true)
    : inBuffer        ? null
    : renderSprite(false);

  return (
    <div className="screen fade-in waiting-screen">
      {bufferWasGuessed && <Confetti />}

      <div style={{
        flex: 1,
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        gap: 28,
        paddingBottom: 16,
      }}>
        {spriteOrExplosion}

        {/* Revealed word during inter-card buffer */}
        {inBuffer && (
          <div style={{
            textAlign: 'center',
            background: 'rgba(0,0,0,0.35)',
            border: `1px solid ${bufferWasGuessed ? 'rgba(100,255,130,0.25)' : 'rgba(255,255,255,0.12)'}`,
            borderRadius: 16,
            padding: '18px 24px',
          }}>
            <div className="eyebrow" style={{ marginBottom: 10 }}>THE WORD WAS</div>
            <div style={{
              fontFamily: 'var(--font-arcade)',
              fontSize: 26,
              letterSpacing: 3,
              color: bufferWasGuessed ? 'var(--good)' : 'var(--accent-2)',
              lineHeight: 1,
            }}>
              {bufferWord}
            </div>
          </div>
        )}

        {/* Live timer block — only during play phase, not during buffer */}
        {isPlaying && !inBuffer && cardStates && (
          <div style={{ textAlign: 'center' }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}>TIME LEFT</div>
            <div className="timer-big" style={{
              color: urgent ? 'var(--bad)' : 'var(--accent)',
              textShadow: urgent
                ? '0 0 40px rgba(255,79,94,0.7)'
                : '0 0 40px rgba(255,94,58,0.5)',
              animation: urgent ? 'tickPulse 0.6s ease-in-out infinite' : undefined,
            }}>
              {String(timeLeft || 0).padStart(2, '00')}
            </div>

            {/* Card status strip */}
            <div style={{ display: 'flex', gap: 8, marginTop: 14, justifyContent: 'center' }}>
              {cardStates.map((s, i) => (
                <div key={i} style={{
                  width: 44, height: 8, borderRadius: 4,
                  background: s.status === 'guessed' ? 'var(--good)'
                            : s.status === 'blasted'  ? 'var(--bad)'
                            : s.status === 'active'   ? 'var(--accent)'
                            : 'rgba(255,255,255,0.1)',
                  boxShadow: s.status === 'active' ? '0 0 14px var(--accent)' : 'none',
                  transition: 'background 200ms',
                }} />
              ))}
            </div>
          </div>
        )}

        {/* Card status strip during buffer (no timer shown) */}
        {inBuffer && cardStates && (
          <div style={{ display: 'flex', gap: 8, justifyContent: 'center' }}>
            {cardStates.map((s, i) => (
              <div key={i} style={{
                width: 44, height: 8, borderRadius: 4,
                background: s.status === 'guessed' ? 'var(--good)'
                          : s.status === 'blasted'  ? 'var(--bad)'
                          : 'rgba(255,255,255,0.1)',
                transition: 'background 200ms',
              }} />
            ))}
          </div>
        )}

        {/* Status label — hidden during buffer */}
        {!inBuffer && (
          <div style={{ textAlign: 'center' }}>
            <div style={{
              fontFamily: 'var(--font-arcade)',
              fontSize: 12,
              letterSpacing: 2,
              color: 'var(--accent)',
              lineHeight: 1.7,
            }}>
              {activeTeam}
            </div>
            <div style={{
              fontFamily: 'var(--font-arcade)',
              fontSize: 8,
              letterSpacing: 2,
              color: 'var(--fg-quiet)',
              marginTop: 4,
              animation: 'waitPulse 1.8s ease-in-out infinite',
            }}>
              {phase === 'pick'  ? 'IS PICKING CARDS'
             : phase === 'order' ? 'IS ORDERING CARDS'
             : phase === 'play'  ? 'IS ACTING IT OUT'
             : 'IS PLAYING'}
            </div>
          </div>
        )}
      </div>

      <style>{`
        @keyframes tickPulse {
          0%,100% { transform: scale(1); }
          50% { transform: scale(1.08); }
        }
      `}</style>
    </div>
  );
}

window.WaitingScreen = WaitingScreen;
