"use client";

import { useQuery } from "@tanstack/react-query";
import { usePathname } from "next/navigation";
import { meetingSummaryOwner } from "../../ministry/meeting-summary/meeting-summary-translations";

import {
  meetingSummaryText,
  meetingSummaryStatusLabels,
  normalizeMeetingSummaryLanguage,
} from "./meeting-summary-i18n";
import {
  fetchMeetingSummaryTranslations,
  type MeetingSummaryTextShape,
  type MeetingSummaryStatusLabelsShape,
} from "./meeting-summary-translation-service";
import type { MeetingSummaryTextOverride } from "../../ministry/meeting-summary/meeting-summary-translations";
import { useAppLanguage } from "@/components/providers/app-language-provider";

export type UseMeetingSummaryTranslationResult = {
  /** Resolved text labels (API override when available, static fallback otherwise). */
  text: MeetingSummaryTextShape;
  /** Resolved status labels (API override when available, static fallback otherwise). */
  statusLabels: MeetingSummaryStatusLabelsShape;
  /** Only real API labels, so static PSWG defaults cannot mask Ministry labels. */
  sharedTextOverride: MeetingSummaryTextOverride;
  /** True while the first API fetch is in flight. */
  loading: boolean;
};

/**
 * Fetches PSWG meeting-summary translation labels from the backend API.
 * Falls back to the static i18n labels when:
 *  - the API call fails (network error, 4xx/5xx), or
 *  - the fetch is still in progress (returns static labels immediately).
 */
export function useMeetingSummaryTranslation(): UseMeetingSummaryTranslationResult {
  const { language } = useAppLanguage();
  const lang = normalizeMeetingSummaryLanguage(language);
  const owner = meetingSummaryOwner(usePathname() ?? "");

  const { data, isPending } = useQuery({
    queryKey: ["meeting-summary-text", owner, lang],
    queryFn: () => fetchMeetingSummaryTranslations(lang, owner ?? "pswg"),
    enabled: owner !== null,
    staleTime: 30_000,
    refetchOnMount: "always",
    refetchOnWindowFocus: "always",
  });

  return {
    text: data?.text ?? meetingSummaryText[lang],
    statusLabels: data?.statusLabels ?? meetingSummaryStatusLabels,
    sharedTextOverride: data?.sharedTextOverride ?? EMPTY_SHARED_OVERRIDE,
    loading: isPending,
  };
}

const EMPTY_SHARED_OVERRIDE: MeetingSummaryTextOverride = {};
