'use client';

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

// ─── Supported languages ──────────────────────────────────────────────────────
export const SUPPORTED_LANGUAGES = [
  { code: 'en', name: 'English',    nativeName: 'English',    flag: '🇺🇸', dir: 'ltr' },
  { code: 'es', name: 'Spanish',    nativeName: 'Español',    flag: '🇪🇸', dir: 'ltr' },
  { code: 'pt', name: 'Portuguese', nativeName: 'Português',  flag: '🇧🇷', dir: 'ltr' },
  { code: 'fr', name: 'French',     nativeName: 'Français',   flag: '🇫🇷', dir: 'ltr' },
  { code: 'de', name: 'German',     nativeName: 'Deutsch',    flag: '🇩🇪', dir: 'ltr' },
  { code: 'zh', name: 'Chinese',    nativeName: '中文',        flag: '🇨🇳', dir: 'ltr' },
  { code: 'ja', name: 'Japanese',   nativeName: '日本語',      flag: '🇯🇵', dir: 'ltr' },
  { code: 'ar', name: 'Arabic',     nativeName: 'العربية',    flag: '🇦🇪', dir: 'rtl' },
  { code: 'hi', name: 'Hindi',      nativeName: 'हिंदी',       flag: '🇮🇳', dir: 'ltr' },
] as const;

export type LangCode = typeof SUPPORTED_LANGUAGES[number]['code'];

// ─── Cookie helpers ───────────────────────────────────────────────────────────
function getLangCookie(): LangCode | null {
  if (typeof document === 'undefined') return null;
  const match = document.cookie.match(/(?:^|;\s*)lang_pref=([^;]+)/);
  return (match?.[1] as LangCode) || null;
}

function setLangCookie(lang: LangCode) {
  const expires = new Date();
  expires.setFullYear(expires.getFullYear() + 1); // 365 days
  document.cookie = `lang_pref=${lang}; expires=${expires.toUTCString()}; path=/; SameSite=Lax`;
}

// ─── Browser language detection ──────────────────────────────────────────────
// Strategy (in order):
//   1. If the user's timezone is in an English-speaking region (US/CA/UK/AU/NZ),
//      always return 'en'. This avoids the case where a US user has an OS
//      locale of pt-BR or es-MX accidentally set but is clearly browsing
//      from the US.
//   2. Otherwise walk navigator.languages (the full preference list) and
//      return the first base code we support.
//   3. Fallback to 'en'.
function detectBrowserLang(): LangCode {
  if (typeof navigator === 'undefined') return 'en';

  const supported = new Set(SUPPORTED_LANGUAGES.map(l => l.code as string));

  // 1. Timezone → English-region override
  try {
    const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || '';
    const englishRegions = [
      'America/',          // US, Canada, most of Latin America (we still bias en here — see note)
      'Pacific/Honolulu',
      'Pacific/Auckland', 'Pacific/Wellington',
      'Australia/',
      'Europe/London', 'Europe/Dublin',
      'Atlantic/Reykjavik',
    ];
    // For America/* we want en specifically for US/CA/etc. Latin America also
    // matches America/* — but English is widely understood and we don't have
    // localized content; better to default to en and let the user opt into
    // another language via the pulldown.
    if (englishRegions.some(prefix => tz === prefix || tz.startsWith(prefix))) {
      return 'en';
    }
  } catch {
    // Intl unavailable — fall through
  }

  // 2. Walk navigator.languages and pick first supported
  const langList: string[] = Array.isArray(navigator.languages) && navigator.languages.length > 0
    ? Array.from(navigator.languages)
    : (navigator.language ? [navigator.language] : ['en']);

  for (const raw of langList) {
    const base = raw.toLowerCase().split('-')[0];
    if (supported.has(base)) return base as LangCode;
  }

  return 'en';
}

// ─── Language Switcher Component ─────────────────────────────────────────────
interface LanguageSwitcherProps {
  currentLang?: LangCode;
  onLanguageChange?: (lang: LangCode) => void;
  compact?: boolean;
}

export default function LanguageSwitcher({ currentLang, onLanguageChange, compact = false }: LanguageSwitcherProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [activeLang, setActiveLang] = useState<LangCode>('en');
  const dropdownRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Priority: prop > cookie > 'en'. We intentionally do NOT auto-detect
    // the browser locale here — site content is English-only at this
    // point, so showing "FR" on a French-locale browser misrepresents
    // the page. Users opt into another language by picking it in the
    // dropdown, which then writes the cookie.
    const lang = currentLang || getLangCookie() || 'en';
    setActiveLang(lang);

    // Apply RTL if Arabic
    if (typeof document !== 'undefined') {
      const html = document.documentElement;
      const langData = SUPPORTED_LANGUAGES.find(l => l.code === lang);
      if (langData?.dir === 'rtl') {
        html.setAttribute('dir', 'rtl');
        html.setAttribute('lang', lang);
      } else {
        html.setAttribute('dir', 'ltr');
        html.setAttribute('lang', lang);
      }
    }
  }, [currentLang]);

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
        setIsOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const handleSelect = (lang: LangCode) => {
    setActiveLang(lang);
    setLangCookie(lang);
    setIsOpen(false);

    // Apply RTL for Arabic + update <html lang>
    const langData = SUPPORTED_LANGUAGES.find(l => l.code === lang);
    if (typeof document !== 'undefined') {
      const html = document.documentElement;
      html.setAttribute('dir', langData?.dir === 'rtl' ? 'rtl' : 'ltr');
      html.setAttribute('lang', lang);
    }

    onLanguageChange?.(lang);

    // Non-English: route the current page through Google Translate's hosted
    // proxy so the user actually sees translated content. English is the
    // canonical/indexable version and just stays put.
    if (lang !== 'en' && typeof window !== 'undefined') {
      const host = window.location.hostname.replace(/\./g, '-');
      const path = window.location.pathname + window.location.search;
      const proxied = `https://${host}.translate.goog${path}?_x_tr_sl=en&_x_tr_tl=${lang}&_x_tr_hl=en`;
      window.location.href = proxied;
    }
  };

  const currentLangData = SUPPORTED_LANGUAGES.find(l => l.code === activeLang) || SUPPORTED_LANGUAGES[0];

  return (
    <div ref={dropdownRef} className="relative z-[100]">
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-1.5 px-2 py-1 rounded text-xs text-[#888] hover:text-white hover:bg-[#FFFFFF] transition-colors focus:outline-none focus-visible:ring-1 focus-visible:ring-[#1D4ED8]"
        aria-label={`Language: ${currentLangData.name}. Click to change.`}
        aria-expanded={isOpen}
        aria-haspopup="listbox"
      >
        <span className="text-sm leading-none">{currentLangData.flag}</span>
        {!compact && (
          <span className="hidden sm:inline">{currentLangData.nativeName}</span>
        )}
        <svg className={`w-3 h-3 transition-transform ${isOpen ? 'rotate-180' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {isOpen && (
        <div
          className="absolute top-full mt-1 right-0 bg-[#111] border border-[#333] rounded-lg shadow-xl z-[100] min-w-[160px] py-1"
          role="listbox"
          aria-label="Select language"
        >
          {SUPPORTED_LANGUAGES.map(lang => (
            <button
              key={lang.code}
              role="option"
              aria-selected={activeLang === lang.code}
              onClick={() => handleSelect(lang.code)}
              className={`w-full flex items-center gap-2.5 px-3 py-2 text-xs transition-colors text-left ${
                activeLang === lang.code
                  ? 'bg-[#1D4ED8]/10 text-[#1D4ED8]'
                  : 'text-[#888] hover:text-white hover:bg-[#FFFFFF]'
              }`}
            >
              <span className="text-sm">{lang.flag}</span>
              <span>{lang.nativeName}</span>
              {activeLang === lang.code && (
                <svg className="w-3 h-3 ml-auto text-[#1D4ED8]" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                </svg>
              )}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── Hook for consuming language preference ───────────────────────────────────
export function useLanguage() {
  const [lang, setLang] = useState<LangCode>('en');

  useEffect(() => {
    const stored = getLangCookie() || detectBrowserLang();
    setLang(stored);
  }, []);

  const changeLang = (newLang: LangCode) => {
    setLang(newLang);
    setLangCookie(newLang);
  };

  const isRTL = SUPPORTED_LANGUAGES.find(l => l.code === lang)?.dir === 'rtl';

  return { lang, changeLang, isRTL };
}
