'use client';

import { useEffect, useRef } from 'react';

/**
 * Generic hook to detect when users translate the page using browser translation features.
 *
 * Uses MutationObserver to detect when Chrome/browser adds translation attributes
 * to the HTML element. When Chrome translates a page, it adds lang attribute changes
 * and font tags with translation metadata.
 *
 * Note: This is a workaround as there's no standard browser API for translation detection.
 *
 * @param onTranslationDetected - Callback invoked when a translation is detected
 */
export function useTranslationDetection(
  onTranslationDetected: (fromLanguage: string, toLanguage: string) => void
) {
  const hasDetectedTranslation = useRef(false);
  const originalLanguage = useRef<string | null>(null);

  useEffect(() => {
    // Only run on client
    if (typeof window === 'undefined' || typeof document === 'undefined')
      return;

    // Store the original page language
    const htmlElement = document.documentElement;
    originalLanguage.current = htmlElement.lang || 'en';

    // Chrome adds font elements with specific attributes during translation
    // Also monitors lang attribute changes on html element
    const observer = new MutationObserver((mutations) => {
      // Skip if we've already detected a translation
      if (hasDetectedTranslation.current) return;

      for (const mutation of mutations) {
        // Exit early if translation already detected in this batch
        if (hasDetectedTranslation.current) break;

        // Check for lang attribute changes on html element
        if (
          mutation.type === 'attributes' &&
          mutation.attributeName === 'lang' &&
          mutation.target === htmlElement
        ) {
          const newLang = htmlElement.lang;
          const oldLang = originalLanguage.current || 'unknown';

          // Only fire callback if language actually changed
          if (newLang !== oldLang) {
            hasDetectedTranslation.current = true;
            onTranslationDetected(oldLang, newLang);
            return; // Exit the entire observer callback
          }
        }

        // Check for Chrome's translation font elements being added
        if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
          for (const node of mutation.addedNodes) {
            // Exit early if translation already detected
            if (hasDetectedTranslation.current) break;

            if (
              node.nodeName === 'FONT' &&
              node instanceof HTMLElement &&
              node.className.includes('translated')
            ) {
              // Chrome translation detected
              const toLanguage = htmlElement.lang || navigator.language;
              hasDetectedTranslation.current = true;
              onTranslationDetected(
                originalLanguage.current || 'unknown',
                toLanguage
              );
              return; // Exit the entire observer callback
            }
          }
        }
      }
    });

    // Observe the html element for lang attribute changes
    observer.observe(htmlElement, {
      attributes: true,
      attributeFilter: ['lang'],
      subtree: true,
      childList: true,
    });

    return () => {
      observer.disconnect();
    };
  }, [onTranslationDetected]);
}
