import { useEffect, useRef, useState } from "react";
import { copyMessage } from "./copy-message.js";
import { useI18n } from "../../shared/I18nProvider.jsx";
import { CheckIcon, CopyIcon } from "../../shared/ActionIcons.jsx";

export function MessageCopyButton({ text, active, onDismiss, standalone = false }) {
  const { t } = useI18n();
  const [copied, setCopied] = useState(false);
  const dismissTimer = useRef(null);

  useEffect(() => {
    if (!active) setCopied(false);
    return () => {
      if (dismissTimer.current) clearTimeout(dismissTimer.current);
    };
  }, [active]);

  async function copy() {
    if (!await copyMessage(text)) {
      onDismiss();
      return;
    }
    setCopied(true);
    dismissTimer.current = setTimeout(() => {
      setCopied(false);
      onDismiss();
    }, 1200);
  }

  return <button type="button" className={`message-copy-button ${copied ? "is-copied" : ""}`} role={standalone ? undefined : "menuitem"} aria-label={copied ? t("conversation.copied") : t(standalone ? "conversation.copy" : "conversation.copyMessage")} title={copied ? t("conversation.copied") : t("conversation.copy")} tabIndex={active ? 0 : -1} disabled={!active || copied} onClick={() => void copy()}>
    {copied
      ? <><CheckIcon /><span className="message-copy-label">{t("conversation.copied")}</span></>
      : <CopyIcon />}
  </button>;
}
