'use client';
import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import {
  Sun, Moon, Menu as MenuIcon, X as CloseIcon,
  Mic, AtSign, Briefcase, PlayCircle, Code2,
} from 'lucide-react';
import { useLanguage } from '@client/contexts/LanguageContext';
import LanguageSwitcher from '@client/components/ui/LanguageSwitcher';

interface InitialBranding {
  site_logo_url: string;
  site_primary_color: string;
  site_title: string;
  site_tagline: string;
  site_font_family: string;
  site_favicon_url: string;
}

const DEMO_MODE_ON = process.env.NEXT_PUBLIC_DEMO_MODE === 'on';
const DEFAULT_ACCENT = '#5B5BD6';

function shadeHex(hex: string, amount: number): string {
  const m = hex.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);
  if (!m) return hex;
  const adj = (n: number) => Math.max(0, Math.min(255, Math.round(n + amount * 255)));
  const r = adj(parseInt(m[1], 16));
  const g = adj(parseInt(m[2], 16));
  const b = adj(parseInt(m[3], 16));
  return '#' + [r, g, b].map(v => v.toString(16).padStart(2, '0')).join('');
}

export default function LandingShell({
  children,
  initialBranding,
}: {
  children: React.ReactNode;
  initialBranding: InitialBranding;
}) {
  const { t } = useLanguage();
  const [dark, setDark] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  // Branding is server-rendered, so these are pure props (no setters needed).
  const logoUrl = initialBranding.site_logo_url;
  const accentHex = initialBranding.site_primary_color || DEFAULT_ACCENT;
  const siteName = initialBranding.site_title || 'RestroAgent';
  const pathname = usePathname();

  const navLinks = [
    { label: t('nav.features', 'Features'), href: '/#features' },
    { label: t('nav.pricing', 'Pricing'), href: '/pricing' },
    ...(DEMO_MODE_ON ? [{ label: t('nav.demo', 'Demo'), href: '/demo' }] : []),
    { 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(() => { setMobileOpen(false); }, [pathname]);

  // Branding (logo, name, accent, font, favicon) is now server-rendered in
  // `(landing)/layout.tsx` and `app/layout.tsx`, so no client fetch / DOM
  // mutation is needed on first paint. Refreshes within a session pick up
  // new branding through the standard Next.js revalidation path.

  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 flex items-center justify-center text-white shadow-sm ${className}`}
          style={{ background: `linear-gradient(135deg, ${accentHex}, ${shadeHex(accentHex, -0.12)})` }}
        >
          <Mic size={15} strokeWidth={2.5} />
        </div>
      )
  );

  const productLinks = [
    { 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' },
    ...(DEMO_MODE_ON ? [{ label: t('nav.demo', 'Live Demo'), href: '/demo' }] : []),
  ];
  const resourcesLinks = [
    { label: t('nav.faq', 'FAQ'), href: '/faq' },
    { label: t('landing.footerBlog', 'Blog'), href: '/blog' },
    { label: t('landing.footerSecurity', 'Security'), href: '/security' },
  ];
  const companyLinks = [
    { label: t('nav.about', 'About'), href: '/about' },
    { label: t('nav.contact', 'Contact'), href: '/contact' },
    { label: t('landing.footerCareers', 'Careers'), href: '/careers' },
  ];
  const legalLinks = [
    { 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' },
  ];

  const FooterCol = ({ heading, links }: { heading: string; links: { label: string; href: string }[] }) => (
    <div>
      <p className="text-xs font-semibold text-zinc-400 uppercase tracking-wider mb-4">{heading}</p>
      <ul className="space-y-2.5">
        {links.map(l => (
          <li key={l.label}>
            <Link href={l.href} className="text-sm text-zinc-500 hover:text-white transition-colors duration-150">
              {l.label}
            </Link>
          </li>
        ))}
      </ul>
    </div>
  );

  return (
    <div
      data-ra-landing
      className="min-h-screen bg-white dark:bg-[#0A0A0A] text-zinc-900 dark:text-zinc-100 antialiased"
    >
      {/* ─── Thin opaque sticky header ─── */}
      <header className="sticky top-0 left-0 right-0 z-50 bg-white/85 dark:bg-[#0A0A0A]/85 backdrop-blur-md border-b border-zinc-200/70 dark:border-zinc-800/70">
        <div className="mx-auto max-w-marketing px-5 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-14">
            <Link href="/" className="flex items-center gap-2 group">
              <LogoMark />
              <span className="font-semibold text-[15px] tracking-tight text-zinc-900 dark:text-white">{siteName}</span>
            </Link>

            <nav className="hidden md:flex items-center gap-1">
              {navLinks.map(link => {
                const isActive = pathname === link.href || (link.href !== '/' && link.href.startsWith('/') && !link.href.includes('#') && pathname?.startsWith(link.href));
                return (
                  <Link
                    key={link.href}
                    href={link.href}
                    className={`px-3 py-1.5 rounded-md text-[13.5px] font-medium transition-colors duration-150 ${
                      isActive
                        ? 'text-zinc-900 dark:text-white'
                        : 'text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-white'
                    }`}
                  >
                    {link.label}
                  </Link>
                );
              })}
            </nav>

            <div className="flex items-center gap-1.5">
              <Link
                href="/login"
                className="hidden md:inline-flex px-3 py-1.5 text-[13.5px] font-medium text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-white transition-colors duration-150"
              >
                {t('auth.signIn', 'Sign in')}
              </Link>
              <Link
                href="/register"
                className="hidden md:inline-flex px-3.5 py-1.5 rounded-md text-[13.5px] font-semibold text-white bg-marketing-accent hover:bg-marketing-accent-hover transition-colors duration-150 shadow-[0_1px_0_rgba(0,0,0,0.05)] focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-white dark:focus-visible:ring-offset-[#0A0A0A] focus-visible:ring-marketing-accent"
              >
                {t('landing.getStarted', 'Get started')}
              </Link>
              <button
                onClick={() => setMobileOpen(o => !o)}
                className="md:hidden p-2 -mr-2 rounded-md text-zinc-700 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-900"
                aria-label={t('common.menu', 'Menu')}
              >
                {mobileOpen ? <CloseIcon size={20} /> : <MenuIcon size={20} />}
              </button>
            </div>
          </div>
        </div>

        {mobileOpen && (
          <div className="md:hidden border-t border-zinc-200 dark:border-zinc-800 bg-white dark:bg-[#0A0A0A] px-5 py-4 space-y-1">
            {navLinks.map(link => (
              <Link
                key={link.href}
                href={link.href}
                className="block px-3 py-2.5 rounded-md text-sm font-medium text-zinc-700 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-900"
              >
                {link.label}
              </Link>
            ))}
            <div className="pt-3 mt-3 border-t border-zinc-200 dark:border-zinc-800 flex flex-col gap-2">
              <Link
                href="/login"
                className="px-3 py-2 rounded-md text-sm font-semibold text-center text-zinc-700 dark:text-zinc-200 border border-zinc-200 dark:border-zinc-800"
              >
                {t('auth.signIn', 'Sign in')}
              </Link>
              <Link
                href="/register"
                className="px-3 py-2 rounded-md text-sm font-semibold text-center text-white bg-marketing-accent hover:bg-marketing-accent-hover"
              >
                {t('landing.getStarted', 'Get started')}
              </Link>
            </div>
          </div>
        )}
      </header>

      <main>{children}</main>

      {/* ─── Footer ─── */}
      <footer className="bg-[#0A0A0A] text-zinc-400 border-t border-zinc-900">
        <div className="mx-auto max-w-marketing px-5 sm:px-6 lg:px-8 py-14 sm:py-16">
          <div className="grid grid-cols-2 md:grid-cols-[2fr_1fr_1fr_1fr_1fr] gap-10">
            <div className="col-span-2 md:col-span-1">
              <Link href="/" className="flex items-center gap-2 mb-4">
                <LogoMark />
                <span className="font-semibold text-[15px] text-white">{siteName}</span>
              </Link>
              <p className="text-sm text-zinc-500 leading-relaxed max-w-xs">
                {t('landing.footerTagline', 'AI voice and chat agents that handle orders, bookings, and customer queries — so your staff can focus on hospitality.')}
              </p>
            </div>

            <FooterCol heading={t('landing.footerProduct', 'Product')} links={productLinks} />
            <FooterCol heading={t('landing.footerResources', 'Resources')} links={resourcesLinks} />
            <FooterCol heading={t('landing.footerCompany', 'Company')} links={companyLinks} />
            <FooterCol heading={t('landing.footerLegal', 'Legal')} links={legalLinks} />
          </div>

          <div className="mt-12 pt-6 border-t border-zinc-900 flex flex-col lg:flex-row items-start lg:items-center justify-between gap-5">
            <div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-5">
              <p className="text-xs text-zinc-600">© {new Date().getFullYear()} {siteName}. {t('landing.allRightsReserved', 'All rights reserved.')}</p>
              <p className="text-[11px] text-zinc-600 max-w-md">
                {t('landing.complianceLine', 'SOC 2 Type II audited · GDPR-ready · PCI-DSS via Stripe.')}
              </p>
            </div>
            <div className="flex items-center gap-2">
              <LanguageSwitcher variant="landing" />
              <button
                onClick={() => setDark(d => !d)}
                className="p-2 rounded-md text-zinc-500 hover:text-white hover:bg-zinc-900 transition-colors duration-150"
                aria-label={t('common.toggleTheme', 'Toggle theme')}
              >
                {dark ? <Sun size={16} /> : <Moon size={16} />}
              </button>
              <div className="flex items-center gap-1.5 ml-2">
                {[
                  { key: 'twitter', label: t('social.twitter', 'Twitter / X'), Icon: AtSign, href: 'https://twitter.com' },
                  { key: 'linkedin', label: t('social.linkedin', 'LinkedIn'), Icon: Briefcase, href: 'https://linkedin.com' },
                  { key: 'youtube', label: t('social.youtube', 'YouTube'), Icon: PlayCircle, href: 'https://youtube.com' },
                  { key: 'github', label: t('social.github', 'GitHub'), Icon: Code2, href: 'https://github.com' },
                ].map(s => (
                  <a
                    key={s.key}
                    href={s.href}
                    target="_blank"
                    rel="noopener noreferrer"
                    aria-label={s.label}
                    className="w-8 h-8 rounded-md flex items-center justify-center text-zinc-500 hover:text-white hover:bg-zinc-900 transition-colors duration-150"
                  >
                    <s.Icon size={14} />
                  </a>
                ))}
              </div>
            </div>
          </div>
        </div>
      </footer>
    </div>
  );
}
