import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import * as React from "react";
import * as RechartsPrimitive from "recharts";
import { cn } from "../../lib/utils.js";
const ChartContext = React.createContext(null);
function useChart() {
  const ctx = React.useContext(ChartContext);
  if (!ctx) throw new Error("useChart 必須在 <ChartContainer> 內使用");
  return ctx;
}
const ChartContainer = React.forwardRef(
  ({ id, className, children, config, ...props }, ref) => {
    const uniqueId = React.useId();
    const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`;
    const ctxValue = React.useMemo(() => ({ config }), [config]);
    return /* @__PURE__ */ jsx(ChartContext.Provider, { value: ctxValue, children: /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        "data-chart": chartId,
        className: cn(
          // 整體視覺套用本 DS typography + token
          // 預設 aspect-video(16:9)— Recharts ResponsiveContainer 需 parent 有高度。
          // Consumer 若需其他比例,包 <AspectRatio ratio={n}> 覆寫(AspectRatio 的 padding-bottom 高度會蓋過此 class)。
          "flex aspect-video justify-center text-caption",
          // recharts 內部預設樣式覆寫:grid / axis / tooltip shadow 等
          "[&_.recharts-cartesian-grid_line]:stroke-divider",
          "[&_.recharts-cartesian-axis-tick_text]:fill-fg-muted",
          "[&_.recharts-polar-grid_[stroke='#ccc']]:stroke-divider",
          "[&_.recharts-reference-line_[stroke='#ccc']]:stroke-divider",
          "[&_.recharts-dot[stroke='#fff']]:stroke-transparent",
          "[&_.recharts-layer]:outline-none",
          "[&_.recharts-sector[stroke='#fff']]:stroke-transparent",
          "[&_.recharts-sector]:outline-none",
          "[&_.recharts-surface]:outline-none",
          className
        ),
        ...props,
        children: [
          /* @__PURE__ */ jsx(ChartStyle, { id: chartId, config }),
          /* @__PURE__ */ jsx(RechartsPrimitive.ResponsiveContainer, { children })
        ]
      }
    ) });
  }
);
ChartContainer.displayName = "ChartContainer";
const THEMES = { light: "", dark: "[data-theme=dark] " };
function ChartStyle({ id, config }) {
  const entries = Object.entries(config).filter(([, v]) => "color" in v || "theme" in v);
  if (entries.length === 0) return null;
  return /* @__PURE__ */ jsx(
    "style",
    {
      dangerouslySetInnerHTML: {
        __html: Object.entries(THEMES).map(([theme, prefix]) => {
          const vars = entries.map(([key, item]) => {
            var _a;
            const color = "theme" in item ? (_a = item.theme) == null ? void 0 : _a[theme] : item.color;
            return color ? `  --color-${key}: ${color};` : null;
          }).filter(Boolean).join("\n");
          return `${prefix}[data-chart=${id}] {
${vars}
}`;
        }).join("\n")
      }
    }
  );
}
const ChartTooltip = RechartsPrimitive.Tooltip;
const ChartTooltipContent = React.forwardRef(
  ({
    active,
    payload,
    className,
    indicator = "dot",
    hideLabel = false,
    hideIndicator = false,
    label,
    labelFormatter,
    labelClassName,
    formatter,
    color,
    nameKey,
    labelKey
  }, ref) => {
    const { config } = useChart();
    const tooltipLabel = React.useMemo(() => {
      var _a;
      if (hideLabel || !(payload == null ? void 0 : payload.length)) return null;
      const [item] = payload;
      const key = `${labelKey || item.dataKey || item.name || "value"}`;
      const itemConfig = getPayloadConfig(config, item, key);
      const value = !labelKey && typeof label === "string" ? ((_a = config[label]) == null ? void 0 : _a.label) || label : itemConfig == null ? void 0 : itemConfig.label;
      if (labelFormatter) return /* @__PURE__ */ jsx("div", { className: cn("font-medium", labelClassName), children: labelFormatter(value, payload) });
      if (!value) return null;
      return /* @__PURE__ */ jsx("div", { className: cn("font-medium", labelClassName), children: value });
    }, [label, labelFormatter, payload, hideLabel, labelClassName, config, labelKey]);
    if (!active || !(payload == null ? void 0 : payload.length)) return null;
    const nestLabel = payload.length === 1 && indicator !== "dot";
    return /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        role: "status",
        "aria-live": "polite",
        className: cn(
          "grid min-w-32 items-start gap-1.5 rounded-md border border-border bg-surface-raised px-2.5 py-1.5 text-caption shadow-[var(--elevation-200)]",
          className
        ),
        children: [
          !nestLabel ? tooltipLabel : null,
          /* @__PURE__ */ jsx("div", { className: "grid gap-1.5", children: payload.map((item, index) => {
            var _a;
            const key = `${nameKey || item.name || item.dataKey || "value"}`;
            const itemConfig = getPayloadConfig(config, item, key);
            const indicatorColor = color || ((_a = item.payload) == null ? void 0 : _a.fill) || item.color;
            return /* @__PURE__ */ jsx(
              "div",
              {
                className: cn(
                  "flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-fg-muted",
                  indicator === "dot" && "items-center"
                ),
                children: formatter && (item == null ? void 0 : item.value) !== void 0 && item.name ? formatter(item.value, item.name, item, index, item.payload) : /* @__PURE__ */ jsxs(Fragment, { children: [
                  (itemConfig == null ? void 0 : itemConfig.icon) ? /* @__PURE__ */ jsx(itemConfig.icon, {}) : !hideIndicator && /* @__PURE__ */ jsx(
                    "div",
                    {
                      className: cn("shrink-0 rounded-xs border-(--color-border) bg-(--color-bg)", {
                        "h-2.5 w-2.5": indicator === "dot",
                        "w-1": indicator === "line",
                        "w-0 border-[1.5px] border-dashed bg-transparent": indicator === "dashed",
                        "my-0.5": nestLabel && indicator === "dashed"
                      }),
                      style: {
                        "--color-bg": indicatorColor,
                        "--color-border": indicatorColor
                      }
                    }
                  ),
                  /* @__PURE__ */ jsxs(
                    "div",
                    {
                      className: cn(
                        "flex flex-1 justify-between leading-none",
                        nestLabel ? "items-end" : "items-center"
                      ),
                      children: [
                        /* @__PURE__ */ jsxs("div", { className: "grid gap-1.5", children: [
                          nestLabel ? tooltipLabel : null,
                          /* @__PURE__ */ jsx("span", { className: "text-fg-secondary", children: (itemConfig == null ? void 0 : itemConfig.label) || item.name })
                        ] }),
                        item.value && /* @__PURE__ */ jsx("span", { className: "text-foreground font-mono font-medium tabular-nums", children: item.value.toLocaleString() })
                      ]
                    }
                  )
                ] })
              },
              item.dataKey || index
            );
          }) })
        ]
      }
    );
  }
);
ChartTooltipContent.displayName = "ChartTooltipContent";
const ChartLegend = RechartsPrimitive.Legend;
const ChartLegendContent = React.forwardRef(
  ({ className, hideIcon = false, payload, verticalAlign = "bottom", nameKey }, ref) => {
    const { config } = useChart();
    if (!(payload == null ? void 0 : payload.length)) return null;
    return /* @__PURE__ */ jsx(
      "div",
      {
        ref,
        className: cn(
          "flex items-center justify-center gap-4",
          verticalAlign === "top" ? "pb-3" : "pt-3",
          className
        ),
        children: payload.map((item) => {
          const key = `${nameKey || item.dataKey || "value"}`;
          const itemConfig = getPayloadConfig(config, item, key);
          return /* @__PURE__ */ jsxs(
            "div",
            {
              className: "flex items-center gap-1.5 text-fg-secondary [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-fg-muted",
              children: [
                (itemConfig == null ? void 0 : itemConfig.icon) && !hideIcon ? /* @__PURE__ */ jsx(itemConfig.icon, {}) : /* @__PURE__ */ jsx("div", { className: "h-2 w-2 shrink-0 rounded-xs", style: { backgroundColor: item.color } }),
                itemConfig == null ? void 0 : itemConfig.label
              ]
            },
            String(item.value)
          );
        })
      }
    );
  }
);
ChartLegendContent.displayName = "ChartLegendContent";
function getPayloadConfig(config, payload, key) {
  if (typeof payload !== "object" || payload === null) return void 0;
  const payloadPayload = "payload" in payload && typeof payload.payload === "object" && payload.payload !== null ? payload.payload : void 0;
  let configLabelKey = key;
  if (key in payload && typeof payload[key] === "string") {
    configLabelKey = payload[key];
  } else if (payloadPayload && key in payloadPayload && typeof payloadPayload[key] === "string") {
    configLabelKey = payloadPayload[key];
  }
  return configLabelKey in config ? config[configLabelKey] : config[key];
}
const chartMeta = {
  component: "Chart",
  family: null,
  // non-family composite / overlay / layout
  variants: {},
  sizes: {},
  states: ["default"],
  tokens: {
    bg: ["bg-surface-raised", "bg-transparent"],
    fg: ["text-fg-muted", "text-fg-secondary", "text-foreground"],
    ring: []
  }
};
export {
  ChartContainer,
  ChartLegend,
  ChartLegendContent,
  ChartStyle,
  ChartTooltip,
  ChartTooltipContent,
  chartMeta
};
//# sourceMappingURL=chart.js.map
