/* Robotic Arm — frame-based animation using pre-rendered PNGs */
const { useEffect, useRef } = React;

/* Frames in closing order: 0 = fingers spread wide (open),
   1 = curling, 2 = closed grip. We blend between adjacent frames so the
   motion is smooth. Frame 3 (open palm reaching) is unused for now. */
/* Per-frame Y offset in displayed px. Use this to nudge frames into vertical
   alignment with the open hand. Negative = up, positive = down. */
const FRAME_Y_OFFSET = [0, 0, 0, 60];

const ARM_FRAMES = [
  "assets/arm-frame-0.png",
  "assets/arm-frame-1.png",
  "assets/arm-frame-2.png",
  "assets/arm-frame-3.png",
];

function RoboticHand({ progress, gripVariant = "default", showSwapNote = false }) {
  // progress 0..1 — 0 = relaxed/open, 1 = clamped onto edge.
  const grip = Math.max(0, Math.min(1, progress));
  // Active frame: hard-cut to avoid pose ghosting.
  const activeIdx = Math.min(
    ARM_FRAMES.length - 1,
    Math.floor(grip * ARM_FRAMES.length)
  );
  const norm = ARM_FRAMES.map((_, i) => (i === activeIdx ? 1 : 0));

  // Smooth Y offset for the WHOLE rig: interpolate between adjacent frame
  // offsets based on grip progress, so the rig position eases between
  // frames instead of snapping when the active frame changes.
  const fScaled = grip * (ARM_FRAMES.length - 1); // 0..3
  const lo = Math.floor(fScaled);
  const hi = Math.min(ARM_FRAMES.length - 1, lo + 1);
  const t = fScaled - lo;
  const stackDy = FRAME_Y_OFFSET[lo] * (1 - t) + FRAME_Y_OFFSET[hi] * t;

  return (
    <div className={`arm-rig grip-${gripVariant}`}>
      <div className="arm-stack" style={{ transform: `translateY(${stackDy}px)` }}>
        {ARM_FRAMES.map((src, i) => (
          <img
            key={i}
            src={src}
            className="arm-img"
            alt=""
            draggable="false"
            style={{ opacity: norm[i] }}
          />
        ))}
      </div>
      {showSwapNote && (
        <div className="hand-swap-note">// arm-render-slot.glb</div>
      )}
    </div>
  );
}

window.RoboticHand = RoboticHand;
