// primitives.jsx — Cards, chip stacks, poker table, badges
// Globals expected: React, Easing, clamp, useSprite

// ── PlayingCard ─────────────────────────────────────────────────────────────
function PlayingCard({ rank = 'A', suit = 's', width = 80, x = 0, y = 0, rotate = 0, faceDown = false, opacity = 1, scale = 1 }) {
  const isRed = suit === 'h' || suit === 'd';
  const suitChar = { s: '♠', h: '♥', d: '♦', c: '♣' }[suit] || '♠';
  const height = width * 1.42;

  const back = (
    <div style={{
      width: '100%', height: '100%',
      background: 'linear-gradient(135deg, #0d3a52 0%, #082233 100%)',
      borderRadius: width * 0.09,
      border: `2px solid #1d5a78`,
      backgroundImage: 'repeating-linear-gradient(45deg, rgba(255,255,255,0.04) 0 4px, transparent 4px 8px), repeating-linear-gradient(-45deg, rgba(255,255,255,0.04) 0 4px, transparent 4px 8px)',
    }}/>
  );

  const face = (
    <div style={{
      width: '100%', height: '100%',
      background: 'linear-gradient(180deg, #fdfcf6 0%, #f3efe2 100%)',
      borderRadius: width * 0.09,
      border: '1px solid rgba(0,0,0,0.18)',
      boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.6)',
      position: 'relative',
      color: isRed ? '#c1303f' : '#0f1219',
      fontFamily: 'Inter, system-ui, sans-serif',
      overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute',
        top: width * 0.07, left: width * 0.10,
        fontSize: width * 0.34, fontWeight: 700,
        lineHeight: 0.95, letterSpacing: '-0.04em',
      }}>{rank}</div>
      <div style={{
        position: 'absolute',
        top: width * 0.42, left: width * 0.10,
        fontSize: width * 0.22, lineHeight: 1,
      }}>{suitChar}</div>
      <div style={{
        position: 'absolute',
        bottom: width * 0.07, right: width * 0.10,
        fontSize: width * 0.34, fontWeight: 700,
        lineHeight: 0.95, letterSpacing: '-0.04em',
        transform: 'rotate(180deg)',
      }}>{rank}</div>
      <div style={{
        position: 'absolute', inset: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: width * 0.55, opacity: 0.85,
      }}>{suitChar}</div>
    </div>
  );

  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      width, height,
      transform: `translate(-50%, -50%) rotate(${rotate}deg) scale(${scale})`,
      opacity,
      filter: 'drop-shadow(0 6px 14px rgba(0,0,0,0.45))',
      willChange: 'transform, opacity',
    }}>
      {faceDown ? back : face}
    </div>
  );
}

// ── Chip — single chip ──────────────────────────────────────────────────────
function Chip({ size = 36, color = '#d4a24a', edge = '#a07a30' }) {
  return (
    <div style={{
      width: size, height: size,
      borderRadius: '50%',
      background: `radial-gradient(circle at 50% 35%, ${color} 0%, ${color} 35%, ${edge} 70%, ${edge} 100%)`,
      border: `1px solid rgba(0,0,0,0.5)`,
      boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.25), 0 1px 2px rgba(0,0,0,0.4)',
      position: 'relative',
    }}>
      <div style={{
        position: 'absolute', inset: '18%',
        borderRadius: '50%',
        border: `1.5px dashed rgba(255,255,255,0.35)`,
      }}/>
    </div>
  );
}

// ── ChipStack — vertical stack of chips ─────────────────────────────────────
function ChipStack({ count = 10, x = 0, y = 0, chipSize = 36, color = '#d4a24a', edge = '#a07a30', label, labelColor = '#f3f1ea' }) {
  const visible = Math.max(0, Math.round(count));
  const overlap = chipSize * 0.18;
  const totalH = chipSize + (visible - 1) * overlap;
  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      transform: 'translate(-50%, -100%)',
      width: chipSize,
      height: totalH,
    }}>
      {Array.from({ length: visible }).map((_, i) => (
        <div key={i} style={{
          position: 'absolute',
          left: 0,
          bottom: i * overlap,
          width: chipSize, height: chipSize,
        }}>
          <Chip size={chipSize} color={color} edge={edge} />
        </div>
      ))}
      {label != null && (
        <div style={{
          position: 'absolute',
          left: '50%', bottom: -28,
          transform: 'translateX(-50%)',
          fontFamily: 'JetBrains Mono, monospace',
          fontSize: 14,
          fontVariantNumeric: 'tabular-nums',
          color: labelColor,
          whiteSpace: 'nowrap',
          letterSpacing: '0.02em',
        }}>{label}</div>
      )}
    </div>
  );
}

// ── ChipPile — wider blob of chips for pots ─────────────────────────────────
function ChipPile({ count = 20, x = 0, y = 0, label, color = '#d4a24a', edge = '#a07a30', radius = 50 }) {
  const visible = Math.min(60, Math.max(0, Math.round(count)));
  const positions = React.useMemo(() => {
    const out = [];
    // deterministic pseudo-random
    for (let i = 0; i < visible; i++) {
      const a = (i * 137.5) * Math.PI / 180;
      const r = Math.sqrt(i / visible) * radius;
      out.push({
        dx: Math.cos(a) * r,
        dy: Math.sin(a) * r * 0.5,
        z: i,
      });
    }
    return out.sort((a,b) => (a.dy - b.dy) || (a.z - b.z));
  }, [visible, radius]);

  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      transform: 'translate(-50%, -50%)',
      width: radius * 2.4, height: radius * 1.6,
    }}>
      {positions.map((p, i) => (
        <div key={i} style={{
          position: 'absolute',
          left: '50%', top: '50%',
          transform: `translate(${p.dx - 13}px, ${p.dy - 13}px)`,
        }}>
          <Chip size={26} color={color} edge={edge} />
        </div>
      ))}
      {label != null && (
        <div style={{
          position: 'absolute',
          left: '50%', top: '100%', marginTop: 8,
          transform: 'translateX(-50%)',
          fontFamily: 'JetBrains Mono, monospace',
          fontSize: 14,
          fontVariantNumeric: 'tabular-nums',
          color: '#f3f1ea',
          whiteSpace: 'nowrap',
          letterSpacing: '0.02em',
        }}>{label}</div>
      )}
    </div>
  );
}

// ── Pill / Badge ────────────────────────────────────────────────────────────
function Pill({ children, color = '#4fd1c5', x = 0, y = 0, size = 14 }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      transform: 'translate(-50%, -50%)',
      padding: '6px 12px',
      borderRadius: 999,
      background: `${color}22`,
      border: `1px solid ${color}66`,
      color,
      fontFamily: 'JetBrains Mono, monospace',
      fontSize: size,
      letterSpacing: '0.08em',
      textTransform: 'uppercase',
      fontWeight: 500,
      whiteSpace: 'nowrap',
    }}>{children}</div>
  );
}

// ── Caption — bottom-of-frame subtitle band ─────────────────────────────────
function Caption({ text, sub }) {
  const { localTime, duration } = useSprite();
  const fadeIn = clamp(localTime / 0.4, 0, 1);
  const fadeOut = clamp((duration - localTime) / 0.4, 0, 1);
  const opacity = Math.min(fadeIn, fadeOut);
  return (
    <div style={{
      position: 'absolute',
      left: 0, right: 0, bottom: 60,
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
      opacity,
      pointerEvents: 'none',
    }}>
      {sub && (
        <div style={{
          fontFamily: 'JetBrains Mono, monospace',
          fontSize: 12,
          letterSpacing: '0.18em',
          textTransform: 'uppercase',
          color: 'rgba(212,162,74,0.85)',
        }}>{sub}</div>
      )}
      <div style={{
        fontFamily: 'Inter, system-ui, sans-serif',
        fontSize: 26,
        fontWeight: 500,
        color: '#f3f1ea',
        textAlign: 'center',
        maxWidth: 1200,
        lineHeight: 1.3,
        letterSpacing: '-0.005em',
        padding: '0 80px',
        textWrap: 'pretty',
      }}>{text}</div>
    </div>
  );
}

// ── Brand mark (top-left) ───────────────────────────────────────────────────
function BrandMark() {
  return (
    <div style={{
      position: 'absolute',
      top: 36, left: 48,
      display: 'flex', alignItems: 'center', gap: 10,
      fontFamily: 'Inter, system-ui, sans-serif',
      color: 'rgba(243,241,234,0.7)',
      fontSize: 13,
      letterSpacing: '0.14em',
      textTransform: 'uppercase',
      fontWeight: 500,
    }}>
      <div style={{
        width: 22, height: 22,
        borderRadius: 5,
        background: 'linear-gradient(135deg, #d4a24a, #8a6520)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: '#0d0f17',
        fontWeight: 800,
        fontSize: 12,
        letterSpacing: 0,
      }}>A</div>
      Academy Poker GTO
    </div>
  );
}

// ── Lesson tag (top-right) ──────────────────────────────────────────────────
function LessonTag({ chapter = 'Lección 03', title = 'Stack-to-Pot Ratio' }) {
  return (
    <div style={{
      position: 'absolute',
      top: 36, right: 48,
      textAlign: 'right',
      fontFamily: 'Inter, system-ui, sans-serif',
    }}>
      <div style={{
        fontFamily: 'JetBrains Mono, monospace',
        fontSize: 11,
        letterSpacing: '0.18em',
        textTransform: 'uppercase',
        color: 'rgba(212,162,74,0.8)',
        marginBottom: 4,
      }}>{chapter}</div>
      <div style={{
        fontSize: 14,
        color: 'rgba(243,241,234,0.6)',
        letterSpacing: '0.02em',
      }}>{title}</div>
    </div>
  );
}

// ── Scene chrome — runs full duration ───────────────────────────────────────
function SceneChrome({ progressLabels = [] }) {
  const time = useTime();
  const { duration } = useTimeline();
  const pct = clamp(time / duration, 0, 1);
  return (
    <React.Fragment>
      <BrandMark />
      <LessonTag />
      {/* Scene progress dots */}
      <div style={{
        position: 'absolute',
        bottom: 28, left: '50%',
        transform: 'translateX(-50%)',
        display: 'flex', gap: 6,
      }}>
        {progressLabels.map((_, i) => {
          const segStart = i / progressLabels.length;
          const segEnd = (i + 1) / progressLabels.length;
          const active = pct >= segStart && pct < segEnd;
          const done = pct >= segEnd;
          return (
            <div key={i} style={{
              width: active ? 32 : 8,
              height: 4,
              borderRadius: 2,
              background: done ? 'rgba(212,162,74,0.6)' : active ? '#d4a24a' : 'rgba(255,255,255,0.12)',
              transition: 'width 240ms, background 240ms',
            }}/>
          );
        })}
      </div>
    </React.Fragment>
  );
}

Object.assign(window, {
  PlayingCard, Chip, ChipStack, ChipPile, Pill, Caption, BrandMark, LessonTag, SceneChrome,
});
