'use client';
import React, { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useLanguage } from '@client/contexts/LanguageContext';
import LanguageSwitcher from '@client/components/ui/LanguageSwitcher';

function SunIcon() {
  return (
    <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"/>
    </svg>
  );
}
function MoonIcon() {
  return (
    <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
    </svg>
  );
}
function MenuIcon() {
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/>
    </svg>
  );
}
function CloseIcon() {
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
    </svg>
  );
}

function DefaultLogoIcon() {
  return (
    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="22"/>
    </svg>
  );
}

function hexToHslString(hex: string): string | null {
  const m = hex.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);
  if (!m) return null;
  let r = parseInt(m[1], 16) / 255;
  let g = parseInt(m[2], 16) / 255;
  let b = parseInt(m[3], 16) / 255;
  const max = Math.max(r, g, b), min = Math.min(r, g, b);
  let h = 0, s = 0;
  const l = (max + min) / 2;
  if (max !== min) {
    const d = max - min;
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
    switch (max) {
      case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
      case g: h = ((b - r) / d + 2) / 6; break;
      default: h = ((r - g) / d + 4) / 6; break;
    }
  }
  return `${Math.round(h * 360)} ${Math.round(s * 100)}% ${Math.round(l * 100)}%`;
}

export default function LandingLayout({ children }: { children: React.ReactNode }) {
  const { t } = useLanguage();
  const [dark, setDark] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [logoUrl, setLogoUrl] = useState('');
  const [accentHex, setAccentHex] = useState('');
  const [siteName, setSiteName] = useState('RestroAgent');
  const pathname = usePathname();

  const navLinks = [
    { label: t('nav.features', 'Features'), href: '/#features' },
    { label: t('nav.pricing', 'Pricing'), href: '/pricing' },
    { label: t('nav.about', 'About'), href: '/about' },
    { label: t('nav.contact', 'Contact'), href: '/contact' },
  ];

  useEffect(() => {
    const stored = localStorage.getItem('ra-theme');
    if (stored === 'dark') setDark(true);
  }, []);

  useEffect(() => {
    if (dark) {
      document.documentElement.classList.add('dark');
      localStorage.setItem('ra-theme', 'dark');
    } else {
      document.documentElement.classList.remove('dark');
      localStorage.setItem('ra-theme', 'light');
    }
  }, [dark]);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  useEffect(() => { setMobileOpen(false); }, [pathname]);

  useEffect(() => {
    fetch('/api/public/branding')
      .then(r => r.json())
      .then((data: { branding: Record<string, string> }) => {
        const b = data.branding ?? {};
        if (b.site_primary_color) {
          const hex = b.site_primary_color;
          setAccentHex(hex);
          const hsl = hexToHslString(hex);
          if (hsl) document.documentElement.style.setProperty('--primary', hsl);
        }
        if (b.site_font_family) {
          const family = b.site_font_family;
          const existingFontLink = document.getElementById('ra-brand-font') as HTMLLinkElement | null;
          if (!existingFontLink) {
            const link = document.createElement('link');
            link.id = 'ra-brand-font';
            link.rel = 'stylesheet';
            link.href = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(family)}:wght@400;500;600;700&display=swap`;
            document.head.appendChild(link);
          }
          const fontStack = `'${family}', sans-serif`;
          document.documentElement.style.fontFamily = fontStack;
          document.body.style.fontFamily = fontStack;
        }
        if (b.site_favicon_url) {
          let link = document.querySelector("link[rel~='icon']") as HTMLLinkElement | null;
          if (!link) {
            link = document.createElement('link');
            link.rel = 'icon';
            document.head.appendChild(link);
          }
          link.href = b.site_favicon_url;
        }
        if (b.site_logo_url) setLogoUrl(b.site_logo_url);
        const title = b.site_title || 'RestroAgent';
        setSiteName(title);
        const tagline = b.site_tagline || '';
        document.title = tagline ? `${tagline} — ${title}` : title;
      })
      .catch(() => {});
  }, []);

  useEffect(() => {
    if (!accentHex) return;
    const id = 'ra-brand-style';
    const existing = document.getElementById(id);
    if (existing) existing.remove();
    const hex = accentHex;
    const style = document.createElement('style');
    style.id = id;
    style.textContent = `
      [data-ra-landing] .bg-orange-500,
      [data-ra-landing] .hover\\:bg-orange-400:hover,
      [data-ra-landing] .hover\\:bg-orange-500:hover { background-color: ${hex} !important; }
      [data-ra-landing] .bg-orange-600,
      [data-ra-landing] .hover\\:bg-orange-600:hover { background-color: ${hex}dd !important; filter: brightness(0.9); }
      [data-ra-landing] .text-orange-500,
      [data-ra-landing] .text-orange-600 { color: ${hex} !important; }
      [data-ra-landing] .text-orange-400,
      [data-ra-landing] .hover\\:text-orange-400:hover,
      [data-ra-landing] .hover\\:text-orange-600:hover { color: ${hex}cc !important; }
      [data-ra-landing] .dark\\:text-orange-400 { color: ${hex}cc !important; }
      [data-ra-landing] .bg-orange-50,
      [data-ra-landing] .hover\\:bg-orange-50:hover { background-color: ${hex}18 !important; }
      [data-ra-landing] .dark\\:bg-orange-500\\/10 { background-color: ${hex}1a !important; }
      [data-ra-landing] .from-orange-500 { --tw-gradient-from: ${hex} !important; }
      [data-ra-landing] .to-orange-600 { --tw-gradient-to: ${hex} !important; }
      [data-ra-landing] .border-orange-500,
      [data-ra-landing] .focus\\:border-orange-500:focus { border-color: ${hex} !important; }
      [data-ra-landing] .ring-orange-500,
      [data-ra-landing] .focus\\:ring-orange-500:focus { --tw-ring-color: ${hex}80 !important; }
      [data-ra-landing] .bg-orange-500\\/10 { background-color: ${hex}1a !important; }
      [data-ra-landing] .hover\\:bg-orange-500:hover { background-color: ${hex} !important; }
      [data-ra-landing] .shadow-orange-500\\/25 { --tw-shadow-color: ${hex}40 !important; }
      [data-ra-landing] .hover\\:shadow-orange-500\\/25:hover { --tw-shadow-color: ${hex}40 !important; }
    `;
    document.head.appendChild(style);
    return () => { document.getElementById(id)?.remove(); };
  }, [accentHex]);

  const LogoMark = ({ className = '' }: { className?: string }) => (
    logoUrl
      ? <img src={logoUrl} alt={siteName} className={`w-8 h-8 rounded-lg object-contain ${className}`} />
      : (
        <div className={`w-8 h-8 rounded-lg bg-gradient-to-br from-orange-500 to-orange-600 flex items-center justify-center shadow-md group-hover:scale-105 group-hover:shadow-orange-500/30 transition-all duration-200 ${className}`}>
          <DefaultLogoIcon />
        </div>
      )
  );

  return (
    <div data-ra-landing className="min-h-screen bg-white dark:bg-[#080a0f] text-slate-900 dark:text-slate-100 transition-colors duration-300">
      {/* Navbar */}
      <header className={`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${scrolled ? 'bg-white/95 dark:bg-[#080a0f]/95 backdrop-blur-xl shadow-sm border-b border-slate-100 dark:border-slate-800/80' : 'bg-transparent'}`}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            {/* Logo */}
            <Link href="/" className="flex items-center gap-2.5 group">
              <LogoMark />
              <span className="font-bold text-lg tracking-tight text-slate-900 dark:text-white">{siteName}</span>
            </Link>

            {/* Desktop Nav */}
            <nav className="hidden md:flex items-center gap-0.5">
              {navLinks.map(link => {
                const isActive = pathname === link.href || (link.href !== '/' && pathname?.startsWith(link.href.replace('#features', '')));
                return (
                  <Link key={link.href} href={link.href}
                    className={`relative px-3.5 py-2 rounded-lg text-sm font-medium transition-all duration-200 group ${isActive ? 'text-orange-600 dark:text-orange-400 bg-orange-50 dark:bg-orange-500/10' : 'text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white hover:bg-slate-100 dark:hover:bg-slate-800'}`}>
                    {link.label}
                    <span className={`absolute bottom-0.5 left-3.5 right-3.5 h-0.5 rounded-full bg-orange-500 transition-all duration-200 ${isActive ? 'opacity-100 scale-x-100' : 'opacity-0 scale-x-0 group-hover:opacity-60 group-hover:scale-x-100'}`} />
                  </Link>
                );
              })}
            </nav>

            {/* Actions */}
            <div className="flex items-center gap-2">
              <LanguageSwitcher variant="landing" />
              <button onClick={() => setDark(d => !d)}
                className="p-2 rounded-lg text-slate-500 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800 transition-all duration-200 hover:scale-105"
                aria-label={t('common.toggleTheme', 'Toggle theme')}>
                {dark ? <SunIcon /> : <MoonIcon />}
              </button>
              <Link href="/login" className="hidden md:inline-flex px-4 py-2 text-sm font-medium text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white transition-colors duration-200 relative group">
                {t('auth.signIn', 'Sign in')}
                <span className="absolute bottom-0.5 left-4 right-4 h-0.5 rounded-full bg-slate-400 opacity-0 scale-x-0 group-hover:opacity-50 group-hover:scale-x-100 transition-all duration-200" />
              </Link>
              <Link href="/register" className="hidden md:inline-flex px-4 py-2 rounded-lg text-sm font-semibold bg-orange-500 hover:bg-orange-600 text-white transition-all duration-200 shadow-sm hover:shadow-md hover:shadow-orange-500/25 hover:-translate-y-0.5 active:scale-95 active:translate-y-0">
                {t('landing.getStarted', 'Get Started')}
              </Link>
              <button onClick={() => setMobileOpen(o => !o)} className="md:hidden p-2 rounded-lg text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors">
                {mobileOpen ? <CloseIcon /> : <MenuIcon />}
              </button>
            </div>
          </div>
        </div>

        {/* Mobile Menu */}
        {mobileOpen && (
          <div className="md:hidden bg-white dark:bg-[#0d0f14] border-t border-slate-100 dark:border-slate-800 px-4 py-4 space-y-1">
            {navLinks.map(link => (
              <Link key={link.href} href={link.href}
                className="block px-3 py-2.5 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-300 hover:bg-orange-50 dark:hover:bg-orange-500/10 hover:text-orange-600 dark:hover:text-orange-400 transition-all duration-150">
                {link.label}
              </Link>
            ))}
            <div className="pt-3 flex flex-col gap-2 border-t border-slate-100 dark:border-slate-800 mt-3">
              <Link href="/login" className="px-3 py-2.5 rounded-lg text-sm font-semibold text-center text-slate-700 dark:text-slate-300 border border-slate-200 dark:border-slate-700 hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors">
                {t('auth.signIn', 'Sign in')}
              </Link>
              <Link href="/register" className="px-3 py-2.5 rounded-lg text-sm font-semibold text-center bg-orange-500 hover:bg-orange-600 text-white transition-all duration-200 shadow-sm hover:shadow-orange-500/25 active:scale-95">
                {t('landing.getStarted', 'Get Started')}
              </Link>
            </div>
          </div>
        )}
      </header>

      {/* Page Content */}
      <main className="pt-16">{children}</main>

      {/* Footer */}
      <footer className="bg-slate-900 dark:bg-slate-950 border-t border-slate-800">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12 md:py-16">
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-[2fr_1fr_1fr_1fr] gap-10 md:gap-12">
            {/* Brand */}
            <div>
              <Link href="/" className="flex items-center gap-2.5 mb-5 group">
                {logoUrl
                  ? <img src={logoUrl} alt={siteName} className="w-8 h-8 rounded-lg object-contain" />
                  : (
                    <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-orange-500 to-orange-600 flex items-center justify-center group-hover:shadow-md group-hover:shadow-orange-500/30 transition-all duration-200">
                      <DefaultLogoIcon />
                    </div>
                  )
                }
                <span className="font-bold text-lg text-white">{siteName}</span>
              </Link>
              <p className="text-sm text-slate-400 leading-relaxed max-w-xs mb-6">
                {t('landing.footerTagline', 'AI-powered voice and chat agents that handle orders, bookings, and customer queries — so your staff can focus on hospitality.')}
              </p>
              {/* Newsletter */}
              <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-3">{t('landing.stayUpdated', 'Stay updated')}</p>
              <div className="flex gap-2">
                <input type="email" placeholder={t('common.emailPlaceholder', 'your@email.com')} className="flex-1 min-w-0 px-3 py-2 text-sm rounded-lg border border-slate-700 bg-slate-800 text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-orange-500/30 focus:border-orange-500 transition-all duration-200" />
                <button className="px-3 py-2 rounded-lg bg-orange-500 hover:bg-orange-400 text-white text-sm font-semibold transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md hover:shadow-orange-500/25 active:scale-95 flex-shrink-0">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
                </button>
              </div>
            </div>

            {/* Links */}
            <div>
              <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-5">{t('landing.footerProduct', 'Product')}</p>
              <ul className="space-y-3">
                {[
                  { label: t('nav.features', 'Features'), href: '/#features' },
                  { label: t('nav.pricing', 'Pricing'), href: '/pricing' },
                  { label: t('landing.footerIntegrations', 'Integrations'), href: '/integrations' },
                  { label: t('landing.footerChangelog', 'Changelog'), href: '/changelog' },
                ].map(l => (
                  <li key={l.label}>
                    <Link href={l.href} className="text-sm text-slate-400 hover:text-orange-400 transition-colors duration-200 relative group inline-block">
                      {l.label}
                      <span className="absolute -bottom-0.5 left-0 right-0 h-px bg-orange-400 opacity-0 scale-x-0 group-hover:opacity-100 group-hover:scale-x-100 transition-all duration-200" />
                    </Link>
                  </li>
                ))}
              </ul>
            </div>
            <div>
              <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-5">{t('landing.footerCompany', 'Company')}</p>
              <ul className="space-y-3">
                {[
                  { label: t('nav.about', 'About'), href: '/about' },
                  { label: t('nav.contact', 'Contact'), href: '/contact' },
                  { label: t('landing.footerCareers', 'Careers'), href: '/careers' },
                  { label: t('nav.faq', 'FAQ'), href: '/faq' },
                ].map(l => (
                  <li key={l.label}>
                    <Link href={l.href} className="text-sm text-slate-400 hover:text-orange-400 transition-colors duration-200 relative group inline-block">
                      {l.label}
                      <span className="absolute -bottom-0.5 left-0 right-0 h-px bg-orange-400 opacity-0 scale-x-0 group-hover:opacity-100 group-hover:scale-x-100 transition-all duration-200" />
                    </Link>
                  </li>
                ))}
              </ul>
            </div>
            <div>
              <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-5">{t('landing.footerLegal', 'Legal')}</p>
              <ul className="space-y-3">
                {[
                  { label: t('landing.privacyPolicy', 'Privacy Policy'), href: '/privacy' },
                  { label: t('landing.termsOfService', 'Terms of Service'), href: '/terms' },
                  { label: t('landing.cookiePolicy', 'Cookie Policy'), href: '/cookie' },
                  { label: t('landing.refundPolicy', 'Refund Policy'), href: '/refund' },
                ].map(l => (
                  <li key={l.label}>
                    <Link href={l.href} className="text-sm text-slate-400 hover:text-orange-400 transition-colors duration-200 relative group inline-block">
                      {l.label}
                      <span className="absolute -bottom-0.5 left-0 right-0 h-px bg-orange-400 opacity-0 scale-x-0 group-hover:opacity-100 group-hover:scale-x-100 transition-all duration-200" />
                    </Link>
                  </li>
                ))}
              </ul>
              {/* Social */}
              <div className="mt-7 flex gap-2.5">
                {[
                  { labelKey: 'social.twitter', labelFallback: 'Twitter', icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.744l7.73-8.835L1.254 2.25H8.08l4.253 5.622zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg> },
                  { labelKey: 'social.linkedin', labelFallback: 'LinkedIn', icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor"><path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6zM2 9h4v12H2z"/><circle cx="4" cy="4" r="2"/></svg> },
                  { labelKey: 'social.youtube', labelFallback: 'YouTube', icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor"><path d="M22.54 6.42a2.78 2.78 0 0 0-1.95-1.96C18.88 4 12 4 12 4s-6.88 0-8.59.46a2.78 2.78 0 0 0-1.95 1.96A29 29 0 0 0 1 12a29 29 0 0 0 .46 5.58A2.78 2.78 0 0 0 3.41 19.6C5.12 20 12 20 12 20s6.88 0 8.59-.46a2.78 2.78 0 0 0 1.95-1.95A29 29 0 0 0 23 12a29 29 0 0 0-.46-5.58zM9.75 15.02V8.98L15.5 12l-5.75 3.02z"/></svg> },
                ].map(s => (
                  <a key={s.labelKey} href="#" aria-label={t(s.labelKey, s.labelFallback)} className="w-8 h-8 rounded-lg bg-slate-800 flex items-center justify-center text-slate-500 hover:bg-orange-500 hover:text-white transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md hover:shadow-orange-500/25">{s.icon}</a>
                ))}
              </div>
            </div>
          </div>

          <div className="mt-12 pt-6 border-t border-slate-800 flex flex-col sm:flex-row items-center justify-between gap-4">
            <p className="text-xs text-slate-600">© {new Date().getFullYear()} {siteName}. {t('landing.allRightsReserved', 'All rights reserved.')}</p>
            <p className="text-xs text-slate-600">{t('landing.builtForRestaurants', 'Built for restaurants that take hospitality seriously.')}</p>
          </div>
        </div>
      </footer>
    </div>
  );
}
