"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get attachConfig () {
        return attachConfig;
    },
    get attachRoot () {
        return attachRoot;
    }
});
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _utils = require("../../utils");
const _hooks = require("../../hooks");
const _base = require("./variations/_size/base");
const _base1 = require("./variations/_view/base");
const _base2 = require("./variations/_helperTextView/base");
const _Attachstyles = require("./Attach.styles");
const _utils1 = require("./utils");
const _Attachtokens = require("./Attach.tokens");
const _components = require("./components");
const _ui = require("./ui");
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
const syncInputFiles = (input, filesToSync)=>{
    if (!_utils.canUseDOM) {
        return;
    }
    input.value = '';
    if (filesToSync.length > 0) {
        const dataTransfer = new DataTransfer();
        filesToSync.forEach((file)=>dataTransfer.items.add(file));
        input.files = dataTransfer.files;
    }
};
const attachRoot = (Root)=>/*#__PURE__*/ (0, _react.forwardRef)((props, outerRef)=>{
        const { flow = 'auto', buttonType = 'button', hideButtonOnAttach = false, hasAttachment = true, multiple, dropdownOptions, acceptedFileFormats, helperText, size, view, helperTextView, className, style, isLoading, disabled, id, name, customIcon, files, onClick, onChange, onClear, ...rest } = props;
        const innerRef = (0, _react.useRef)(null);
        const localInputRef = (0, _react.useRef)(null);
        const inputRef = (0, _hooks.useForkRef)(outerRef, localInputRef);
        const buttonRef = (0, _react.useRef)(null);
        const fileWrapperWidthRef = (0, _react.useRef)(null);
        const fileWrapperHelperRef = (0, _react.useRef)(null);
        const cellHelperRefs = (0, _react.useRef)({});
        const [innerFilesInfo, setInnerFilesInfo] = (0, _react.useState)({});
        const [hasHiddenFiles, setHasHiddenFiles] = (0, _react.useState)(false);
        const [visibilityMap, setVisibilityMap] = (0, _react.useState)({});
        const controlledFilesInfo = (0, _react.useMemo)(()=>{
            if (files === undefined) {
                return undefined;
            }
            return files.reduce((acc, file, ind)=>{
                const fileKey = `${ind}_${file.name}`;
                acc[fileKey] = {
                    ...(0, _utils1.getFilenameParts)(file.name, size, customIcon),
                    file
                };
                return acc;
            }, {});
        }, [
            files,
            size,
            customIcon
        ]);
        const filesInfo = controlledFilesInfo !== undefined ? controlledFilesInfo : innerFilesInfo;
        const mergedFilesInfo = (0, _react.useMemo)(()=>{
            if (Object.keys(visibilityMap).length === 0) {
                return filesInfo;
            }
            const result = {};
            Object.entries(filesInfo).forEach(([key, info])=>{
                result[key] = {
                    ...info,
                    isVisible: visibilityMap[key] !== false
                };
            });
            return result;
        }, [
            filesInfo,
            visibilityMap
        ]);
        const filesLength = Object.keys(filesInfo).length;
        const horizontalClass = flow === 'horizontal' ? _Attachtokens.classes.horizontal : undefined;
        const verticalClass = flow === 'vertical' ? _Attachtokens.classes.vertical : undefined;
        const autoClass = flow === 'auto' ? _Attachtokens.classes.auto : undefined;
        const withHelperTextClass = helperText ? _Attachtokens.classes.withHelperText : undefined;
        const accept = acceptedFileFormats?.join(',');
        const handleClick = (e)=>{
            if (!localInputRef.current) {
                return;
            }
            if (onClick) {
                onClick(e);
            }
            localInputRef.current.click();
        };
        const handleChange = (e)=>{
            const fileList = e.target.files;
            if (onChange) {
                onChange(e);
            }
            if (!fileList || fileList.length === 0) {
                return;
            }
            const fileArray = Array.from(fileList);
            if (!hasAttachment || files !== undefined) {
                if (localInputRef.current) {
                    localInputRef.current.value = '';
                }
                return;
            }
            const filesData = fileArray.reduce((acc, file, ind)=>{
                const fileKey = `${ind}_${file.name}`;
                acc[fileKey] = {
                    ...(0, _utils1.getFilenameParts)(file.name, size, customIcon),
                    file
                };
                return acc;
            }, {});
            if (localInputRef.current) {
                syncInputFiles(localInputRef.current, fileArray);
            }
            cellHelperRefs.current = {};
            setInnerFilesInfo(filesData);
            setHasHiddenFiles(false);
        };
        const handleClear = (fileKey)=>{
            if (!localInputRef.current) {
                return;
            }
            if (onClear) {
                onClear(filesInfo[fileKey]);
            }
            if (files !== undefined) {
                return;
            }
            const updatedFilesInfo = {
                ...innerFilesInfo
            };
            delete updatedFilesInfo[fileKey];
            setInnerFilesInfo(updatedFilesInfo);
            delete cellHelperRefs.current[fileKey];
            syncInputFiles(localInputRef.current, Object.values(updatedFilesInfo).map((fi)=>fi.file));
        };
        const getCellRef = (element, key)=>{
            if (!cellHelperRefs?.current) {
                return;
            }
            if (element) {
                cellHelperRefs.current[key] = element;
            } else {
                delete cellHelperRefs.current[key];
            }
        };
        const updateHiddenFiles = ()=>{
            if (!multiple || Object.keys(filesInfo).length === 0) {
                setHasHiddenFiles(false);
                return;
            }
            if (flow !== 'horizontal') {
                setHasHiddenFiles(false);
                setVisibilityMap({});
                return;
            }
            if (!fileWrapperWidthRef.current || !fileWrapperHelperRef.current || !Object.keys(cellHelperRefs.current).length) {
                return;
            }
            const fileWrapper = fileWrapperWidthRef.current;
            const fileWrapperWidth = fileWrapper.clientWidth;
            const fileWrapperGap = parseInt(window.getComputedStyle(fileWrapper).columnGap ?? 0, 10);
            let totalWidth = 0;
            const firstHidden = Object.entries(cellHelperRefs.current).findIndex(([_, cell])=>{
                totalWidth += cell.clientWidth + fileWrapperGap;
                return totalWidth > fileWrapperWidth;
            });
            setHasHiddenFiles(firstHidden >= 0);
            const newKeys = Object.keys(filesInfo);
            const filesInfoHiddenKeys = firstHidden >= 0 ? newKeys.slice(firstHidden) : [];
            const newVisibilityMap = {};
            filesInfoHiddenKeys.forEach((key)=>{
                newVisibilityMap[key] = false;
            });
            setVisibilityMap(newVisibilityMap);
        };
        (0, _react.useEffect)(()=>{
            if (files === undefined || !localInputRef.current) {
                return;
            }
            syncInputFiles(localInputRef.current, files);
        }, [
            files
        ]);
        (0, _hooks.useIsomorphicLayoutEffect)(()=>{
            updateHiddenFiles();
        }, [
            filesLength,
            flow,
            multiple
        ]);
        (0, _react.useEffect)(()=>{
            if (flow !== 'horizontal' || !multiple) {
                return;
            }
            const observer = new ResizeObserver(()=>{
                updateHiddenFiles();
            });
            if (innerRef.current) {
                observer.observe(innerRef.current);
            }
            return ()=>observer.disconnect();
        }, [
            filesLength,
            flow,
            multiple
        ]);
        const RootWrapper = ({ children })=>{
            return /*#__PURE__*/ _react.default.createElement(Root, {
                size: size,
                view: view
            }, children);
        };
        return /*#__PURE__*/ _react.default.createElement(Root, {
            className: (0, _utils.cx)(horizontalClass, verticalClass, autoClass, withHelperTextClass, className),
            style: style,
            size: size,
            view: view,
            helperTextView: helperTextView,
            ref: innerRef
        }, /*#__PURE__*/ _react.default.createElement(_Attachstyles.StyledHiddenInput, {
            ref: inputRef,
            accept: accept,
            type: "file",
            id: id,
            name: name,
            multiple: multiple,
            onChange: handleChange
        }), (!hideButtonOnAttach || !filesLength) && /*#__PURE__*/ _react.default.createElement(_Attachstyles.StyledAttachButtonWrapper, null, /*#__PURE__*/ _react.default.createElement(_components.AttachButton, {
            ref: buttonRef,
            buttonType: buttonType,
            isLoading: isLoading,
            disabled: disabled,
            onClick: handleClick,
            ...rest
        }), helperText && /*#__PURE__*/ _react.default.createElement(_Attachstyles.StyledHelperText, null, helperText)), (hasAttachment || hideButtonOnAttach) && Boolean(filesLength) && Object.values(mergedFilesInfo)[0].isVisible && /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/ _react.default.createElement(_Attachstyles.FilesWrapper, {
            className: (0, _utils.cx)(horizontalClass, verticalClass, autoClass),
            applyOverflow: multiple && flow === 'horizontal'
        }, Object.entries(mergedFilesInfo).map(([key, { extension, filenameWithoutExtension, cellContentLeft, isVisible }])=>{
            if (!isVisible) {
                return;
            }
            return /*#__PURE__*/ _react.default.createElement(_ui.CellUI, {
                key: key,
                filenameWithoutExtension: filenameWithoutExtension,
                extension: extension,
                size: size,
                cellContentLeft: cellContentLeft,
                multiple: multiple,
                flow: flow,
                onClick: ()=>handleClear(key)
            });
        }))), (hasAttachment || hideButtonOnAttach) && hasHiddenFiles && /*#__PURE__*/ _react.default.createElement(_ui.DropdownUI, {
            rootWrapper: RootWrapper,
            size: size,
            filesInfo: mergedFilesInfo,
            customIcon: customIcon,
            handleClear: handleClear,
            ...dropdownOptions,
            placement: dropdownOptions?.placement ?? 'bottom'
        }), multiple && flow === 'horizontal' && /*#__PURE__*/ _react.default.createElement(_components.HiddenWidthHelper, {
            ref: fileWrapperWidthRef,
            hasHiddenFiles: hasHiddenFiles,
            size: size
        }), multiple && flow === 'horizontal' && (hasAttachment || hideButtonOnAttach) && Boolean(filesLength) && /*#__PURE__*/ _react.default.createElement(_Attachstyles.FilesWrapper, {
            ref: fileWrapperHelperRef,
            className: (0, _utils.cx)(horizontalClass, _Attachtokens.classes.horizontalHidden)
        }, Object.entries(filesInfo).map(([key, { extension, filenameWithoutExtension, cellContentLeft }])=>/*#__PURE__*/ _react.default.createElement(_ui.CellUI, {
                key: key,
                ref: (el)=>getCellRef(el, key),
                filenameWithoutExtension: filenameWithoutExtension,
                extension: extension,
                size: size,
                cellContentLeft: cellContentLeft,
                multiple: multiple,
                flow: flow,
                isHelper: true
            }))));
    });
const attachConfig = {
    name: 'Attach',
    tag: 'div',
    layout: attachRoot,
    base: _Attachstyles.base,
    variations: {
        view: {
            css: _base1.base
        },
        helperTextView: {
            css: _base2.base
        },
        size: {
            css: _base.base
        }
    },
    defaults: {
        view: 'default',
        helperTextView: 'default',
        size: 'm'
    }
};
