function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _array_without_holes(arr) {
    if (Array.isArray(arr)) return _array_like_to_array(arr);
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
    try {
        var info = gen[key](arg);
        var value = info.value;
    } catch (error) {
        reject(error);
        return;
    }
    if (info.done) {
        resolve(value);
    } else {
        Promise.resolve(value).then(_next, _throw);
    }
}
function _async_to_generator(fn) {
    return function() {
        var self = this, args = arguments;
        return new Promise(function(resolve, reject) {
            var gen = fn.apply(self, args);
            function _next(value) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
            }
            function _throw(err) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
            }
            _next(undefined);
        });
    };
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _non_iterable_spread() {
    throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
    }
    return target;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        target[key] = source[key];
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _to_array(arr) {
    return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_rest();
}
function _to_consumable_array(arr) {
    return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
function _ts_generator(thisArg, body) {
    var f, y, t, _ = {
        label: 0,
        sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
        },
        trys: [],
        ops: []
    }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
    return d(g, "next", {
        value: verb(0)
    }), d(g, "throw", {
        value: verb(1)
    }), d(g, "return", {
        value: verb(2)
    }), typeof Symbol === "function" && d(g, Symbol.iterator, {
        value: function() {
            return this;
        }
    }), g;
    function verb(n) {
        return function(v) {
            return step([
                n,
                v
            ]);
        };
    }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while(g && (g = 0, op[0] && (_ = 0)), _)try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [
                op[0] & 2,
                t.value
            ];
            switch(op[0]){
                case 0:
                case 1:
                    t = op;
                    break;
                case 4:
                    _.label++;
                    return {
                        value: op[1],
                        done: false
                    };
                case 5:
                    _.label++;
                    y = op[1];
                    op = [
                        0
                    ];
                    continue;
                case 7:
                    op = _.ops.pop();
                    _.trys.pop();
                    continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                        _ = 0;
                        continue;
                    }
                    if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                        _.label = op[1];
                        break;
                    }
                    if (op[0] === 6 && _.label < t[1]) {
                        _.label = t[1];
                        t = op;
                        break;
                    }
                    if (t && _.label < t[2]) {
                        _.label = t[2];
                        _.ops.push(op);
                        break;
                    }
                    if (t[2]) _.ops.pop();
                    _.trys.pop();
                    continue;
            }
            op = body.call(thisArg, _);
        } catch (e) {
            op = [
                6,
                e
            ];
            y = 0;
        } finally{
            f = t = 0;
        }
        if (op[0] & 5) throw op[1];
        return {
            value: op[0] ? op[1] : void 0,
            done: true
        };
    }
}
import React, { forwardRef, useEffect, useRef, useState } from "react";
import { canUseDOM, cx, getSizeValueFromProp } from "../../utils";
import { useForkRef, useResizeObserver } from "../../hooks";
import { IconArrowBarDown } from "../_Icon";
import { base as viewCSS } from "./variations/_view/base";
import { base as sizeCSS } from "./variations/_size/base";
import { base as disabledCSS } from "./variations/_disabled/base";
import { base, Content, Description, DescriptionHelper, DropzoneHandlerOverlay, HiddenInput, StyledIcon, Title, TitleHelper, ContentWrapper, IconWrapper } from "./Dropzone.styles";
import { classes, privateTokens } from "./Dropzone.tokens";
export var dropzoneRoot = function dropzoneRoot(Root) {
    return /*#__PURE__*/ forwardRef(function(_0, _1) {
        var _ref = [
            _0,
            _1
        ], _ref1 = _to_array(_ref), _ref2 = _ref1[0], _rest = _ref1.slice(1), className = _ref2.className, style = _ref2.style, accept = _ref2.accept, multiple = _ref2.multiple, title = _ref2.title, description = _ref2.description, icon = _ref2.icon, _ref_iconPlacement = _ref2.iconPlacement, iconPlacement = _ref_iconPlacement === void 0 ? 'left' : _ref_iconPlacement, size = _ref2.size, view = _ref2.view, disabled = _ref2.disabled, stretch = _ref2.stretch, width = _ref2.width, height = _ref2.height, onDragEnter = _ref2.onDragEnter, onDragLeave = _ref2.onDragLeave, onDragOver = _ref2.onDragOver, onDrop = _ref2.onDrop, validator = _ref2.validator, onClick = _ref2.onClick, onChange = _ref2.onChange, onChoseFiles = _ref2.onChoseFiles, rest = _object_without_properties(_ref2, [
            "className",
            "style",
            "accept",
            "multiple",
            "title",
            "description",
            "icon",
            "iconPlacement",
            "size",
            "view",
            "disabled",
            "stretch",
            "width",
            "height",
            "onDragEnter",
            "onDragLeave",
            "onDragOver",
            "onDrop",
            "validator",
            "onClick",
            "onChange",
            "onChoseFiles"
        ]), _rest1 = _sliced_to_array(_rest, 1), outerRef = _rest1[0];
        var _useState = _sliced_to_array(useState(false), 2), isDropzoneActive = _useState[0], setIsDropzoneActive = _useState[1];
        var _useState1 = _sliced_to_array(useState(title), 2), innerTitle = _useState1[0], setInnerTitle = _useState1[1];
        var _useState2 = _sliced_to_array(useState(description), 2), innerDescription = _useState2[0], setInnerDescription = _useState2[1];
        var inputRef = useRef(null);
        var forkInputRef = useForkRef(outerRef, inputRef);
        var contentRef = useRef(null);
        var iconWrapperRef = useRef(null);
        var iconRef = useRef(null);
        var contentWrapperRef = useRef(null);
        var titleRef = useRef(null);
        var titleHelperRef = useRef(null);
        var descriptionRef = useRef(null);
        var descriptionHelperRef = useRef(null);
        var innerWidth = width ? getSizeValueFromProp(width) : 'fit-content';
        var innerHeight = height ? getSizeValueFromProp(height) : 'fit-content';
        var isTitleString = typeof title === 'string';
        var isDescriptionString = typeof description === 'string';
        var processFiles = function processFiles(rawFiles, callback, afterAction) {
            return _async_to_generator(function() {
                var files, res;
                return _ts_generator(this, function(_state) {
                    switch(_state.label){
                        case 0:
                            if (!(rawFiles === null || rawFiles === void 0 ? void 0 : rawFiles.length)) {
                                return [
                                    2
                                ];
                            }
                            files = _to_consumable_array(rawFiles);
                            res = {
                                acceptedFiles: files
                            };
                            if (!validator) return [
                                3,
                                2
                            ];
                            return [
                                4,
                                validator === null || validator === void 0 ? void 0 : validator(files)
                            ];
                        case 1:
                            res = _state.sent();
                            _state.label = 2;
                        case 2:
                            if (!callback) return [
                                3,
                                4
                            ];
                            return [
                                4,
                                callback(res)
                            ];
                        case 3:
                            _state.sent();
                            _state.label = 4;
                        case 4:
                            if (afterAction) {
                                afterAction();
                            }
                            return [
                                2
                            ];
                    }
                });
            })();
        };
        var handleDragEnter = function handleDragEnter(event) {
            if (disabled) {
                return;
            }
            event.preventDefault();
            event.stopPropagation();
            if (onDragEnter) {
                onDragEnter(event);
            }
            setIsDropzoneActive(true);
        };
        var handleDragLeave = function handleDragLeave(event) {
            if (disabled) {
                return;
            }
            event.preventDefault();
            if (onDragLeave) {
                onDragLeave(event);
            }
            setIsDropzoneActive(false);
        };
        var handleDragOver = function handleDragOver(event) {
            if (disabled) {
                return;
            }
            event.preventDefault();
            if (onDragOver) {
                onDragOver(event);
            }
            var _event_dataTransfer = event.dataTransfer, rawFiles = _event_dataTransfer.files;
            if (!isDropzoneActive && rawFiles && rawFiles.length > 0) {
                setIsDropzoneActive(true);
            }
        };
        var handleDrop = function handleDrop(event) {
            return _async_to_generator(function() {
                var _event_dataTransfer, rawFiles, afterAction;
                return _ts_generator(this, function(_state) {
                    switch(_state.label){
                        case 0:
                            if (disabled) {
                                return [
                                    2
                                ];
                            }
                            event.preventDefault();
                            event.persist();
                            _event_dataTransfer = event.dataTransfer, rawFiles = _event_dataTransfer.files;
                            afterAction = function afterAction() {
                                event.dataTransfer.clearData();
                                setIsDropzoneActive(false);
                            };
                            return [
                                4,
                                processFiles(rawFiles, onDrop, afterAction)
                            ];
                        case 1:
                            _state.sent();
                            return [
                                2
                            ];
                    }
                });
            })();
        };
        var handleClick = function handleClick(event) {
            if (!inputRef.current || disabled) {
                return;
            }
            inputRef.current.click();
            if (onClick) {
                onClick(event);
            }
        };
        var handleChange = function handleChange(event) {
            return _async_to_generator(function() {
                var _event_target, rawFiles;
                return _ts_generator(this, function(_state) {
                    switch(_state.label){
                        case 0:
                            if (disabled) {
                                return [
                                    2
                                ];
                            }
                            if (onChange) {
                                onChange(event);
                            }
                            _event_target = event.target, rawFiles = _event_target.files;
                            return [
                                4,
                                processFiles(rawFiles, onChoseFiles)
                            ];
                        case 1:
                            _state.sent();
                            return [
                                2
                            ];
                    }
                });
            })();
        };
        var truncateContent = function truncateContent() {
            if (!canUseDOM || !(descriptionRef === null || descriptionRef === void 0 ? void 0 : descriptionRef.current) || !(contentWrapperRef === null || contentWrapperRef === void 0 ? void 0 : contentWrapperRef.current) || !(titleRef === null || titleRef === void 0 ? void 0 : titleRef.current) || !(titleHelperRef === null || titleHelperRef === void 0 ? void 0 : titleHelperRef.current) || !(iconRef === null || iconRef === void 0 ? void 0 : iconRef.current) || !(iconWrapperRef === null || iconWrapperRef === void 0 ? void 0 : iconWrapperRef.current) || !(contentRef === null || contentRef === void 0 ? void 0 : contentRef.current) || !(descriptionHelperRef === null || descriptionHelperRef === void 0 ? void 0 : descriptionHelperRef.current) || !width && !height) {
                return;
            }
            var contentHeight = contentRef.current.offsetHeight;
            var iconHeight = iconRef.current.offsetHeight;
            var iconWidth = iconPlacement === 'top' ? 0 : iconRef.current.offsetWidth;
            var titleHeight = titleRef.current.offsetHeight;
            var iconContentGap = iconPlacement === 'top' ? Number(window.getComputedStyle(iconWrapperRef.current).rowGap.replace('px', '')) : 0;
            var availableWidth = contentRef.current.offsetWidth - iconWidth - iconContentGap;
            var contentGap = Number(window.getComputedStyle(contentWrapperRef.current).rowGap.replace('px', ''));
            var titleFontWidth = Math.floor(titleHelperRef.current.offsetWidth);
            var titleFontHeight = Math.floor(titleHelperRef.current.offsetHeight);
            var descriptionFontWidth = Math.floor(descriptionHelperRef.current.offsetWidth);
            var descriptionFontHeight = Math.floor(descriptionHelperRef.current.offsetHeight);
            var titleAvailableHeight = contentHeight - iconHeight - iconContentGap - descriptionFontHeight - contentGap;
            var titleMaxChars = Math.floor(availableWidth / titleFontWidth * (titleAvailableHeight / titleFontHeight));
            var resTitleLength = 0;
            if (title && isTitleString) {
                var newTitle = title.length <= titleMaxChars ? title : "".concat(title.slice(0, titleMaxChars - 3), "...");
                resTitleLength = newTitle.length;
                setInnerTitle(newTitle);
            }
            var resultTitleHeight = Math.floor(titleFontHeight * titleFontWidth * resTitleLength / availableWidth);
            var descriptionAvailableHeight = titleAvailableHeight >= titleHeight + 2 * descriptionFontHeight ? contentHeight - resultTitleHeight - iconContentGap - contentGap : descriptionFontHeight;
            var descriptionMaxChars = Math.floor(availableWidth / descriptionFontWidth * (descriptionAvailableHeight / descriptionFontHeight));
            if (description && isDescriptionString) {
                var newDescription = description.length <= descriptionMaxChars ? description : "".concat(description.slice(0, descriptionMaxChars - 3), "...");
                setInnerDescription(newDescription);
            }
        };
        useResizeObserver(contentRef, truncateContent);
        useEffect(function() {
            truncateContent();
        }, [
            title,
            description,
            iconPlacement
        ]);
        var _obj;
        return /*#__PURE__*/ React.createElement(Root, {
            className: cx(className, isDropzoneActive && classes.active, stretch && classes.stretch, disabled && classes.disabled),
            view: view,
            size: size,
            disabled: disabled,
            tabIndex: 0,
            style: _object_spread_props(_object_spread({}, style), (_obj = {}, _define_property(_obj, privateTokens.width, innerWidth), _define_property(_obj, privateTokens.height, innerHeight), _obj))
        }, /*#__PURE__*/ React.createElement(DropzoneHandlerOverlay, {
            onDragEnter: handleDragEnter,
            onDragLeave: handleDragLeave,
            onDragOver: handleDragOver,
            onDrop: handleDrop,
            onClick: handleClick
        }), /*#__PURE__*/ React.createElement(Content, {
            ref: contentRef
        }, /*#__PURE__*/ React.createElement(IconWrapper, {
            ref: iconWrapperRef,
            className: cx(iconPlacement === 'top' && classes.verticalContentPlacing)
        }, /*#__PURE__*/ React.createElement(StyledIcon, {
            ref: iconRef
        }, icon || /*#__PURE__*/ React.createElement(IconArrowBarDown, {
            color: "inherit",
            size: "s"
        })), /*#__PURE__*/ React.createElement(ContentWrapper, {
            ref: contentWrapperRef
        }, title && isTitleString ? /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(Title, {
            ref: titleRef
        }, innerTitle), /*#__PURE__*/ React.createElement(TitleHelper, {
            ref: titleHelperRef
        }, "C")) : title, description && isDescriptionString ? /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(Description, {
            ref: descriptionRef
        }, innerDescription), /*#__PURE__*/ React.createElement(DescriptionHelper, {
            ref: descriptionHelperRef
        }, "C")) : description))), /*#__PURE__*/ React.createElement(HiddenInput, _object_spread({
            ref: forkInputRef,
            type: "file",
            accept: accept,
            multiple: multiple,
            tabIndex: -1,
            onChange: handleChange
        }, rest)));
    });
};
export var dropzoneConfig = {
    name: 'Dropzone',
    tag: 'div',
    layout: dropzoneRoot,
    base: base,
    variations: {
        view: {
            css: viewCSS
        },
        size: {
            css: sizeCSS
        },
        disabled: {
            css: disabledCSS,
            attrs: true
        }
    },
    defaults: {
        view: 'default',
        size: 'm'
    }
};
