"use client";

import { useState, useEffect, useRef } from 'react';
import { Menu, X, ChevronDown, ArrowRight, ArrowUpRight } from 'lucide-react';
import covaThermImg from '@/assets/produits/Covalba-CovaTherm1-Produit.webp';
import covaSealImg from '@/assets/produits/Covalba-CovaSeal1-Produit.webp';
import covaMetalImg from '@/assets/produits/Covalba-CovaMeta1-Produit.webp';
import laqueSolaireImg from '@/assets/produits/Covalba-CovaTherm-Light-Produit.webp';
import WpImage from '@/components/ui/WpImage';
import LanguageSwitcher from '@/components/LanguageSwitcher';
import { I18N_NAV } from '@/config/i18nNav';
import { type Locale, localizedUri } from '@/config/i18nRoutes';

// Images produit, mappées par slug (dernier segment du href) — partagées entre
// les 3 langues (les slugs produit sont identiques fr/en/es).
const PRODUCT_IMG: Record<string, { src: string; width: number; height: number }> = {
  covatherm: { src: covaThermImg.src, width: covaThermImg.width, height: covaThermImg.height },
  'covaseal-20': { src: covaSealImg.src, width: covaSealImg.width, height: covaSealImg.height },
  'covametal-20': { src: covaMetalImg.src, width: covaMetalImg.width, height: covaMetalImg.height },
  'covatherm-light': { src: laqueSolaireImg.src, width: laqueSolaireImg.width, height: laqueSolaireImg.height },
};

type DropdownKey = 'solutions' | 'secteurs' | 'covalba' | null;

interface NavbarProps {
  lightBg?: boolean; // true = fond clair (pages produit), false = fond sombre (homepage)
  locale?: Locale;
}

const Navbar = ({ lightBg = false, locale = 'fr' }: NavbarProps) => {
  const { products, roofTypes, sectors, company, ui, topBar } = I18N_NAV[locale];
  const homeHref = localizedUri(locale, '/');
  const ctaHref = localizedUri(locale, '/diagnostic');
  const allSolutionsHref = locale === 'fr' ? '/nos-solutions-cool-roof' : homeHref;

  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [activeDropdown, setActiveDropdown] = useState<DropdownKey>(null);
  const [mobileExpanded, setMobileExpanded] = useState<DropdownKey>(null);
  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

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

  // Close mobile menu on resize to desktop
  useEffect(() => {
    const onResize = () => { if (window.innerWidth >= 1024) setMobileOpen(false); };
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  const openDropdown = (key: DropdownKey) => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    setActiveDropdown(key);
  };

  const scheduleClose = () => {
    closeTimer.current = setTimeout(() => setActiveDropdown(null), 120);
  };

  // Sur fond clair non-scrollé : texte sombre. Sur fond sombre non-scrollé : texte blanc.
  const unscrolledTextClass = lightBg
    ? 'text-foreground/70 hover:text-foreground'
    : 'text-white/90 hover:text-white';

  // Sur-navbar : discrète, visible uniquement en haut (repliée au scroll).
  const topBarTextClass = lightBg
    ? 'text-foreground/55 hover:text-foreground'
    : 'text-white/65 hover:text-white';

  const linkClass = `text-sm font-medium transition-colors duration-200 flex items-center gap-1 ${
    scrolled ? 'text-foreground hover:text-primary' : unscrolledTextClass
  }`;

  const dropdownBase =
    'absolute top-full left-0 mt-2 bg-card rounded-2xl shadow-[0_8px_40px_rgba(26,42,58,0.12)] border border-border overflow-hidden z-50';

  return (
    <nav
      className={`fixed top-0 left-0 right-0 z-50 transition-all duration-500 ${
        scrolled ? 'bg-card/95 backdrop-blur-md shadow-sm' : 'bg-transparent'
      }`}
    >
      {/* Sur-navbar : accès applicateur, discrète, repliée au scroll */}
      <div
        className={`overflow-hidden transition-all duration-500 ease-out ${
          lightBg ? 'bg-foreground/[0.03]' : 'bg-[#0b1a2b]/30'
        } ${scrolled ? 'max-h-0 opacity-0' : 'max-h-12 opacity-100'}`}
      >
        <div className={`container mx-auto px-4 lg:px-8 flex items-center justify-end gap-3 lg:gap-4 h-8 lg:h-9 border-b ${lightBg ? 'border-border/60' : 'border-white/10'}`}>
          <a
            href={topBar.devenir.href}
            className={`text-[11px] lg:text-xs font-medium transition-colors duration-200 ${topBarTextClass}`}
          >
            {topBar.devenir.name}
          </a>
          <span aria-hidden="true" className={lightBg ? 'text-foreground/25' : 'text-white/30'}>·</span>
          <a
            href={topBar.espace.href}
            target="_blank"
            rel="noopener noreferrer"
            className={`group inline-flex items-center gap-1 text-[11px] lg:text-xs font-medium transition-colors duration-200 ${topBarTextClass}`}
          >
            {topBar.espace.name}
            <ArrowUpRight className="w-3 h-3 transition-transform duration-300 group-hover:translate-x-0.5 group-hover:-translate-y-0.5" />
          </a>
        </div>
      </div>

      <div className="container mx-auto px-4 lg:px-8 flex items-center justify-between h-16 lg:h-20">

        {/* Logo */}
        <a href={homeHref} className="flex-shrink-0">
          <img
            src="/logo-covalba.svg"
            alt="Covalba"
            className={`h-8 lg:h-10 transition-all duration-500 ${
              scrolled
                ? ''
                : lightBg
                  ? '' // fond clair → logo couleur normale
                  : 'brightness-0 invert' // fond sombre → logo blanc
            }`}
          />
        </a>

        {/* Desktop nav */}
        <div className="hidden lg:flex items-center gap-7">

          {/* Solutions — mega menu */}
          <div
            className="relative"
            onMouseEnter={() => openDropdown('solutions')}
            onMouseLeave={scheduleClose}
          >
            <button className={linkClass}>
              {ui.solutions} <ChevronDown className={`w-3.5 h-3.5 transition-transform duration-200 ${activeDropdown === 'solutions' ? 'rotate-180' : ''}`} />
            </button>

            {activeDropdown === 'solutions' && (
              <div
                className={`${dropdownBase} w-[860px]`}
                onMouseEnter={() => openDropdown('solutions')}
                onMouseLeave={scheduleClose}
              >
                <div className="p-4">
                  <p className="text-[10px] uppercase tracking-[0.2em] font-semibold text-foreground/30 font-body px-2 pb-3">
                    {ui.ranges}
                  </p>
                  <div className="flex gap-1">
                    {products.map((p) => {
                      const img = PRODUCT_IMG[p.href.split('/').pop() ?? ''];
                      return (
                        <a
                          key={p.name}
                          href={p.href}
                          className="group flex-1 flex flex-col rounded-xl hover:bg-secondary transition-colors duration-200 border border-transparent hover:border-border overflow-hidden"
                        >
                          {/* Image produit */}
                          <div className="h-28 bg-gradient-to-b from-muted/50 to-muted/20 flex items-center justify-center px-4 pt-3">
                            {img ? (
                              <WpImage
                                image={{
                                  sourceUrl: img.src,
                                  altText: p.name,
                                  width: img.width,
                                  height: img.height,
                                }}
                                className="h-24 w-32 object-contain object-bottom drop-shadow-md transition-transform duration-300 group-hover:scale-105"
                              />
                            ) : (
                              <div className="h-24 w-full rounded-lg bg-primary/8 flex items-center justify-center">
                                <span className="text-primary/30 text-xs font-body font-semibold">—</span>
                              </div>
                            )}
                          </div>
                          {/* Infos */}
                          <div className="px-3 py-3 flex flex-col gap-2 flex-1">
                            <span className="inline-block text-[8px] font-bold text-primary bg-primary/10 px-2 py-0.5 rounded-full font-body w-fit uppercase tracking-[0.1em]">
                              {p.tag}
                            </span>
                            <p className="font-satoshi font-black text-base text-foreground group-hover:text-primary transition-colors leading-tight">{p.name}</p>
                            <p className="text-xs text-foreground/50 font-body leading-relaxed">{p.need}</p>
                          </div>
                        </a>
                      );
                    })}
                  </div>
                  <div className="border-t border-border mt-3 pt-3 px-2">
                    <p className="mb-2 text-[10px] uppercase tracking-[0.18em] font-semibold text-foreground/30 font-body">
                      {ui.byRoofType}
                    </p>
                    <div className="flex flex-wrap gap-1.5">
                      {roofTypes.map((roof) => (
                        <a
                          key={roof.name}
                          href={roof.href}
                          className="rounded-full bg-secondary px-3 py-1.5 text-xs font-semibold text-foreground/62 transition-colors hover:bg-primary/10 hover:text-primary"
                        >
                          {roof.name}
                        </a>
                      ))}
                    </div>
                  </div>
                  <div className="border-t border-border mt-3 pt-3 px-2 flex items-center justify-between">
                    <p className="text-xs text-foreground/35 font-body">{ui.reassurance}</p>
                    <a href={allSolutionsHref} className="flex items-center gap-1 text-xs font-semibold text-primary hover:gap-2 transition-all">
                      {ui.allSolutions} <ArrowRight className="w-3 h-3" />
                    </a>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Vous êtes */}
          <div
            className="relative"
            onMouseEnter={() => openDropdown('secteurs')}
            onMouseLeave={scheduleClose}
          >
            <button className={linkClass}>
              {ui.youAre} <ChevronDown className={`w-3.5 h-3.5 transition-transform duration-200 ${activeDropdown === 'secteurs' ? 'rotate-180' : ''}`} />
            </button>

            {activeDropdown === 'secteurs' && (
              <div
                className={`${dropdownBase} w-52`}
                onMouseEnter={() => openDropdown('secteurs')}
                onMouseLeave={scheduleClose}
              >
                <div className="p-2">
                  {sectors.map((s) => (
                    <a
                      key={s.name}
                      href={s.href}
                      className="flex items-center justify-between px-4 py-2.5 text-sm text-foreground rounded-xl hover:bg-secondary hover:text-primary transition-colors duration-200 font-medium"
                    >
                      {s.name}
                      {s.badge && (
                        <span className="text-[10px] font-bold text-primary bg-primary/10 px-2 py-0.5 rounded-full font-body">{s.badge}</span>
                      )}
                    </a>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Covalba */}
          <div
            className="relative"
            onMouseEnter={() => openDropdown('covalba')}
            onMouseLeave={scheduleClose}
          >
            <button className={linkClass}>
              {ui.company} <ChevronDown className={`w-3.5 h-3.5 transition-transform duration-200 ${activeDropdown === 'covalba' ? 'rotate-180' : ''}`} />
            </button>

            {activeDropdown === 'covalba' && (
              <div
                className={`${dropdownBase} w-52`}
                onMouseEnter={() => openDropdown('covalba')}
                onMouseLeave={scheduleClose}
              >
                <div className="p-2">
                  {company.map((c) => (
                    <a
                      key={c.name}
                      href={c.href}
                      className="block px-4 py-2.5 text-sm text-foreground rounded-xl hover:bg-secondary hover:text-primary transition-colors duration-200 font-medium"
                    >
                      {c.name}
                    </a>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>

        {/* CTA + sélecteur de langue desktop */}
        <div className="hidden lg:flex items-center gap-4">
          <LanguageSwitcher />
          <a
            href={ctaHref}
            className="group inline-flex items-center gap-2 cta-gradient text-white font-semibold pl-6 pr-2 py-2 rounded-full transition-all duration-300 active:scale-[0.97]"
          >
            <span className="text-[15px]">{ui.cta}</span>
            <span className="flex items-center justify-center w-8 h-8 rounded-full bg-white/20 transition-transform duration-500 ease-[cubic-bezier(0.32,0.72,0,1)] group-hover:translate-x-0.5 group-hover:scale-105">
              <ArrowRight className="w-3.5 h-3.5" />
            </span>
          </a>
        </div>

        {/* Burger mobile */}
        <button
          className="lg:hidden p-2 -mr-2"
          onClick={() => setMobileOpen(!mobileOpen)}
          aria-label="Menu"
        >
          {mobileOpen
            ? <X className={`w-6 h-6 ${scrolled || lightBg ? 'text-foreground' : 'text-white'}`} />
            : <Menu className={`w-6 h-6 ${scrolled || lightBg ? 'text-foreground' : 'text-white'}`} />
          }
        </button>
      </div>

      {/* Mobile menu */}
      {mobileOpen && (
        <div className="lg:hidden bg-card border-t border-border">
          <div className="px-4 py-4 space-y-1">

            {/* Solutions mobile */}
            <div>
              <button
                onClick={() => setMobileExpanded(mobileExpanded === 'solutions' ? null : 'solutions')}
                className="w-full flex items-center justify-between py-3 text-sm font-semibold text-foreground"
              >
                {ui.solutions}
                <ChevronDown className={`w-4 h-4 transition-transform ${mobileExpanded === 'solutions' ? 'rotate-180' : ''}`} />
              </button>
              {mobileExpanded === 'solutions' && (
                <div className="pl-4 pb-2 space-y-1">
                  {products.map((p) => (
                    <a key={p.name} href={p.href} className="block py-2 text-sm text-foreground/70 hover:text-primary" onClick={() => setMobileOpen(false)}>
                      {p.name}
                    </a>
                  ))}
                  <div className="pt-2">
                    <p className="py-1 text-[10px] uppercase tracking-[0.18em] font-semibold text-foreground/35">
                      {ui.byRoofType}
                    </p>
                    {roofTypes.map((roof) => (
                      <a key={roof.name} href={roof.href} className="block py-2 text-sm text-foreground/70 hover:text-primary" onClick={() => setMobileOpen(false)}>
                        {roof.name}
                      </a>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* Vous êtes mobile */}
            <div>
              <button
                onClick={() => setMobileExpanded(mobileExpanded === 'secteurs' ? null : 'secteurs')}
                className="w-full flex items-center justify-between py-3 text-sm font-semibold text-foreground"
              >
                {ui.youAre}
                <ChevronDown className={`w-4 h-4 transition-transform ${mobileExpanded === 'secteurs' ? 'rotate-180' : ''}`} />
              </button>
              {mobileExpanded === 'secteurs' && (
                <div className="pl-4 pb-2 space-y-1">
                  {sectors.map((s) => (
                    <a key={s.name} href={s.href} className="block py-2 text-sm text-foreground/70 hover:text-primary" onClick={() => setMobileOpen(false)}>
                      {s.name}
                    </a>
                  ))}
                </div>
              )}
            </div>

            {/* Covalba mobile */}
            <div>
              <button
                onClick={() => setMobileExpanded(mobileExpanded === 'covalba' ? null : 'covalba')}
                className="w-full flex items-center justify-between py-3 text-sm font-semibold text-foreground"
              >
                {ui.company}
                <ChevronDown className={`w-4 h-4 transition-transform ${mobileExpanded === 'covalba' ? 'rotate-180' : ''}`} />
              </button>
              {mobileExpanded === 'covalba' && (
                <div className="pl-4 pb-2 space-y-1">
                  {company.map((c) => (
                    <a key={c.name} href={c.href} className="block py-2 text-sm text-foreground/70 hover:text-primary" onClick={() => setMobileOpen(false)}>
                      {c.name}
                    </a>
                  ))}
                </div>
              )}
            </div>

            <div className="pt-3 border-t border-border flex items-center justify-between gap-3">
              <a
                href={ctaHref}
                className="group flex-1 inline-flex items-center justify-center gap-2 cta-gradient text-white font-semibold pl-6 pr-2 py-3 rounded-full"
                onClick={() => setMobileOpen(false)}
              >
                <span className="text-sm">{ui.cta}</span>
                <span className="flex items-center justify-center w-8 h-8 rounded-full bg-white/20">
                  <ArrowRight className="w-3.5 h-3.5" />
                </span>
              </a>
              <LanguageSwitcher variant="mobile" />
            </div>
          </div>
        </div>
      )}
    </nav>
  );
};

export default Navbar;
