"use client";

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

import styles from "../blog.module.css";

/**
 * Blog code block — design's `.code-block` frame (traffic-light bar + language
 * label) around the rehype-pretty-code highlighted <pre>, with a copy button.
 */
export function BlogPre({
  children,
  ...props
}: React.ComponentPropsWithoutRef<"pre"> & { "data-language"?: string }) {
  const ref = useRef<HTMLPreElement>(null);
  const [copied, setCopied] = useState(false);
  const lang = props["data-language"];

  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={styles.codeBlock}>
      <div className={styles.cbBar}>
        <span className={styles.d} style={{ background: "#ff5f57" }} />
        <span className={styles.d} style={{ background: "#febc2e" }} />
        <span className={styles.d} style={{ background: "#28c840" }} />
        {lang ? <span className={styles.lang}>{lang}</span> : null}
        <button
          type="button"
          onClick={copy}
          aria-label="Copy code"
          className={styles.copyBtn}
        >
          {copied ? (
            <IconCheck className="text-brand-success size-4" />
          ) : (
            <IconCopy className="size-4" />
          )}
        </button>
      </div>
      <pre ref={ref} {...props}>
        {children}
      </pre>
    </div>
  );
}
