// Camera — wraps a scene and applies timed zoom/pan to specific regions.
// Each stop: { t, scale, x, y, ease } — x,y are stage-coordinate focal points (0..W, 0..H).
// The camera translates so the focal point stays centered, then scales.

function Camera({ stops, stageW = 1920, stageH = 1080, children }) {
  const { localTime } = useSprite();

  // Interpolate current stop
  let scale = 1, fx = stageW / 2, fy = stageH / 2;
  if (stops.length === 0) {
    // identity
  } else if (localTime <= stops[0].t) {
    scale = stops[0].scale ?? 1;
    fx = stops[0].x ?? stageW / 2;
    fy = stops[0].y ?? stageH / 2;
  } else if (localTime >= stops[stops.length - 1].t) {
    const s = stops[stops.length - 1];
    scale = s.scale ?? 1;
    fx = s.x ?? stageW / 2;
    fy = s.y ?? stageH / 2;
  } else {
    for (let i = 0; i < stops.length - 1; i++) {
      const a = stops[i], b = stops[i + 1];
      if (localTime >= a.t && localTime <= b.t) {
        const span = b.t - a.t;
        const t = span > 0 ? (localTime - a.t) / span : 0;
        const ease = b.ease || Easing.easeInOutCubic;
        const eased = ease(t);
        scale = (a.scale ?? 1) + ((b.scale ?? 1) - (a.scale ?? 1)) * eased;
        fx = (a.x ?? stageW / 2) + ((b.x ?? stageW / 2) - (a.x ?? stageW / 2)) * eased;
        fy = (a.y ?? stageH / 2) + ((b.y ?? stageH / 2) - (a.y ?? stageH / 2)) * eased;
        break;
      }
    }
  }

  // Translate so focal point sits at stage center after scaling
  let tx = (stageW / 2 - fx) * scale;
  let ty = (stageH / 2 - fy) * scale;

  // Clamp so the scaled content always covers the stage — no black gaps at edges.
  // At scale s, content is (W*s, H*s). Valid tx range: [W - W*s, 0] = [W*(1-s), 0].
  const minTx = stageW * (1 - scale);
  const minTy = stageH * (1 - scale);
  tx = Math.min(0, Math.max(minTx, tx));
  ty = Math.min(0, Math.max(minTy, ty));

  return (
    <div style={{
      position: 'absolute', inset: 0,
      overflow: 'hidden',
      transform: `translate(${tx}px, ${ty}px) scale(${scale})`,
      transformOrigin: '0 0',
      willChange: 'transform',
    }}>
      {children}
    </div>
  );
}

Object.assign(window, { Camera });
