'use client'

import { ChevronDown, Globe } from 'lucide-react'
import Image from 'next/image'
import Link from 'next/link'
import { useEffect, useRef, useState } from 'react'
import {
  type DashboardLanguage,
  useDashboardI18n,
} from '@/components/I18nProvider'
import { marketplaceUrl } from '@/lib/urls'

const DASHBOARD_LOGO_SRC = '/dashboard/rentalcardrive.png'

type FooterItem = {
  label: string
  href?: string
}

const localeOptions: Array<{ value: DashboardLanguage; label: string }> = [
  { value: 'en', label: 'Global (English)' },
  { value: 'ar', label: 'NorthAfrica (Arabic)' },
  { value: 'fr', label: 'Europ (French)' },
]

function getFooterContent(language: DashboardLanguage): {
  primary: FooterItem[]
  secondary: FooterItem[]
  localeLabel: string
  rightsLabel: string
} {
  switch (language) {
    case 'fr':
      return {
        primary: [
          { label: 'À propos de nous', href: `${marketplaceUrl}/footer/about-us` },
          { label: 'Conditions d’utilisation', href: `${marketplaceUrl}/footer/terms-of-service` },
          { label: 'Sécurité', href: `${marketplaceUrl}/footer/security` },
          { label: 'Conformité', href: `${marketplaceUrl}/footer/compliance` },
          { label: 'Politique de confidentialité', href: `${marketplaceUrl}/footer/privacy-policy` },
          { label: 'Politique relative aux cookies', href: `${marketplaceUrl}/footer/cookie-policy` },
        ],
        secondary: [
          { label: 'Newsletter', href: `${marketplaceUrl}/footer/newsletter` },
          { label: 'Contacter les ventes', href: `${marketplaceUrl}/footer/contact-sales` },
          { label: 'Nos bureaux', href: `${marketplaceUrl}/footer/our-offices` },
        ],
        localeLabel: 'Europ (French)',
        rightsLabel: 'Tous droits réservés.',
      }
    case 'ar':
      return {
        primary: [
          { label: 'من نحن', href: `${marketplaceUrl}/footer/about-us` },
          { label: 'شروط الاستخدام', href: `${marketplaceUrl}/footer/terms-of-service` },
          { label: 'الأمان', href: `${marketplaceUrl}/footer/security` },
          { label: 'الامتثال', href: `${marketplaceUrl}/footer/compliance` },
          { label: 'سياسة الخصوصية', href: `${marketplaceUrl}/footer/privacy-policy` },
          { label: 'سياسة ملفات تعريف الارتباط', href: `${marketplaceUrl}/footer/cookie-policy` },
        ],
        secondary: [
          { label: 'النشرة الإخبارية', href: `${marketplaceUrl}/footer/newsletter` },
          { label: 'تواصل مع المبيعات', href: `${marketplaceUrl}/footer/contact-sales` },
          { label: 'مكاتبنا', href: `${marketplaceUrl}/footer/our-offices` },
        ],
        localeLabel: 'NorthAfrica (Arabic)',
        rightsLabel: 'جميع الحقوق محفوظة.',
      }
    case 'en':
    default:
      return {
        primary: [
          { label: 'About Us', href: `${marketplaceUrl}/footer/about-us` },
          { label: 'Terms of Service', href: `${marketplaceUrl}/footer/terms-of-service` },
          { label: 'Security', href: `${marketplaceUrl}/footer/security` },
          { label: 'Compliance', href: `${marketplaceUrl}/footer/compliance` },
          { label: 'Privacy Policy', href: `${marketplaceUrl}/footer/privacy-policy` },
          { label: 'Cookie Policy', href: `${marketplaceUrl}/footer/cookie-policy` },
        ],
        secondary: [
          { label: 'Newsletter', href: `${marketplaceUrl}/footer/newsletter` },
          { label: 'Contact Sales', href: `${marketplaceUrl}/footer/contact-sales` },
          { label: 'Our Offices', href: `${marketplaceUrl}/footer/our-offices` },
        ],
        localeLabel: 'Global (English)',
        rightsLabel: 'All rights reserved.',
      }
  }
}

export default function PublicShell({ children }: { children: React.ReactNode }) {
  const { language, setLanguage, theme, setTheme } = useDashboardI18n()
  const localeMenuRef = useRef<HTMLDivElement | null>(null)
  const [localeMenuOpen, setLocaleMenuOpen] = useState(false)
  const dict = {
    en: {
      home: 'Home',
      marketplace: 'Marketplace',
      signIn: 'Sign in',
      createAccount: 'Create account',
      preferences: 'Workspace preferences',
      theme: 'Theme',
      light: 'Light',
      medium: 'Medium',
      dark: 'Dark',
    },
    fr: {
      home: 'Accueil',
      marketplace: 'Marketplace',
      signIn: 'Connexion',
      createAccount: 'Créer un compte',
      preferences: 'Preferences espace',
      theme: 'Mode',
      light: 'Clair',
      medium: 'Moyen',
      dark: 'Sombre',
    },
    ar: {
      home: 'الرئيسية',
      marketplace: 'السوق',
      signIn: 'تسجيل الدخول',
      createAccount: 'إنشاء حساب',
      preferences: 'تفضيلات المساحة',
      theme: 'الوضع',
      light: 'فاتح',
      medium: 'متوسط',
      dark: 'داكن',
    },
  }[language]
  const footerContent = getFooterContent(language)
  const availableLocaleOptions = localeOptions.filter((option) => option.value !== language)

  useEffect(() => {
    function handlePointerDown(event: MouseEvent) {
      if (!localeMenuRef.current?.contains(event.target as Node)) {
        setLocaleMenuOpen(false)
      }
    }

    document.addEventListener('mousedown', handlePointerDown)
    return () => document.removeEventListener('mousedown', handlePointerDown)
  }, [])

  return (
    <div className="min-h-screen bg-[radial-gradient(circle_at_top,#dbeafe,transparent_35%),linear-gradient(180deg,#f8fafc,white)] transition-colors dark:bg-[radial-gradient(circle_at_top,rgba(37,99,235,0.18),transparent_35%),linear-gradient(180deg,#020617,#0f172a)] dark:text-slate-100">
      <header className="sticky top-0 z-30 border-b border-stone-200 bg-white/85 backdrop-blur-md transition-colors dark:border-stone-800 dark:bg-stone-950/85">
        <div className="mx-auto flex max-w-7xl flex-col gap-3 px-4 py-3 sm:px-6 lg:flex-row lg:items-center lg:justify-between lg:px-8 lg:py-2">
          <a href={marketplaceUrl} className="flex items-center gap-3 text-sm font-bold uppercase tracking-[0.2em] text-stone-900 dark:text-stone-100">
            <Image
              src={DASHBOARD_LOGO_SRC}
              alt="RentalDriveGo"
              width={36}
              height={36}
              className="h-9 w-9 rounded-md object-contain"
            />
            <span>RentalDriveGo</span>
          </a>

          <div className="flex flex-col gap-3 lg:flex-row lg:items-center">
            <nav className="flex items-center gap-1 overflow-x-auto">
              <a href={marketplaceUrl} className="rounded-full px-4 py-2 text-sm font-medium text-stone-600 transition hover:bg-stone-100 hover:text-stone-900 dark:text-stone-300 dark:hover:bg-stone-800 dark:hover:text-stone-100">
                {dict.home}
              </a>
              <a href={`${marketplaceUrl}/explore`} className="rounded-full px-4 py-2 text-sm font-medium text-stone-600 transition hover:bg-stone-100 hover:text-stone-900 dark:text-stone-300 dark:hover:bg-stone-800 dark:hover:text-stone-100">
                {dict.marketplace}
              </a>
              <a href={`${marketplaceUrl}/sign-in`} className="rounded-full px-4 py-2 text-sm font-medium text-stone-600 transition hover:bg-stone-100 hover:text-stone-900 dark:text-stone-300 dark:hover:bg-stone-800 dark:hover:text-stone-100">
                {dict.signIn}
              </a>
              <Link href="/sign-up" className="ml-2 rounded-full bg-stone-900 px-5 py-2 text-sm font-semibold text-white transition hover:bg-stone-700 dark:bg-amber-400 dark:text-stone-950 dark:hover:bg-amber-300">
                {dict.createAccount}
              </Link>
            </nav>
            <div className="shrink-0">
              <div className="flex items-center gap-2 rounded-full border border-stone-200/70 bg-white/90 px-2 py-1 shadow-sm dark:border-stone-700 dark:bg-stone-900/80">
                <span className="px-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-stone-500 dark:text-stone-400">
                  {dict.theme}
                </span>
                {(['light', 'medium', 'dark'] as const).map((value) => {
                  const active = value === theme
                  return (
                    <button
                      key={value}
                      type="button"
                      onClick={() => setTheme(value)}
                      className={`rounded-full px-3 py-1.5 text-xs font-semibold transition ${
                        active
                          ? 'bg-stone-900 text-white dark:bg-amber-400 dark:text-stone-950'
                          : 'text-stone-600 hover:bg-stone-100 dark:text-stone-300 dark:hover:bg-stone-800'
                      }`}
                    >
                      {value === 'light' ? dict.light : value === 'medium' ? dict.medium : dict.dark}
                    </button>
                  )
                })}
              </div>
            </div>
          </div>
        </div>
      </header>
      <div>{children}</div>
      <footer className="border-t border-stone-200 bg-white/90 px-4 py-8 text-stone-600 transition-colors dark:border-white/5 dark:bg-[#111111] dark:text-stone-300">
        <div className="mx-auto flex max-w-7xl flex-col items-center gap-5 text-center px-0 sm:px-2 lg:px-0">
          <nav className="flex flex-wrap items-center justify-center gap-y-3 text-sm">
            {footerContent.primary.map((item, index) => (
              <div key={item.label} className="flex items-center">
                <FooterNavItem item={item} />
                {index < footerContent.primary.length - 1 ? (
                  <span className="px-2 text-stone-400 dark:text-stone-600" aria-hidden="true">|</span>
                ) : null}
              </div>
            ))}
          </nav>

          <div className="flex flex-wrap items-center justify-center gap-y-3 text-sm">
            {footerContent.secondary.map((item) => (
              <div key={item.label} className="flex items-center">
                <FooterNavItem item={item} />
                <span className="px-2 text-stone-400 dark:text-stone-600" aria-hidden="true">|</span>
              </div>
            ))}
            <div ref={localeMenuRef} className="relative px-3">
              <button
                type="button"
                onClick={() => setLocaleMenuOpen((open) => !open)}
                className="inline-flex items-center gap-2 text-sky-600 transition hover:text-sky-700 dark:text-sky-400 dark:hover:text-sky-300"
                aria-expanded={localeMenuOpen}
                aria-haspopup="menu"
              >
                <Globe className="h-4 w-4" />
                <span>{footerContent.localeLabel}</span>
                <ChevronDown className={`h-4 w-4 transition-transform ${localeMenuOpen ? 'rotate-180' : ''}`} />
              </button>
              {localeMenuOpen ? (
                <div className="absolute left-1/2 top-full z-20 mt-3 w-56 -translate-x-1/2 overflow-hidden rounded-2xl border border-stone-200 bg-white/95 text-left shadow-[0_20px_60px_rgba(0,0,0,0.12)] backdrop-blur dark:border-stone-800 dark:bg-stone-950/95 dark:shadow-[0_20px_60px_rgba(0,0,0,0.35)]">
                  {availableLocaleOptions.map((option) => (
                    <button
                      key={option.value}
                      type="button"
                      onClick={() => {
                        setLanguage(option.value)
                        setLocaleMenuOpen(false)
                      }}
                      className="flex w-full items-center gap-3 px-4 py-3 text-sm text-stone-700 transition hover:bg-stone-100 hover:text-stone-950 dark:text-stone-200 dark:hover:bg-stone-900 dark:hover:text-white"
                    >
                      <Globe className="h-4 w-4 text-sky-600 dark:text-sky-400" />
                      <span>{option.label}</span>
                    </button>
                  ))}
                </div>
              ) : null}
            </div>
          </div>

          <p className="text-sm text-stone-500 dark:text-stone-400">
            &copy; {new Date().getFullYear()} RentalDriveGo. {footerContent.rightsLabel}
          </p>
        </div>
      </footer>
    </div>
  )
}

function FooterNavItem({ item }: { item: FooterItem }) {
  const className = 'px-3 text-stone-600 transition hover:text-stone-950 dark:text-stone-300 dark:hover:text-white'

  if (item.href) {
    return (
      <a href={item.href} className={className}>
        {item.label}
      </a>
    )
  }

  return <span className={className}>{item.label}</span>
}
