"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 FileUpload = (0, react_1.forwardRef)(({ name, label, helperText, error: externalError, isRequired = false, isDisabled = false, isReadOnly = false, isInvalid: externalInvalid, size = 'md', accept, multiple = false, maxSize, maxFiles, showPreview = true, showFileList = true, showDropZone = true, dropZoneText = 'Drag and drop files here, or click to browse', dropZoneIcon = '📁', browseButtonText = 'Browse Files', removeButtonText = 'Remove', previewButtonText = 'Preview', className = '', wrapperClassName = '', labelClassName = '', inputClassName = '', errorClassName = '', helperTextClassName = '', dropZoneClassName = '', fileListClassName = '', fileItemClassName = '', previewClassName = '', validateOnChange = false, validateOnBlur = true, onFileSelect, onFileRemove, onFilePreview, onDrop, onDragEnter, onDragLeave, onDragOver, onChange, onBlur, ...props }, ref) => {
    const theme = (0, acui_1.useTheme)();
    const formContext = react_1.default.useContext(FormContext);
    const [files, setFiles] = (0, react_1.useState)([]);
    const [isDragging, setIsDragging] = (0, react_1.useState)(false);
    const [previewUrl, setPreviewUrl] = (0, react_1.useState)(null);
    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 validateFiles = (0, react_1.useCallback)((newFiles) => {
        if (maxSize) {
            const oversizedFiles = newFiles.filter(file => file.size > maxSize);
            if (oversizedFiles.length > 0) {
                const fileNames = oversizedFiles.map(f => f.name).join(', ');
                throw new Error(`Files exceed maximum size: ${fileNames}`);
            }
        }
        if (maxFiles && newFiles.length > maxFiles) {
            throw new Error(`Maximum ${maxFiles} file(s) allowed`);
        }
        if (accept) {
            const acceptedTypes = accept.split(',').map(type => type.trim());
            const invalidFiles = newFiles.filter(file => {
                return !acceptedTypes.some(type => {
                    if (type.startsWith('.')) {
                        return file.name.toLowerCase().endsWith(type.toLowerCase());
                    }
                    return file.type.match(new RegExp(type.replace('*', '.*')));
                });
            });
            if (invalidFiles.length > 0) {
                const fileNames = invalidFiles.map(f => f.name).join(', ');
                throw new Error(`Invalid file type(s): ${fileNames}`);
            }
        }
    }, [maxSize, maxFiles, accept]);
    const handleFileSelect = (0, react_1.useCallback)((selectedFiles) => {
        if (!selectedFiles?.length)
            return;
        try {
            const newFiles = Array.from(selectedFiles);
            validateFiles(newFiles);
            if (multiple) {
                setFiles(prev => [...prev, ...newFiles]);
                onFileSelect?.([...files, ...newFiles]);
                if (formContext) {
                    setFieldValue(name, [...files, ...newFiles]);
                }
            }
            else {
                setFiles([newFiles[0]]);
                onFileSelect?.([newFiles[0]]);
                if (formContext) {
                    setFieldValue(name, newFiles[0]);
                }
            }
            if (showPreview && newFiles[0].type.startsWith('image/')) {
                const url = URL.createObjectURL(newFiles[0]);
                setPreviewUrl(url);
            }
        }
        catch (err) {
            if (err instanceof Error) {
                setFieldError?.(name, err.message);
            }
        }
    }, [multiple, validateFiles, onFileSelect, formContext, name, setFieldValue, setFieldError, files, showPreview]);
    const handleChange = (0, react_1.useCallback)((e) => {
        handleFileSelect(e.target.files);
        onChange?.(e);
        if (formContext && validateOnChange) {
            setFieldTouched(name, true);
        }
    }, [handleFileSelect, onChange, formContext, name, setFieldTouched, validateOnChange]);
    const handleBlur = (0, react_1.useCallback)((e) => {
        onBlur?.(e);
        if (formContext && validateOnBlur) {
            setFieldTouched(name, true);
        }
    }, [onBlur, formContext, name, setFieldTouched, validateOnBlur]);
    const handleRemove = (0, react_1.useCallback)((file) => {
        setFiles(prev => prev.filter(f => f !== file));
        onFileRemove?.(file);
        if (formContext) {
            setFieldValue(name, multiple ? files.filter(f => f !== file) : null);
        }
        if (previewUrl && file === files[0]) {
            URL.revokeObjectURL(previewUrl);
            setPreviewUrl(null);
        }
    }, [multiple, onFileRemove, formContext, name, setFieldValue, files, previewUrl]);
    const handlePreview = (0, react_1.useCallback)((file) => {
        if (file.type.startsWith('image/')) {
            const url = URL.createObjectURL(file);
            setPreviewUrl(url);
            onFilePreview?.(file);
        }
    }, [onFilePreview]);
    const handleDrop = (0, react_1.useCallback)((e) => {
        e.preventDefault();
        setIsDragging(false);
        handleFileSelect(e.dataTransfer.files);
        onDrop?.(Array.from(e.dataTransfer.files));
    }, [handleFileSelect, onDrop]);
    const handleDragEnter = (0, react_1.useCallback)((e) => {
        e.preventDefault();
        setIsDragging(true);
        onDragEnter?.(e);
    }, [onDragEnter]);
    const handleDragLeave = (0, react_1.useCallback)((e) => {
        e.preventDefault();
        setIsDragging(false);
        onDragLeave?.(e);
    }, [onDragLeave]);
    const handleDragOver = (0, react_1.useCallback)((e) => {
        e.preventDefault();
        onDragOver?.(e);
    }, [onDragOver]);
    const labelId = react_1.default.useId();
    const errorId = react_1.default.useId();
    const helperTextId = react_1.default.useId();
    const dropZoneId = react_1.default.useId();
    const ariaProps = {
        'aria-invalid': isInvalid ? true : undefined,
        'aria-required': isRequired ? true : undefined,
        'aria-labelledby': label ? labelId : undefined,
        'aria-describedby': [
            error ? errorId : null,
            helperText ? helperTextId : null,
            showDropZone ? dropZoneId : null
        ].filter(Boolean).join(' ') || undefined
    };
    return ((0, jsx_runtime_1.jsxs)("div", { className: `bf-file-upload-wrapper ${wrapperClassName}`, "data-size": size, "data-invalid": isInvalid, "data-disabled": isDisabled, "data-readonly": isReadOnly, children: [label && ((0, jsx_runtime_1.jsxs)("label", { id: labelId, htmlFor: name, className: `bf-file-upload-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-file-upload-container", children: [showDropZone && ((0, jsx_runtime_1.jsx)("div", { id: dropZoneId, className: `bf-file-upload-dropzone ${dropZoneClassName}`, "data-dragging": isDragging, onDrop: handleDrop, onDragEnter: handleDragEnter, onDragLeave: handleDragLeave, onDragOver: handleDragOver, role: "button", tabIndex: 0, "aria-label": dropZoneText, onClick: () => inputRef.current?.click(), onKeyDown: (e) => {
                            if (e.key === 'Enter' || e.key === ' ') {
                                e.preventDefault();
                                inputRef.current?.click();
                            }
                        }, children: (0, jsx_runtime_1.jsxs)("div", { className: "bf-file-upload-dropzone-content", children: [(0, jsx_runtime_1.jsx)("span", { className: "bf-file-upload-dropzone-icon", "aria-hidden": "true", children: dropZoneIcon }), (0, jsx_runtime_1.jsx)("span", { className: "bf-file-upload-dropzone-text", children: dropZoneText }), (0, jsx_runtime_1.jsx)("button", { type: "button", className: "bf-file-upload-browse-button", onClick: (e) => {
                                        e.stopPropagation();
                                        inputRef.current?.click();
                                    }, disabled: isDisabled || isReadOnly, children: browseButtonText })] }) })), (0, jsx_runtime_1.jsx)("input", { ref: combinedRef, type: "file", id: name, name: name, accept: accept, multiple: multiple, onChange: handleChange, onBlur: handleBlur, disabled: isDisabled, readOnly: isReadOnly, required: isRequired, ...ariaProps, className: `bf-file-upload-input ${inputClassName} ${className}`, style: { display: 'none' }, ...props }), showFileList && files.length > 0 && ((0, jsx_runtime_1.jsx)("ul", { className: `bf-file-upload-list ${fileListClassName}`, role: "list", "aria-label": "Uploaded files", children: files.map((file, index) => ((0, jsx_runtime_1.jsxs)("li", { className: `bf-file-upload-item ${fileItemClassName}`, role: "listitem", children: [(0, jsx_runtime_1.jsx)("span", { className: "bf-file-upload-item-name", children: file.name }), (0, jsx_runtime_1.jsxs)("span", { className: "bf-file-upload-item-size", children: [(file.size / 1024).toFixed(1), " KB"] }), (0, jsx_runtime_1.jsxs)("div", { className: "bf-file-upload-item-actions", children: [showPreview && file.type.startsWith('image/') && ((0, jsx_runtime_1.jsx)("button", { type: "button", className: "bf-file-upload-preview-button", onClick: () => handlePreview(file), disabled: isDisabled || isReadOnly, "aria-label": `${previewButtonText} ${file.name}`, children: previewButtonText })), (0, jsx_runtime_1.jsx)("button", { type: "button", className: "bf-file-upload-remove-button", onClick: () => handleRemove(file), disabled: isDisabled || isReadOnly, "aria-label": `${removeButtonText} ${file.name}`, children: removeButtonText })] })] }, `${file.name}-${index}`))) })), showPreview && previewUrl && ((0, jsx_runtime_1.jsxs)("div", { className: `bf-file-upload-preview ${previewClassName}`, role: "img", "aria-label": "File preview", children: [(0, jsx_runtime_1.jsx)("img", { src: previewUrl, alt: "Preview" }), (0, jsx_runtime_1.jsx)("button", { type: "button", className: "bf-file-upload-preview-close", onClick: () => {
                                    URL.revokeObjectURL(previewUrl);
                                    setPreviewUrl(null);
                                }, "aria-label": "Close preview", children: "\u2715" })] }))] }), error && ((0, jsx_runtime_1.jsx)("div", { id: errorId, className: `bf-file-upload-error ${errorClassName}`, role: "alert", "aria-live": "assertive", children: error })), helperText && !error && ((0, jsx_runtime_1.jsx)("div", { id: helperTextId, className: `bf-file-upload-helper-text ${helperTextClassName}`, role: "status", children: helperText }))] }));
});
FileUpload.displayName = 'FileUpload';
exports.default = (0, react_1.memo)(FileUpload);
//# sourceMappingURL=FileUpload.js.map