import React, { useState, useRef, useEffect } from "react";
import "../../assets/css/button.css";
import { useOutsideClickDetector } from "../../hooks/useOutsideClickDetector";
import { onClickA11y } from "../utils";
const DropdownButton = ({ buttonLabel = "Label", buttonOptions = [], mainAction, }) => {
    const wrapperRef = useRef(null);
    const [expanded, setExpanded] = useState(false);
    const [className, setClassName] = useState("");
    const moveElementIntoView = () => {
        var _a, _b;
        const bottomViewPort = window.innerHeight + window.scrollY;
        const domRect = (_b = (_a = wrapperRef === null || wrapperRef === void 0 ? void 0 : wrapperRef.current) === null || _a === void 0 ? void 0 : _a.querySelector(".finsemble-dropdown-action__btn-options")) === null || _b === void 0 ? void 0 : _b.getBoundingClientRect();
        const elementBottom = domRect ? domRect.y + domRect.height + window.scrollY : null;
        if (elementBottom && elementBottom > bottomViewPort) {
            setClassName("flow-up");
        }
    };
    useEffect(() => {
        if (expanded) {
            moveElementIntoView();
        }
    }, [expanded]);
    useOutsideClickDetector(wrapperRef, () => setExpanded(false));
    const options = buttonOptions.map((option, index) => (React.createElement("div", { key: index, className: "finsemble-dropdown-action__btn-option", role: "button", ...onClickA11y(() => {
            option.clickHandler();
            setExpanded(false);
        }), ...(option.buttonLabel ? { "aria-label": option.buttonLabel } : "") }, option.buttonLabel)));
    const buttonAction = () => {
        if (expanded) {
            setExpanded(false);
            return;
        }
        if (mainAction) {
            mainAction();
        }
        else {
            () => setExpanded(!expanded);
        }
    };
    return (React.createElement("div", { ref: wrapperRef, className: "finsemble-dropdown-action__btn-container" },
        React.createElement("div", { className: "finsemble-dropdown-action__btn" },
            React.createElement("span", { className: "btn-label", role: "button", ...onClickA11y(buttonAction), ...(buttonLabel ? { "aria-label": buttonLabel } : "") }, buttonLabel),
            React.createElement("span", { className: "separator" }),
            React.createElement("div", { className: "expand-options", role: "button", ...onClickA11y(() => setExpanded(!expanded), (e) => {
                    if (e.key === "Enter") {
                        moveElementIntoView();
                    }
                }), "aria-label": "expand-options" },
                React.createElement("span", { className: "caret" }))),
        expanded ? React.createElement("div", { className: `finsemble-dropdown-action__btn-options ${className}` }, options) : null));
};
export default DropdownButton;
//# sourceMappingURL=DropdownButton.js.map