import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useToast } from "@/hooks/use-toast";
import {
  AUTOPLAY_BLOCKED_EVENT,
  type AutoplayBlockedDetail,
} from "@/lib/notification-sounds";

/**
 * When a notification sound is attempted before the browser has
 * accepted a user gesture — or, on iPad, when the AudioContext refuses
 * to resume because the device is in silent mode — the player
 * dispatches a custom event. We surface a toast with the appropriate
 * guidance. On iOS the toast also tells the user to check Control
 * Center / the silent switch since "click anywhere" alone won't help
 * when the hardware mute is on.
 */
export function useAutoplayHint(): void {
  const { t } = useTranslation();
  const { toast } = useToast();
  useEffect(() => {
    const handler = (e: Event) => {
      const detail = (e as CustomEvent<AutoplayBlockedDetail>).detail;
      const isIos = !!detail?.isIos;
      // #628: the autoplay hint was previously an auto-dismissing
      // toast that the user could easily miss while looking at the
      // iPad from across the room. Make it sticky (no auto-dismiss)
      // so it stays on screen until acknowledged — otherwise the
      // first incoming order goes silently unnoticed and the user
      // never realises notifications need a tap to unlock.
      toast({
        title: t("notifSettings.autoplayHintTitle"),
        description: isIos
          ? t("notifSettings.autoplayHintIos")
          : t("notifSettings.autoplayHint"),
        duration: Number.POSITIVE_INFINITY,
      });
    };
    window.addEventListener(AUTOPLAY_BLOCKED_EVENT, handler);
    return () => window.removeEventListener(AUTOPLAY_BLOCKED_EVENT, handler);
  }, [t, toast]);
}
