"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from "react";
import { cn } from "@stigmer/theme";
import { getUserMessage } from "@stigmer/sdk";
import { formatCost, formatTokenCount } from "../execution/UsageWidget";
import { useOrgUsageReport } from "./useOrgUsageReport";
import { DATE_RANGE_PRESETS, dateRangeFromPreset, formatDateRange, presetLabel, } from "./date-range";
import { CreditRunwayIndicator } from "./CreditRunwayIndicator";
import { AgentBreakdownList } from "./AgentBreakdownList";
import { HarnessSplitCard } from "./HarnessSplitCard";
import { ExportButton } from "./ExportButton";
import { useExportCSV } from "./useExportCSV";
/**
 * Self-contained dashboard panel showing organization-wide LLM usage metrics.
 *
 * Displays summary cards (total cost, LLM calls, tokens), a daily cost
 * bar chart, and per-model breakdown with call counts and token splits.
 * Data is fetched via `getOrgUsageReport` with a configurable date range.
 *
 * All visual properties flow through `--stgm-*` design tokens. Zero
 * Console dependencies — safe for platform builder embedding.
 *
 * @example
 * ```tsx
 * <OrgUsagePanel orgId={activeOrg.metadata.id} />
 * ```
 */
export function OrgUsagePanel({ orgId, className }) {
    const [preset, setPreset] = useState("30d");
    const dateRange = dateRangeFromPreset(preset);
    const { report, isLoading, error } = useOrgUsageReport(orgId, dateRange);
    const { exportCSV, isExporting } = useExportCSV(report, orgId);
    const daysInRange = Number.parseInt(preset, 10);
    if (isLoading) {
        return (_jsxs("div", { className: cn("space-y-4", className), "aria-busy": "true", "aria-label": "Loading usage data", children: [_jsx("div", { className: "flex gap-2", children: DATE_RANGE_PRESETS.map((p) => (_jsx("div", { className: "h-7 w-16 animate-pulse rounded-md bg-muted-subtle" }, p))) }), _jsx("div", { className: "grid grid-cols-3 gap-3", children: Array.from({ length: 3 }, (_, i) => (_jsx("div", { className: "h-[72px] animate-pulse rounded-lg bg-muted-subtle" }, i))) }), _jsx("div", { className: "h-40 animate-pulse rounded-lg bg-muted-subtle" })] }));
    }
    if (error) {
        return (_jsx("p", { className: cn("text-destructive text-xs", className), role: "alert", children: getUserMessage(error) }));
    }
    if (!report)
        return null;
    return (_jsxs("div", { className: cn("space-y-6", className), children: [_jsxs("div", { className: "flex items-center justify-between gap-3", children: [_jsx(DateRangeSelector, { activePreset: preset, onPresetChange: setPreset, dateRange: dateRange }), _jsx(ExportButton, { onExport: exportCSV, isExporting: isExporting, disabled: !report || report.modelBreakdown.length === 0 })] }), _jsx(SummaryCards, { report: report, daysInRange: daysInRange }), report.dailyCosts.length > 0 && (_jsx(DailyCostChart, { entries: report.dailyCosts })), report.harnessBreakdown.length > 0 && (_jsx(HarnessSplitCard, { breakdown: report.harnessBreakdown })), report.topAgentsByCost.length > 0 && (_jsx(AgentBreakdownList, { agents: report.topAgentsByCost, totalBillableCostMicros: report.totalBillableCostMicros })), report.modelBreakdown.length > 0 && (_jsx(ModelBreakdownList, { models: report.modelBreakdown })), report.modelBreakdown.length === 0 && _jsx(EmptyState, {})] }));
}
// ---------------------------------------------------------------------------
// DateRangeSelector (internal)
// ---------------------------------------------------------------------------
function DateRangeSelector({ activePreset, onPresetChange, dateRange, }) {
    return (_jsxs("div", { className: "flex items-center gap-3", role: "group", "aria-label": "Date range", children: [_jsx("div", { className: "flex gap-1.5", children: DATE_RANGE_PRESETS.map((p) => (_jsx("button", { type: "button", onClick: () => onPresetChange(p), "aria-pressed": p === activePreset, className: cn("rounded-md px-2.5 py-1 text-xs font-medium transition-colors", p === activePreset
                        ? "bg-primary text-primary-foreground"
                        : "bg-muted text-muted-foreground hover:text-foreground hover:bg-accent"), children: presetLabel(p) }, p))) }), _jsx("span", { className: "text-xs tabular-nums text-muted-foreground", children: formatDateRange(dateRange) })] }));
}
// ---------------------------------------------------------------------------
// SummaryCards (internal)
// ---------------------------------------------------------------------------
function microsToUsd(micros) {
    return Number(micros) / 1_000_000;
}
function SummaryCards({ report, daysInRange, }) {
    const { totalLlmCalls, totalTokens } = report.modelBreakdown.reduce((acc, m) => ({
        totalLlmCalls: acc.totalLlmCalls + m.callCount,
        totalTokens: acc.totalTokens +
            Number(m.inputTokens) +
            Number(m.outputTokens) +
            Number(m.cacheCreationInputTokens) +
            Number(m.cacheReadInputTokens),
    }), { totalLlmCalls: 0, totalTokens: 0 });
    return (_jsxs("div", { role: "group", "aria-label": "Usage summary", className: "space-y-2", children: [_jsxs("div", { className: "grid grid-cols-3 gap-3", children: [_jsxs("div", { className: "rounded-lg border border-border bg-card px-3.5 py-3", children: [_jsx("div", { className: "text-lg font-semibold tabular-nums text-foreground", children: formatCost(microsToUsd(report.totalBillableCostMicros)) }), _jsx("div", { className: "text-xs text-muted-foreground", children: "Total Cost" }), _jsx(CreditRunwayIndicator, { totalBillableCostMicros: report.totalBillableCostMicros, daysInRange: daysInRange, className: "mt-0.5 block" })] }), _jsxs("div", { className: "rounded-lg border border-border bg-card px-3.5 py-3", children: [_jsx("div", { className: "text-lg font-semibold tabular-nums text-foreground", children: formatCompactNumber(totalLlmCalls) }), _jsx("div", { className: "text-xs text-muted-foreground", children: "LLM Calls" })] }), _jsxs("div", { className: "rounded-lg border border-border bg-card px-3.5 py-3", children: [_jsx("div", { className: "text-lg font-semibold tabular-nums text-foreground", children: formatCompactNumber(totalTokens) }), _jsx("div", { className: "text-xs text-muted-foreground", children: "Tokens" })] })] }), _jsxs("div", { className: "grid grid-cols-3 gap-3", children: [_jsxs("div", { className: "rounded-lg border border-border-muted bg-card/50 px-3.5 py-2.5", children: [_jsx("div", { className: "text-sm font-semibold tabular-nums text-foreground", children: formatCompactNumber(report.totalExecutions) }), _jsx("div", { className: "text-[0.65rem] text-muted-foreground", children: "Executions" })] }), _jsxs("div", { className: "rounded-lg border border-border-muted bg-card/50 px-3.5 py-2.5", children: [_jsx("div", { className: "text-sm font-semibold tabular-nums text-foreground", children: formatCompactNumber(report.totalAgents) }), _jsx("div", { className: "text-[0.65rem] text-muted-foreground", children: "Agents" })] }), _jsxs("div", { className: "rounded-lg border border-border-muted bg-card/50 px-3.5 py-2.5", children: [_jsx("div", { className: "text-sm font-semibold tabular-nums text-foreground", children: formatCompactNumber(report.totalSessions) }), _jsx("div", { className: "text-[0.65rem] text-muted-foreground", children: "Sessions" })] })] })] }));
}
// ---------------------------------------------------------------------------
// DailyCostChart (internal) — CSS-only bar chart
// ---------------------------------------------------------------------------
const CHART_HEIGHT_PX = 128;
function DailyCostChart({ entries }) {
    const maxCost = Math.max(...entries.map((e) => microsToUsd(e.billableCostMicros)), 0);
    const [hoveredIdx, setHoveredIdx] = useState(null);
    return (_jsxs("div", { children: [_jsx("h3", { className: "mb-2 text-xs font-semibold text-foreground", children: "Daily Cost" }), _jsxs("div", { className: "rounded-lg border border-border bg-card px-3 pb-2 pt-3", children: [_jsx("div", { className: "mb-1 h-4", children: hoveredIdx !== null && entries[hoveredIdx] && (_jsxs("span", { className: "text-xs tabular-nums text-muted-foreground", children: [formatChartDate(entries[hoveredIdx].date), " \u00B7 ", formatCost(microsToUsd(entries[hoveredIdx].billableCostMicros)), " \u00B7 ", formatTokenCount(Number(entries[hoveredIdx].totalTokens)), " tokens"] })) }), _jsx("div", { className: "flex items-end gap-px", style: { height: CHART_HEIGHT_PX }, role: "img", "aria-label": "Daily cost bar chart", children: entries.map((entry, i) => {
                            const ratio = maxCost > 0 ? microsToUsd(entry.billableCostMicros) / maxCost : 0;
                            const heightPx = Math.max(ratio * CHART_HEIGHT_PX, 2);
                            return (_jsx("div", { className: "group relative flex-1", style: { height: CHART_HEIGHT_PX }, onMouseEnter: () => setHoveredIdx(i), onMouseLeave: () => setHoveredIdx(null), children: _jsx("div", { className: cn("absolute inset-x-0 bottom-0 rounded-t-sm transition-colors", hoveredIdx === i
                                        ? "bg-chart-1"
                                        : "bg-chart-1/70"), style: { height: heightPx } }) }, entry.date));
                        }) }), entries.length > 0 && (_jsxs("div", { className: "mt-1.5 flex justify-between", children: [_jsx("span", { className: "text-[0.6rem] tabular-nums text-muted-foreground", children: formatChartDate(entries[0].date) }), entries.length > 2 && (_jsx("span", { className: "text-[0.6rem] tabular-nums text-muted-foreground", children: formatChartDate(entries[Math.floor(entries.length / 2)].date) })), entries.length > 1 && (_jsx("span", { className: "text-[0.6rem] tabular-nums text-muted-foreground", children: formatChartDate(entries[entries.length - 1].date) }))] }))] })] }));
}
// ---------------------------------------------------------------------------
// ModelBreakdownList (internal)
// ---------------------------------------------------------------------------
function ModelBreakdownList({ models, }) {
    return (_jsxs("div", { children: [_jsx("h3", { className: "mb-2 text-xs font-semibold text-foreground", children: "Model Breakdown" }), _jsxs("div", { className: "rounded-lg border border-border bg-card", role: "table", "aria-label": "Model usage breakdown", children: [_jsxs("div", { role: "row", className: "grid grid-cols-[1fr_auto_auto_auto_auto] gap-x-4 border-b border-border px-3.5 py-2 text-[0.65rem] font-medium uppercase tracking-wider text-muted-foreground", children: [_jsx("span", { role: "columnheader", children: "Model" }), _jsx("span", { role: "columnheader", className: "text-right", children: "Calls" }), _jsx("span", { role: "columnheader", className: "text-right", children: "Input" }), _jsx("span", { role: "columnheader", className: "text-right", children: "Output" }), _jsx("span", { role: "columnheader", className: "text-right", children: "Cost" })] }), models.map((m) => {
                        const inputTok = Number(m.inputTokens);
                        const cacheCreation = Number(m.cacheCreationInputTokens);
                        const cacheRead = Number(m.cacheReadInputTokens);
                        const totalInput = inputTok + cacheCreation + cacheRead;
                        const hasCache = cacheRead > 0 || cacheCreation > 0;
                        return (_jsxs("div", { className: "border-b border-border-muted px-3.5 py-2 last:border-b-0", children: [_jsxs("div", { role: "row", className: "grid grid-cols-[1fr_auto_auto_auto_auto] gap-x-4", children: [_jsxs("div", { role: "cell", className: "min-w-0", children: [_jsx("span", { className: "block truncate text-xs font-medium text-foreground", children: m.model }), _jsx("span", { className: "text-[0.65rem] text-muted-foreground", children: m.provider })] }), _jsx("span", { role: "cell", className: "self-center text-right text-xs tabular-nums text-muted-foreground", children: formatCompactNumber(m.callCount) }), _jsx("span", { role: "cell", className: "self-center text-right text-xs tabular-nums text-muted-foreground", children: formatCompactNumber(totalInput) }), _jsx("span", { role: "cell", className: "self-center text-right text-xs tabular-nums text-muted-foreground", children: formatCompactNumber(Number(m.outputTokens)) }), _jsx("span", { role: "cell", className: "self-center text-right text-xs tabular-nums text-foreground", children: formatCost(microsToUsd(m.billableCostMicros)) })] }), hasCache && (_jsxs("div", { className: "mt-0.5 text-[0.6rem] tabular-nums text-muted-foreground", children: ["cache", " ", cacheRead > 0 &&
                                            `${formatCompactNumber(cacheRead)} read`, cacheRead > 0 && cacheCreation > 0 &&
                                            " · ", cacheCreation > 0 &&
                                            `${formatCompactNumber(cacheCreation)} write`] }))] }, `${m.model}\0${m.provider}`));
                    })] })] }));
}
// ---------------------------------------------------------------------------
// EmptyState (internal)
// ---------------------------------------------------------------------------
function EmptyState() {
    return (_jsxs("div", { className: "flex flex-col items-center justify-center py-12 text-center", children: [_jsx(ChartIcon, { className: "text-muted-foreground mb-3 size-8" }), _jsx("p", { className: "text-sm font-medium text-foreground", children: "No usage data yet" }), _jsx("p", { className: "mt-1 max-w-xs text-xs text-muted-foreground", children: "Usage data will appear here once agents start running executions in this organization." })] }));
}
function ChartIcon({ className }) {
    return (_jsxs("svg", { width: "24", height: "24", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", className: className, "aria-hidden": "true", children: [_jsx("path", { d: "M3 3v18h18" }), _jsx("path", { d: "M7 16l4-8 4 4 4-6" })] }));
}
// ---------------------------------------------------------------------------
// Formatting helpers
// ---------------------------------------------------------------------------
/**
 * Format a number with compact suffixes for dashboard cards.
 * Examples: 847 -> "847", 2_340 -> "2.3K", 1_200_000 -> "1.2M"
 */
function formatCompactNumber(n) {
    if (n >= 1_000_000) {
        const v = n / 1_000_000;
        return v >= 100 ? `${Math.round(v)}M` : `${trimTrailingZero(v.toFixed(1))}M`;
    }
    if (n >= 1_000) {
        const v = n / 1_000;
        return v >= 100 ? `${Math.round(v)}K` : `${trimTrailingZero(v.toFixed(1))}K`;
    }
    return String(n);
}
function trimTrailingZero(s) {
    return s.endsWith(".0") ? s.slice(0, -2) : s;
}
/**
 * Format a YYYY-MM-DD date for chart axis labels (e.g. "Apr 02").
 */
function formatChartDate(iso) {
    const [y, m, d] = iso.split("-").map(Number);
    const date = new Date(y, m - 1, d);
    return new Intl.DateTimeFormat("en-US", {
        month: "short",
        day: "2-digit",
    }).format(date);
}
//# sourceMappingURL=OrgUsagePanel.js.map