// Scene 2: Die extraction.
// Wafer is now zoomed in. Hero die lifts up and out, leaving an empty slot.
// Then it scales up, centered, ready to become a chip.

const EXTRACT_INK = 'rgba(244, 241, 236, 0.85)';
const EXTRACT_DIM = 'rgba(244, 241, 236, 0.22)';
const EXTRACT_ACCENT = '#6DD0FF';

// A single die rendered with internal detail (becomes the focus die)
function HeroDieDetail({ x = 0, y = 0, w = 200, h = 160, lineProgress = 1, accent = EXTRACT_ACCENT }) {
  // Internal grid suggesting circuit blocks, drawn as lines that "appear" by lineProgress (0..1)
  const blocks = [
    { x: 0.05, y: 0.05, w: 0.4, h: 0.35 },
    { x: 0.55, y: 0.05, w: 0.4, h: 0.35 },
    { x: 0.05, y: 0.5, w: 0.9, h: 0.2 },
    { x: 0.05, y: 0.78, w: 0.25, h: 0.18 },
    { x: 0.35, y: 0.78, w: 0.6, h: 0.18 },
  ];
  const traces = [
    [[0.45, 0.22], [0.55, 0.22]],
    [[0.5, 0.4], [0.5, 0.5]],
    [[0.18, 0.7], [0.18, 0.78]],
    [[0.65, 0.7], [0.65, 0.78]],
  ];

  return (
    <svg
      width={w} height={h}
      viewBox={`0 0 ${w} ${h}`}
      style={{ position: 'absolute', left: x, top: y, overflow: 'visible' }}
    >
      <rect x={0} y={0} width={w} height={h} fill="#0B0D11" stroke={accent} strokeWidth={1.6} />
      {/* Corner crop marks */}
      {[
        [0, 0], [w, 0], [0, h], [w, h],
      ].map(([cx, cy], i) => {
        const sx = cx === 0 ? 1 : -1;
        const sy = cy === 0 ? 1 : -1;
        return (
          <g key={i} stroke={accent} strokeWidth={1.4} fill="none">
            <line x1={cx} y1={cy} x2={cx + sx * 10} y2={cy} />
            <line x1={cx} y1={cy} x2={cx} y2={cy + sy * 10} />
          </g>
        );
      })}
      {/* Internal blocks */}
      {blocks.map((b, i) => {
        const reveal = clamp(lineProgress * blocks.length - i, 0, 1);
        return (
          <rect
            key={i}
            x={b.x * w} y={b.y * h}
            width={b.w * w} height={b.h * h}
            fill="none"
            stroke={EXTRACT_INK}
            strokeWidth={0.9}
            opacity={reveal * 0.85}
          />
        );
      })}
      {/* Inner traces */}
      {traces.map((t, i) => (
        <line
          key={i}
          x1={t[0][0] * w} y1={t[0][1] * h}
          x2={t[1][0] * w} y2={t[1][1] * h}
          stroke={EXTRACT_INK}
          strokeWidth={0.7}
          opacity={lineProgress * 0.7}
        />
      ))}
    </svg>
  );
}

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

  const HERO = window.WAFER_HERO;
  const heroCx = HERO.x + HERO.w / 2;
  const heroCy = HERO.y + HERO.h / 2;

  // Continuing from Scene 1: wafer is zoomed in (scale ~1.4) and panned to hero.
  // Hold briefly, then die scales up massively as wafer scales/fades back.
  const waferScale = interpolate(
    [0, duration * 0.3, duration],
    [1.4, 1.5, 2.2],
    Easing.easeInCubic
  )(t);

  const waferOpacity = interpolate(
    [0, duration * 0.4, duration * 0.85, duration],
    [1, 0.85, 0.15, 0],
    Easing.easeInOutCubic
  )(t);

  // Wafer pan (continuing from end of scene 1)
  const wPanX = -heroCx * waferScale;
  const wPanY = -heroCy * waferScale;

  // Hero die lifts: a separate copy of the hero die animates
  // from its wafer position up to centered, scaled large.
  // Phase A (0 - 0.35): die "lifts" — a thin ghost outline rises with corner marks
  // Phase B (0.35 - 1.0): die scales to large centered detail view

  // Position of hero die in screen coords given waferScale + pan:
  // hero center in screen = 960 + wPanX + heroCx * waferScale = 960
  // (since wPanX cancels heroCx * waferScale). So hero center stays at 960,540.

  const liftLift = interpolate([0, duration * 0.35], [0, 1], Easing.easeOutCubic)(t);
  const detailReveal = interpolate([duration * 0.3, duration * 0.7], [0, 1], Easing.easeOutCubic)(t);
  // Die size animates directly to a target on-screen size.
  // Start: matches wafer hero die at scale 1.4 (~62 x 50 px).
  // End:   ~720 x 590 px so it dominates the frame and hands cleanly to Scene 3.
  const startW = HERO.w * 1.4;
  const startH = HERO.h * 1.4;
  const endW = 720;
  const endH = 590;
  const dieW = interpolate(
    [0, duration * 0.3, duration],
    [startW, startW * 1.6, endW],
    Easing.easeInOutCubic
  )(t);
  const dieH = interpolate(
    [0, duration * 0.3, duration],
    [startH, startH * 1.6, endH],
    Easing.easeInOutCubic
  )(t);

  // Slight upward drift during lift phase
  const liftY = interpolate([0, duration * 0.35], [0, -8], Easing.easeOutQuad)(t) * liftLift;

  return (
    <>
      {/* Wafer continues, fading + scaling */}
      <div style={{ opacity: waferOpacity }}>
        <Wafer
          cx={960 + wPanX}
          cy={540 + wPanY}
          scale={waferScale}
          rotation={0}
          heroPulse={0}
          dimOthers={1}
        />
      </div>

      {/* Empty slot left behind on wafer (subtle) */}
      {liftLift > 0.1 && waferOpacity > 0.05 && (
        <div style={{
          position: 'absolute',
          left: 960, top: 540,
          width: HERO.w * waferScale,
          height: HERO.h * waferScale,
          transform: 'translate(-50%, -50%)',
          border: `1px dashed ${EXTRACT_DIM}`,
          opacity: waferOpacity * 0.6,
        }} />
      )}

      {/* The hero die, lifting & scaling */}
      <div style={{
        position: 'absolute',
        left: 960, top: 540 + liftY,
        width: 0, height: 0,
        transform: 'translate(-50%, -50%)',
      }}>
        <HeroDieDetail
          x={-dieW / 2}
          y={-dieH / 2}
          w={dieW}
          h={dieH}
          lineProgress={detailReveal}
          accent={EXTRACT_ACCENT}
        />
      </div>

      {/* Caption */}
      <div style={{
        position: 'absolute',
        left: 960, top: 900,
        transform: 'translate(-50%, -50%)',
        fontFamily: 'JetBrains Mono, ui-monospace, monospace',
        fontSize: 13,
        letterSpacing: '0.16em',
        color: 'rgba(244, 241, 236, 0.55)',
        textTransform: 'uppercase',
        whiteSpace: 'nowrap',
        opacity: interpolate(
          [duration * 0.25, duration * 0.45, duration * 0.85, duration],
          [0, 1, 1, 0],
          Easing.easeInOutCubic
        )(t),
      }}>
        single die · extracted
      </div>
    </>
  );
}

window.Scene2_Extract = Scene2_Extract;
window.HeroDieDetail = HeroDieDetail;
