import { jsx, jsxs } from 'react/jsx-runtime';
import { useContext } from 'react';
import { cn } from '../../../utils/cn.js';
import { ColorPickerContext } from './ColorPicker.js';
import { parseColor } from './colorUtils.js';

/**
 * ColorPickerPresets - Grid of preset color swatches
 * Allows quick selection from predefined colors
 */
const ColorPickerPresets = ({ colors: customColors, className, ...props }) => {
    const context = useContext(ColorPickerContext);
    if (!context) {
        throw new Error('ColorPickerPresets must be used within a ColorPicker');
    }
    const { setColor, color, theme, presetColors } = context;
    // Use custom colors if provided, otherwise use context presetColors
    const colors = customColors || presetColors;
    // Don't render if no preset colors
    if (!colors || colors.length === 0) {
        return null;
    }
    const handlePresetClick = (presetColor) => {
        const parsed = parseColor(presetColor);
        if (parsed) {
            setColor(parsed);
        }
    };
    const handleKeyDown = (e, presetColor) => {
        if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            handlePresetClick(presetColor);
        }
    };
    // Check if a preset is currently selected
    const isSelected = (presetColor) => {
        const parsed = parseColor(presetColor);
        if (!parsed)
            return false;
        return (Math.abs(parsed.h - color.h) < 1 &&
            Math.abs(parsed.s - color.s) < 1 &&
            Math.abs(parsed.l - color.l) < 1);
    };
    return (jsx("div", { className: cn(theme.presetGridStyle, className), ...props, children: colors.map((presetColor, index) => {
            const selected = isSelected(presetColor);
            return (jsxs("button", { type: "button", role: "button", tabIndex: 0, onClick: () => handlePresetClick(presetColor), onKeyDown: (e) => handleKeyDown(e, presetColor), "data-selected": selected ? '' : undefined, className: cn(theme.presetSwatchStyle), "aria-label": `Select color ${presetColor}`, title: presetColor, children: [jsx("div", { className: "absolute inset-0 rounded", style: {
                            backgroundImage: 'url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAMUlEQVQ4T2NkYGAQYcAP3uCTZhw1gGGYhAGBZIA/nYDCgBDAm9BGDWAAJyRCgLaBCAAgXwixzAS0pgAAAABJRU5ErkJggg==")',
                            backgroundSize: '8px 8px',
                        } }), jsx("div", { className: "absolute inset-0 rounded", style: {
                            backgroundColor: presetColor,
                        } })] }, `${presetColor}-${index}`));
        }) }));
};
ColorPickerPresets.displayName = 'ColorPickerPresets';

export { ColorPickerPresets };
