// Top navigation + footer
const { useState: useStateNav } = React;

function Nav({ route, setRoute, onSearchClick }) {
  const [menuOpen, setMenuOpen] = useStateNav(false);
  const isMobile = useMobile();
  const auth = window.useAuth ? window.useAuth() : { user: null };
  const role = auth.user?.role || null;
  const canModerate = role === "moderator" || role === "admin";
  const isContributor = !!role;

  // Compteur de révisions pending pour le badge de la nav (moderators+ uniquement)
  const [pendingCount, setPendingCount] = useStateNav(0);
  React.useEffect(() => {
    if (!canModerate) { setPendingCount(0); return; }
    const fetchCount = () => {
      (window.authedFetch || fetch)("/api/list-revisions?count_only=true&status=pending", { cache: "no-store" })
        .then(r => r.ok ? r.json() : null)
        .then(d => { if (d?.count != null) setPendingCount(d.count); })
        .catch(() => {});
    };
    fetchCount();
    // Polling léger toutes les 60 secondes
    const interval = setInterval(fetchCount, 60000);
    return () => clearInterval(interval);
  }, [canModerate]);

  // Items de nav — Modération ajoutée pour les contributeurs+
  // (les contribs voient leur historique, les modos la queue à traiter)
  const items = [
    { id: "home", label: "Accueil" },
    { id: "catalogue", label: "Catalogue" },
    { id: "identifier", label: "Identifier" },
    { id: "calendrier", label: "Calendrier" },
    { id: "poles", label: "Grappes" },
    { id: "familles", label: "Familles" },
    ...(isContributor ? [{ id: "moderation", label: "Modération", badge: canModerate ? pendingCount : 0 }] : []),
    ...(role === "admin" ? [{ id: "admin", label: "Admin" }] : []),
  ];

  const handleRoute = (id) => {
    setRoute(id);
    setMenuOpen(false);
  };

  if (isMobile) {
    return (
      <header style={{ ...navWrap, background: "var(--nav-bg)" }}>
        {/* Barre supérieure mobile */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 20px", height: 58 }}>
          <button onClick={() => handleRoute("home")} style={{ ...brand, gap: 10 }}>
            <span style={{ ...brandMark, width: 32, height: 32 }}>
              <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.2">
                <circle cx="12" cy="12" r="11" />
                <path d="M6 16 Q12 4 18 8 Q14 16 6 16 Z" fill="currentColor" opacity=".15" />
                <path d="M6 16 Q12 4 18 8" />
                <line x1="6" y1="16" x2="14" y2="10" />
              </svg>
            </span>
            <span style={{ fontFamily: "var(--display)", fontSize: 20, letterSpacing: ".02em" }}>Herbarium</span>
          </button>

          <button
            onClick={() => setMenuOpen(!menuOpen)}
            style={{ width: 38, height: 38, display: "grid", placeItems: "center", border: "1px solid var(--line)", background: "transparent", flexShrink: 0 }}
            aria-label={menuOpen ? "Fermer le menu" : "Ouvrir le menu"}
            aria-expanded={menuOpen}
          >
            {menuOpen
              ? <IconClose size={16} />
              : <svg width="18" height="12" viewBox="0 0 18 12" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
                  <line x1="0" y1="1.5" x2="18" y2="1.5"/>
                  <line x1="0" y1="10.5" x2="18" y2="10.5"/>
                </svg>
            }
          </button>
        </div>

        {/* Tiroir de navigation */}
        {menuOpen && (
          <nav style={{ borderTop: "1px solid var(--line-soft)", background: "var(--cream)" }}>
            {items.map((it) => (
              <button
                key={it.id}
                onClick={() => handleRoute(it.id)}
                style={{
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "space-between",
                  width: "100%",
                  padding: "18px 20px",
                  borderBottom: "1px solid var(--line-soft)",
                  fontFamily: "var(--serif)",
                  fontSize: 22,
                  letterSpacing: ".01em",
                  color: route === it.id ? "var(--ink)" : "var(--ink-soft)",
                  background: route === it.id ? "rgba(45,67,41,0.04)" : "transparent",
                  textAlign: "left",
                }}
              >
                <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
                  {it.label}
                  {it.badge > 0 && (
                    <span style={{
                      display: "inline-grid", placeItems: "center",
                      minWidth: 22, height: 22, padding: "0 7px",
                      background: "#d92d20", color: "#fff",
                      borderRadius: 11,
                      fontFamily: "var(--mono)", fontSize: 11, fontWeight: 600, lineHeight: 1,
                    }}>{it.badge}</span>
                  )}
                </span>
                {route === it.id && (
                  <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--moss-deep)", display: "inline-block", flexShrink: 0 }} />
                )}
              </button>
            ))}
            {/* Action de création — équivalent mobile du bouton « Nouvelle fiche » du desktop */}
            <button
              onClick={() => handleRoute("edit")}
              style={{
                display: "flex", alignItems: "center", gap: 10,
                width: "100%", padding: "18px 20px",
                borderBottom: "1px solid var(--line-soft)",
                fontFamily: "var(--mono)", fontSize: 11, letterSpacing: ".18em", textTransform: "uppercase",
                color: "var(--ink-mute)", background: "transparent", textAlign: "left",
              }}
            >
              <IconPlus size={12} /> Nouvelle fiche
            </button>
            {window.UserBadge && (
              <div style={{ padding: "18px 20px", display: "flex", justifyContent: "flex-end" }}>
                <window.UserBadge />
              </div>
            )}
          </nav>
        )}
      </header>
    );
  }

  // Navigation bureau
  return (
    <header style={navWrap}>
      <div style={navInner}>
        <button onClick={() => setRoute("home")} style={brand}>
          <span style={brandMark}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.2">
              <circle cx="12" cy="12" r="11" />
              <path d="M6 16 Q12 4 18 8 Q14 16 6 16 Z" fill="currentColor" opacity=".15" />
              <path d="M6 16 Q12 4 18 8" />
              <line x1="6" y1="16" x2="14" y2="10" />
            </svg>
          </span>
          <span style={brandText}>
            <span style={brandName}>Herbarium</span>
            <span style={brandSub}>Inventaire botanique partagé</span>
          </span>
        </button>

        <nav style={navList}>
          {items.map((it) => (
            <button
              key={it.id}
              onClick={() => setRoute(it.id)}
              style={{ ...navItem, ...(route === it.id ? navItemActive : {}) }}
            >
              {it.label}
              {it.badge > 0 && (
                <span style={{
                  display: "inline-grid", placeItems: "center",
                  marginLeft: 6, minWidth: 18, height: 18, padding: "0 5px",
                  background: "#d92d20", color: "#fff",
                  borderRadius: 9,
                  fontFamily: "var(--mono)", fontSize: 10, fontWeight: 600,
                  lineHeight: 1,
                }}>{it.badge}</span>
              )}
              <span style={{ ...navUnderline, transform: route === it.id ? "scaleX(1)" : "scaleX(0)" }} />
            </button>
          ))}
        </nav>

        <div style={navTools}>
          <button style={navIcon} title="Recherche" onClick={onSearchClick}><IconSearch size={15} /></button>
          {window.UserBadge && <window.UserBadge />}
          <button onClick={() => setRoute("edit")} className="nav-cta">
            <IconPlus size={13} />
            Nouvelle fiche
          </button>
        </div>
      </div>
    </header>
  );
}

function Footer() {
  const isMobile = useMobile();

  if (isMobile) {
    return (
      <footer style={{ ...footWrap, marginTop: 60 }}>
        <div style={{ padding: "44px 20px 36px" }}>
          <div style={{ marginBottom: 24 }}>
            <div className="h-italic" style={{ fontSize: 26 }}>Herbarium</div>
            <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--ink-mute)", marginTop: 6 }}>
              Recueil collaboratif · {new Date().getFullYear()}
            </div>
          </div>
          <div style={{ fontFamily: "var(--serif)", fontSize: 14, fontStyle: "italic", color: "var(--ink-mute)", lineHeight: 1.55, borderTop: "1px solid var(--line-soft)", paddingTop: 20 }}>
            « La nature est là qui t'invite et qui t'aime. »
            <div style={{ marginTop: 8, fontFamily: "var(--mono)", fontSize: 10, letterSpacing: ".14em", fontStyle: "normal" }}>— Alphonse de Lamartine</div>
          </div>
        </div>
      </footer>
    );
  }

  return (
    <footer style={footWrap}>
      <div style={footInner}>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <div className="h-italic" style={{ fontSize: 26 }}>Herbarium</div>
          <div style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--ink-mute)" }}>
            Recueil collaboratif · {new Date().getFullYear()}
          </div>
        </div>
        <div style={footCols}>
          <FootCol title="Le projet" items={["Manifeste", "Comité botanique", "Charte de contribution", "Mentions légales"]} />
          <FootCol title="Explorer" items={["Catalogue", "Familles", "Usages", "Floraison"]} />
          <FootCol title="Jardins associés" items={["Jardin Aimé", "Jardin Médicinal", "Syracuse", "Knossos", "Palmyre"]} />
        </div>
        <div style={{ fontFamily: "var(--serif)", fontSize: 19, lineHeight: 1.4, fontStyle: "italic", color: "var(--ink-soft)", maxWidth: 320 }}>
          « Il faut cultiver notre jardin. »
          <div style={{ marginTop: 10, fontFamily: "var(--mono)", fontSize: 11, letterSpacing: ".14em", fontStyle: "normal", color: "var(--ink-mute)" }}>— Voltaire</div>
        </div>
      </div>
    </footer>
  );
}

function FootCol({ title, items }) {
  return (
    <div>
      <div className="kicker" style={{ marginBottom: 14 }}>{title}</div>
      <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 8 }}>
        {items.map((i) => (
          <li key={i} style={{ fontFamily: "var(--serif)", fontSize: 16, color: "var(--ink-soft)", cursor: "pointer" }}>
            {i}
          </li>
        ))}
      </ul>
    </div>
  );
}

const navWrap = { position: "sticky", top: 0, zIndex: 50, backdropFilter: "blur(10px)", WebkitBackdropFilter: "blur(10px)", background: "var(--nav-bg)", borderBottom: "1px solid var(--line-soft)" };
const navInner = { maxWidth: 1400, margin: "0 auto", padding: "16px 40px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 32 };
const brand = { display: "flex", alignItems: "center", gap: 12, padding: 0 };
const brandMark = { width: 38, height: 38, display: "grid", placeItems: "center", color: "var(--moss-deep)", border: "1px solid var(--line)", borderRadius: "50%", background: "var(--cream)" };
const brandText = { display: "flex", flexDirection: "column", alignItems: "flex-start", lineHeight: 1 };
const brandName = { fontFamily: "var(--display)", fontSize: 22, letterSpacing: ".02em" };
const brandSub = { fontFamily: "var(--mono)", fontSize: 9.5, letterSpacing: ".18em", textTransform: "uppercase", color: "var(--ink-mute)", marginTop: 4 };
const navList = { display: "flex", alignItems: "center", gap: 6 };
// inline-flex + alignItems center : le libellé et la pastille de compteur restent
// sur une même ligne, centrés verticalement — sinon la pastille (haute) décale la
// ligne de base et désaligne l'item par rapport à ses voisins.
const navItem = { position: "relative", display: "inline-flex", alignItems: "center", padding: "10px 14px", fontFamily: "var(--serif)", fontSize: 16, color: "var(--ink-soft)", letterSpacing: ".01em" };
const navItemActive = { color: "var(--ink)" };
const navUnderline = { position: "absolute", left: 14, right: 14, bottom: 4, height: 1, background: "var(--moss-deep)", transformOrigin: "left", transition: "transform 280ms var(--ease)" };
const navTools = { display: "flex", alignItems: "center", gap: 10 };
const navIcon = { width: 36, height: 36, border: "1px solid var(--line)", borderRadius: "50%", display: "grid", placeItems: "center", color: "var(--ink-soft)" };
// Bouton « Nouvelle fiche » : pilule contour, défini en CSS (.nav-cta) pour le :hover.

const footWrap = { borderTop: "1px solid var(--line-soft)", marginTop: 100, background: "linear-gradient(180deg, transparent, rgba(45,67,41,0.06))" };
const footInner = { maxWidth: 1400, margin: "0 auto", padding: "70px 40px 50px", display: "grid", gridTemplateColumns: "1fr 2fr 1fr", gap: 60, alignItems: "start" };
const footCols = { display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 40 };

Object.assign(window, { Nav, Footer });
