import { useState, useEffect, useRef } from 'react';
import Copy from 'copy-to-clipboard';
import type { Locale, Translations } from '../type';

const translations: Translations = {
  en: {
    copy: 'Click To Copy',
    copied: 'Copied!',
  },
  zh: {
    copy: '点击复制',
    copied: '已复制!',
  },
};

export default function useCopy({ content, locale = 'en' }: { content?: string; locale?: Locale }) {
  const [copied, setCopied] = useState(false);
  const containerRef = useRef<HTMLElement | null>(null);
  const copy = (e: React.MouseEvent) => {
    if (e) {
      e.stopPropagation();
    }

    Copy(content || (containerRef.current?.textContent ?? ''));
    setCopied(true);
  };

  useEffect(() => {
    let timer: ReturnType<typeof setTimeout>;
    if (copied) {
      timer = setTimeout(() => setCopied(false), 2000);
    }
    return () => clearTimeout(timer);
  }, [copied]);

  return {
    containerRef,
    copied,
    copy,
    texts: translations[locale] || translations.en,
  };
}
