"use client";
import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { Popover, PopoverContent, PopoverTrigger, } from "../../components/ui/popover";
import { useParheliaSettings } from "../hooks/useParheliaSettings";
export function AgentCostDisplay({ className = "", response, totalTokens, costLimit, }) {
    const [showCostPopover, setShowCostPopover] = useState(false);
    const costPopoverRef = useRef(null);
    const parheliaSettings = useParheliaSettings();
    const currency = parheliaSettings?.currency || "USD";
    const limit = costLimit != null ? Number(costLimit) : null;
    // Handle click outside for cost popover
    useEffect(() => {
        function handleClickOutside(event) {
            if (costPopoverRef.current &&
                !costPopoverRef.current.contains(event.target)) {
                setShowCostPopover(false);
            }
        }
        if (showCostPopover) {
            document.addEventListener("click", handleClickOutside);
            return () => {
                document.removeEventListener("click", handleClickOutside);
            };
        }
    }, [showCostPopover]);
    // Calculate estimated cost based on typical pricing (rough estimates)
    // Claude 3.5 Sonnet pricing: ~$3/MTok input, ~$15/MTok output
    const calculateEstimatedCost = (inputTokens, outputTokens, cachedTokens, cacheWriteTokens = 0) => {
        // Cached tokens are a subset of input tokens, not additional tokens
        const freshInputTokens = inputTokens - cachedTokens;
        const inputCost = (freshInputTokens / 1000000) * 3; // $3 per million tokens
        const outputCost = (outputTokens / 1000000) * 15; // $15 per million tokens
        const cachedCost = (cachedTokens / 1000000) * 0.3; // Cached tokens are typically much cheaper
        const cacheWriteCost = (cacheWriteTokens / 1000000) * 3.75; // Cache write tokens cost more
        return {
            inputCost,
            outputCost,
            cachedCost,
            cacheWriteCost,
            totalCost: inputCost + outputCost + cachedCost + cacheWriteCost,
        };
    };
    // Use actual cost data if available, otherwise calculate estimates
    const currentCost = response
        ? response.totalCost !== undefined
            ? {
                inputCost: response.inputCost ?? 0,
                outputCost: response.outputCost ?? 0,
                cachedCost: response.cachedCost ?? 0,
                cacheWriteCost: response.cacheWriteCost ?? 0,
                totalCost: response.totalCost,
            }
            : calculateEstimatedCost(response.numInputTokens, response.numOutputTokens, response.numCachedTokens, response.numCacheWriteTokens ?? 0)
        : null;
    const displayTotalCost = totalTokens?.totalCost ?? currentCost?.totalCost ?? 0;
    const hasTokenData = response &&
        (response.numInputTokens > 0 ||
            response.numOutputTokens > 0 ||
            response.numCachedTokens > 0);
    const hasTotalData = totalTokens &&
        (totalTokens.input > 0 || totalTokens.output > 0 || totalTokens.cached > 0);
    const hasCostData = (response && response.totalCost && response.totalCost > 0) ||
        (totalTokens && totalTokens.totalCost && totalTokens.totalCost > 0);
    if (!hasTokenData && !hasTotalData && !hasCostData && !(limit && limit > 0)) {
        return null;
    }
    // Calculate percentage of limit used
    const percentUsed = limit && limit > 0 ? Math.min((displayTotalCost / limit) * 100, 100) : null;
    // Determine color based on usage
    const getColorClass = () => {
        if (!percentUsed)
            return "text-gray-400";
        if (percentUsed >= 100)
            return "text-red-500";
        if (percentUsed >= 80)
            return "text-orange-500";
        if (percentUsed >= 60)
            return "text-yellow-600";
        return "text-gray-400";
    };
    return (_jsx("div", { className: `relative ${className}`, ref: costPopoverRef, "data-testid": "agent-cost-display", children: _jsxs(Popover, { open: showCostPopover, onOpenChange: setShowCostPopover, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs("div", { className: `cursor-pointer text-right text-[10px] hover:text-gray-600 ${getColorClass()}`, "data-testid": "agent-cost-display-trigger", children: ["Total Cost: ", displayTotalCost.toFixed(2), " ", currency, limit && limit > 0 && ` / ${limit.toFixed(2)} ${currency}`] }) }), _jsx(PopoverContent, { className: "w-80 p-4", align: "end", side: "bottom", "data-testid": "agent-cost-display-popover", children: _jsxs("div", { className: "space-y-4", children: [_jsx("div", { className: "border-b pb-2", children: _jsxs("h4", { className: "flex items-center justify-between text-sm font-semibold", children: [_jsx("div", { children: "Cost Breakdown" }), _jsxs("span", { className: "text-sm font-semibold", children: [displayTotalCost.toFixed(2), " ", currency, limit && limit > 0 && (_jsxs("span", { className: "ml-1 text-xs text-gray-500", children: ["/ ", limit.toFixed(2), " ", currency] }))] })] }) }), limit && limit > 0 && (_jsxs("div", { className: "rounded-md bg-gray-50 p-3", children: [_jsxs("div", { className: "mb-2 flex items-center justify-between text-xs", children: [_jsx("span", { className: "font-medium text-gray-700", children: "Cost Limit Usage" }), _jsxs("span", { className: `font-semibold ${getColorClass()}`, children: [percentUsed?.toFixed(1), "%"] })] }), _jsx("div", { className: "h-2 w-full overflow-hidden rounded-full bg-gray-200", children: _jsx("div", { className: `h-full transition-all ${percentUsed && percentUsed >= 100
                                                ? "bg-red-500"
                                                : percentUsed && percentUsed >= 80
                                                    ? "bg-orange-500"
                                                    : percentUsed && percentUsed >= 60
                                                        ? "bg-yellow-500"
                                                        : "bg-theme-secondary"}`, style: { width: `${Math.min(percentUsed || 0, 100)}%` } }) }), percentUsed != null && percentUsed >= 90 && (_jsx("p", { className: "mt-2 text-xs text-gray-600", children: percentUsed >= 100
                                            ? "Cost limit reached. Execution will stop on next API call."
                                            : "Approaching cost limit. Consider extending if needed." }))] })), _jsx("div", { className: "space-y-3", children: (hasTotalData || hasTokenData) && (_jsx(_Fragment, { children: _jsx("div", { className: "space-y-2", children: hasTotalData ? (_jsxs(_Fragment, { children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsx("span", { className: "text-xs text-gray-500", children: "Input tokens:" }), _jsxs("span", { className: "text-xs", children: [totalTokens.input.toLocaleString(), " (", totalTokens.inputCost.toFixed(2), " ", currency, ")"] })] }), _jsxs("div", { className: "flex items-center justify-between", children: [_jsx("span", { className: "text-xs text-gray-500", children: "Output tokens:" }), _jsxs("span", { className: "text-xs", children: [totalTokens.output.toLocaleString(), " (", totalTokens.outputCost.toFixed(2), " ", currency, ")"] })] }), totalTokens.cached > 0 && (_jsxs("div", { className: "flex items-center justify-between", "data-testid": "cached-tokens-row", children: [_jsx("span", { className: "text-xs text-gray-500", children: "Cached tokens:" }), _jsxs("span", { className: "text-xs", "data-testid": "cached-tokens-value", children: [totalTokens.cached.toLocaleString(), " (", totalTokens.cachedCost.toFixed(2), " ", currency, ")"] })] })), totalTokens.cacheWrite > 0 && (_jsxs("div", { className: "flex items-center justify-between", children: [_jsx("span", { className: "text-xs text-gray-500", children: "Cache write tokens:" }), _jsxs("span", { className: "text-xs", children: [totalTokens.cacheWrite.toLocaleString(), " (", (totalTokens.cacheWriteCost ?? 0).toFixed(2), " ", currency, ")"] })] })), totalTokens.imageCost > 0 && (_jsxs("div", { className: "flex items-center justify-between", children: [_jsx("span", { className: "text-xs text-gray-500", children: "Image generation:" }), _jsxs("span", { className: "text-xs", children: [totalTokens.imageCost.toFixed(2), " ", currency] })] }))] })) : (_jsx(_Fragment, { children: response && currentCost && (_jsxs(_Fragment, { children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsx("span", { className: "text-xs text-gray-500", children: "Input tokens:" }), _jsxs("span", { className: "text-xs", children: [response.numInputTokens.toLocaleString(), "(", currentCost.inputCost.toFixed(2), " ", currency, ")"] })] }), _jsxs("div", { className: "flex items-center justify-between", children: [_jsx("span", { className: "text-xs text-gray-500", children: "Output tokens:" }), _jsxs("span", { className: "text-xs", children: [response.numOutputTokens.toLocaleString(), "(", currentCost.outputCost.toFixed(2), " ", currency, ")"] })] }), response.numCachedTokens > 0 && (_jsxs("div", { className: "flex items-center justify-between", "data-testid": "cached-tokens-row", children: [_jsx("span", { className: "text-xs text-gray-500", children: "Cached tokens:" }), _jsxs("span", { className: "text-xs", "data-testid": "cached-tokens-value", children: [response.numCachedTokens.toLocaleString(), "(", currentCost.cachedCost.toFixed(2), " ", currency, ")"] })] })), response.numCacheWriteTokens &&
                                                        response.numCacheWriteTokens > 0 && (_jsxs("div", { className: "flex items-center justify-between", children: [_jsx("span", { className: "text-xs text-gray-500", children: "Cache write tokens:" }), _jsxs("span", { className: "text-xs", children: [response.numCacheWriteTokens.toLocaleString(), "(", currentCost.cacheWriteCost.toFixed(2), " ", currency, ")"] })] })), _jsx("div", { className: "mt-2 text-xs text-gray-400", children: "* Estimated costs based on typical Claude 3.5 pricing" })] })) })) }) })) })] }) })] }) }));
}
//# sourceMappingURL=AgentCostDisplay.js.map