"use client";

import { useMemo, useEffect, useRef } from "react";
import { useLanguage } from "@/src/lib/context/LanguageContext";

interface ProgramDetailClientProps {
  defaultContent: React.ReactNode;
  translatedContent: React.ReactNode | null;
}

/**
 * Client component that handles language switching for program detail pages
 * Wraps the detail page content and provides language-aware rendering
 * Only reloads when user explicitly toggles language from navbar, NOT on initial hydration or cookie loading
 */
export default function ProgramDetailClient({
  defaultContent,
  translatedContent,
}: ProgramDetailClientProps) {
  const { currentLanguage, hasToggled } = useLanguage();
  const reloadTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const RELOAD_DEBOUNCE_MS = 500;

  // Switch content based on selected language.
  //
  // The provider stores whatever `?lang=` carries - a real code such as "de" -
  // and only the navbar toggle still produces the legacy "translated" sentinel.
  // Gating on that sentinel alone meant a ?lang=de URL rendered the English
  // tree even though the translated tree had already been fetched and rendered
  // right beside it. Any language other than "default" means "show the
  // translation", which is how the provider's own body class decides too.
  const displayContent = useMemo(() => {
    const wantsTranslation = currentLanguage !== "default";

    return wantsTranslation && translatedContent
      ? translatedContent
      : defaultContent;
  }, [currentLanguage, defaultContent, translatedContent]);

  // Only reload on explicit USER-initiated language changes
  useEffect(() => {
    // Only reload if the user manually clicked the toggle switch
    if (!hasToggled) {
      return;
    }


    // Cancel any pending reload
    if (reloadTimeoutRef.current) {
      clearTimeout(reloadTimeoutRef.current);
    }

    // Debounce the reload
    reloadTimeoutRef.current = setTimeout(() => {
      window.location.reload();
    }, RELOAD_DEBOUNCE_MS);
  }, [currentLanguage, hasToggled]);

  return <>{displayContent}</>;
}
