"use client";
import * as React from 'react';
import { clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
import { jsx, jsxs } from 'react/jsx-runtime';

function cn(...inputs) {
  return twMerge(clsx(inputs));
}
function OrgChart({
  root,
  collapsible = true,
  defaultExpandedDepth = Number.POSITIVE_INFINITY,
  nodeWidth = 180,
  nodeHeight = 64,
  width = 800,
  height = 480,
  onNodeClick,
  className,
  ...rest
}) {
  const [d3h, setD3h] = React.useState(null);
  const [collapsed, setCollapsed] = React.useState(() => seedCollapsed(root, defaultExpandedDepth));
  React.useEffect(() => {
    let cancelled = false;
    void import('d3-hierarchy').then((mod) => {
      if (!cancelled) setD3h(mod);
    });
    return () => {
      cancelled = true;
    };
  }, []);
  React.useEffect(() => {
    setCollapsed(seedCollapsed(root, defaultExpandedDepth));
  }, [root, defaultExpandedDepth]);
  if (!d3h) {
    return /* @__PURE__ */ jsx(
      "div",
      {
        "data-hex-org-chart-loading": true,
        "aria-busy": "true",
        className: cn("inline-block bg-muted/20", className),
        style: { width, height }
      }
    );
  }
  const { nodes, links } = layout(d3h, root, collapsed, width, height, nodeHeight);
  const desc = `Organizational chart with ${nodes.length} visible node${nodes.length === 1 ? "" : "s"}, rooted at "${root.label}"`;
  const handleClick = (node) => {
    onNodeClick?.(node);
    if (!collapsible) return;
    const hasChildren = node.children && node.children.length > 0;
    if (!hasChildren) return;
    setCollapsed((prev) => {
      const next = new Set(prev);
      if (next.has(node.id)) next.delete(node.id);
      else next.add(node.id);
      return next;
    });
  };
  return /* @__PURE__ */ jsxs(
    "svg",
    {
      ...rest,
      "data-hex-org-chart": true,
      role: "img",
      width,
      height,
      viewBox: `0 0 ${width} ${height}`,
      className: cn("block", className),
      children: [
        /* @__PURE__ */ jsx("title", { children: "Org chart" }),
        /* @__PURE__ */ jsx("desc", { children: desc }),
        /* @__PURE__ */ jsx("g", { "data-hex-org-chart-links": true, children: links.map((l) => /* @__PURE__ */ jsx(
          "path",
          {
            d: `M${l.source.x},${l.source.y} C${l.source.x},${(l.source.y + l.target.y) / 2} ${l.target.x},${(l.source.y + l.target.y) / 2} ${l.target.x},${l.target.y}`,
            fill: "none",
            stroke: "hsl(var(--muted-foreground))",
            strokeOpacity: 0.5,
            strokeWidth: 1
          },
          l.id
        )) }),
        /* @__PURE__ */ jsx("g", { "data-hex-org-chart-nodes": true, children: nodes.map((n) => /* @__PURE__ */ jsxs(
          "g",
          {
            "data-hex-org-chart-node": true,
            "data-depth": n.depth,
            transform: `translate(${n.x - nodeWidth / 2},${n.y - nodeHeight / 2})`,
            style: collapsible || onNodeClick ? { cursor: "pointer" } : void 0,
            onClick: collapsible || onNodeClick ? () => handleClick(n.node) : void 0,
            children: [
              /* @__PURE__ */ jsx(
                "rect",
                {
                  width: nodeWidth,
                  height: nodeHeight,
                  rx: 8,
                  ry: 8,
                  fill: "hsl(var(--card))",
                  stroke: "hsl(var(--border))",
                  strokeWidth: 1
                }
              ),
              /* @__PURE__ */ jsx(
                "text",
                {
                  x: 12,
                  y: 24,
                  fontSize: 13,
                  fontWeight: 600,
                  fill: "hsl(var(--foreground))",
                  children: truncate(n.node.label, Math.floor((nodeWidth - 24) / 7))
                }
              ),
              n.node.subtitle ? /* @__PURE__ */ jsx(
                "text",
                {
                  x: 12,
                  y: 42,
                  fontSize: 11,
                  fill: "hsl(var(--muted-foreground))",
                  children: truncate(n.node.subtitle, Math.floor((nodeWidth - 24) / 6))
                }
              ) : null,
              n.collapsedCount > 0 ? /* @__PURE__ */ jsxs("g", { transform: `translate(${nodeWidth - 28},${nodeHeight - 18})`, children: [
                /* @__PURE__ */ jsx(
                  "rect",
                  {
                    width: 20,
                    height: 14,
                    rx: 7,
                    ry: 7,
                    fill: "hsl(var(--primary))",
                    opacity: 0.85
                  }
                ),
                /* @__PURE__ */ jsx(
                  "text",
                  {
                    x: 10,
                    y: 10,
                    fontSize: 9,
                    fontWeight: 600,
                    fill: "hsl(var(--primary-foreground))",
                    textAnchor: "middle",
                    children: `+${n.collapsedCount}`
                  }
                )
              ] }) : null
            ]
          },
          n.node.id
        )) })
      ]
    }
  );
}
function seedCollapsed(root, maxDepth) {
  if (!Number.isFinite(maxDepth)) return /* @__PURE__ */ new Set();
  const collapsed = /* @__PURE__ */ new Set();
  const walk = (n, depth) => {
    if (depth >= maxDepth && n.children && n.children.length > 0) {
      collapsed.add(n.id);
      return;
    }
    n.children?.forEach((c) => walk(c, depth + 1));
  };
  walk(root, 0);
  return collapsed;
}
function layout(d3h, root, collapsed, width, height, nodeHeight) {
  const indexById = /* @__PURE__ */ new Map();
  indexNodes(root, indexById);
  const visible = pruneCollapsed(root, collapsed);
  const hierarchy = d3h.hierarchy(visible);
  const layoutRoot = d3h.tree().size([width - 32, height - nodeHeight])(hierarchy);
  const nodes = [];
  layoutRoot.each((d) => {
    const original = indexById.get(d.data.id);
    const collapsedCount = collapsed.has(d.data.id) && original ? countDescendants(original) : 0;
    nodes.push({ node: d.data, x: d.x + 16, y: d.y + nodeHeight / 2, depth: d.depth, collapsedCount });
  });
  const links = layoutRoot.links().map((link, i) => ({
    source: { x: link.source.x + 16, y: link.source.y + nodeHeight / 2 },
    target: { x: link.target.x + 16, y: link.target.y + nodeHeight / 2 },
    id: `l-${i}`
  }));
  return { nodes, links };
}
function pruneCollapsed(node, collapsed) {
  if (collapsed.has(node.id)) {
    return { ...node, children: void 0 };
  }
  if (!node.children || node.children.length === 0) return node;
  return { ...node, children: node.children.map((c) => pruneCollapsed(c, collapsed)) };
}
function indexNodes(node, out) {
  out.set(node.id, node);
  if (!node.children) return;
  for (const c of node.children) indexNodes(c, out);
}
function countDescendants(node) {
  if (!node.children || node.children.length === 0) return 0;
  return node.children.reduce((sum, c) => sum + 1 + countDescendants(c), 0);
}
function truncate(s, max) {
  if (s.length <= max) return s;
  return `${s.slice(0, Math.max(1, max - 1))}\u2026`;
}

export { OrgChart };
//# sourceMappingURL=org-chart.js.map
//# sourceMappingURL=org-chart.js.map