import { CopyButton } from '@/components/ui/copy-button';

/** Tokenizes JSON text for simple syntax highlighting using design tokens. */
const highlight = (json: string) => {
  const parts: Array<{ text: string; className?: string }> = [];
  const pattern = /("(?:\\u[a-fA-F0-9]{4}|\\[^u]|[^\\"])*"(?:\s*:)?|\b(?:true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g;
  let last = 0;
  for (const match of json.matchAll(pattern)) {
    const index = match.index ?? 0;
    if (index > last) parts.push({ text: json.slice(last, index) });
    const token = match[0];
    const className = token.startsWith('"')
      ? token.trimEnd().endsWith(':')
        ? 'text-primary'
        : 'text-success'
      : token === 'true' || token === 'false'
        ? 'text-accent'
        : token === 'null'
          ? 'text-subtle-foreground'
          : 'text-warning';
    parts.push({ text: token, className });
    last = index + token.length;
  }
  if (last < json.length) parts.push({ text: json.slice(last) });
  return parts;
};

export function JsonBlock({ value, label = 'Copy JSON' }: { value: unknown; label?: string }) {
  const json = JSON.stringify(value ?? {}, null, 2);
  return (
    <div className="relative overflow-hidden rounded-lg border border-border bg-surface-muted">
      <div className="absolute right-2 top-2">
        <CopyButton notify value={json} label={label} className="bg-surface shadow-xs" />
      </div>
      <pre className="max-h-[60vh] overflow-auto p-4 pr-12 font-mono text-caption leading-5 text-foreground">
        <code>
          {highlight(json).map((part, index) =>
            part.className === undefined ? (
              part.text
            ) : (
              <span key={index} className={part.className}>
                {part.text}
              </span>
            ),
          )}
        </code>
      </pre>
    </div>
  );
}
