import { useCallback, useEffect, useRef, useState } from 'react';

/* ============================================================================
   USE COPY TO CLIPBOARD — write a string to the clipboard with "copied!" state.
   ----------------------------------------------------------------------------
   Returns a `copy(text)` action and a `copied` flag that flips true on success
   and auto-resets after `resetDelay` ms (default 2000). The flag is the single
   source of truth for swapping a button's icon/label. `copy` resolves to the
   boolean result so callers can react to failure if they want.
   ========================================================================== */

interface UseCopyToClipboardOptions {
  /** how long `copied` stays true after a successful copy, in ms */
  resetDelay?: number;
}

export function useCopyToClipboard({ resetDelay = 2000 }: UseCopyToClipboardOptions = {}) {
  const [copied, setCopied] = useState(false);
  const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const clearPending = useCallback(() => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }
  }, []);

  // drop any pending reset when the consumer unmounts
  useEffect(() => clearPending, [clearPending]);

  const copy = useCallback(
    async (text: string): Promise<boolean> => {
      if (!navigator?.clipboard) {
        console.error('Clipboard API not available');
        return false;
      }

      try {
        await navigator.clipboard.writeText(text);
        setCopied(true);
        clearPending();
        timeoutRef.current = setTimeout(() => setCopied(false), resetDelay);
        return true;
      } catch (err) {
        console.error('Failed to copy:', err);
        setCopied(false);
        return false;
      }
    },
    [resetDelay, clearPending]
  );

  return { copied, copy };
}

export default useCopyToClipboard;
