"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { cnb } from "cnbuilder";
import { forwardRef } from "react";
import { overlay } from "../overlay/overlayStyles.js";
import { CircularProgress } from "../progress/CircularProgress.js";
import { LinearProgress } from "../progress/LinearProgress.js";
import { useAsyncAction } from "../useAsyncAction.js";
import { useEnsuredId } from "../useEnsuredId.js";
import { Button } from "./Button.js";
const noop = ()=>{
// do nothing
};
/**
 * **Client Component**
 *
 * The async button can be used to render a loading indicator within a button
 * during an async task. The loading spinner can be shown either by enabling the
 * `loading` prop or returning a promise from the `onClick` event which will
 * continue to show the loading indicator until the promise has been resolved.
 *
 * @example
 * Async onClick
 * ```tsx
 * import { AsyncButton } from "@react-md/core";
 * import { useState, type ReactElement } from "react";
 *
 * function Example(): ReactElement {
 *   const [data, setData] = useState(null);
 *   return (
 *     <AsyncButton
 *       type="submit"
 *       onClick={async () => {
 *         const response = await fetch("/my-api");
 *         const json = await response.json();
 *         setData(json);
 *       }}
 *     >
 *       Submit
 *     </AsyncButton>
 *   );
 * }
 * ```
 *
 * @example
 * Manual Loading State
 * ```tsx
 * import { AsyncButton } from "@react-md/core";
 * import { useMutation } from "@tanstack/query";
 * import { useState, type ReactElement } from "react";
 *
 * function Example(): ReactElement {
 *   const { isLoading, mutate } = useMutation({
 *     mutationFn: (newTodo) => fetch('/todos', {
 *       method: "POST",
 *       body: JSON.stringify(newTodo),
 *     }),
 *   });
 *
 *   return (
 *     <AsyncButton
 *       type="submit"
 *       loading={isLoading}
 *       onClick={() => {
 *         mutate({ id: Date.now(), title: "Create example" });
 *       }}
 *     >
 *       Create Todo
 *     </AsyncButton>
 *   );
 * }
 * ```
 *
 * @remarks \@since 6.0.0
 */ export const AsyncButton = /*#__PURE__*/ forwardRef(function AsyncButton(props, ref) {
    const { id: propId, onClick = noop, children, floating = null, theme = floating ? "secondary" : "clear", themeType = floating ? "contained" : "flat", buttonType = floating ? "icon" : "text", className, disabled, loading: propLoading = false, loadingType = "circular-overlay", loadingChildren, loadingDisabledTheme = false, afterAddon: propAfterAddon, beforeAddon: propBeforeAddon, linearProgressProps, circularProgressProps, progressAriaLabel, progressAriaLabelledBy: propProgressAriaLabelledBy, ...remaining } = props;
    const id = useEnsuredId(propId, "async-button");
    const { handleAsync, pending } = useAsyncAction({
        disabled
    });
    const loading = pending || propLoading;
    let progressTheme = "current-color";
    if (theme === "clear" || theme === "disabled") {
        progressTheme = "primary";
    }
    let progressAriaLabelledBy = propProgressAriaLabelledBy;
    if (!progressAriaLabel && !linearProgressProps?.["aria-label"] && !linearProgressProps?.["aria-labelledby"] && !circularProgressProps?.["aria-label"] && !circularProgressProps?.["aria-labelledby"]) {
        progressAriaLabelledBy = id;
    }
    const progress = loadingType.includes("linear") ? /*#__PURE__*/ _jsx(LinearProgress, {
        "aria-label": progressAriaLabel,
        "aria-labelledby": progressAriaLabelledBy,
        ...linearProgressProps,
        theme: progressTheme
    }) : /*#__PURE__*/ _jsx(CircularProgress, {
        "aria-label": progressAriaLabel,
        "aria-labelledby": progressAriaLabelledBy,
        ...circularProgressProps,
        theme: progressTheme
    });
    let afterAddon = propAfterAddon;
    let beforeAddon = propBeforeAddon;
    let overlayElement;
    let isOverlayCover = false;
    switch(loadingType){
        case "circular-before":
            beforeAddon = loading ? progress : propBeforeAddon;
            break;
        case "circular-after":
            afterAddon = loading ? progress : propAfterAddon;
            break;
        case "circular-overlay":
        case "linear-above":
        case "linear-below":
            {
                let alignItems = "center";
                if (loadingType === "linear-above") {
                    alignItems = "start";
                } else if (loadingType === "linear-below") {
                    alignItems = "end";
                } else {
                    isOverlayCover = true;
                }
                overlayElement = loading && /*#__PURE__*/ _jsx("span", {
                    className: overlay({
                        active: true,
                        visible: true,
                        absolute: true,
                        align: alignItems
                    }),
                    children: progress
                });
                break;
            }
    }
    return /*#__PURE__*/ _jsxs(Button, {
        ...remaining,
        "aria-disabled": loading || undefined,
        id: id,
        ref: ref,
        disabled: disabled,
        floating: floating,
        className: cnb("rmd-button--async", loading && isOverlayCover && "rmd-button--async-overlay", className),
        theme: loading && loadingDisabledTheme ? "disabled" : theme,
        themeType: themeType,
        buttonType: buttonType,
        onClick: handleAsync((event)=>Promise.resolve(onClick(event))),
        children: [
            beforeAddon,
            loading && typeof loadingChildren !== "undefined" ? loadingChildren : children,
            afterAddon,
            overlayElement
        ]
    });
});

//# sourceMappingURL=AsyncButton.js.map