// Scene 1: Silicon wafer establishing shot.
// Orthographic top-down view. Dies arranged on a circular wafer.
// Camera zooms toward one die over time.

const WAFER_INK = 'rgba(244, 241, 236, 0.85)';
const WAFER_DIM = 'rgba(244, 241, 236, 0.35)';
const WAFER_FAINT = 'rgba(244, 241, 236, 0.12)';
const WAFER_ACCENT = '#6DD0FF';

// Generate die grid that fits inside a circular wafer.
function generateDies(radius, dieW, dieH, gap) {
  const dies = [];
  const cols = Math.ceil((radius * 2) / (dieW + gap)) + 2;
  const rows = Math.ceil((radius * 2) / (dieH + gap)) + 2;
  const startX = -((cols * (dieW + gap)) / 2);
  const startY = -((rows * (dieH + gap)) / 2);
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      const x = startX + c * (dieW + gap);
      const y = startY + r * (dieH + gap);
      // Check all 4 corners inside wafer with small inset
      const inset = 6;
      const corners = [
        [x + inset, y + inset],
        [x + dieW - inset, y + inset],
        [x + inset, y + dieH - inset],
        [x + dieW - inset, y + dieH - inset],
      ];
      const ok = corners.every(([cx, cy]) => Math.hypot(cx, cy) <= radius - 4);
      if (ok) dies.push({ r, c, x, y, w: dieW, h: dieH });
    }
  }
  return dies;
}

// The hero die — centered die in the grid.
function findHeroDie(dies) {
  let best = null, bestD = Infinity;
  for (const d of dies) {
    const cx = d.x + d.w / 2, cy = d.y + d.h / 2;
    const dist = Math.hypot(cx, cy);
    if (dist < bestD) { bestD = dist; best = d; }
  }
  return best;
}

const WAFER_RADIUS = 360;
const DIE_W = 44;
const DIE_H = 36;
const DIE_GAP = 3;
const DIES = generateDies(WAFER_RADIUS, DIE_W, DIE_H, DIE_GAP);
const HERO = findHeroDie(DIES);

// Export so other scenes can position to match the hero die.
window.WAFER_HERO = HERO;
window.WAFER_DIES = DIES;
window.WAFER_RADIUS = WAFER_RADIUS;

function Wafer({ cx = 960, cy = 540, scale = 1, rotation = 0, heroPulse = 0, dimOthers = 0 }) {
  // dimOthers: 0..1 — fade out non-hero dies
  return (
    <div style={{
      position: 'absolute',
      left: cx, top: cy,
      width: 0, height: 0,
      transform: `translate(-50%, -50%) scale(${scale}) rotate(${rotation}deg)`,
      transformOrigin: 'center',
      willChange: 'transform',
    }}>
      <svg
        width={WAFER_RADIUS * 2 + 80}
        height={WAFER_RADIUS * 2 + 80}
        viewBox={`${-WAFER_RADIUS - 40} ${-WAFER_RADIUS - 40} ${WAFER_RADIUS * 2 + 80} ${WAFER_RADIUS * 2 + 80}`}
        style={{
          position: 'absolute',
          left: -(WAFER_RADIUS + 40),
          top: -(WAFER_RADIUS + 40),
          overflow: 'visible',
        }}
      >
        {/* Outer wafer ring */}
        <circle cx={0} cy={0} r={WAFER_RADIUS} fill="none" stroke={WAFER_INK} strokeWidth={1.4} />
        {/* Inner faint ring (edge bevel) */}
        <circle cx={0} cy={0} r={WAFER_RADIUS - 6} fill="none" stroke={WAFER_FAINT} strokeWidth={1} />
        {/* Notch (flat / orientation mark at bottom) */}
        <path
          d={`M ${-22} ${WAFER_RADIUS} L 0 ${WAFER_RADIUS - 14} L ${22} ${WAFER_RADIUS}`}
          fill="#0B0D11"
          stroke={WAFER_INK}
          strokeWidth={1.4}
          strokeLinejoin="round"
        />

        {/* Crosshair reticle, very faint */}
        <line x1={-WAFER_RADIUS} y1={0} x2={WAFER_RADIUS} y2={0} stroke={WAFER_FAINT} strokeWidth={0.5} strokeDasharray="2 4" />
        <line x1={0} y1={-WAFER_RADIUS} x2={0} y2={WAFER_RADIUS} stroke={WAFER_FAINT} strokeWidth={0.5} strokeDasharray="2 4" />

        {/* Dies */}
        {DIES.map((d, i) => {
          const isHero = d === HERO;
          const baseOpacity = isHero ? 1 : 1 - dimOthers * 0.85;
          const stroke = isHero ? WAFER_ACCENT : WAFER_INK;
          const strokeOpacity = isHero ? 1 : (1 - dimOthers * 0.7);
          return (
            <g key={i} opacity={baseOpacity}>
              <rect
                x={d.x} y={d.y}
                width={d.w} height={d.h}
                fill="none"
                stroke={stroke}
                strokeOpacity={strokeOpacity}
                strokeWidth={isHero ? 1.4 : 0.8}
              />
              {/* Tiny inner detail — gives them texture */}
              {!isHero && (
                <line
                  x1={d.x + 4} y1={d.y + d.h - 4}
                  x2={d.x + d.w - 4} y2={d.y + d.h - 4}
                  stroke={WAFER_INK}
                  strokeOpacity={strokeOpacity * 0.4}
                  strokeWidth={0.6}
                />
              )}
            </g>
          );
        })}

        {/* Hero die highlight pulse ring */}
        {heroPulse > 0 && HERO && (
          <rect
            x={HERO.x - 4 - heroPulse * 8}
            y={HERO.y - 4 - heroPulse * 8}
            width={HERO.w + 8 + heroPulse * 16}
            height={HERO.h + 8 + heroPulse * 16}
            fill="none"
            stroke={WAFER_ACCENT}
            strokeWidth={1.2}
            opacity={1 - heroPulse}
          />
        )}
      </svg>

      {/* Caption — below wafer, only when zoomed out */}
      {dimOthers < 0.3 && (
        <div style={{
          position: 'absolute',
          left: 0, top: WAFER_RADIUS + 40,
          transform: 'translateX(-50%)',
          fontFamily: 'JetBrains Mono, ui-monospace, monospace',
          fontSize: 13,
          letterSpacing: '0.12em',
          color: 'rgba(244, 241, 236, 0.55)',
          textTransform: 'uppercase',
          whiteSpace: 'nowrap',
          opacity: 1 - dimOthers * 3,
        }}>
          300mm wafer · {DIES.length} dies
        </div>
      )}
    </div>
  );
}

function Scene1_Wafer() {
  const { localTime, duration } = useSprite();

  // Camera animation: starts wide, zooms into hero die over the scene.
  // At end, hero die fills more of the frame.
  const t = localTime;

  // Scale: 1 -> 1.4 over scene
  const scale = interpolate(
    [0, duration * 0.4, duration],
    [0.95, 1.05, 1.4],
    Easing.easeInOutCubic
  )(t);

  const rotation = interpolate(
    [0, duration],
    [-2, 2],
    Easing.linear
  )(t);

  // Camera pan to center hero die at end (HERO is roughly at origin already)
  // but we'll shift slightly so the focus is correct.
  const heroCx = HERO.x + HERO.w / 2;
  const heroCy = HERO.y + HERO.h / 2;
  const panX = interpolate([0, duration], [0, -heroCx * scale], Easing.easeInOutCubic)(t);
  const panY = interpolate([0, duration], [0, -heroCy * scale], Easing.easeInOutCubic)(t);

  // Pulse appears late
  const pulse = interpolate(
    [duration * 0.55, duration * 0.85, duration],
    [0, 0.5, 1],
    Easing.easeOutCubic
  )(t);

  // Dim others late
  const dim = interpolate(
    [duration * 0.5, duration],
    [0, 0.6],
    Easing.easeInOutCubic
  )(t);

  return (
    <Wafer
      cx={960 + panX}
      cy={540 + panY}
      scale={scale}
      rotation={rotation}
      heroPulse={pulse}
      dimOthers={dim}
    />
  );
}

window.Scene1_Wafer = Scene1_Wafer;
window.Wafer = Wafer;
