import { __assign, __rest } from "tslib";
import React, { forwardRef, useEffect, useRef, cloneElement } from "react";
import useDebounce from "../hooks/useDebounce";
import getTextWidth from "../utils/getTextWidth";
import { ButtonComponent } from "./style";
import { buttonViewTypeDefault, buttonSizeDefault } from "./types";
import { getWithBlock } from "./helpers";
var Button = forwardRef(function (_a, ref) {
    var children = _a.children, icon = _a.icon, _b = _a.viewType, viewType = _b === void 0 ? buttonViewTypeDefault : _b, isDisabled = _a.isDisabled, _c = _a.size, size = _c === void 0 ? buttonSizeDefault : _c, color = _a.color, width = _a.width, href = _a.href, className = _a.className, onClick = _a.onClick, _d = _a.testId, testId = _d === void 0 ? "button" : _d, isPressed = _a.isPressed, props = __rest(_a, ["children", "icon", "viewType", "isDisabled", "size", "color", "width", "href", "className", "onClick", "testId", "isPressed"]);
    var textButtonRef = useRef(null);
    var setButtonTitle = function () {
        if (textButtonRef.current) {
            var parent_1 = textButtonRef.current.parentNode;
            var parentWidth = getWithBlock(parent_1, Boolean(icon));
            var fontParent = getComputedStyle(parent_1).font;
            parent_1.setAttribute("title", "");
            if (typeof children === "string") {
                var childrenWidth = getTextWidth(children, fontParent);
                if (parentWidth < childrenWidth) {
                    parent_1.setAttribute("title", children);
                }
            }
        }
    };
    var setButtonTitleDebounce = useDebounce(setButtonTitle, 500);
    useEffect(function () {
        window.addEventListener("resize", setButtonTitleDebounce);
        setButtonTitle();
        return function () { return window.removeEventListener("resize", setButtonTitleDebounce); };
    }, []);
    var handleClick = function (event) {
        onClick && !isDisabled && !href && onClick(event);
    };
    return (React.createElement(ButtonComponent, __assign({ isPressed: isPressed, className: className, viewType: viewType, disabled: isDisabled, size: size, as: viewType === "link" && href ? "a" : "button", href: href, "$color": color, width: width, onClick: handleClick, ref: ref, "$content": children, "data-testid": testId }, props),
        icon &&
            cloneElement(icon, { className: "lead-icon", width: 16, height: 16 }),
        typeof children === "string" ? (React.createElement("div", { className: "button-text", ref: textButtonRef }, children)) : (children)));
});
Button.displayName = "Button";
export default Button;
