import { jsx } from 'react/jsx-runtime';
import { useContext, useRef, useState, useCallback, useEffect } from 'react';
import { cn } from '../../../utils/cn.js';
import { ColorPickerContext } from './ColorPicker.js';
import { hslToRgb, rgbToHsv } from './colorUtils.js';

/**
 * ColorPicker2DCanvas - Main 2D draggable color picker
 * Horizontal axis: Saturation (0-100%)
 * Vertical axis: Brightness/Value (0-100%)
 * This is the PRIMARY feature of the color picker
 */
const ColorPicker2DCanvas = ({ className }) => {
    const context = useContext(ColorPickerContext);
    const canvasRef = useRef(null);
    const [isDragging, setIsDragging] = useState(false);
    if (!context) {
        throw new Error('ColorPicker2DCanvas must be used within a ColorPicker');
    }
    const { color, setColor } = context;
    // Convert HSL to HSV for the 2D picker (works better with saturation/brightness)
    const rgb = hslToRgb(color.h, color.s, color.l);
    const hsv = rgbToHsv(rgb.r, rgb.g, rgb.b);
    // Position is based on HSV saturation and value
    const positionX = hsv.s / 100; // 0-1
    const positionY = 1 - hsv.v / 100; // 0-1 (inverted because canvas top = bright)
    const updateColorFromPosition = useCallback((clientX, clientY) => {
        if (!canvasRef.current)
            return;
        const rect = canvasRef.current.getBoundingClientRect();
        const x = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
        const y = Math.max(0, Math.min(1, (clientY - rect.top) / rect.height));
        // X = saturation (0-100)
        // Y = brightness/value (100-0, inverted)
        const newSaturation = x * 100;
        const newValue = (1 - y) * 100;
        // Convert HSV back to HSL
        color.h;
        const s = newSaturation;
        const v = newValue;
        // HSV to HSL conversion
        const l = ((2 - s / 100) * v) / 2;
        const sl = l !== 0 && l !== 100
            ? ((v - l) / Math.min(l, 100 - l)) * 100
            : 0;
        setColor({
            ...color,
            s: Math.round(sl),
            l: Math.round(l),
        });
    }, [color, setColor]);
    const handlePointerDown = (e) => {
        e.preventDefault();
        setIsDragging(true);
        updateColorFromPosition(e.clientX, e.clientY);
    };
    const handlePointerMove = useCallback((e) => {
        if (!isDragging)
            return;
        updateColorFromPosition(e.clientX, e.clientY);
    }, [isDragging, updateColorFromPosition]);
    const handlePointerUp = useCallback(() => {
        setIsDragging(false);
    }, []);
    useEffect(() => {
        if (isDragging) {
            window.addEventListener('pointermove', handlePointerMove);
            window.addEventListener('pointerup', handlePointerUp);
            return () => {
                window.removeEventListener('pointermove', handlePointerMove);
                window.removeEventListener('pointerup', handlePointerUp);
            };
        }
    }, [isDragging, handlePointerMove, handlePointerUp]);
    // Background gradient based on current hue
    const hueColor = `hsl(${color.h}, 100%, 50%)`;
    return (jsx("div", { ref: canvasRef, onPointerDown: handlePointerDown, className: cn('relative w-full h-48 cursor-crosshair rounded-lg overflow-hidden touch-none select-none', className), style: {
            background: `
          linear-gradient(to top, #000, transparent),
          linear-gradient(to right, #fff, ${hueColor})
        `,
        }, role: "slider", "aria-label": "Color saturation and brightness", "aria-valuemin": 0, "aria-valuemax": 100, tabIndex: 0, children: jsx("div", { className: "absolute w-4 h-4 border-2 border-white rounded-full shadow-lg pointer-events-none", style: {
                left: `${positionX * 100}%`,
                top: `${positionY * 100}%`,
                transform: 'translate(-50%, -50%)',
                boxShadow: '0 0 0 1px rgba(0,0,0,0.3), 0 2px 4px rgba(0,0,0,0.2)',
            } }) }));
};
ColorPicker2DCanvas.displayName = 'ColorPicker2DCanvas';

export { ColorPicker2DCanvas };
