"use client";
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { globalLucideIcons } from '@windrun-huaiin/base-ui/components/server';
import { themeButtonGradientClass, themeButtonGradientHoverClass, themeIconColor } from '@windrun-huaiin/base-ui/lib';
import { cn } from '@windrun-huaiin/lib/utils';
import { createContext, useContext, useState, useRef, useEffect, useMemo } from 'react';
import { useFingerprint } from './use-fingerprint.mjs';
import { CopyableText } from '@windrun-huaiin/base-ui/ui';

const FingerprintContext = createContext(undefined);
/**
 * Fingerprint Provider Component
 * 为应用提供fingerprint和匿名用户管理功能
 */
function FingerprintProvider({ children, config }) {
    const fingerprintData = useFingerprint(config);
    return (jsx(FingerprintContext.Provider, { value: fingerprintData, children: children }));
}
/**
 * Hook to use fingerprint context
 */
function useFingerprintContext() {
    const context = useContext(FingerprintContext);
    if (context === undefined) {
        throw new Error('useFingerprintContext must be used within a FingerprintProvider');
    }
    return context;
}
/**
 * Safe hook to use fingerprint context - returns null if no provider
 * 安全版本的fingerprint context hook - 如果没有Provider则返回null
 */
function useFingerprintContextSafe() {
    const context = useContext(FingerprintContext);
    return context || null;
}
/**
 * HOC for components that need fingerprint functionality
 * Note: This HOC now requires config to be passed externally
 */
function withFingerprint(Component, config) {
    return function FingerprintWrappedComponent(props) {
        return (jsx(FingerprintProvider, { config: config, children: jsx(Component, Object.assign({}, props)) }));
    };
}
/**
 * 组件：显示用户状态和积分信息（用于调试）
 */
function FingerprintStatus() {
    const { fingerprintId, xUser, xCredit, xSubscription, error } = useFingerprintContext();
    const [isOpen, setIsOpen] = useState(false);
    const modalRef = useRef(null);
    const handleToggle = () => setIsOpen(prev => !prev);
    const handleBackdropClick = (e) => {
        if (e.target === e.currentTarget)
            setIsOpen(false);
    };
    useEffect(() => {
        const handleEscKey = (e) => {
            if (e.key === 'Escape' && isOpen)
                setIsOpen(false);
        };
        if (isOpen)
            document.addEventListener('keydown', handleEscKey);
        return () => document.removeEventListener('keydown', handleEscKey);
    }, [isOpen]);
    useEffect(() => {
        if (xUser && !xUser.fingerprintId) {
            console.warn('xUser.fingerprintId is missing:', xUser);
        }
    }, [xUser]);
    const creditBuckets = useMemo(() => {
        if (!xCredit)
            return [];
        return [
            {
                key: 'paid',
                label: '订阅积分',
                icon: jsx(globalLucideIcons.Settings2, { className: "size-4 text-green-500 dark:text-green-300" }),
                balance: xCredit.balancePaid,
                total: xCredit.totalPaidLimit,
                start: xCredit.paidStart,
                end: xCredit.paidEnd,
            },
            {
                key: 'oneTimePaid',
                label: '一次性积分',
                icon: jsx(globalLucideIcons.Coins, { className: "size-4 text-amber-500 dark:text-amber-300" }),
                balance: xCredit.balanceOneTimePaid,
                total: xCredit.totalOneTimePaidLimit,
                start: xCredit.oneTimePaidStart,
                end: xCredit.oneTimePaidEnd,
            },
            {
                key: 'free',
                label: '免费积分',
                icon: jsx(globalLucideIcons.Gift, { className: "size-4 text-purple-500 dark:text-purple-300" }),
                balance: xCredit.balanceFree,
                total: xCredit.totalFreeLimit,
                start: xCredit.freeStart,
                end: xCredit.freeEnd,
            },
        ];
    }, [xCredit]);
    const subscriptionStatus = useMemo(() => {
        var _a, _b;
        if (!xSubscription) {
            return {
                status: '未订阅',
                priceName: '--',
                creditsAllocated: '--',
                period: '无记录',
            };
        }
        return {
            status: (_a = xSubscription.status) !== null && _a !== void 0 ? _a : '--',
            priceName: (_b = xSubscription.priceName) !== null && _b !== void 0 ? _b : '--',
            creditsAllocated: typeof xSubscription.creditsAllocated === 'number'
                ? formatNumber(xSubscription.creditsAllocated)
                : '--',
            period: formatRangeText(xSubscription.subPeriodStart, xSubscription.subPeriodEnd),
        };
    }, [xSubscription]);
    const userStatus = (xUser === null || xUser === void 0 ? void 0 : xUser.status) || '--';
    const totalCredits = formatNumber(xCredit === null || xCredit === void 0 ? void 0 : xCredit.totalBalance);
    const subStatus = subscriptionStatus.status;
    return (jsxs(Fragment, { children: [!isOpen && (jsx("button", { onClick: handleToggle, type: "button", "aria-label": "Fingerprint debug panel", className: cn('fixed left-2 top-2 md:left-2 md:top-3 z-10000 inline-flex size-8 md:size-11 items-center justify-center rounded-full', themeButtonGradientClass, themeButtonGradientHoverClass, 'text-white rounded-full shadow-lg hover:shadow-xl transition-all duration-300'), children: jsx(globalLucideIcons.Lightbulb, { className: "size-6 text-white" }) })), isOpen && (jsxs(Fragment, { children: [jsx("div", { onClick: handleBackdropClick, className: "fixed inset-0 z-9998 bg-black/60 backdrop-blur-sm" }), jsxs("div", { ref: modalRef, className: cn('fixed inset-3 z-9999 mx-auto w-[min(95vw,520px)] overflow-y-auto rounded-2xl border', 'border-slate-200/70 bg-white/95 p-4 shadow-2xl backdrop-blur-sm', 'font-sans text-sm text-slate-700 dark:border-white/12 dark:bg-slate-950/95 dark:text-slate-200', 'sm:inset-auto md:left-2 sm:top-1 md:right-auto sm:w-[min(520px,95vw)] sm:p-5'), children: [jsx("header", { className: "mb-4", children: jsxs("div", { className: "flex items-start justify-between gap-3", children: [jsxs("div", { className: cn("flex items-center gap-2 text-base font-bold tracking-wider", themeIconColor), children: [jsx(globalLucideIcons.ShieldUser, { className: "size-4" }), "Fingerprint Debug Panel"] }), jsx("button", { type: "button", "aria-label": "Close fingerprint panel", className: "rounded-full p-2 text-slate-500 transition hover:bg-slate-100 hover:text-slate-700 dark:text-slate-300 dark:hover:bg-white/10 dark:hover:text-white", onClick: () => setIsOpen(false), children: jsx(globalLucideIcons.X, { className: "size-4" }) })] }) }), jsxs("section", { className: "space-y-1", children: [jsx(PanelSection, { icon: jsx(globalLucideIcons.Fingerprint, { className: "size-4" }), title: "\u7528\u6237\u4FE1\u606F", rightInfo: jsx(StatusTag, { value: userStatus }), items: [
                                            { label: '用户ID', value: jsx(CopyableText, { text: (xUser === null || xUser === void 0 ? void 0 : xUser.userId) || '' }) },
                                            { label: '用户昵称', value: jsx(CopyableText, { text: (xUser === null || xUser === void 0 ? void 0 : xUser.userName) || '' }) },
                                            { label: 'FingerprintID', value: jsx(CopyableText, { text: (xUser === null || xUser === void 0 ? void 0 : xUser.fingerprintId) || fingerprintId || '' }) },
                                            { label: 'Clerk用户', value: jsx(CopyableText, { text: (xUser === null || xUser === void 0 ? void 0 : xUser.clerkUserId) || '' }) },
                                            { label: '邮箱', value: jsx(CopyableText, { text: (xUser === null || xUser === void 0 ? void 0 : xUser.email) || '' }) },
                                            { label: 'Stripe客户', value: jsx(CopyableText, { text: (xUser === null || xUser === void 0 ? void 0 : xUser.stripeCusId) || '' }) },
                                            { label: '创建时间', value: (xUser === null || xUser === void 0 ? void 0 : xUser.createdAt) || '--' },
                                        ] }), jsxs("div", { className: "space-y-2 rounded-xl border border-slate-200/70 bg-white/80 p-4 shadow-sm dark:border-white/12 dark:bg-slate-900/50", children: [jsx(PanelHeader, { icon: jsx(globalLucideIcons.Gem, { className: "size-4" }), title: "\u79EF\u5206\u4FE1\u606F", rightInfo: jsx("span", { className: cn("font-semibold", themeIconColor), children: totalCredits }) }), jsx("div", { className: "space-y-3", children: creditBuckets.length > 0 ? (creditBuckets.map((bucket) => {
                                                    const percent = Math.round(computeProgress(bucket.balance, bucket.total) * 100);
                                                    return (jsxs("div", { className: "rounded-lg border border-slate-200/70 bg-white/70 p-3 dark:border-white/10 dark:bg-slate-900/40", children: [jsxs("div", { className: "flex items-center justify-between text-xs font-medium text-slate-600 dark:text-slate-300", children: [jsxs("div", { className: "flex items-center gap-1.5", children: [bucket.icon, jsx("span", { children: bucket.label })] }), jsxs("span", { className: "font-semibold text-slate-700 dark:text-slate-100", children: [formatNumber(bucket.balance), " / ", formatNumber(bucket.total)] })] }), jsx("div", { className: "mt-2 h-1.5 w-full rounded-full bg-slate-200 dark:bg-slate-800", children: jsx("div", { className: "h-full rounded-full bg-linear-to-r from-purple-500 via-pink-500 to-rose-400 transition-[width]", style: { width: `${percent}%` } }) }), jsxs("div", { className: "mt-2 flex items-center justify-between text-[11px] text-slate-500 dark:text-slate-400", children: [jsx("span", { children: formatRangeText(bucket.start, bucket.end) }), jsxs("span", { children: [percent, "%"] })] })] }, bucket.key));
                                                })) : (jsx(EmptyPlaceholder, { label: "\u6682\u65E0\u79EF\u5206\u6570\u636E", icon: jsx(globalLucideIcons.DatabaseZap, { className: "size-4" }) })) })] }), jsx(PanelSection, { icon: jsx(globalLucideIcons.Bell, { className: "size-4" }), title: "\u8BA2\u9605\u4FE1\u606F", rightInfo: jsx(StatusTag, { value: subStatus }), items: [
                                            { label: '订阅方案', value: subscriptionStatus.priceName },
                                            { label: '有效期', value: subscriptionStatus.period },
                                            { label: '分配额度', value: subscriptionStatus.creditsAllocated },
                                            { label: '订阅ID', value: jsx(CopyableText, { text: (xSubscription === null || xSubscription === void 0 ? void 0 : xSubscription.paySubscriptionId) || '' }) },
                                            { label: 'OrderID', value: jsx(CopyableText, { text: (xSubscription === null || xSubscription === void 0 ? void 0 : xSubscription.orderId) || '' }) },
                                            { label: 'Price ID', value: jsx(CopyableText, { text: (xSubscription === null || xSubscription === void 0 ? void 0 : xSubscription.priceId) || '' }) },
                                        ] }), error && (jsxs("div", { className: "flex items-start gap-2 rounded-xl border border-amber-200 bg-amber-50 p-3 text-xs text-amber-600 shadow-sm dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-200", children: [jsx(globalLucideIcons.X, { className: "mt-0.5 size-4" }), jsx("span", { children: error })] }))] })] })] }))] }));
}
/* ==================== 新增辅助组件 ==================== */
// 标题行：左侧图标+标题，右侧信息（右对齐）
function PanelHeader({ icon, title, rightInfo }) {
    return (jsxs("div", { className: "flex items-center justify-between mb-3", children: [jsxs("div", { className: "flex items-center gap-2 text-sm font-semibold text-slate-700 dark:text-slate-100", children: [jsx("span", { className: "flex size-6 items-center justify-center rounded-full bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300", children: icon }), jsx("span", { className: cn("rounded-full bg-purple-100 px-2 py-1 text-xs font-bold", themeIconColor), children: title })] }), jsx("span", { className: "text-sm font-medium text-slate-600 dark:text-slate-300", children: rightInfo })] }));
}
function PanelSection({ icon, title, rightInfo, items }) {
    return (jsxs("div", { className: "rounded-xl border border-slate-200/70 bg-white/85 p-4 shadow-sm dark:border-white/12 dark:bg-slate-900/45", children: [jsx(PanelHeader, { icon: icon, title: title, rightInfo: rightInfo }), jsx("dl", { className: "grid grid-cols-1 gap-y-1.5 text-xs text-slate-500 dark:text-slate-300", children: items.map((item) => (jsxs("div", { className: "flex items-center justify-between gap-3", children: [jsx("dt", { className: "text-slate-400 dark:text-slate-500", children: item.label }), jsx("dd", { className: "text-right font-medium text-slate-600 dark:text-slate-100", children: item.value })] }, item.label))) })] }));
}
function EmptyPlaceholder({ label, icon }) {
    return (jsxs("div", { className: "flex items-center justify-center gap-2 rounded-lg border border-dashed border-slate-200 bg-slate-50 py-6 text-xs text-slate-400 dark:border-white/10 dark:bg-slate-900/30 dark:text-slate-500", children: [icon, jsx("span", { children: label })] }));
}
function formatNumber(value) {
    if (typeof value !== 'number' || Number.isNaN(value))
        return '--';
    return new Intl.NumberFormat('zh-CN', { maximumFractionDigits: 0 }).format(value);
}
function computeProgress(balance, total) {
    if (typeof balance !== 'number' || typeof total !== 'number' || Number.isNaN(balance) || Number.isNaN(total) || total <= 0) {
        return 0;
    }
    const ratio = balance / total;
    if (!Number.isFinite(ratio))
        return 0;
    return Math.min(Math.max(ratio, 0), 1);
}
function formatRangeText(start, end) {
    const safeStart = start && start.trim() ? start : '';
    const safeEnd = end && end.trim() ? end : '';
    if (!safeStart && !safeEnd) {
        return '无记录';
    }
    if (!safeStart) {
        return safeEnd;
    }
    if (!safeEnd) {
        return safeStart;
    }
    return `${safeStart} - ${safeEnd}`;
}
function StatusTag({ value }) {
    if (!value)
        return jsx("span", { className: "text-slate-400", children: "None" });
    const normalized = value.toLowerCase();
    const colorMap = {
        // 绿色：正常/活跃
        registered: 'bg-green-100 text-green-700 dark:bg-green-500/20 dark:text-green-300',
        active: 'bg-green-100 text-green-700 dark:bg-green-500/20 dark:text-green-300',
        trialing: 'bg-green-100 text-green-700 dark:bg-green-500/20 dark:text-green-300',
        // 灰色：失效/删除
        canceled: 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-400',
        frozen: 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-400',
        deleted: 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-400',
        expired: 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-400',
        past_due: 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-400',
        // 橙色：待处理/异常
        pending: 'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-300',
        failed: 'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-300',
        unpaid: 'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-300',
        incomplete: 'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-300',
    };
    const defaultColor = 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-400';
    const badgeClass = colorMap[normalized] || defaultColor;
    return (jsx("span", { className: cn('inline-block rounded-full px-2 py-0.5 text-xs capitalize font-medium', badgeClass), children: value }));
}

export { FingerprintProvider, FingerprintStatus, useFingerprintContext, useFingerprintContextSafe, withFingerprint };
