"use client";

import { useRef, useState } from "react";
import { IconCheck, IconCopy } from "@tabler/icons-react";

// Code block wrapper: always-dark panel (Protocol style) with a copy button.
// rehype-pretty-code provides the syntax-highlighted spans inside <pre>.
export function Pre({
  className,
  children,
  ...props
}: React.ComponentPropsWithoutRef<"pre">) {
  const ref = useRef<HTMLPreElement>(null);
  const [copied, setCopied] = useState(false);

  const copy = async () => {
    const text = ref.current?.textContent ?? "";
    try {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    } catch {
      // clipboard unavailable — ignore
    }
  };

  return (
    <div className="group relative my-6 overflow-hidden rounded-2xl bg-zinc-900 ring-1 ring-white/10">
      <pre
        ref={ref}
        className="overflow-x-auto p-4 text-sm text-zinc-100 [&_code]:bg-transparent [&_code]:p-0 [&_code]:shadow-none"
        {...props}
      >
        {children}
      </pre>
      <button
        type="button"
        onClick={copy}
        aria-label="Copy code"
        className="absolute top-2.5 right-2.5 rounded-lg p-1.5 text-zinc-400 opacity-0 transition group-hover:opacity-100 hover:bg-white/5 hover:text-zinc-200 focus-visible:opacity-100"
      >
        {copied ? (
          <IconCheck className="size-4 text-brand-success" />
        ) : (
          <IconCopy className="size-4" />
        )}
      </button>
    </div>
  );
}
