"use client";
import { __awaiter } from '../../node_modules/.pnpm/@rollup_plugin-typescript@12.1.4_rollup@4.46.2_tslib@2.8.1_typescript@5.9.3/node_modules/tslib/tslib.es6.mjs';
import { jsxs, jsx } from 'react/jsx-runtime';
import { useClerk } from '@clerk/nextjs';
import { GradientButton } from '../../fuma/mdx/gradient-button.mjs';
import { globalLucideIcons } from '@windrun-huaiin/base-ui/components/server';
import { cn } from '@windrun-huaiin/lib/utils';
import { useState, useRef, useCallback, useMemo, useLayoutEffect } from 'react';
import { redirectToCustomerPortal } from '../money-price/customer-portal.mjs';
import { useCreditNavPopover } from './credit-nav-button.mjs';

const clampPercent = (value) => Math.min(100, Math.max(0, Math.round(value)));
const formatNumber = (locale, value) => new Intl.NumberFormat(locale, {
    maximumFractionDigits: 0,
}).format(value);
function CreditOverviewClient({ data, locale, translations, className, expiringSoonThresholdDays = 7, customActionHandlers, }) {
    var _a;
    const { redirectToSignIn } = useClerk();
    const navPopover = useCreditNavPopover();
    const isMobile = (_a = navPopover === null || navPopover === void 0 ? void 0 : navPopover.isMobile) !== null && _a !== void 0 ? _a : false;
    const [bucketExpanded, setBucketExpanded] = useState(false);
    const userToggledRef = useRef(false);
    const closeNavPopover = useCallback((options) => {
        if (!navPopover) {
            return;
        }
        if (options === null || options === void 0 ? void 0 : options.defer) {
            if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') {
                window.requestAnimationFrame(() => navPopover.close());
            }
            else {
                setTimeout(() => navPopover.close(), 0);
            }
            return;
        }
        navPopover.close();
    }, [navPopover]);
    const buckets = useMemo(() => {
        return (data.buckets || []).map((bucket) => {
            var _a, _b, _c;
            const limit = Math.max(bucket.limit, 0);
            const rawProgress = typeof bucket.progressPercent === 'number'
                ? bucket.progressPercent
                : limit > 0
                    ? (bucket.balance / limit) * 100
                    : bucket.balance > 0
                        ? 100
                        : 0;
            const computedLabel = (_b = (_a = bucket.label) !== null && _a !== void 0 ? _a : translations.bucketDefaultLabels[bucket.kind]) !== null && _b !== void 0 ? _b : bucket.kind;
            const computedStatus = (_c = bucket.status) !== null && _c !== void 0 ? _c : deriveStatus(bucket.expiresAt, expiringSoonThresholdDays);
            return Object.assign(Object.assign({}, bucket), { progress: clampPercent(rawProgress), computedLabel,
                computedStatus });
        });
    }, [data.buckets, translations.bucketDefaultLabels, expiringSoonThresholdDays]);
    const hasBuckets = buckets.length > 0;
    const subscription = data.subscription;
    const pricingContext = data.pricingContext;
    const ctaBehaviors = data.ctaBehaviors;
    const getModalMoneyPriceData = useCallback((mode) => {
        if (!pricingContext) {
            return null;
        }
        if (mode !== 'onetime') {
            return pricingContext.moneyPriceData;
        }
        const hasOnetimeOption = pricingContext.moneyPriceData.billingSwitch.options.some((option) => option.key === 'onetime');
        if (!hasOnetimeOption) {
            return pricingContext.moneyPriceData;
        }
        return Object.assign(Object.assign({}, pricingContext.moneyPriceData), { billingSwitch: Object.assign(Object.assign({}, pricingContext.moneyPriceData.billingSwitch), { defaultKey: 'onetime' }) });
    }, [pricingContext]);
    const requestPricingModal = useCallback((mode) => {
        if (!pricingContext || !(navPopover === null || navPopover === void 0 ? void 0 : navPopover.openPricingModal)) {
            return false;
        }
        const dataForMode = getModalMoneyPriceData(mode);
        if (!dataForMode) {
            return false;
        }
        navPopover.openPricingModal({
            mode,
            modalMoneyPriceData: dataForMode,
            pricingContext,
        });
        return true;
    }, [getModalMoneyPriceData, navPopover, pricingContext]);
    const executeAuthAction = useCallback((action) => __awaiter(this, void 0, void 0, function* () {
        var _a;
        const endpoint = (_a = action.endpoint) !== null && _a !== void 0 ? _a : pricingContext === null || pricingContext === void 0 ? void 0 : pricingContext.customerPortalApiEndpoint;
        if (!endpoint) {
            console.warn('[CreditOverview] Auth action requires an endpoint.');
            return false;
        }
        return redirectToCustomerPortal({
            customerPortalApiEndpoint: endpoint,
            redirectToSignIn,
            returnUrl: action.returnUrl,
        });
    }), [pricingContext, redirectToSignIn]);
    const executeConfiguredAction = useCallback((action, key, device) => __awaiter(this, void 0, void 0, function* () {
        if (device === 'mobile' && action.kind === 'modal') {
            console.warn(`[CreditOverview] Mobile device cannot run modal action for "${key}". Adjust configuration.`);
            return false;
        }
        switch (action.kind) {
            case 'modal': {
                const opened = requestPricingModal(action.mode);
                if (opened) {
                    closeNavPopover({ defer: true });
                }
                return opened;
            }
            case 'redirect': {
                if (!action.url || action.url === '#') {
                    console.warn(`[CreditOverview] Redirect URL missing for action "${key}".`);
                    return false;
                }
                window.location.href = action.url;
                closeNavPopover();
                return true;
            }
            case 'auth': {
                const handled = yield executeAuthAction(action);
                if (handled) {
                    closeNavPopover();
                }
                return handled;
            }
            case 'custom': {
                const handler = customActionHandlers === null || customActionHandlers === void 0 ? void 0 : customActionHandlers[action.handlerKey];
                if (!handler) {
                    console.warn(`[CreditOverview] Custom action "${action.handlerKey}" missing handler for "${key}".`);
                    return false;
                }
                yield handler();
                closeNavPopover();
                return true;
            }
            default:
                return false;
        }
    }), [closeNavPopover, customActionHandlers, executeAuthAction, requestPricingModal]);
    const runConfiguredAction = useCallback((key, fallback) => __awaiter(this, void 0, void 0, function* () {
        var _a;
        const device = isMobile ? 'mobile' : 'desktop';
        const deviceAction = (_a = ctaBehaviors === null || ctaBehaviors === void 0 ? void 0 : ctaBehaviors[key]) === null || _a === void 0 ? void 0 : _a[device];
        if (deviceAction) {
            const handled = yield executeConfiguredAction(deviceAction, key, device);
            if (handled) {
                return;
            }
            console.warn(`[CreditOverview] Configured action "${key}" for ${device} did not complete successfully. Falling back to default behavior.`);
        }
        else if (ctaBehaviors === null || ctaBehaviors === void 0 ? void 0 : ctaBehaviors[key]) {
            console.warn(`[CreditOverview] Missing ${device} configuration for action "${key}". Falling back to default behavior.`);
        }
        yield Promise.resolve(fallback());
    }), [ctaBehaviors, executeConfiguredAction, isMobile]);
    const fallbackSubscribe = useCallback(() => __awaiter(this, void 0, void 0, function* () {
        if (!isMobile) {
            const opened = requestPricingModal('subscription');
            if (opened) {
                closeNavPopover({ defer: true });
                return;
            }
        }
        console.warn(`[CreditOverview] Missing subscribe action for ${isMobile ? 'mobile' : 'desktop'} device. Dropdown will simply close.`);
        closeNavPopover();
    }), [closeNavPopover, isMobile, requestPricingModal]);
    const fallbackManage = useCallback(() => __awaiter(this, void 0, void 0, function* () {
        const handled = yield redirectToCustomerPortal({
            customerPortalApiEndpoint: pricingContext === null || pricingContext === void 0 ? void 0 : pricingContext.customerPortalApiEndpoint,
            redirectToSignIn,
        });
        if (handled) {
            closeNavPopover();
            return;
        }
        if (!isMobile) {
            const opened = requestPricingModal('subscription');
            if (opened) {
                closeNavPopover({ defer: true });
            }
        }
    }), [
        closeNavPopover,
        isMobile,
        pricingContext,
        redirectToSignIn,
        requestPricingModal,
    ]);
    const fallbackOnetime = useCallback(() => __awaiter(this, void 0, void 0, function* () {
        if (!isMobile) {
            const opened = requestPricingModal('onetime');
            if (opened) {
                closeNavPopover({ defer: true });
                return;
            }
        }
        console.warn(`[CreditOverview] Missing onetime action for ${isMobile ? 'mobile' : 'desktop'} device. Dropdown will simply close.`);
        closeNavPopover();
    }), [closeNavPopover, isMobile, requestPricingModal]);
    const handleSubscribeAction = useCallback(() => __awaiter(this, void 0, void 0, function* () {
        if (subscription) {
            return;
        }
        yield runConfiguredAction('subscribe', fallbackSubscribe);
    }), [fallbackSubscribe, runConfiguredAction, subscription]);
    const handleManageAction = useCallback(() => __awaiter(this, void 0, void 0, function* () {
        if (!subscription) {
            return;
        }
        yield runConfiguredAction('manage', fallbackManage);
    }), [fallbackManage, runConfiguredAction, subscription]);
    const handleOnetimeAction = useCallback(() => __awaiter(this, void 0, void 0, function* () {
        yield runConfiguredAction('onetime', fallbackOnetime);
    }), [fallbackOnetime, runConfiguredAction]);
    useLayoutEffect(() => {
        if (userToggledRef.current) {
            return;
        }
        setBucketExpanded(!isMobile);
    }, [isMobile]);
    const toggleBucketExpanded = useCallback(() => {
        userToggledRef.current = true;
        setBucketExpanded((prev) => !prev);
    }, []);
    const expandBuckets = useCallback(() => {
        userToggledRef.current = true;
        setBucketExpanded(true);
    }, []);
    return (jsxs("section", { className: cn("flex flex-col gap-2 p-2 shadow-inner rounded-xl bg-white dark:bg-slate-900", className), children: [jsxs("header", { className: "relative rounded-2xl bg-linear-to-bl from-indigo-200/60 via-indigo-400/90 to-purple-200/50 p-4 shadow-inner dark:from-indigo-300/20 dark:via-slate-400 dark:to-slate-500/50 sm:p-6", children: [jsxs("div", { className: "flex flex-col gap-2 sm:gap-3", children: [jsxs("div", { className: "flex items-center justify-start rounded-full ", children: [jsx(globalLucideIcons.Gem, { "aria-hidden": true, className: "mr-2 h-6 w-6 sm:h-8 sm:w-8" }), jsx("span", { className: "text-sm font-medium sm:text-base", children: translations.totalLabel })] }), jsx("div", { className: "flex justify-center text-3xl font-semibold leading-tight sm:text-4xl", children: formatNumber(locale, data.totalBalance) }), jsxs("div", { className: "flex-1 flex-col gap-1", children: [jsx("p", { className: "text-xs text-gray-700 dark:text-slate-100 sm:text-sm", children: translations.subscriptionPeriodLabel }), jsx("h4", { className: "text-xl font-semibold sm:text-2xl", children: subscription ? subscription.planName : translations.subscriptionInactive })] }), jsx("div", { className: "pt-2 sm:pt-0", children: jsx(GradientButton, { title: subscription ? translations.subscriptionManage : translations.subscribePay, align: "center", icon: subscription ? jsx(globalLucideIcons.Settings2, {}) : jsx(globalLucideIcons.Bell, {}), openInNewTab: false, className: "w-full", onClick: subscription ? handleManageAction : handleSubscribeAction }) })] }), jsx("div", { className: "absolute right-3 top-3 sm:right-6 sm:top-6", children: jsx(HoverInfo, { label: translations.totalLabel, description: translations.summaryDescription }) })] }), jsxs("section", { className: "relative flex flex-col gap-3 rounded-2xl border p-4 shadow-inner sm:gap-2 sm:p-5", children: [jsxs("div", { className: "flex flex-wrap items-center justify-between gap-2", children: [jsx("h3", { className: "text-base font-semibold text-gray-500 dark:text-slate-100 sm:text-lg", children: translations.bucketsTitle }), hasBuckets ? (jsx("button", { type: "button", "aria-expanded": bucketExpanded, "aria-label": bucketExpanded ? translations.hiddenDetail : translations.expandDetail, onClick: toggleBucketExpanded, className: "flex h-7 w-7 items-center justify-center rounded-full border border-transparent bg-white text-purple-600 shadow-[0_6px_20px_rgba(99,102,241,0.25)] transition-colors hover:text-purple-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-purple-500 dark:bg-[#1b1541] dark:text-purple-100 dark:hover:text-purple-50 dark:shadow-[0_6px_22px_rgba(112,86,255,0.35)]", children: bucketExpanded ? (jsx(globalLucideIcons.ChevronUp, { className: "h-4 w-4" })) : (jsx(globalLucideIcons.ChevronDown, { className: "h-4 w-4" })) })) : null] }), hasBuckets ? (bucketExpanded ? (jsx("ul", { className: "flex flex-col gap-2", children: buckets.map((bucket) => {
                            const balanceDisplay = formatNumber(locale, bucket.balance);
                            return (jsxs("li", { "data-credit-kind": bucket.kind, className: "rounded-2xl border border-slate-200/70 bg-white/85 px-3 py-3 text-sm shadow-sm transition-transform hover:-translate-y-0.5 hover:shadow-md dark:border-slate-800/60 dark:bg-slate-900/60 sm:px-4", children: [jsxs("div", { className: "grid grid-cols-[1fr_auto] items-center gap-3 text-xs sm:text-sm", children: [jsx("span", { className: "flex min-w-0 items-center gap-2", children: jsx("span", { className: "max-w-full truncate rounded-full bg-purple-50 px-2 py-1 text-xs font-semibold text-purple-600 shadow-sm dark:bg-purple-500/20 dark:text-purple-100 sm:text-sm", children: bucket.computedLabel }) }), jsx("span", { className: "flex min-w-0 justify-end", children: jsx("span", { className: "text-right text-base font-semibold leading-tight text-gray-500 dark:text-slate-100 sm:text-lg", title: balanceDisplay, children: balanceDisplay }) })] }), jsx("div", { className: "mt-3 flex justify-end gap-2", children: jsxs("span", { className: "text-[11px] font-semibold text-gray-500 dark:text-slate-100 sm:text-xs", children: [translations.expiredAtLabel, ": ", bucket.expiresAt] }) })] }, bucket.kind));
                        }) })) : (jsx("button", { type: "button", onClick: expandBuckets, className: "w-full rounded-2xl border border-slate-200/70 bg-white/85 p-6 sm:px-4 text-sm shadow-sm transition-transform hover:-translate-y-0.5 hover:shadow-md dark:border-slate-800/60 dark:bg-slate-900/60 hover:text-purple-500", children: translations.expandDetail }))) : (jsx("div", { className: "w-full rounded-2xl border border-slate-200/70 bg-white/85 p-6 sm:px-4 text-sm shadow-sm transition-transform dark:border-slate-800/60 dark:bg-slate-900/60 text-center", children: translations.bucketsEmpty })), jsx(GradientButton, { title: translations.onetimeBuy, icon: jsx(globalLucideIcons.ShoppingCart, {}), align: "center", className: "w-full text-sm sm:text-base", onClick: handleOnetimeAction })] })] }));
}
function deriveStatus(expiresAt, thresholdDays = 7) {
    if (!expiresAt) {
        return 'active';
    }
    const expires = new Date(expiresAt);
    if (Number.isNaN(expires.getTime())) {
        return 'active';
    }
    const diff = differenceInDays(expires, new Date());
    if (diff < 0) {
        return 'expired';
    }
    if (diff <= thresholdDays) {
        return 'expiringSoon';
    }
    return 'active';
}
function differenceInDays(later, earlier) {
    const msInDay = 86400000;
    return Math.floor((later.getTime() - earlier.getTime()) / msInDay);
}
function HoverInfo({ description, variant = 'default' }) {
    if (!description) {
        return null;
    }
    return (jsxs("span", { className: "group relative inline-flex shrink-0", children: [jsx("button", { type: "button", "aria-label": description, className: cn('flex h-7 w-7 items-center justify-center rounded-full border text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-purple-500', variant === 'muted'
                    ? 'border-transparent bg-slate-100 text-slate-500 hover:text-slate-700 dark:bg-slate-800/70 dark:text-slate-100 dark:hover:text-slate-100'
                    : 'border-transparent bg-white text-purple-600 shadow-[0_6px_20px_rgba(99,102,241,0.25)] hover:text-purple-700 dark:bg-[#1b1541] dark:text-purple-100 dark:hover:text-purple-50 dark:shadow-[0_6px_22px_rgba(112,86,255,0.35)]'), children: jsx(globalLucideIcons.CircleQuestionMark, { className: "h-3.5 w-3.5" }) }), jsx("span", { role: "tooltip", className: "pointer-events-none absolute top-full right-full z-50 mt-3 w-max max-w-[260px] translate-x-4 rounded-xl border border-slate-200/70 bg-slate-900/95 px-3 py-2 text-xs leading-relaxed text-white opacity-0 shadow-xl ring-1 ring-black/30 transition-all duration-150 ease-out group-hover:-translate-y-1 group-hover:opacity-100 group-focus-within:-translate-y-1 group-focus-within:opacity-100 dark:border-slate-700/60 dark:bg-slate-800/95", children: jsx("span", { className: "mt-1 block text-white dark:text-slate-100", children: description }) })] }));
}

export { CreditOverviewClient };
