"use client";

import { useCallback } from "react";
import { useToast } from "@/hooks/useToast";

export function useShare() {
  const toast = useToast();

  const copyToClipboard = useCallback(
    async (text: string, successMsg = "已复制") => {
      try {
        await navigator.clipboard.writeText(text);
        toast.show(successMsg);
      } catch {
        toast.show("复制失败，请手动复制");
      }
    },
    [toast],
  );

  /** Try the native Web Share API; calls `fallback` if unavailable. Returns true if native share was triggered. */
  const share = useCallback(
    async (data: ShareData, fallback?: () => void): Promise<boolean> => {
      try {
        if (navigator.share && navigator.canShare?.(data)) {
          await navigator.share(data);
          return true;
        }
      } catch (e) {
        if (e instanceof Error && e.name === "AbortError") return true;
      }
      fallback?.();
      return false;
    },
    [],
  );

  return { share, copyToClipboard };
}
