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

function cn(...inputs) {
  return twMerge(clsx(inputs));
}
function TimeAxis({
  events,
  start,
  end,
  width = 720,
  height = 200,
  tickCount = 6,
  onEventClick,
  className,
  ...rest
}) {
  const laidOut = React.useMemo(
    () => layout(events, start, end, width, height, tickCount),
    [events, start, end, width, height, tickCount]
  );
  const desc = events.length === 0 ? "Empty time axis" : `Time axis with ${events.length} event${events.length === 1 ? "" : "s"}, range ${laidOut.startLabel} to ${laidOut.endLabel}`;
  return /* @__PURE__ */ jsxs(
    "svg",
    {
      ...rest,
      "data-hex-time-axis": true,
      role: "img",
      width,
      height,
      viewBox: `0 0 ${width} ${height}`,
      className: cn("block", className),
      children: [
        /* @__PURE__ */ jsx("title", { children: "Time axis" }),
        /* @__PURE__ */ jsx("desc", { children: desc }),
        /* @__PURE__ */ jsxs("g", { "data-hex-time-axis-axis": true, children: [
          /* @__PURE__ */ jsx(
            "line",
            {
              x1: laidOut.axisLeft,
              x2: laidOut.axisRight,
              y1: laidOut.axisY,
              y2: laidOut.axisY,
              stroke: "hsl(var(--muted-foreground))",
              strokeWidth: 1
            }
          ),
          laidOut.ticks.map((tick, i) => /* @__PURE__ */ jsxs("g", { "data-hex-time-axis-tick": true, children: [
            /* @__PURE__ */ jsx(
              "line",
              {
                x1: tick.x,
                x2: tick.x,
                y1: laidOut.axisY - 4,
                y2: laidOut.axisY + 4,
                stroke: "hsl(var(--muted-foreground))",
                strokeWidth: 1
              }
            ),
            /* @__PURE__ */ jsx(
              "text",
              {
                x: tick.x,
                y: laidOut.axisY + 18,
                textAnchor: "middle",
                fontSize: 10,
                fill: "hsl(var(--muted-foreground))",
                children: tick.label
              }
            )
          ] }, `tick-${i}`))
        ] }),
        /* @__PURE__ */ jsx("g", { "data-hex-time-axis-events": true, children: laidOut.events.map((e) => {
          const interactive = Boolean(onEventClick);
          const handleActivate = () => onEventClick?.(e.event);
          return /* @__PURE__ */ jsxs(
            "g",
            {
              "data-hex-time-axis-event": true,
              "data-row": e.rowIndex,
              className: interactive ? "focus-visible:outline-none focus-visible:outline-2 focus-visible:outline-ring" : void 0,
              role: interactive ? "button" : void 0,
              tabIndex: interactive ? 0 : void 0,
              "aria-label": interactive ? `${e.event.label} on ${formatDate(toDate(e.event.date))}` : void 0,
              style: interactive ? { cursor: "pointer" } : void 0,
              onClick: interactive ? handleActivate : void 0,
              onKeyDown: interactive ? (k) => activateOnKey(k, handleActivate) : void 0,
              children: [
                /* @__PURE__ */ jsx(
                  "line",
                  {
                    x1: e.x,
                    x2: e.x,
                    y1: e.y,
                    y2: laidOut.axisY,
                    stroke: "hsl(var(--muted-foreground))",
                    strokeOpacity: 0.65,
                    strokeWidth: 1
                  }
                ),
                /* @__PURE__ */ jsx(
                  "circle",
                  {
                    cx: e.x,
                    cy: e.y,
                    r: 5,
                    fill: "hsl(var(--primary))",
                    stroke: "hsl(var(--background))",
                    strokeWidth: 2
                  }
                ),
                /* @__PURE__ */ jsx(
                  "text",
                  {
                    x: e.x + 8,
                    y: e.y + 4,
                    fontSize: 11,
                    fill: "hsl(var(--foreground))",
                    style: { paintOrder: "stroke", pointerEvents: "none" },
                    stroke: "hsl(var(--background))",
                    strokeWidth: 3,
                    strokeLinejoin: "round",
                    children: e.event.label
                  }
                )
              ]
            },
            e.event.id
          );
        }) })
      ]
    }
  );
}
function layout(events, start, end, width, height, tickCount) {
  const margin = 32;
  const axisLeft = margin;
  const axisRight = width - margin;
  const axisY = height - 40;
  const usableWidth = axisRight - axisLeft;
  const validEvents = events.filter((e) => Number.isFinite(toDate(e.date).getTime()));
  if (validEvents.length === 0) {
    return {
      events: [],
      ticks: [],
      axisY,
      axisLeft,
      axisRight,
      startLabel: "\u2014",
      endLabel: "\u2014"
    };
  }
  const dates = validEvents.map((e) => toDate(e.date).getTime());
  const explicitMin = start != null ? toDate(start).getTime() : NaN;
  const explicitMax = end != null ? toDate(end).getTime() : NaN;
  const minTs = Number.isFinite(explicitMin) ? explicitMin : Math.min(...dates);
  const maxTs = Number.isFinite(explicitMax) ? explicitMax : Math.max(...dates);
  const span = Math.max(1, maxTs - minTs);
  const tToX = (t) => axisLeft + (t - minTs) / span * usableWidth;
  const MIN_GAP_PX = 48;
  const ROW_HEIGHT_PX = 22;
  const maxRows = Math.max(1, Math.floor((axisY - 10 - 24) / ROW_HEIGHT_PX) + 1);
  const rowsLastX = [];
  const positioned = validEvents.map((event) => ({ event, t: toDate(event.date).getTime() })).sort((a, b) => a.t - b.t || a.event.id.localeCompare(b.event.id)).map(({ event, t }) => {
    const x = tToX(t);
    let rowIndex = rowsLastX.findIndex((lastX) => x - lastX >= MIN_GAP_PX);
    if (rowIndex === -1) {
      if (rowsLastX.length < maxRows) {
        rowIndex = rowsLastX.length;
        rowsLastX.push(x);
      } else {
        rowIndex = maxRows - 1;
        rowsLastX[rowIndex] = x;
      }
    } else {
      rowsLastX[rowIndex] = x;
    }
    return { event, x, y: 24 + rowIndex * ROW_HEIGHT_PX, rowIndex };
  });
  const rawTicks = [];
  for (let i = 0; i < tickCount; i++) {
    const t = minTs + i / Math.max(1, tickCount - 1) * span;
    rawTicks.push({ x: tToX(t), label: formatTick(new Date(t), span) });
  }
  const ticks = rawTicks.map((t, i) => ({
    x: t.x,
    label: i > 0 && rawTicks[i - 1]?.label === t.label ? "" : t.label
  }));
  return {
    events: positioned,
    ticks,
    axisY,
    axisLeft,
    axisRight,
    startLabel: formatDate(new Date(minTs)),
    endLabel: formatDate(new Date(maxTs))
  };
}
function toDate(v) {
  if (v instanceof Date) return v;
  if (typeof v === "number") return new Date(v);
  return new Date(v);
}
function formatDate(d) {
  if (Number.isNaN(d.getTime())) return "\u2014";
  return d.toISOString().slice(0, 10);
}
function formatTick(d, spanMs) {
  if (Number.isNaN(d.getTime())) return "\u2014";
  const ONE_DAY = 24 * 60 * 60 * 1e3;
  if (spanMs <= 7 * ONE_DAY) {
    return d.toISOString().slice(0, 10);
  }
  if (spanMs <= 90 * ONE_DAY) {
    return d.toISOString().slice(5, 10);
  }
  if (spanMs <= 730 * ONE_DAY) {
    return d.toISOString().slice(0, 7);
  }
  return String(d.getUTCFullYear());
}
function activateOnKey(e, fn) {
  if (e.key === "Enter" || e.key === " ") {
    e.preventDefault();
    fn();
  }
}

export { TimeAxis };
//# sourceMappingURL=time-axis.js.map
//# sourceMappingURL=time-axis.js.map