import React, { useState } from 'react';

export const ZoomableImage: React.FC<{ src: string; alt: string }> = ({
  src,
  alt,
}) => {
  const [isZoomed, setIsZoomed] = useState(false);
  const [zoomPosition, setZoomPosition] = useState({ x: 50, y: 50 });

  const handleMouseMove = (
    e: React.MouseEvent<HTMLImageElement, MouseEvent>
  ) => {
    const {
      left,
      top,
      width,
      height,
    } = e.currentTarget.getBoundingClientRect();
    const x = ((e.clientX - left) / width) * 100;
    const y = ((e.clientY - top) / height) * 100;
    setZoomPosition({ x, y });
  };

  const handleTouchMove = (e: React.TouchEvent<HTMLImageElement>) => {
    const {
      left,
      top,
      width,
      height,
    } = e.currentTarget.getBoundingClientRect();
    const touch = e.touches[0];
    const x = ((touch.clientX - left) / width) * 100;
    const y = ((touch.clientY - top) / height) * 100;
    setZoomPosition({ x, y });
  };

  const handleZoomToggle = () => {
    setIsZoomed(!isZoomed);
  };

  return (
    <img
      src={src}
      alt={alt}
      onMouseMove={handleMouseMove}
      onTouchMove={handleTouchMove}
      onClick={handleZoomToggle} // Toggle zoom on click/tap
      style={{
        width: '100%',
        height: '100%',
        objectFit: 'cover',
        transform: isZoomed ? 'scale(1.5)' : 'scale(1)',
        transformOrigin: `${zoomPosition.x}% ${zoomPosition.y}%`,
        transition: 'transform 0.3s ease',
        cursor: 'pointer', // Indicate interactivity
      }}
    />
  );
};
