"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = __importStar(require("react"));
const acui_1 = require("@Acme Corporation/acui");
const ColorPicker = (0, react_1.forwardRef)(({ name, label, helperText, error: externalError, isRequired = false, isDisabled = false, isReadOnly = false, isInvalid: externalInvalid, size = 'md', format = 'hex', showPreview = true, showInput = true, showAlpha = false, defaultColor = '#000000', presetColors = [
    '#000000', '#FFFFFF', '#FF0000', '#00FF00', '#0000FF',
    '#FFFF00', '#FF00FF', '#00FFFF', '#808080', '#800000',
    '#808000', '#008000', '#800080', '#008080', '#000080'
], className = '', wrapperClassName = '', labelClassName = '', inputClassName = '', errorClassName = '', helperTextClassName = '', previewClassName = '', presetClassName = '', validateOnChange = false, validateOnBlur = true, onChange, onBlur, value, defaultValue, ...props }, ref) => {
    const theme = (0, acui_1.useTheme)();
    const formContext = react_1.default.useContext(FormContext);
    const [localValue, setLocalValue] = (0, react_1.useState)(value ?? defaultValue ?? defaultColor);
    const [isOpen, setIsOpen] = (0, react_1.useState)(false);
    const inputRef = react_1.default.useRef(null);
    const combinedRef = react_1.default.useCallback((node) => {
        inputRef.current = node;
        if (typeof ref === 'function') {
            ref(node);
        }
        else if (ref) {
            ref.current = node;
        }
    }, [ref]);
    const { errors = {}, touched = {}, setFieldValue, setFieldTouched, setFieldError } = formContext || {};
    const error = externalError || errors[name];
    const isInvalid = externalInvalid || (touched[name] && !!error);
    const isControlled = value !== undefined;
    const formatColor = (0, react_1.useCallback)((color) => {
        if (!color)
            return '';
        try {
            const tempInput = document.createElement('input');
            tempInput.type = 'color';
            tempInput.value = color;
            switch (format) {
                case 'rgb': {
                    const rgb = tempInput.value.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);
                    if (!rgb)
                        return color;
                    return `rgb(${parseInt(rgb[1], 16)}, ${parseInt(rgb[2], 16)}, ${parseInt(rgb[3], 16)})`;
                }
                case 'hsl': {
                    const rgb = tempInput.value.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);
                    if (!rgb)
                        return color;
                    const r = parseInt(rgb[1], 16) / 255;
                    const g = parseInt(rgb[2], 16) / 255;
                    const b = parseInt(rgb[3], 16) / 255;
                    const max = Math.max(r, g, b);
                    const min = Math.min(r, g, b);
                    let h = 0;
                    let s = 0;
                    const l = (max + min) / 2;
                    if (max !== min) {
                        const d = max - min;
                        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
                        switch (max) {
                            case r:
                                h = (g - b) / d + (g < b ? 6 : 0);
                                break;
                            case g:
                                h = (b - r) / d + 2;
                                break;
                            case b:
                                h = (r - g) / d + 4;
                                break;
                        }
                        h /= 6;
                    }
                    return `hsl(${Math.round(h * 360)}, ${Math.round(s * 100)}%, ${Math.round(l * 100)}%)`;
                }
                case 'hex':
                default:
                    return tempInput.value;
            }
        }
        catch {
            return color;
        }
    }, [format]);
    const handleChange = (0, react_1.useCallback)((e) => {
        const inputValue = e.target.value;
        if (!isControlled) {
            setLocalValue(inputValue);
        }
        onChange?.(e);
        if (formContext && validateOnChange) {
            setFieldValue(name, inputValue);
        }
    }, [isControlled, onChange, formContext, name, setFieldValue, validateOnChange]);
    const handleBlur = (0, react_1.useCallback)((e) => {
        onBlur?.(e);
        if (formContext && validateOnBlur) {
            setFieldTouched(name, true);
        }
        setIsOpen(false);
    }, [onBlur, formContext, name, setFieldTouched, validateOnBlur]);
    const handlePresetClick = (0, react_1.useCallback)((color) => {
        if (isDisabled || isReadOnly)
            return;
        const event = {
            target: {
                name,
                value: color,
            },
        };
        if (!isControlled) {
            setLocalValue(color);
        }
        onChange?.(event);
        if (formContext) {
            setFieldValue(name, color);
        }
    }, [isDisabled, isReadOnly, isControlled, onChange, formContext, name, setFieldValue]);
    const currentValue = isControlled ? value : localValue;
    const displayValue = formatColor(currentValue);
    const labelId = react_1.default.useId();
    const errorId = react_1.default.useId();
    const helperTextId = react_1.default.useId();
    const presetId = react_1.default.useId();
    const ariaInvalid = isInvalid ? 'true' : undefined;
    const ariaRequired = isRequired ? 'true' : undefined;
    const ariaDescribedBy = [
        error ? errorId : null,
        helperText ? helperTextId : null,
        presetColors.length ? presetId : null
    ].filter(Boolean).join(' ') || undefined;
    return ((0, jsx_runtime_1.jsxs)("div", { className: `bf-color-picker-wrapper ${wrapperClassName}`, "data-size": size, "data-invalid": isInvalid, "data-disabled": isDisabled, "data-readonly": isReadOnly, "data-open": isOpen, children: [label && ((0, jsx_runtime_1.jsxs)("label", { id: labelId, htmlFor: name, className: `bf-color-picker-label ${labelClassName}`, children: [label, isRequired && (0, jsx_runtime_1.jsx)("span", { className: "bf-required-mark", "aria-hidden": "true", children: "*" })] })), (0, jsx_runtime_1.jsxs)("div", { className: "bf-color-picker-container", children: [showPreview && ((0, jsx_runtime_1.jsx)("div", { className: `bf-color-picker-preview ${previewClassName}`, style: { backgroundColor: currentValue }, "aria-hidden": "true" })), showInput && ((0, jsx_runtime_1.jsx)("input", { ref: combinedRef, type: "color", id: name, name: name, value: currentValue, onChange: handleChange, onBlur: handleBlur, onFocus: () => setIsOpen(true), disabled: isDisabled, readOnly: isReadOnly, required: isRequired, "aria-labelledby": label ? labelId : undefined, "aria-invalid": ariaInvalid, "aria-required": ariaRequired, "aria-describedby": ariaDescribedBy, className: `bf-color-picker-input ${inputClassName} ${className}`, ...props })), presetColors.length > 0 && ((0, jsx_runtime_1.jsx)("div", { id: presetId, className: `bf-color-picker-presets ${presetClassName}`, role: "listbox", "aria-label": "Color presets", children: presetColors.map((color, index) => ((0, jsx_runtime_1.jsx)("button", { type: "button", role: "option", "aria-selected": color === currentValue, className: "bf-color-picker-preset", style: { backgroundColor: color }, onClick: () => handlePresetClick(color), disabled: isDisabled || isReadOnly, tabIndex: isOpen ? 0 : -1, children: (0, jsx_runtime_1.jsx)("span", { className: "bf-sr-only", children: color }) }, color))) }))] }), error && ((0, jsx_runtime_1.jsx)("div", { id: errorId, className: `bf-color-picker-error ${errorClassName}`, role: "alert", "aria-live": "assertive", children: error })), helperText && !error && ((0, jsx_runtime_1.jsx)("div", { id: helperTextId, className: `bf-color-picker-helper-text ${helperTextClassName}`, role: "status", children: helperText }))] }));
});
ColorPicker.displayName = 'ColorPicker';
exports.default = (0, react_1.memo)(ColorPicker);
//# sourceMappingURL=ColorPicker.js.map