"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 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, onClick, onChange, onClear, ...rest } = props;
        const innerRef = (0, _react.useRef)(null);
        const ref = (0, _hooks.useForkRef)(outerRef, innerRef);
        const inputRef = (0, _react.useRef)(null);
        const buttonRef = (0, _react.useRef)(null);
        const fileWrapperWidthRef = (0, _react.useRef)(null);
        const fileWrapperHelperRef = (0, _react.useRef)(null);
        const cellHelperRefs = (0, _react.useRef)({});
        const [filesInfo, setFilesInfo] = (0, _react.useState)({});
        const [hasHiddenFiles, setHasHiddenFiles] = (0, _react.useState)(false);
        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 (!inputRef.current) {
                return;
            }
            if (onClick) {
                onClick(e);
            }
            inputRef.current.click();
        };
        const handleChange = (e)=>{
            const fileList = e.target.files;
            if (!fileList || fileList.length === 0) {
                return;
            }
            if (onChange) {
                onChange(e);
            }
            if (!hasAttachment) {
                return;
            }
            const fileArray = Array.from(fileList);
            const filesData = fileArray.reduce((acc, file, ind)=>{
                const fileKey = `${ind}_${file.name}`;
                acc[fileKey] = (0, _utils1.getFilenameParts)(file.name, size, customIcon);
                return acc;
            }, {});
            cellHelperRefs.current = {};
            setFilesInfo(filesData);
            setHasHiddenFiles(false);
        };
        const handleClear = (fileKey)=>{
            if (!inputRef.current) {
                return;
            }
            if (onClear) {
                onClear(filesInfo[fileKey]);
            }
            setFilesInfo((prevFileInfo)=>{
                const updatedFilesInfo = {
                    ...prevFileInfo
                };
                delete updatedFilesInfo[fileKey];
                return updatedFilesInfo;
            });
            delete cellHelperRefs.current[fileKey];
            setHasHiddenFiles(false);
        };
        const getCellRef = (element, key)=>{
            if (element && cellHelperRefs?.current) {
                cellHelperRefs.current[key] = element;
            }
        };
        const updateHiddenFiles = ()=>{
            const newFilesInfo = {
                ...filesInfo
            };
            if (!multiple || Object.keys(filesInfo).length === 0) {
                setHasHiddenFiles(false);
                return;
            }
            if (flow !== 'horizontal') {
                Object.keys(newFilesInfo).forEach((key)=>{
                    newFilesInfo[key].isVisible = true;
                });
                setHasHiddenFiles(false);
                setFilesInfo(newFilesInfo);
                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;
                if (totalWidth > fileWrapperWidth) {
                    setHasHiddenFiles(true);
                    return true;
                }
                return false;
            });
            const newKeys = Object.keys(newFilesInfo);
            const filesInfoVisibleKeys = firstHidden >= 0 ? newKeys.slice(0, firstHidden) : newKeys;
            const filesInfoHiddenKeys = firstHidden >= 0 ? newKeys.slice(firstHidden) : [];
            filesInfoVisibleKeys.forEach((key)=>{
                newFilesInfo[key].isVisible = true;
            });
            filesInfoHiddenKeys.forEach((key)=>{
                newFilesInfo[key].isVisible = false;
            });
            setFilesInfo(newFilesInfo);
        };
        (0, _react.useLayoutEffect)(()=>{
            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: ref
        }, /*#__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(filesInfo)[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(filesInfo).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: filesInfo,
            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'
    }
};
