import React, { useEffect, useRef } from 'react';

const GoogleTranslateWidget = ({
  pageLanguage = 'en',
  includedLanguages = 'en,fr,de,it,es',
}) => {
  const scriptLoaded = useRef(false);
  const observerRef = useRef(null);

  useEffect(() => {
    // Early hiding of all potential Google elements that might flash
    const earlyStyle = document.createElement('style');
    earlyStyle.setAttribute('data-google-translate-early-style', 'true');
    earlyStyle.innerHTML = `
      /* Hide all potential Google Translate elements early */
      .goog-te-banner-frame,
      .goog-te-spinner-pos,
      .goog-te-spinner,
      .goog-te-balloon-frame,
      .goog-tooltip,
      #goog-gt-tt,
      .goog-te-menu-frame,
      .goog-te-balloon,
      .goog-te-ftab,
      #gt-nvframe,
      div[id^="goog-gt-"],
      .VIpgJd-ZVi9od-xl07Ob-lTBxed,
      .VIpgJd-ZVi9od-aZ2wEe-wOHMyf,
      .VIpgJd-ZVi9od-aZ2wEe-OiiCO {
        display: none !important;
        visibility: hidden !important;
      }
      iframe.skiptranslate {
        display: none !important;
        visibility: hidden !important;
      }
      body {
        top: 0 !important;
      }
      /* Hide Google Translate widget */
      #google_translate_element,
      .goog-te-gadget {
        position: fixed !important;
        left: -9999px !important;
        visibility: hidden !important;
      }
      /* Remove hover effects on translated text early */
      font:hover,
      .translated-ltr font,
      .translated-rtl font {
        background: transparent !important;
        box-shadow: none !important;
        outline: none !important;
        pointer-events: none !important;
        cursor: inherit !important;
      }
    `;
    document.head.appendChild(earlyStyle);

    // Check if script is already loaded to avoid duplicates
    if (scriptLoaded.current) return;
    scriptLoaded.current = true;

    // Create a global callback
    window.googleTranslateElementInit = () => {
      new window.google.translate.TranslateElement(
        {
          pageLanguage,
          includedLanguages,
          layout: window.google.translate.TranslateElement.InlineLayout.HORIZONTAL,
          autoDisplay: false, // Important to prevent auto-display of banner
        },
        'google_translate_element'
      );
      
      // Function to remove "Powered by" text
      const removePoweredBy = () => {
        const gadgets = document.querySelectorAll('.goog-te-gadget, .goog-te-gadget-simple');
        gadgets.forEach(gadget => {
          // Hide all spans except the one containing the select
          const spans = gadget.querySelectorAll('span');
          spans.forEach(span => {
            if (!span.querySelector('select') && !span.querySelector('.goog-te-combo')) {
              span.style.display = 'none';
              span.style.visibility = 'hidden';
              span.style.fontSize = '0';
            }
          });
          
          // Remove text nodes containing "Powered by"
          const walker = document.createTreeWalker(
            gadget,
            NodeFilter.SHOW_TEXT,
            null
          );
          let node;
          while (node = walker.nextNode()) {
            if (node.textContent && (
              node.textContent.trim().includes('Powered by') ||
              node.textContent.trim().includes('powered by') ||
              (node.textContent.trim().includes('Google') && !node.parentElement?.querySelector('select'))
            )) {
              // Check if it's not inside the select dropdown
              let parent = node.parentElement;
              let isInSelect = false;
              while (parent && parent !== gadget) {
                if (parent.tagName === 'SELECT' || parent.classList.contains('goog-te-combo')) {
                  isInSelect = true;
                  break;
                }
                parent = parent.parentElement;
              }
              if (!isInSelect) {
                node.textContent = '';
              }
            }
          }
        });
      };
      
      // Run removal immediately and after a short delay
      setTimeout(removePoweredBy, 100);
      setTimeout(removePoweredBy, 500);
      setTimeout(removePoweredBy, 1000);
      
      // More comprehensive CSS to handle various states
      const style = document.createElement('style');
      style.setAttribute('data-google-translate-style', 'true');
      style.innerHTML = `
        /* Hide Google Translate banner and preloader */
        .goog-te-banner-frame,
        .goog-te-spinner-pos {
          display: none !important;
          visibility: hidden !important;
        }
        
        iframe.skiptranslate {
          display: none !important;
          visibility: hidden !important;
        }
        
        /* Prevent the body from being shifted */
        body {
          top: 0 !important;
          position: static !important;
        }
        
        /* Language selector styling - Header Theme - Top Info Style */
        /* Hide "Powered by" text using font-size: 0 technique */
        .goog-te-gadget {
          display: inline-block !important;
          color: #ffffff !important;
          font-family: "Open Sans", sans-serif !important;
          font-size: 0 !important;
          line-height: 18px !important;
        }
        
        /* Reset font-size for the select dropdown - Match top-info style */
        .goog-te-gadget select,
        .goog-te-gadget .goog-te-combo,
        select.goog-te-combo {
          font-size: 14px !important;
        }
        
        /* Remove "Powered by" text - comprehensive hiding */
        .goog-te-gadget span {
          display: none !important;
          font-size: 0 !important;
          visibility: hidden !important;
        }
        
        .goog-te-gadget .goog-te-gadget-text {
          display: none !important;
        }
        
        .goog-te-gadget-simple {
          font-size: 0 !important;
        }
        
        .goog-te-gadget-simple .goog-te-combo {
          font-size: 14px !important;
        }
        
        /* Show only the dropdown - Clean Top Info Style with Visible Dropdown */
        .goog-te-gadget .goog-te-combo {
          display: inline-block !important;
          padding: 4px 8px 4px 24px !important;
          width: auto !important;
          min-width: 100px !important;
          border: 1px solid rgba(255, 255, 255, 0.3) !important;
          border-radius: 3px !important;
          height: auto !important;
          line-height: 18px !important;
          font-family: "Open Sans", sans-serif !important;
          font-size: 14px !important;
          font-weight: 400 !important;
          color: #ffffff !important;
          background-color: rgba(255, 255, 255, 0.1) !important;
          background-image: url('data:image/svg+xml;charset=UTF-8,<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12"><path fill="%23ffffff" d="M6 9L1 4h10z"/></svg>') !important;
          background-repeat: no-repeat !important;
          background-position: left 6px center !important;
          background-size: 10px !important;
          cursor: pointer !important;
          outline: none !important;
          letter-spacing: 0 !important;
          -webkit-appearance: none !important;
          -moz-appearance: none !important;
          appearance: none !important;
          vertical-align: middle !important;
          transition: all 0.3s !important;
        }
        
        /* Top-info wrapper styling for translate widget */
        .top-info.header-translate {
          display: inline-block !important;
          position: relative !important;
          float: left !important;
        }
        
        .top-info.header-translate .goog-te-gadget {
          display: inline-block !important;
          vertical-align: middle !important;
        }
        
        .top-info.header-translate .goog-te-combo {
          font-size: 14px !important;
          font-family: "Open Sans", sans-serif !important;
          font-weight: 400 !important;
          line-height: 18px !important;
          color: #ffffff !important;
          margin-left: 0 !important;
          display: inline-block !important;
          vertical-align: middle !important;
        }
        
        /* Menu item wrapper styling for translate widget (backwards compatibility) */
        .header-translate-menu .goog-te-combo {
          font-size: 20px !important;
        }
        
        /* Hover effect with theme colors - gold accent */
        .top-info.header-translate .goog-te-combo:hover {
          color: #ffffff !important;
          background-color: rgba(255, 255, 255, 0.15) !important;
          border-color: #ae9548 !important;
        }
        
        .top-info.header-translate .goog-te-combo:focus {
          outline: none !important;
          color: #ffffff !important;
          border-color: #ae9548 !important;
        }
        
        /* Menu item hover color (for backwards compatibility if used in menu) */
        .header-translate-menu .goog-te-combo:hover {
          color: #ae9548 !important;
        }
        
        .header-translate-menu:hover .goog-te-combo {
          color: #ae9548 !important;
        }
        
        /* Fix for the dropdown */
        select.goog-te-combo {
          max-width: 100% !important;
          box-sizing: border-box !important;
        }
        
        /* Style dropdown options - Dark background with readable text */
        select.goog-te-combo option {
          background-color: #ffffff !important;
          color: #242424 !important;
          padding: 8px 12px !important;
          font-size: 14px !important;
          font-family: "Open Sans", sans-serif !important;
        }
        
        /* Selected option styling */
        select.goog-te-combo option:checked,
        select.goog-te-combo option:focus {
          background-color: #ae9548 !important;
          color: #ffffff !important;
        }
        
        /* Header-specific wrapper styling - Menu Item */
        .header-translate-menu {
          margin-left: 0 !important;
          margin-right: 0 !important;
          display: inline-block !important;
          vertical-align: middle !important;
          line-height: normal !important;
        }
        
        .header-translate-menu .goog-te-gadget {
          display: inline-block !important;
          vertical-align: middle !important;
        }
        
        /* Make translate widget match menu item styling */
        .header-translate-menu a {
          display: inline-block !important;
          padding: 0 !important;
        }
        
        /* Ensure dropdown is visible and styled as menu item */
        .header-translate-menu .goog-te-combo {
          vertical-align: middle !important;
          margin-top: 0 !important;
        }
        
        /* Old header-translate class for backwards compatibility */
        .header-translate .goog-te-gadget {
          display: inline-block !important;
        }
        
        .header-translate {
          display: inline-flex !important;
          align-items: center !important;
          height: 100% !important;
        }
        
        /* Additional styling for dropdown when opened - Clean visible dropdown */
        .goog-te-menu-frame {
          border-radius: 4px !important;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
        }
        
        .goog-te-menu-value {
          color: #242424 !important;
        }
        
        /* Dropdown menu - White background for readability with theme colors */
        .goog-te-menu2 {
          background-color: #ffffff !important;
          border: 1px solid rgba(0, 0, 0, 0.1) !important;
          border-radius: 4px !important;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
          padding: 4px 0 !important;
        }
        
        .goog-te-menu2 .goog-te-menu2-item {
          color: #242424 !important;
          font-family: "Open Sans", sans-serif !important;
          font-size: 14px !important;
          padding: 8px 12px !important;
          background-color: transparent !important;
        }
        
        .goog-te-menu2 .goog-te-menu2-item:hover,
        .goog-te-menu2 .goog-te-menu2-item-selected {
          background-color: #ae9548 !important;
          color: #ffffff !important;
        }
        
        /* Ensure country flags are visible in dropdown */
        .goog-te-menu2 .goog-te-menu2-item .text {
          display: inline-block !important;
          margin-left: 24px !important;
        }
        
        /* Flag images in dropdown */
        .goog-te-menu2 .goog-te-menu2-item img {
          display: inline-block !important;
          margin-right: 8px !important;
          vertical-align: middle !important;
          width: 16px !important;
          height: 12px !important;
        }
        
        /* Translation animation fixes */
        .goog-text-highlight {
          background-color: transparent !important;
          box-shadow: none !important;
        }
        
        /* Hide Google Translate hover popups/tooltips */
        .goog-te-balloon-frame,
        .goog-tooltip,
        .goog-tooltip:hover,
        #goog-gt-tt,
        .goog-te-menu-frame,
        .goog-te-menu-value,
        .goog-te-balloon,
        .goog-te-ftab,
        #gt-nvframe {
          display: none !important;
          visibility: hidden !important;
          opacity: 0 !important;
          pointer-events: none !important;
        }
        
        /* Remove ALL hover effects on translated text */
        font[style*="background-color"],
        font[style*="background:"],
        font:hover,
        span.notranslate:hover,
        .translated-ltr font,
        .translated-rtl font {
          background-color: transparent !important;
          background: transparent !important;
          box-shadow: none !important;
          outline: none !important;
          border: none !important;
          cursor: inherit !important;
        }
        
        /* Disable pointer events on Google Translate font wrappers */
        body.translated-ltr font,
        body.translated-rtl font,
        html.translated-ltr font,
        html.translated-rtl font {
          pointer-events: none !important;
          user-select: text !important;
          -webkit-user-select: text !important;
          cursor: inherit !important;
        }
        
        /* Re-enable pointer events on actual interactive elements */
        body.translated-ltr a font,
        body.translated-rtl a font,
        body.translated-ltr button font,
        body.translated-rtl button font,
        body.translated-ltr input font,
        body.translated-rtl input font {
          pointer-events: auto !important;
        }
        
        /* Remove Google Translate selection styling */
        ::selection {
          background-color: highlight !important;
        }
        
        /* Hide the floating Google Translate edit box */
        #goog-gt-tt,
        .goog-te-spinner-pos,
        .VIpgJd-ZVi9od-xl07Ob-lTBxed,
        .VIpgJd-ZVi9od-aZ2wEe-wOHMyf,
        .VIpgJd-ZVi9od-aZ2wEe-OiiCO {
          display: none !important;
          visibility: hidden !important;
        }
        
        /* Hide the translate widget container completely */
        #google_translate_element {
          position: fixed !important;
          left: -9999px !important;
          top: -9999px !important;
          width: 0 !important;
          height: 0 !important;
          overflow: hidden !important;
          visibility: hidden !important;
          pointer-events: none !important;
          z-index: -9999 !important;
        }
        
        /* Hide any Google Translate related popups */
        div[id^="goog-gt-"],
        div[class^="goog-te-"] {
          display: none !important;
          visibility: hidden !important;
        }
        
        /* Keep the hidden select functional but invisible */
        .goog-te-gadget,
        .goog-te-combo {
          position: fixed !important;
          left: -9999px !important;
          top: -9999px !important;
          visibility: hidden !important;
        }
      `;
      document.head.appendChild(style);
      
      // Observer to monitor and correct any changes Google Translate might make
      if (observerRef.current) {
        observerRef.current.disconnect();
      }
      
      observerRef.current = new MutationObserver((mutations) => {
        // Force body position to stay at top: 0
        if (document.body.style.top && document.body.style.top !== '0px') {
          document.body.style.top = '0px';
        }
        
        // Hide any Google Translate frames that might appear
        const frames = document.querySelectorAll('.goog-te-banner-frame, .goog-te-spinner-pos');
        frames.forEach(frame => {
          frame.style.display = 'none';
          frame.style.visibility = 'hidden';
        });
        
        // Remove "Powered by" text
        removePoweredBy();
      });
      
      observerRef.current.observe(document.body, { 
        attributes: true, 
        childList: true,
        subtree: true
      });
    };

    // Create script element to load the Google Translate script
    const script = document.createElement('script');
    script.src = '//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit';
    script.async = true;
    document.body.appendChild(script);

    // Clean up when component unmounts
    return () => {
      if (observerRef.current) {
        observerRef.current.disconnect();
      }
      
      if (script.parentNode) {
        document.body.removeChild(script);
      }
      
      delete window.googleTranslateElementInit;
      
      // Remove added styles
      document.querySelectorAll('style[data-google-translate-style], style[data-google-translate-early-style]').forEach(el => {
        if (el.parentNode) {
          el.parentNode.removeChild(el);
        }
      });
    };
  }, []);

  // Hidden container - LanguageSwitcher will trigger translations
  return (
    <div 
      id="google_translate_element" 
      className="notranslate"
      style={{ 
        position: 'fixed',
        left: '-9999px',
        top: '-9999px',
        width: 0,
        height: 0,
        overflow: 'hidden',
        visibility: 'hidden',
        pointerEvents: 'none',
        zIndex: -9999
      }} 
    />
  );
};

export default GoogleTranslateWidget;
