import { useCallback } from "react";

import { notification } from "../utils/notifications.util";

const useCopy = () => {
  const handleCopy = useCallback((text: string) => {
    if (
      typeof window !== "undefined" &&
      navigator.clipboard &&
      navigator.clipboard.writeText
    ) {
      navigator.clipboard
        .writeText(text)
        .then(() => {
          notification.notifySuccess("Copied to clipboard!");
        })
        .catch(() => {
          notification.notifyError("Failed to copy text");
        });
    } else {
      // Fallback for environments without clipboard API
      try {
        const textArea = document.createElement("textarea");
        textArea.value = text;
        textArea.style.position = "fixed"; // Prevent scrolling to bottom of page
        textArea.style.opacity = "0"; // Hide the element
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand("copy");
        document.body.removeChild(textArea);

        notification.notifySuccess("Copied to clipboard!");
      } catch (err) {
        console.log("🚀 ~ useCopy ~ err:", err);
        notification.notifyError("Failed to copy text");
      }
    }
  }, []);

  return {
    handleCopy,
  };
};

export default useCopy;
