"use client";

import { useEffect, useRef } from "react";

type TechDocArticleProps = {
  contentHtml: string;
};

export function TechDocArticle({ contentHtml }: TechDocArticleProps) {
  const articleRef = useRef<HTMLElement>(null);

  useEffect(() => {
    const article = articleRef.current;
    if (!article) {
      return;
    }

    const timeouts: ReturnType<typeof setTimeout>[] = [];
    const buttons: HTMLButtonElement[] = [];
    const copyText = async (text: string) => {
      if (navigator.clipboard?.writeText) {
        await navigator.clipboard.writeText(text);
        return;
      }

      const textarea = document.createElement("textarea");
      textarea.value = text;
      textarea.setAttribute("readonly", "");
      textarea.style.position = "fixed";
      textarea.style.opacity = "0";
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand("copy");
      textarea.remove();
    };

    article.querySelectorAll("pre").forEach((pre) => {
      const code = pre.querySelector("code");
      pre.setAttribute("data-language", code?.getAttribute("lang")?.toUpperCase() || "CODE");

      const button = document.createElement("button");
      button.type = "button";
      button.className = "tech-doc-code-copy";
      button.textContent = "复制";

      button.addEventListener("click", async () => {
        const text = code?.textContent?.trimEnd();
        if (!text) {
          return;
        }

        try {
          await copyText(text);
          button.textContent = "已复制";
          button.dataset.copied = "true";

          const timeout = setTimeout(() => {
            button.textContent = "复制";
            delete button.dataset.copied;
          }, 1400);
          timeouts.push(timeout);
        } catch {
          button.textContent = "复制失败";
        }
      });

      pre.appendChild(button);
      buttons.push(button);
    });

    return () => {
      timeouts.forEach(clearTimeout);
      buttons.forEach((button) => button.remove());
    };
  }, [contentHtml]);

  return (
    <article
      ref={articleRef}
      className="tech-doc-content min-w-0 max-w-full rounded-[1.75rem] border border-white/10 bg-[#090915]/95 p-5 shadow-2xl shadow-cyan-500/10 sm:p-8 lg:p-10"
      dangerouslySetInnerHTML={{ __html: contentHtml }}
    />
  );
}
