"use client";

import { useEffect } from "react";
import { toast } from "sonner";
import { Fancybox as NativeFancybox } from "@fancyapps/ui";
import { getApiErrorMessage } from "@/lib/api/errors";
import { toastApiError } from "@/lib/api/toastApiError";
import { learnServeReadErrorAction } from "./learnServeReadError";

/**
 * A 404 on this route is a real outcome — an unpublished or deleted
 * opportunity — so it redirects rather than sitting on an empty page, with the
 * server's own localized `msg` when it sends one.
 *
 * Any other failed first read is shown in place by
 * `LearnServeDetailsUnavailable` (server message + retry), so it is not toasted
 * a second time; only a failed background refetch over a page that is still
 * showing the earlier record gets a toast.
 */
export function useLearnServeErrorRedirect(
  error: unknown,
  selectedLanguage: string,
  t: (key: string) => string,
  replace: (path: string) => void,
  hasData = false
) {
  useEffect(() => {
    const action = learnServeReadErrorAction(error, hasData);
    if (action === "redirect") {
      toast.error(getApiErrorMessage(error, selectedLanguage, t("COMMON.LEARN_SERVE_OPPORTUNITY_NOT_FOUND")));
      replace("/404");
      return;
    }

    if (action === "toast") toastApiError(error, selectedLanguage, t("COMMON.ERROR_FETCHING_OPPORTUNITY"));
  }, [error, selectedLanguage, t, replace, hasData]);
}

/**
 * Fancybox previews the post-completion gallery in place of a new browser tab.
 */
export function useLearnServeGalleries(id: string) {
  useEffect(() => {
    const galleryIds = [`opportunity-gallery-${id}`];
    galleryIds.forEach((galleryId) =>
      NativeFancybox.bind(`[data-fancybox="${galleryId}"]`, {
        showClass: "fancybox-zoomIn",
        hideClass: "fancybox-zoomOut",
      })
    );
    return () => {
      galleryIds.forEach((galleryId) =>
        NativeFancybox.unbind(`[data-fancybox="${galleryId}"]`)
      );
      NativeFancybox.close();
    };
  }, [id]);
}
