// layout.jsx — Top nav with mega-menu + Footer

const { useState, useEffect, useRef } = React;

// ─── Icons ───────────────────────────────────────────────────────────
const Icon = {
  Logo: ({ size = 36 }) => (
    <img src="LOGO.png" width={size} height={size} alt="Logo OPN" style={{ objectFit: "contain", display: "block" }} />
  ),
  Chevron: ({ size = 14, dir = "down" }) => (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none" style={{ transform: dir === "up" ? "rotate(180deg)" : dir === "right" ? "rotate(-90deg)" : "none", transition: "transform 200ms" }}>
      <path d="M4 6l4 4 4-4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  ),
  Search: ({ size = 16 }) => (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none">
      <circle cx="7" cy="7" r="5" stroke="currentColor" strokeWidth="1.5" />
      <path d="M11 11l3 3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
    </svg>
  ),
  ArrowRight: ({ size = 14 }) => (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none">
      <path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  ),
  Check: ({ size = 14 }) => (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none">
      <path d="M3 8.5L6.5 12L13 4.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  ),
  X: ({ size = 14 }) => (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none">
      <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
    </svg>
  ),
  Menu: ({ size = 20 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
      <path d="M4 7h16M4 12h16M4 17h16" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
    </svg>
  ),
  Phone: ({ size = 16 }) => <svg width={size} height={size} viewBox="0 0 16 16" fill="none"><path d="M3 3.5C3 2.7 3.7 2 4.5 2H6l1.5 3-1.5 1c.5 2 2 3.5 4 4l1-1.5L14 10v1.5c0 .8-.7 1.5-1.5 1.5C7.3 13 3 8.7 3 3.5z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/></svg>,
  Mail: ({ size = 16 }) => <svg width={size} height={size} viewBox="0 0 16 16" fill="none"><rect x="2" y="3.5" width="12" height="9" rx="1.5" stroke="currentColor" strokeWidth="1.4"/><path d="M2.5 4.5L8 9l5.5-4.5" stroke="currentColor" strokeWidth="1.4"/></svg>,
  Pin: ({ size = 16 }) => <svg width={size} height={size} viewBox="0 0 16 16" fill="none"><path d="M8 14s-5-4.5-5-8.5C3 3 5.2 1 8 1s5 2 5 4.5C13 9.5 8 14 8 14z" stroke="currentColor" strokeWidth="1.4"/><circle cx="8" cy="5.5" r="1.8" stroke="currentColor" strokeWidth="1.4"/></svg>,
  Doc: ({ size = 18 }) => <svg width={size} height={size} viewBox="0 0 20 20" fill="none"><path d="M5 2h7l4 4v11a1 1 0 01-1 1H5a1 1 0 01-1-1V3a1 1 0 011-1z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/><path d="M12 2v4h4M7 10h6M7 13h6" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>,
  Cal:  ({ size = 18 }) => <svg width={size} height={size} viewBox="0 0 20 20" fill="none"><rect x="3" y="4.5" width="14" height="13" rx="1.5" stroke="currentColor" strokeWidth="1.4"/><path d="M3 8h14M7 2.5v3M13 2.5v3" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>,
  Help: ({ size = 18 }) => <svg width={size} height={size} viewBox="0 0 20 20" fill="none"><circle cx="10" cy="10" r="7.5" stroke="currentColor" strokeWidth="1.4"/><path d="M7.5 7.5c0-1.4 1.1-2.5 2.5-2.5s2.5 1.1 2.5 2.5c0 1.4-2.5 1.8-2.5 3.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/><circle cx="10" cy="14.5" r="0.8" fill="currentColor"/></svg>,
  Alert: ({ size = 18 }) => <svg width={size} height={size} viewBox="0 0 20 20" fill="none"><path d="M10 2.5L18 16H2L10 2.5z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/><path d="M10 8v4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/><circle cx="10" cy="14" r="0.8" fill="currentColor"/></svg>,
  Users:({ size = 18 }) => <svg width={size} height={size} viewBox="0 0 20 20" fill="none"><circle cx="7" cy="7.5" r="2.5" stroke="currentColor" strokeWidth="1.4"/><circle cx="14" cy="8.5" r="2" stroke="currentColor" strokeWidth="1.4"/><path d="M2.5 16c0-2.5 2-4.5 4.5-4.5s4.5 2 4.5 4.5M12 16c0-1.9 1.4-3.5 3-3.5s2.5 1.6 2.5 3.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>,
  Map:  ({ size = 18 }) => <svg width={size} height={size} viewBox="0 0 20 20" fill="none"><path d="M7 3l-4.5 1.5v13L7 16l6 1.5L17.5 16V3L13 4.5 7 3z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/><path d="M7 3v13M13 4.5v13" stroke="currentColor" strokeWidth="1.4"/></svg>,
  Shield:({ size = 18 }) => <svg width={size} height={size} viewBox="0 0 20 20" fill="none"><path d="M10 2L3.5 4.5v5C3.5 13.5 6.5 16.5 10 18c3.5-1.5 6.5-4.5 6.5-8.5v-5L10 2z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/><path d="M7 10l2 2 4-4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  Book: ({ size = 18 }) => <svg width={size} height={size} viewBox="0 0 20 20" fill="none"><path d="M3 4.5C3 3.7 3.7 3 4.5 3H9v13H4.5c-.8 0-1.5-.7-1.5-1.5v-10zM17 4.5C17 3.7 16.3 3 15.5 3H11v13h4.5c.8 0 1.5-.7 1.5-1.5v-10z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/></svg>,
  Building:({size=18})=> <svg width={size} height={size} viewBox="0 0 20 20" fill="none"><rect x="3.5" y="5" width="13" height="13" stroke="currentColor" strokeWidth="1.4"/><path d="M7 8.5h2M7 11.5h2M11 8.5h2M11 11.5h2M7 14.5h6M10 2v3" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>,
  News: ({ size = 18 }) => <svg width={size} height={size} viewBox="0 0 20 20" fill="none"><rect x="2.5" y="4" width="15" height="12" rx="1" stroke="currentColor" strokeWidth="1.4"/><path d="M5.5 7.5h6M5.5 10h9M5.5 12.5h9" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>,
  Bell: ({ size = 16 }) => <svg width={size} height={size} viewBox="0 0 16 16" fill="none"><path d="M4 11.5V8a4 4 0 018 0v3.5l1 1.5H3l1-1.5z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/><path d="M6.5 14a1.5 1.5 0 003 0" stroke="currentColor" strokeWidth="1.4"/></svg>,
  Download:({size=14})=> <svg width={size} height={size} viewBox="0 0 16 16" fill="none"><path d="M8 2v9m0 0l-3-3m3 3l3-3M3 14h10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  Lock: ({ size = 16 }) => <svg width={size} height={size} viewBox="0 0 16 16" fill="none"><rect x="3" y="7.5" width="10" height="7" rx="1" stroke="currentColor" strokeWidth="1.4"/><path d="M5 7.5V5a3 3 0 016 0v2.5" stroke="currentColor" strokeWidth="1.4"/></svg>,
};
window.Icon = Icon;

// ─── Mega menu data ──────────────────────────────────────────────────
const MEGA = {
  "L'Ordre": {
    intro: { title: "L'Ordre des Pharmaciens", text: "Institution de régulation et de déontologie de la pharmacie au Niger.", route: "ordre" },
    items: [
      { icon: "Building", title: "Présentation", text: "Mission, vision et valeurs", route: "ordre" },
      { icon: "Users",    title: "Bureau & Conseil", text: "Les membres élus", route: "bureau" },
      { icon: "Book",     title: "Historique", text: "50 années d'engagement", route: "histoire" },
      { icon: "Doc",      title: "Bilan annuel 2025", text: "Rapport d'activité et comptes", route: "bilan" },
      { icon: "News",     title: "Espace presse", text: "Communiqués & photothèque", route: "presse" },
      { icon: "Map",      title: "L'Ordre en chiffres", text: "Données ouvertes & cartes", route: "chiffres" },
    ],
  },
  "Annuaire": {
    intro: { title: "Trouver un pharmacien", text: "Consultez le tableau de l'Ordre et localisez les pharmacies du Niger.", route: "annuaire" },
    items: [
      { icon: "Users", title: "Tableau de l'Ordre", text: "Liste officielle des inscrits", route: "annuaire" },
      { icon: "Map",   title: "Carte des pharmacies", text: "Localiser une pharmacie", route: "annuaire#carte" },
      { icon: "Bell",  title: "Pharmacies de garde", text: "Aujourd'hui et ce week-end", route: "garde" },
      { icon: "Shield",title: "Vérifier une inscription", text: "Contrôler le statut d'un confrère", route: "verifier" },
    ],
  },
  "Services": {
    intro: { title: "Services & ressources", text: "Outils pratiques, textes réglementaires et formations professionnelles.", route: "services" },
    items: [
      { icon: "Doc",   title: "Réglementation",     text: "Textes officiels, décrets, arrêtés", route: "reglementation" },
      { icon: "Cal",   title: "Formations & Événements", text: "Agenda et inscriptions", route: "formations" },
      { icon: "Book",  title: "Proposer une formation", text: "Soumettre un projet DPC", route: "proposer" },
      { icon: "Help",  title: "FAQ & Guides santé", text: "Fiches grand public", route: "guides" },
      { icon: "Alert", title: "Alertes sanitaires", text: "Médicaments falsifiés & rappels", route: "alertes" },
      { icon: "Alert", title: "Signaler un manquement", text: "Formulaire confidentiel", route: "signaler" },
      { icon: "Users", title: "Carrières & stages", text: "Offres d'emploi pharma", route: "carrieres" },
    ],
  },
  "Public": {
    intro: { title: "Pour le grand public", text: "Trouver une pharmacie, comprendre les médicaments, savoir quand alerter.", route: "guides" },
    items: [
      { icon: "Bell",  title: "Pharmacies de garde", text: "Trouver une pharmacie ouverte", route: "garde" },
      { icon: "Book",  title: "Guides santé", text: "Bien utiliser ses médicaments", route: "guides" },
      { icon: "Users", title: "Portraits & Podcasts", text: "« Paroles de pharmaciens »", route: "portraits" },
      { icon: "Alert", title: "Alertes sanitaires", text: "Rappels & vigilance", route: "alertes" },
    ],
  },
};

const NAV_ITEMS = [
  { label: "Accueil",    route: "accueil",    mega: null },
  { label: "L'Ordre",    route: "ordre",      mega: "L'Ordre" },
  { label: "Actualités", route: "actualites", mega: null },
  { label: "Annuaire",   route: "annuaire",   mega: "Annuaire" },
  { label: "Services",   route: "services",   mega: "Services" },
  { label: "Grand public", route: "guides",   mega: "Public" },
  { label: "Contact",    route: "contact",    mega: null },
];
window.NAV_ITEMS = NAV_ITEMS;

// ─── Top Bar ─────────────────────────────────────────────────────────
function TopBar({ route, navigate, tweaks, setTweak }) {
  const [openMega, setOpenMega] = useState(null);
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const timer = useRef(null);

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

  useEffect(() => { setMobileOpen(false); setOpenMega(null); }, [route]);

  const onEnter = (name) => {
    clearTimeout(timer.current);
    if (MEGA[name]) setOpenMega(name);
    else setOpenMega(null);
  };
  const onLeave = () => {
    timer.current = setTimeout(() => setOpenMega(null), 120);
  };

  return (
    <header className={`topbar ${scrolled ? "scrolled" : ""}`} onMouseLeave={onLeave}>
      <div className="topbar-inner">
        <a href="#accueil" className="brand" onClick={(e) => { e.preventDefault(); navigate("accueil"); }}>
          <Icon.Logo size={42} />
          <span className="brand-text">
            <span className="brand-name">Ordre des Pharmaciens</span>
            <span className="brand-sub">République du Niger</span>
          </span>
        </a>

        <nav className="nav-main">
          {NAV_ITEMS.map((item) => (
            <button
              key={item.label}
              className={`nav-link ${route === item.route ? "active" : ""}`}
              onMouseEnter={() => onEnter(item.mega)}
              onClick={() => navigate(item.route)}
            >
              {item.label}
              {item.mega && <Icon.Chevron size={12} />}
            </button>
          ))}
        </nav>

        <div className="nav-actions">
          {setTweak && <LangSwitcher tweaks={tweaks} setTweak={setTweak} />}
          <button className="btn btn-ghost btn-sm" onClick={() => navigate("verifier")}>
            <Icon.Check size={14} /> Vérifier
          </button>
          <button className="btn btn-accent btn-sm" onClick={() => navigate("connexion")}>
            <Icon.Lock size={13} /> Espace membre
          </button>
          <button className="mobile-trigger" onClick={() => setMobileOpen(!mobileOpen)} aria-label="Menu">
            <Icon.Menu />
          </button>
        </div>
      </div>

      {/* Mega menu */}
      {openMega && MEGA[openMega] && (
        <div className="mega" onMouseEnter={() => clearTimeout(timer.current)} onMouseLeave={onLeave}>
          <div className="mega-inner">
            <div className="mega-intro">
              <div className="eyebrow">Section</div>
              <h3 className="serif">{MEGA[openMega].intro.title}</h3>
              <p className="muted">{MEGA[openMega].intro.text}</p>
              <button className="btn btn-primary btn-sm" onClick={() => navigate(MEGA[openMega].intro.route)} style={{ marginTop: 8 }}>
                Tout voir <Icon.ArrowRight size={12} />
              </button>
            </div>
            <div className="mega-grid">
              {MEGA[openMega].items.map((it) => {
                const I = Icon[it.icon];
                return (
                  <button key={it.title} className="mega-card" onClick={() => navigate(it.route.split("#")[0])}>
                    <div className="mega-card-icon"><I /></div>
                    <div>
                      <div className="mega-card-title">{it.title}</div>
                      <div className="mega-card-text">{it.text}</div>
                    </div>
                  </button>
                );
              })}
            </div>
          </div>
        </div>
      )}

      {/* Mobile */}
      {mobileOpen && (
        <div className="mobile-menu">
          {NAV_ITEMS.map((it) => (
            <button key={it.label} className="mobile-link" onClick={() => navigate(it.route)}>{it.label}</button>
          ))}
          <div className="mobile-actions">
            <button className="btn btn-ghost" onClick={() => navigate("verifier")}>Vérifier</button>
            <button className="btn btn-accent" onClick={() => navigate("connexion")}>Espace membre</button>
          </div>
        </div>
      )}
    </header>
  );
}

// ─── Footer ──────────────────────────────────────────────────────────
function Footer({ navigate }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-top">
          <div className="footer-brand">
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16 }}>
              <Icon.Logo size={44} />
              <div>
                <div style={{ fontFamily: "var(--ff-serif)", fontSize: 18, color: "#fff" }}>Ordre des Pharmaciens</div>
                <div style={{ fontSize: 12, color: "rgba(255,255,255,0.6)", letterSpacing: "0.08em", textTransform: "uppercase" }}>République du Niger</div>
              </div>
            </div>
            <p style={{ color: "rgba(255,255,255,0.65)", fontSize: 14, maxWidth: 320 }}>
              Institution de régulation, de déontologie et de protection de la santé publique en matière pharmaceutique.
            </p>
          </div>

          <div className="footer-col">
            <div className="footer-h">Navigation</div>
            <button onClick={() => navigate("ordre")}>L'Ordre</button>
            <button onClick={() => navigate("actualites")}>Actualités</button>
            <button onClick={() => navigate("annuaire")}>Annuaire</button>
            <button onClick={() => navigate("services")}>Services</button>
            <button onClick={() => navigate("contact")}>Contact</button>
          </div>

          <div className="footer-col">
            <div className="footer-h">Services</div>
            <button onClick={() => navigate("reglementation")}>Réglementation</button>
            <button onClick={() => navigate("formations")}>Formations</button>
            <button onClick={() => navigate("alertes")}>Alertes sanitaires</button>
            <button onClick={() => navigate("garde")}>Pharmacies de garde</button>
            <button onClick={() => navigate("guides")}>Guides santé</button>
            <button onClick={() => navigate("signaler")}>Signaler un manquement</button>
          </div>

          <div className="footer-col">
            <div className="footer-h">Newsletter</div>
            <p style={{ color: "rgba(255,255,255,0.65)", fontSize: 13, marginBottom: 10 }}>
              Recevez chaque mois la Lettre de l'Ordre : alertes, communiqués, événements.
            </p>
            <NewsletterForm inline />
            <div className="footer-h" style={{ marginTop: 24 }}>Contact</div>
            <div className="footer-contact"><Icon.Pin size={14} /> Avenue de la République,<br/>Niamey, Niger</div>
            <div className="footer-contact"><Icon.Phone size={14} /> +227 20 00 00 00</div>
            <div className="footer-contact"><Icon.Mail size={14} /> contact@opn.ne</div>
          </div>
        </div>

        <div className="footer-bottom">
          <div>© 2026 Ordre des Pharmaciens du Niger. Tous droits réservés.</div>
          <div className="footer-legal">
            <button>Mentions légales</button>
            <button>Politique de confidentialité</button>
            <button>Accessibilité</button>
          </div>
        </div>
      </div>
    </footer>
  );
}

window.TopBar = TopBar;
window.Footer = Footer;
