'use client';
import { useEffect, useRef, useState } from 'react';

interface Props {
  rewardName: string;
  rewardValue?: number | null;
  onFullyScratched?: () => void;
}

export default function ScratchCard({ rewardName, rewardValue, onFullyScratched }: Props) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [scratched, setScratched] = useState(false);
  const [percent, setPercent] = useState(0);
  const isDrawing = useRef(false);
  const notified = useRef(false);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    // Draw scratch layer
    ctx.fillStyle = '#c0a060';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // Pattern texture
    ctx.fillStyle = 'rgba(0,0,0,0.15)';
    for (let i = 0; i < canvas.width; i += 20) {
      for (let j = 0; j < canvas.height; j += 20) {
        ctx.fillRect(i, j, 10, 10);
      }
    }

    // Text hint
    ctx.fillStyle = '#fff';
    ctx.font = 'bold 16px sans-serif';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText('🪙 Gosok di sini!', canvas.width / 2, canvas.height / 2);
  }, []);

  const getPos = (e: React.MouseEvent | React.TouchEvent, canvas: HTMLCanvasElement) => {
    const rect = canvas.getBoundingClientRect();
    const scaleX = canvas.width / rect.width;
    const scaleY = canvas.height / rect.height;
    if ('touches' in e) {
      return {
        x: (e.touches[0].clientX - rect.left) * scaleX,
        y: (e.touches[0].clientY - rect.top) * scaleY,
      };
    }
    return {
      x: (e.clientX - rect.left) * scaleX,
      y: (e.clientY - rect.top) * scaleY,
    };
  };

  const scratch = (e: React.MouseEvent | React.TouchEvent) => {
    if (!isDrawing.current || scratched) return;
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    const pos = getPos(e, canvas);
    ctx.globalCompositeOperation = 'destination-out';
    ctx.beginPath();
    ctx.arc(pos.x, pos.y, 28, 0, Math.PI * 2);
    ctx.fill();

    // Check percentage scratched
    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    let transparent = 0;
    for (let i = 3; i < imageData.data.length; i += 4) {
      if (imageData.data[i] === 0) transparent++;
    }
    const pct = Math.round((transparent / (canvas.width * canvas.height)) * 100);
    setPercent(pct);

    if (pct > 60 && !notified.current) {
      notified.current = true;
      setScratched(true);
      onFullyScratched?.();
    }
  };

  return (
    <div className="relative w-full max-w-xs mx-auto select-none">
      {/* Reward underneath */}
      <div className="absolute inset-0 rounded-2xl bg-gradient-to-br from-yellow-400 to-amber-500 flex flex-col items-center justify-center p-4 text-center">
        <div className="text-5xl mb-2">🎁</div>
        <p className="text-white font-bold text-lg leading-tight">{rewardName}</p>
        {rewardValue != null && rewardValue > 0 && (
          <p className="text-yellow-100 text-sm mt-1">
            Senilai Rp {rewardValue.toLocaleString('id-ID')}
          </p>
        )}
        {scratched && (
          <p className="text-white/80 text-xs mt-3 animate-bounce">✨ Selamat! ✨</p>
        )}
      </div>

      {/* Scratch layer */}
      <canvas
        ref={canvasRef}
        width={320}
        height={200}
        className={`relative rounded-2xl w-full cursor-crosshair touch-none transition-opacity duration-500 ${scratched ? 'opacity-0 pointer-events-none' : 'opacity-100'}`}
        style={{ aspectRatio: '320/200' }}
        onMouseDown={() => { isDrawing.current = true; }}
        onMouseUp={() => { isDrawing.current = false; }}
        onMouseLeave={() => { isDrawing.current = false; }}
        onMouseMove={scratch}
        onTouchStart={(e) => { e.preventDefault(); isDrawing.current = true; scratch(e); }}
        onTouchEnd={() => { isDrawing.current = false; }}
        onTouchMove={(e) => { e.preventDefault(); scratch(e); }}
      />

      {!scratched && (
        <p className="text-center text-xs text-gray-400 mt-2">
          {percent > 0 ? `${percent}% tergosok` : 'Gesek untuk reveal hadiah'}
        </p>
      )}
    </div>
  );
}
