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

// src/lib/color.ts
function parseHslTriplet(triplet) {
  const parts = triplet.trim().split(/\s+/);
  return {
    h: Number.parseFloat(parts[0]) || 0,
    s: Number.parseFloat(parts[1]) || 0,
    l: Number.parseFloat(parts[2]) || 0
  };
}
function hslToRgb(h, s, l) {
  const sN = s / 100;
  const lN = l / 100;
  const k = (n) => (n + h / 30) % 12;
  const a = sN * Math.min(lN, 1 - lN);
  const f = (n) => lN - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1));
  return {
    r: Math.round(255 * f(0)),
    g: Math.round(255 * f(8)),
    b: Math.round(255 * f(4))
  };
}
function hslTripletToHex(triplet) {
  const { h, s, l } = parseHslTriplet(triplet);
  const { r, g, b } = hslToRgb(h, s, l);
  const toHex = (n) => n.toString(16).padStart(2, "0");
  return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}
function cn(...inputs) {
  return twMerge(clsx(inputs));
}
var DARK_FALLBACK = {
  background: "#0a0a0a",
  foreground: "#e5e5e5",
  selectionBackground: "#404040"
};
var LIGHT_FALLBACK = {
  background: "#fafafa",
  foreground: "#171717",
  selectionBackground: "#d4d4d4"
};
function readCssVarAsHex(name) {
  if (typeof document === "undefined") return null;
  const triplet = getComputedStyle(document.documentElement).getPropertyValue(`--${name}`).trim();
  if (!triplet) return null;
  return hslTripletToHex(triplet);
}
function Terminal({
  output,
  onInput,
  cols = 80,
  rows = 24,
  theme = "dark",
  cursorBlink = true,
  disableInput = false,
  className,
  ...rest
}) {
  const containerRef = React.useRef(null);
  const termRef = React.useRef(null);
  const writtenRef = React.useRef("");
  const onInputRef = React.useRef(onInput);
  onInputRef.current = onInput;
  const outputRef = React.useRef(output);
  outputRef.current = output;
  React.useEffect(() => {
    if (!containerRef.current) return;
    let disposed = false;
    let inputDispose = null;
    void (async () => {
      const xtermModule = await import('@xterm/xterm');
      if (disposed || !containerRef.current) return;
      const fallback = theme === "dark" ? DARK_FALLBACK : LIGHT_FALLBACK;
      const bgHex = readCssVarAsHex("background") ?? fallback.background;
      const fgHex = readCssVarAsHex("foreground") ?? fallback.foreground;
      const term = new xtermModule.Terminal({
        cols,
        rows,
        cursorBlink,
        disableStdin: disableInput,
        theme: {
          background: bgHex,
          foreground: fgHex,
          cursor: fgHex,
          selectionBackground: fallback.selectionBackground
        },
        fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
        fontSize: 13
      });
      term.open(containerRef.current);
      termRef.current = term;
      const latest = normalizeOutput(outputRef.current);
      if (latest) {
        term.write(latest);
        writtenRef.current = latest;
      }
      inputDispose = term.onData((data) => {
        onInputRef.current?.(data);
      });
    })();
    return () => {
      disposed = true;
      inputDispose?.dispose();
      termRef.current?.dispose();
      termRef.current = null;
      writtenRef.current = "";
    };
  }, []);
  React.useEffect(() => {
    const term = termRef.current;
    if (!term) return;
    const next = normalizeOutput(output);
    if (next === writtenRef.current) return;
    if (next.startsWith(writtenRef.current)) {
      const delta = next.slice(writtenRef.current.length);
      if (delta) term.write(delta);
    } else {
      term.reset();
      if (next) term.write(next);
    }
    writtenRef.current = next;
  }, [output]);
  const fallbackTriplet = theme === "dark" ? "0 0% 4%" : "0 0% 98%";
  const themeBg = `hsl(var(--background, ${fallbackTriplet}))`;
  return /* @__PURE__ */ jsx(
    "div",
    {
      ...rest,
      ref: containerRef,
      "data-hex-terminal": true,
      "data-theme": theme,
      style: { backgroundColor: themeBg, ...rest.style ?? {} },
      className: cn(
        "overflow-hidden rounded-md border p-2",
        "font-mono text-sm leading-tight",
        // xterm.js mounts hidden helper elements (`<textarea>` for
        // keyboard / IME input, `.xterm-char-measure-element` for
        // sizing). Both inherit the page's foreground token, which
        // axe flags as sub-AA against the locked-dark surface even
        // though they're visually offscreen. Force their visible
        // color transparent so axe stops complaining; AT can still
        // read the textarea (xterm's intended IME path), but the
        // rendered output appears in xterm's canvas — not the
        // textarea — so AT won't see meaningful content there.
        "[&_textarea]:!text-transparent [&_textarea]:!caret-transparent",
        "[&_.xterm-char-measure-element]:!text-transparent",
        className
      )
    }
  );
}
function normalizeOutput(value) {
  if (value == null) return "";
  return Array.isArray(value) ? value.join("") : value;
}

export { Terminal };
//# sourceMappingURL=terminal.js.map
//# sourceMappingURL=terminal.js.map