"use client";

import React, { useState, useRef } from 'react';
import styles from './ProductZoom.module.css';

type ProductZoomProps = {
  mainImageSrc: string;
  highResImageSrc?: string;
  children?: React.ReactNode;
};

const ProductZoom = ({ mainImageSrc, highResImageSrc, children }: ProductZoomProps) => {
  const [zoomData, setZoomData] = useState({
    show: false,
    lensX: 0,
    lensY: 0,
    bgX: 0,
    bgY: 0,
    imageWidth: 0,
    imageHeight: 0,
  });
  
  const imageRef = useRef<HTMLImageElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  
  const LENS_SIZE = 100;
  const ZOOM_LEVEL = 3.4;

  const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
    if (!imageRef.current) return;

    const { left, top, width, height } = imageRef.current.getBoundingClientRect();

    const x = e.clientX - left;
    const y = e.clientY - top;

    let lensX = x - LENS_SIZE / 2;
    let lensY = y - LENS_SIZE / 2;

    if (lensX < 0) lensX = 0;
    if (lensY < 0) lensY = 0;
    if (lensX > width - LENS_SIZE) lensX = width - LENS_SIZE;
    if (lensY > height - LENS_SIZE) lensY = height - LENS_SIZE;

    const bgX = lensX * ZOOM_LEVEL;
    const bgY = lensY * ZOOM_LEVEL;

    setZoomData({
      show: true,
      lensX,
      lensY,
      bgX,
      bgY,
      imageWidth: width,
      imageHeight: height,
    });
  };

  const zoomPaneWidth = Math.round((LENS_SIZE * ZOOM_LEVEL));
  const zoomPaneHeight = Math.round((LENS_SIZE * ZOOM_LEVEL));

  return (
    <div className={styles.productLayout} ref={containerRef}>
      <div 
        className={styles.mainImageContainer}
        onMouseMove={handleMouseMove}
        onMouseLeave={() => setZoomData((prev) => ({ ...prev, show: false }))}
        onMouseEnter={(e) => handleMouseMove(e)}
      >
        <img 
          ref={imageRef} 
          src={mainImageSrc} 
          alt="Product" 
          className={styles.mainImage} 
        />
        
        {zoomData.show && (
          <div 
            className={styles.lens}
            style={{
              width: `${LENS_SIZE}px`,
              height: `${LENS_SIZE}px`,
              left: `${zoomData.lensX}px`,
              top: `${zoomData.lensY}px`
            }}
          />
        )}
        {children}
      </div>

      {zoomData.show && (
        <div 
          className={styles.zoomResultPane}
          style={{
            backgroundImage: `url(${highResImageSrc || mainImageSrc})`,
            backgroundPosition: `-${zoomData.bgX}px -${zoomData.bgY}px`,
            backgroundSize: `${zoomData.imageWidth * ZOOM_LEVEL}px ${zoomData.imageHeight * ZOOM_LEVEL}px`,
            width: `${zoomPaneWidth}px`,
            height: `${zoomPaneHeight}px`,
          }}
        />
      )}
    </div>
  );
};

export default ProductZoom;