'use client';

import { useEffect } from 'react';

export default function VideoConsentObserver(): null {
  useEffect(() => {
    function handleYouTubeEmbeds(): void {
      const consent = localStorage.getItem('azopus-cookie-consent');
      let hasYouTubeConsent = false;

      if (consent) {
        const allowedCookies = consent.split('@')[0].split(',');
        hasYouTubeConsent =
          allowedCookies.includes('MARKETING') && allowedCookies.includes('FUNCTIONAL');
      }

      // If consent is given, replace placeholders back to iframes
      if (hasYouTubeConsent) {
        const placeholders = document.querySelectorAll('.youtube-consent-placeholder');
        placeholders.forEach((placeholder) => {
          // Look for original iframe data (if we saved it)
          const originalSrc = (placeholder as HTMLElement).dataset.originalSrc;

          if (originalSrc) {
            const newIframe = document.createElement('iframe');
            newIframe.src = originalSrc;
            newIframe.style.width = (placeholder as HTMLElement).style.width;
            newIframe.style.height = (placeholder as HTMLElement).style.height;
            newIframe.frameBorder = '0';
            newIframe.allow =
              'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
            newIframe.allowFullscreen = true;

            placeholder.parentNode?.replaceChild(newIframe, placeholder);
          }
        });
        return; // If consent exists, don't continue with placeholder creation
      }

      // Find all YouTube iframes that haven't been processed yet
      const youtubeIframes = document.querySelectorAll(
        'iframe[src*="youtube.com"]:not([data-consent-handled]), iframe[src*="youtube-nocookie.com"]:not([data-consent-handled])'
      );

      youtubeIframes.forEach((iframe) => {
        const iframeElement = iframe as HTMLIFrameElement;

        // Mark as handled to avoid processing again
        iframeElement.dataset.consentHandled = 'true';

        // Extract video ID from src
        const videoId = extractYouTubeId(iframeElement.src);

        // Create placeholder
        const placeholder = createYouTubePlaceholder(videoId, iframeElement);

        // Replace iframe with placeholder
        iframeElement.parentNode?.replaceChild(placeholder, iframeElement);
      });
    }

    function extractYouTubeId(url: string): string | null {
      const match = url.match(/(?:youtube\.com\/embed\/|youtube-nocookie\.com\/embed\/)([^?&]+)/);
      return match ? match[1] : null;
    }

    function createYouTubePlaceholder(
      videoId: string | null,
      originalIframe: HTMLIFrameElement
    ): HTMLDivElement {
      const placeholder = document.createElement('div');
      placeholder.className =
        'youtube-consent-placeholder relative bg-gray-800 flex flex-col items-center justify-center text-white p-4';
      placeholder.style.width = originalIframe.offsetWidth
        ? originalIframe.offsetWidth + 'px'
        : '100%';
      placeholder.style.height = originalIframe.offsetHeight
        ? originalIframe.offsetHeight + 'px'
        : '315px';
      placeholder.style.minHeight = '200px';

      // Save original iframe data
      placeholder.dataset.videoId = videoId || '';
      placeholder.dataset.originalSrc = originalIframe.src;

      placeholder.innerHTML = `
        <div class="text-center mb-4">
          <div class="text-lg font-bold mb-2">YouTube videó</div>
          <div class="text-sm opacity-75 mb-4">
            A videó megtekintéséhez <a href="/sutitajekoztato" class="force-white">sütiket</a> kell elfogadnia!
          </div>
        </div>
        <button class="bg-mma-blue hover:bg-mma-yellow px-4 py-2 rounded text-mma-yellow hover:text-mma-blue font-bold transition-colors youtube-load-btn">
          Elfogadom
        </button>
      `;

      // Add click handler to accept cookies and load video
      const loadBtn = placeholder.querySelector('.youtube-load-btn') as HTMLButtonElement;
      loadBtn?.addEventListener('click', (event) => {
        event.stopPropagation();
        event.preventDefault();

        // Update cookie consent
        const currentConsent = localStorage.getItem('azopus-cookie-consent') || '';
        const parts = currentConsent.split('@');
        const cookieArray = parts[0] ? parts[0].split(',') : ['MANDATORY'];

        // Add MARKETING and FUNCTIONAL if not already present
        if (!cookieArray.includes('MARKETING')) cookieArray.push('MARKETING');
        if (!cookieArray.includes('FUNCTIONAL')) cookieArray.push('FUNCTIONAL');

        // Update localStorage
        localStorage.setItem('azopus-cookie-consent', cookieArray.join(',') + '@' + Date.now());

        // Process all YouTube embeds now that consent is given
        handleYouTubeEmbeds();
      });

      return placeholder;
    }

    const checkYouTubeEmbeds = (): void => {
      setTimeout(() => {
        handleYouTubeEmbeds();
      }, 100); // Small delay to ensure content is rendered
    };

    // Run on initial load
    checkYouTubeEmbeds();

    // Run whenever the DOM changes (for dynamic content)
    const observer = new MutationObserver((mutations: MutationRecord[]) => {
      let shouldCheck = false;
      mutations.forEach((mutation) => {
        if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
          // Check if any added nodes contain iframes
          mutation.addedNodes.forEach((node) => {
            if (node.nodeType === Node.ELEMENT_NODE) {
              const element = node as Element;
              if (element.tagName === 'IFRAME' || element.querySelector('iframe')) {
                shouldCheck = true;
              }
            }
          });
        }
      });

      if (shouldCheck) {
        checkYouTubeEmbeds();
      }
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true,
    });

    // listen for custom event sent by the CookieModal
    const handleCustomEvent = (): void => {
      checkYouTubeEmbeds();
    };

    window.addEventListener('reCheckYouTubeEmbeds', handleCustomEvent);

    // cleanup
    return () => {
      observer.disconnect();
      window.removeEventListener('reCheckYouTubeEmbeds', handleCustomEvent);
    };
  }, []);

  return null;
}
