'use client';

import { useTranslations } from 'next-intl';

import LiteYouTubeEmbed from 'react-lite-youtube-embed';
import 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css';

interface YoutubeVideoProps {
  id: string | null | undefined;
  title?: string;
  backgroundSize?: 'contain' | 'cover';
  onPlayStart?: () => void;
  poster?: 'default' | 'mqdefault' | 'hqdefault' | 'sddefault' | 'maxresdefault';
  /**
   * Load the real iframe immediately and start playing. Skips the lazy-load
   * placeholder — use only when playback is already user-initiated (e.g. inside
   * a modal the user just opened). Consent gating still applies via
   * VideoConsentObserver, which targets the generated iframe.
   */
  autoplay?: boolean;
}

export const extractYouTubeId = (input: string | null | undefined): string | null => {
  if (!input) return null;

  // If it's already just the video ID (11 characters)
  if (typeof input === 'string' && input.length === 11 && !/[\/=&?]/.test(input)) {
    return input;
  }

  // Handle array format (your current case)
  if (Array.isArray(input) && input[1]) {
    return extractYouTubeId(input[1]);
  }

  // Handle full YouTube URLs
  const url = typeof input === 'string' ? input : String(input);

  // Match various YouTube URL formats
  const patterns = [
    /(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/,
    /youtube\.com\/watch\?.*v=([a-zA-Z0-9_-]{11})/,
    /youtu\.be\/([a-zA-Z0-9_-]{11})/,
  ];

  for (const pattern of patterns) {
    const match = url.match(pattern);
    if (match && match[1]) {
      return match[1];
    }
  }

  return null;
};

const YouTubeVideo: React.FC<YoutubeVideoProps> = ({
  id,
  title,
  backgroundSize = 'contain',
  onPlayStart,
  poster = 'hqdefault',
  autoplay = false,
}) => {
  const t = useTranslations('accessibility');
  const accessibleTitle = title || t('video');

  if (!id) return null;

  const videoId = extractYouTubeId(id);

  if (!videoId) {
    console.error('Invalid YouTube video ID:', id);
    return null;
  }

  if (autoplay) {
    return (
      <iframe
        className="h-full w-full"
        src={`https://www.youtube.com/embed/${videoId}?autoplay=1&rel=0&playsinline=1`}
        title={accessibleTitle}
        frameBorder={0}
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
        allowFullScreen
      />
    );
  }

  return (
    <LiteYouTubeEmbed
      wrapperClass="w-full h-full yt-lite relative flex items-center justify-center"
      playerClass="youtube-play-button"
      id={videoId}
      title={accessibleTitle}
      onIframeAdded={onPlayStart}
      style={{
        backgroundSize: backgroundSize,
        backgroundRepeat: 'no-repeat',
      }}
      poster={poster}
    />
  );
};

export default YouTubeVideo;
