'use client'

import { motion, AnimatePresence } from 'motion/react'
import { Menu, X, Globe, ChevronDown } from 'lucide-react'
import Link from 'next/link'
import { useLanguage } from '@/lib/i18n'
import type { SupportedLanguage } from '@/lib/i18n/load-translations'
import { useEffect, useRef, useState, type ReactNode } from 'react'

const LANDING_LANGS: { code: SupportedLanguage; labelKey: string }[] = [
  { code: 'fr', labelKey: 'languages.fr' },
  { code: 'en', labelKey: 'languages.en' },
  { code: 'es', labelKey: 'languages.es' },
  { code: 'de', labelKey: 'languages.de' },
  { code: 'it', labelKey: 'languages.it' },
  { code: 'pt', labelKey: 'languages.pt' },
  { code: 'nl', labelKey: 'languages.nl' },
  { code: 'pl', labelKey: 'languages.pl' },
  { code: 'ru', labelKey: 'languages.ru' },
  { code: 'zh', labelKey: 'languages.zh' },
  { code: 'ja', labelKey: 'languages.ja' },
  { code: 'ko', labelKey: 'languages.ko' },
  { code: 'ar', labelKey: 'languages.ar' },
  { code: 'fa', labelKey: 'languages.fa' },
  { code: 'hi', labelKey: 'languages.hi' },
]

export type PublicSitePage = 'home' | 'pricing'

function resolvePublicHref(href: string, currentPage: PublicSitePage): string {
  if (!href.startsWith('#')) return href
  if (href === '#pricing' && currentPage === 'pricing') return '/pricing'
  if (currentPage === 'home') return href
  const id = href.replace(/^#/, '')
  return id === 'pricing' ? '/pricing' : `/#${id}`
}

export function PublicSiteChrome({
  children,
  currentPage,
  onHashNavigate,
}: {
  children: ReactNode
  currentPage: PublicSitePage
  onHashNavigate?: (hash: string) => void
}) {
  const { t, language, setLanguage } = useLanguage()
  const [menuOpen, setMenuOpen] = useState(false)
  const [langOpen, setLangOpen] = useState(false)
  const langRef = useRef<HTMLDivElement>(null)

  const NAV = [
    { href: '#product', label: t('landing.nav.secondBrain') },
    { href: '#echo', label: t('landing.nav.echo') },
    { href: '#agents', label: t('landing.nav.agents') },
    { href: '#pricing', label: t('landing.nav.pricing') },
  ]

  useEffect(() => {
    if (!langOpen) return
    const onPointer = (e: MouseEvent) => {
      if (langRef.current && !langRef.current.contains(e.target as Node)) setLangOpen(false)
    }
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setLangOpen(false)
    }
    document.addEventListener('mousedown', onPointer)
    document.addEventListener('keydown', onKey)
    return () => {
      document.removeEventListener('mousedown', onPointer)
      document.removeEventListener('keydown', onKey)
    }
  }, [langOpen])

  useEffect(() => {
    const root = document.querySelector<HTMLElement>('[data-public-scroll-root]')
    if (!root) return
    const prev = root.style.overflow
    if (menuOpen) root.style.overflow = 'hidden'
    else root.style.overflow = prev || ''
    return () => { root.style.overflow = prev }
  }, [menuOpen])

  const goSection = (event: React.MouseEvent<HTMLAnchorElement>, hash: string) => {
    setMenuOpen(false)
    if (currentPage === 'home' && onHashNavigate) {
      event.preventDefault()
      onHashNavigate(hash)
      window.history.replaceState(null, '', hash)
    }
  }

  return (
    <div className="min-h-screen bg-[#0B0A09] text-[#F4F1EA] font-[family-name:var(--font-manrope)] selection:bg-[#D4A373]/40 selection:text-white">
      <nav className="fixed top-0 left-0 right-0 z-[100] px-5 sm:px-8 py-4 flex items-center justify-between bg-[#0B0A09]/70 backdrop-blur-xl border-b border-white/[0.06]">
        <Link href="/" className="flex items-center gap-2.5 group">
          <div className="w-9 h-9 bg-[#F4F1EA] text-[#0B0A09] flex items-center justify-center rounded-lg transition-transform group-hover:scale-105">
            <span className="font-serif text-xl font-bold leading-none">M</span>
          </div>
          <span className="font-serif text-xl font-medium tracking-tight text-[#F4F1EA]">Memento</span>
        </Link>
        <div className="hidden lg:flex items-center gap-8">
          {NAV.map((l) => (
            <Link
              key={l.href}
              href={resolvePublicHref(l.href, currentPage)}
              onClick={(event) => goSection(event, l.href)}
              className={`text-[13px] transition-colors ${
                (currentPage === 'pricing' && l.href === '#pricing')
                  ? 'text-white'
                  : 'text-white/75 hover:text-white'
              }`}
            >
              {l.label}
            </Link>
          ))}
        </div>
        <div className="flex items-center gap-2 sm:gap-3">
          <div ref={langRef} className="relative">
            <button
              type="button"
              onClick={() => setLangOpen((o) => !o)}
              aria-expanded={langOpen}
              aria-haspopup="listbox"
              aria-label={t('landing.nav.language')}
              className="inline-flex items-center gap-1.5 px-3 py-2 rounded-full border border-white/15 text-[12px] text-white/70 hover:text-white hover:border-white/30 transition-colors"
            >
              <Globe size={14} />
              <span className="uppercase font-semibold tracking-wide">{language}</span>
              <ChevronDown size={12} className={`opacity-60 transition-transform ${langOpen ? 'rotate-180' : ''}`} />
            </button>
            <AnimatePresence>
              {langOpen && (
                <motion.ul
                  role="listbox"
                  initial={{ opacity: 0, y: 6 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: 6 }}
                  transition={{ duration: 0.15 }}
                  className="absolute end-0 mt-2 w-48 max-h-72 overflow-y-auto rounded-2xl border border-white/10 bg-[#141210] shadow-2xl py-1.5 z-[110]"
                >
                  {LANDING_LANGS.map((lang) => (
                    <li key={lang.code} role="option" aria-selected={language === lang.code}>
                      <button
                        type="button"
                        onClick={() => {
                          setLanguage(lang.code)
                          setLangOpen(false)
                        }}
                        className={`w-full text-start px-4 py-2.5 text-[13px] transition-colors ${
                          language === lang.code
                            ? 'bg-[#D4A373]/15 text-[#D4A373]'
                            : 'text-white/70 hover:bg-white/5 hover:text-white'
                        }`}
                      >
                        {t(lang.labelKey)}
                      </button>
                    </li>
                  ))}
                </motion.ul>
              )}
            </AnimatePresence>
          </div>

          <Link href="/login" className="hidden sm:inline text-[13px] text-white/75 hover:text-white transition-colors px-2">
            {t('landing.nav.login')}
          </Link>
          <Link
            href="/register"
            className="hidden sm:inline-flex items-center gap-2 px-5 py-2.5 rounded-full bg-[#F4F1EA] text-[#0B0A09] text-[13px] font-semibold hover:bg-white transition-colors"
          >
            {t('landing.nav.cta')}
          </Link>
          <button
            type="button"
            aria-label={menuOpen ? t('landing.nav.closeMenu') : t('landing.nav.openMenu')}
            onClick={() => setMenuOpen((o) => !o)}
            className="lg:hidden w-10 h-10 rounded-full border border-white/15 flex items-center justify-center text-white/80"
          >
            {menuOpen ? <X size={18} /> : <Menu size={18} />}
          </button>
        </div>
      </nav>

      <AnimatePresence>
        {menuOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-[99] bg-[#0B0A09] pt-24 px-8 lg:hidden"
          >
            <div className="flex flex-col gap-1">
              {NAV.map((l) => (
                <Link
                  key={l.href}
                  href={resolvePublicHref(l.href, currentPage)}
                  onClick={(event) => goSection(event, l.href)}
                  className="py-4 text-3xl font-serif border-b border-white/10"
                >
                  {l.label}
                </Link>
              ))}
              <Link
                href="/login"
                onClick={() => setMenuOpen(false)}
                className="mt-10 py-4 text-2xl font-serif text-white/80 text-center border-b border-white/10"
              >
                {t('landing.nav.login')}
              </Link>
              <Link href="/register" onClick={() => setMenuOpen(false)} className="mt-4 py-4 rounded-2xl bg-[#F4F1EA] text-[#0B0A09] text-center font-semibold">
                {t('landing.nav.cta')}
              </Link>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      <div className={currentPage === 'home' ? '' : 'pt-20'}>
        {children}
      </div>

      <footer className="px-5 sm:px-8 py-14 border-t border-white/[0.06]">
        <div className="max-w-6xl mx-auto flex flex-col md:flex-row justify-between gap-10">
          <div className="max-w-xs">
            <div className="flex items-center gap-2 mb-3">
              <div className="w-7 h-7 bg-[#F4F1EA] text-[#0B0A09] flex items-center justify-center rounded-md">
                <span className="font-serif font-bold text-sm">M</span>
              </div>
              <span className="font-serif text-lg">Memento</span>
            </div>
            <p className="text-sm text-white/60">{t('landing.footer.desc')}</p>
          </div>
          <div className="grid grid-cols-3 gap-10 text-sm">
            {(['product', 'community', 'legal'] as const).map((section) => (
              <div key={section}>
                <p className="text-[13px] font-medium tracking-wide text-white/70 mb-3">
                  {t(`landing.footer.${section}.title`)}
                </p>
                <ul className="space-y-2 text-white/70">
                  {[0, 1, 2].map((j) => {
                    const label = t(`landing.footer.${section}.link${j}`)
                    const href = t(`landing.footer.${section}.link${j}Href`)
                    if (!label || label.startsWith('landing.')) return null
                    const resolved = resolvePublicHref(href, currentPage)
                    return (
                      <li key={j}>
                        {resolved.startsWith('/') ? (
                          <Link href={resolved} className="hover:text-white transition-colors">{label}</Link>
                        ) : (
                          <a href={resolved} className="hover:text-white transition-colors">{label}</a>
                        )}
                      </li>
                    )
                  })}
                </ul>
              </div>
            ))}
          </div>
        </div>
        <p className="max-w-6xl mx-auto mt-12 pt-8 border-t border-white/[0.06] text-[13px] text-white/70 tracking-wide">
          © 2026 Memento. {t('landing.footer.rights')}
        </p>
      </footer>
    </div>
  )
}
