'use client'

import * as motion from 'framer-motion/m'

const SIZE = 56

export interface FlyingImageProps {
  imageUrl: string
  startRect: DOMRect
  endRect: DOMRect
  onComplete: () => void
}

// The cloned product image that arcs from the card to the cart icon.
// Rendered once, globally, by CartUIContext's portal — see useFlyToCart's
// "single flight slot" note there for why this isn't per-component.
export default function FlyingImage({ imageUrl, startRect, endRect, onComplete }: FlyingImageProps) {
  const startX = startRect.left + startRect.width / 2 - SIZE / 2
  const startY = startRect.top + startRect.height / 2 - SIZE / 2
  const endX = endRect.left + endRect.width / 2 - SIZE / 2
  const endY = endRect.top + endRect.height / 2 - SIZE / 2
  const midX = (startX + endX) / 2
  const midY = Math.min(startY, endY) - 80 // lift at the midpoint

  return (
    <motion.img
      src={imageUrl}
      alt=""
      aria-hidden
      initial={{ x: startX, y: startY, scale: 1, rotate: 0, opacity: 1 }}
      animate={{
        x: [startX, midX, endX],
        y: [startY, midY, endY],
        scale: [1, 1.1, 0.25],
        rotate: [0, 12, -8],
        opacity: [1, 1, 0.5],
      }}
      transition={{ duration: 0.78, ease: [0.2, 0.75, 0.25, 1], times: [0, 0.5, 1] }}
      onAnimationComplete={onComplete}
      className="fixed top-0 left-0 rounded-xl object-cover shadow-lg pointer-events-none"
      style={{ width: SIZE, height: SIZE, zIndex: 9999 }}
    />
  )
}
