var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import * as React from "react";
import { useEffect, useState } from "react";
import ReactDOM from "react-dom";
import { useFloating, offset, flip, shift, autoUpdate } from "@floating-ui/react";
import { cn } from "@utils";
import { dropdownVariants, dropdownHeaderVariants } from "./dropdownVariants";
import { DropdownToggle } from "./dropdownToggle";
import {} from "./dropdownItem";
import { keyboardKeys } from "@constants";
export const Dropdown = React.forwardRef((_a, ref) => {
    var { size = "md", children, header, ctaContent, portalTarget = typeof document !== "undefined" ? document.body : undefined, disabled = false, ctaClassName, className } = _a, props = __rest(_a, ["size", "children", "header", "ctaContent", "portalTarget", "disabled", "ctaClassName", "className"]);
    const [itemList, setItem] = useState([]);
    const [dropdownShow, setShowDropdown] = useState(false);
    // Floating UI hook
    const { x, y, refs, strategy, update } = useFloating({
        placement: "bottom-start",
        middleware: [offset(8), flip(), shift()],
        whileElementsMounted: autoUpdate
    });
    // Listener to toggle state on button press
    const toggle = () => {
        setShowDropdown((isDropdownOpen) => !isDropdownOpen);
        setTimeout(() => update === null || update === void 0 ? void 0 : update(), 0);
    };
    // Listener to close the dropdown when focus moves away from it
    const handleBlur = (event) => {
        if (!event.currentTarget.contains(event.relatedTarget)) {
            setShowDropdown(false);
        }
    };
    // Listener to add func to esc, up, down arrows for nav
    const dropdownKeyPress = (event) => {
        var _a, _b;
        if (event.key === keyboardKeys.escape) {
            setShowDropdown(false);
        }
        else if (event.key === keyboardKeys.arrowUp) {
            if ((_a = document.activeElement) === null || _a === void 0 ? void 0 : _a.previousElementSibling) {
                document.activeElement.previousElementSibling.focus();
            }
        }
        else if (event.key === keyboardKeys.arrowDown) {
            if ((_b = document.activeElement) === null || _b === void 0 ? void 0 : _b.nextElementSibling) {
                document.activeElement.nextElementSibling.focus();
            }
        }
    };
    // Effect to calibrate children and button content
    useEffect(() => {
        if (!children) {
            return;
        }
        const itemArray = [];
        React.Children.forEach(children, (child, index) => {
            const childElement = child;
            const position = index === 0
                ? "first"
                : index === React.Children.count(children) - 1
                    ? "last"
                    : "middle";
            const clone = React.cloneElement(childElement, {
                dropdownShow,
                setShowDropdown,
                index,
                key: index,
                size,
                position
            });
            itemArray.push(clone);
        });
        setItem(itemArray);
    }, [children, ctaContent, dropdownShow, size]);
    return children ? (_jsxs(_Fragment, { children: [_jsx(DropdownToggle, { ref: refs.setReference, onClick: toggle, ctaClassName: ctaClassName, disabled: disabled, children: ctaContent }), portalTarget && ReactDOM.createPortal(_jsx("div", Object.assign({ className: cn(className) }, props, { ref: ref, children: _jsxs("div", { ref: refs.setFloating, onKeyUp: dropdownKeyPress, style: {
                        position: strategy,
                        top: y !== null && y !== void 0 ? y : 0,
                        left: x !== null && x !== void 0 ? x : 0,
                        width: "max-content"
                    }, onBlur: handleBlur, className: cn(dropdownVariants({ size }), dropdownShow ? "block" : "hidden"), children: [header && (_jsx("div", { className: dropdownHeaderVariants({
                                type: typeof header === "string" ? "text" : "custom"
                            }), children: header })), itemList.map((item) => item)] }) })), portalTarget)] })) : null;
});
Dropdown.displayName = "Dropdown";
//# sourceMappingURL=dropdown.js.map