// Nav — collapsible sidebar (desktop) + hamburger drawer (mobile).
//
// Desktop: pill sidebar with sections + page links + CTA. A collapse toggle
//   shrinks it to a 52px icon rail saved in localStorage.
// Mobile: hidden sidebar; hamburger button opens a full-height left drawer.

function Nav({ active = "projeto", onNavigate }) {
  const [scrolled,     setScrolled]     = React.useState(false);
  const [collapsed,    setCollapsed]    = React.useState(() => {
    try { return localStorage.getItem("nav-collapsed") === "true"; } catch { return false; }
  });
  const [drawerOpen,   setDrawerOpen]   = React.useState(false);
  const [isMobile,     setIsMobile]     = React.useState(window.innerWidth < 768);

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

  React.useEffect(() => {
    const onResize = () => setIsMobile(window.innerWidth < 768);
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);

  // Close drawer on Escape
  React.useEffect(() => {
    if (!drawerOpen) return;
    const h = (e) => { if (e.key === "Escape") setDrawerOpen(false); };
    document.addEventListener("keydown", h);
    return () => document.removeEventListener("keydown", h);
  }, [drawerOpen]);

  // Prevent body scroll when drawer open
  React.useEffect(() => {
    document.body.style.overflow = (drawerOpen && isMobile) ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [drawerOpen, isMobile]);

  const toggleCollapsed = () => {
    const next = !collapsed;
    setCollapsed(next);
    try { localStorage.setItem("nav-collapsed", String(next)); } catch {}
    if (next) {
      document.body.setAttribute("data-nav-collapsed", "");
    } else {
      document.body.removeAttribute("data-nav-collapsed");
    }
  };

  // Sync body attribute on mount from saved state
  React.useEffect(() => {
    if (!isMobile) {
      if (collapsed) {
        document.body.setAttribute("data-nav-collapsed", "");
      } else {
        document.body.removeAttribute("data-nav-collapsed");
      }
    }
  }, [isMobile]);

  const sections = [
    { id: "projeto",      label: "Projeto" },
    { id: "experimentos", label: "Experiências" },
    { id: "impacto",      label: "Impacto" },
    { id: "galeria",      label: "Galeria" },
  ];

  const pages = [
    { label: "Catálogo",   href: "./catalogo.html" },
    { label: "Calendário", href: "./calendario.html" },
    { label: "Equipe",     href: "./equipe.html" },
    { label: "Sobre",      href: "./sobre.html" },
    { label: "Missão",     href: "./missao.html" },
  ];

  const actions = [
    { label: "Parcerias",     href: "./parceria.html" },
    { label: "Levar à Escola", href: "./levar.html" },
  ];

  const handleSection = (id) => {
    onNavigate && onNavigate(id);
    setDrawerOpen(false);
  };

  // ─────────────────────────────── MOBILE ────────────────────────────────

  if (isMobile) {
    return (
      <>
        {/* Hamburger pill — top-right */}
        <button
          aria-label="Abrir menu"
          onClick={() => setDrawerOpen(true)}
          style={{
            position: "fixed", top: 16, right: 16, zIndex: 200,
            display: "flex", alignItems: "center", gap: 10,
            padding: "11px 16px",
            background: scrolled ? "rgba(6,9,20,0.92)" : "rgba(6,9,20,0.78)",
            backdropFilter: "blur(20px)", WebkitBackdropFilter: "blur(20px)",
            border: "1px solid rgba(255,255,255,0.09)",
            borderRadius: "var(--r-lg)",
            cursor: "pointer",
            transition: "background 0.3s",
            boxShadow: "0 8px 32px rgba(0,0,0,0.4)",
          }}>
          <img src="./assets/logo-white.svg" alt=""
            style={{ width: 22, height: 22, filter: "drop-shadow(0 0 8px rgba(45,111,247,0.5))" }} />
          {/* Hamburger lines */}
          <div style={{ display: "flex", flexDirection: "column", gap: 4, width: 18 }}>
            <div style={{ height: 1.5, background: "var(--fg-2)", borderRadius: 2 }} />
            <div style={{ height: 1.5, background: "var(--fg-2)", borderRadius: 2, width: "70%" }} />
            <div style={{ height: 1.5, background: "var(--fg-2)", borderRadius: 2 }} />
          </div>
        </button>

        {/* Backdrop */}
        {drawerOpen && (
          <div
            onClick={() => setDrawerOpen(false)}
            style={{
              position: "fixed", inset: 0, zIndex: 299,
              background: "rgba(4,6,12,0.72)",
              backdropFilter: "blur(4px)", WebkitBackdropFilter: "blur(4px)",
              animation: "fadeIn 0.22s ease-out both",
            }}
          />
        )}

        {/* Drawer */}
        <nav
          aria-hidden={!drawerOpen}
          style={{
            position: "fixed", top: 0, left: 0, bottom: 0,
            width: 280, zIndex: 300,
            background: "rgba(6,9,20,0.97)",
            backdropFilter: "blur(24px)", WebkitBackdropFilter: "blur(24px)",
            borderRight: "1px solid var(--line)",
            display: "flex", flexDirection: "column",
            padding: "24px 20px 32px",
            transform: drawerOpen ? "translateX(0)" : "translateX(-100%)",
            transition: "transform 0.32s var(--ease-out)",
            overflowY: "auto",
            boxShadow: drawerOpen ? "0 0 60px rgba(0,0,0,0.7)" : "none",
          }}>
          {/* Drawer header */}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 28 }}>
            <a href="#top" onClick={() => { handleSection("top"); }} style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <img src="./assets/logo-white.svg" alt="Física Além do Papel"
                style={{ width: 30, height: 30, filter: "drop-shadow(0 0 10px rgba(45,111,247,0.5))" }} />
              <span style={{
                fontFamily: "var(--font-wordmark)", fontWeight: 500,
                letterSpacing: "0.1em", fontSize: 11.5, lineHeight: 1.3, color: "var(--fg-1)",
              }}>FÍSICA<br/>ALÉM DO<br/>PAPEL</span>
            </a>
            <button
              aria-label="Fechar menu"
              onClick={() => setDrawerOpen(false)}
              style={{
                width: 36, height: 36, borderRadius: "50%",
                background: "rgba(255,255,255,0.06)",
                border: "1px solid var(--line)",
                color: "var(--fg-2)", fontSize: 18, cursor: "pointer",
                display: "flex", alignItems: "center", justifyContent: "center",
              }}>×</button>
          </div>

          <div style={{ height: 1, background: "var(--line)", marginBottom: 20 }} />

          {/* Sections */}
          <DrawerGroup label="Seções">
            {sections.map(l => (
              <DrawerLink key={l.id}
                href={`#${l.id}`}
                active={active === l.id}
                onClick={() => handleSection(l.id)}>
                {l.label}
              </DrawerLink>
            ))}
          </DrawerGroup>

          <DrawerDivider />

          {/* Pages */}
          <DrawerGroup label="Páginas">
            {pages.map(p => (
              <DrawerLink key={p.label} href={p.href}>{p.label}</DrawerLink>
            ))}

          </DrawerGroup>

          <DrawerDivider />

          {/* Actions */}
          <DrawerGroup label="Conexão">
            {actions.map(a => (
              <DrawerLink key={a.label} href={a.href}>{a.label}</DrawerLink>
            ))}
          </DrawerGroup>

          {/* CTA */}
          <div style={{ marginTop: "auto", paddingTop: 24 }}>
            <a href="./contato.html" className="btn btn-primary"
              style={{ width: "100%", justifyContent: "center", textDecoration: "none" }}>
              Contato <span className="arrow">→</span>
            </a>
          </div>
        </nav>
      </>
    );
  }

  // ─────────────────────────────── DESKTOP ───────────────────────────────

  const navW = collapsed ? 52 : 220;

  return (
    <header style={{
      position: "fixed", top: 0, bottom: 0, left: 12, zIndex: 100,
      display: "flex", alignItems: "center", pointerEvents: "none",
    }}>
      <nav style={{
        pointerEvents: "auto",
        display: "flex", flexDirection: "column", alignItems: "stretch",
        gap: 0,
        padding: collapsed ? "20px 10px" : "22px 18px",
        background: scrolled ? "rgba(8,12,24,0.85)" : "rgba(8,12,24,0.48)",
        backdropFilter: "blur(24px)",
        WebkitBackdropFilter: "blur(24px)",
        border: "1px solid var(--line)",
        borderRadius: "var(--r-lg)",
        transition: "all 0.38s var(--ease-out)",
        boxShadow: scrolled ? "0 16px 40px rgba(0,0,0,0.5)" : "none",
        width: navW,
        overflow: "hidden",
        minHeight: 0,
      }}>

        {/* Logo */}
        <a href="#top"
          onClick={() => onNavigate && onNavigate("top")}
          title="Física Além do Papel"
          style={{
            display: "flex", alignItems: "center",
            gap: collapsed ? 0 : 10,
            justifyContent: collapsed ? "center" : "flex-start",
            marginBottom: collapsed ? 16 : 18,
            flexShrink: 0,
          }}>
          <img src="./assets/logo-white.svg" alt="Física Além do Papel"
            style={{ width: 30, height: 30, flexShrink: 0, filter: "drop-shadow(0 0 12px rgba(45,111,247,0.45))" }} />
          {!collapsed && (
            <span style={{
              fontFamily: "var(--font-wordmark)", fontWeight: 500,
              letterSpacing: "0.1em", fontSize: 11.5, lineHeight: 1.3,
              color: "var(--fg-1)", whiteSpace: "nowrap",
            }}>FÍSICA<br/>ALÉM DO<br/>PAPEL</span>
          )}
        </a>

        <SidebarDivider />

        {/* Section links with scroll-spy */}
        {!collapsed && (
          <SidebarGroupLabel>Seções</SidebarGroupLabel>
        )}
        <div style={{ display: "flex", flexDirection: "column", gap: 2, marginBottom: 8 }}>
          {sections.map(l => (
            <SidebarLink key={l.id}
              href={`#${l.id}`}
              active={active === l.id}
              collapsed={collapsed}
              onClick={() => { onNavigate && onNavigate(l.id); }}
              dot>
              {l.label}
            </SidebarLink>
          ))}
        </div>

        <SidebarDivider />

        {/* Page links */}
        {!collapsed && (
          <SidebarGroupLabel>Páginas</SidebarGroupLabel>
        )}
        <div style={{ display: "flex", flexDirection: "column", gap: 2, marginBottom: 8 }}>
          {pages.map(p => (
            <SidebarLink key={p.label} href={p.href} collapsed={collapsed}>
              {p.label}
            </SidebarLink>
          ))}
        </div>

        <SidebarDivider />

        {/* Action links */}
        {!collapsed && (
          <SidebarGroupLabel>Conexão</SidebarGroupLabel>
        )}
        <div style={{ display: "flex", flexDirection: "column", gap: 2, marginBottom: 16 }}>
          {actions.map(a => (
            <SidebarLink key={a.label} href={a.href} collapsed={collapsed} accent>
              {a.label}
            </SidebarLink>
          ))}
        </div>

        {/* CTA */}
        {!collapsed && (
          <a href="./contato.html" className="btn btn-primary"
            style={{ padding: "11px 12px", fontSize: 12.5, borderRadius: "var(--r-md)", justifyContent: "center", textDecoration: "none" }}>
            Contato <span className="arrow">→</span>
          </a>
        )}

        {/* Collapse toggle */}
        <button
          onClick={toggleCollapsed}
          title={collapsed ? "Expandir" : "Recolher"}
          style={{
            marginTop: collapsed ? 12 : 14,
            alignSelf: "center",
            background: "rgba(255,255,255,0.04)",
            border: "1px solid var(--line)",
            borderRadius: "var(--r-sm)",
            width: 28, height: 22,
            cursor: "pointer", color: "var(--fg-4)",
            fontSize: 11, lineHeight: 1,
            display: "flex", alignItems: "center", justifyContent: "center",
            transition: "all 0.2s",
            flexShrink: 0,
          }}
          onMouseOver={(e) => e.currentTarget.style.color = "var(--fg-1)"}
          onMouseOut={(e) => e.currentTarget.style.color = "var(--fg-4)"}
        >
          {collapsed ? "›" : "‹"}
        </button>
      </nav>
    </header>
  );
}

// ─── Sub-components ───────────────────────────────────────────────────────

function SidebarDivider() {
  return <div style={{ height: 1, background: "var(--line)", margin: "8px 0" }} />;
}

function SidebarGroupLabel({ children }) {
  return (
    <div style={{
      fontFamily: "var(--font-mono)", fontSize: 9,
      color: "var(--fg-4)", letterSpacing: "0.22em",
      textTransform: "uppercase", padding: "4px 6px 6px",
    }}>{children}</div>
  );
}

function SidebarLink({ href, children, active, collapsed, dot, accent, onClick }) {
  const [hover, setHover] = React.useState(false);
  const isAccent = accent && !active;

  return (
    <a
      href={href}
      onClick={onClick}
      onMouseOver={() => setHover(true)}
      onMouseOut={() => setHover(false)}
      title={collapsed ? children : undefined}
      style={{
        fontFamily: "var(--font-display)", fontSize: 13, fontWeight: active ? 500 : 400,
        padding: collapsed ? "8px 0" : "8px 10px",
        borderRadius: "var(--r-sm)",
        color: active
          ? "var(--plasma-cyan)"
          : hover
            ? "var(--fg-1)"
            : isAccent
              ? "var(--electric-soft)"
              : "var(--fg-2)",
        background: active ? "rgba(0,229,255,0.08)" : hover ? "rgba(255,255,255,0.04)" : "transparent",
        transition: "color 0.18s, background 0.18s",
        display: "flex", alignItems: "center",
        gap: collapsed ? 0 : 8,
        justifyContent: collapsed ? "center" : "flex-start",
        whiteSpace: "nowrap",
        textDecoration: "none",
      }}
    >
      {dot && (
        <span style={{
          width: 5, height: 5, borderRadius: "50%", flexShrink: 0,
          background: active ? "var(--plasma-cyan)" : hover ? "var(--fg-3)" : "var(--line-strong)",
          boxShadow: active ? "0 0 8px var(--plasma-cyan)" : "none",
          transition: "all 0.18s",
        }} />
      )}
      {!collapsed && children}
    </a>
  );
}

function DrawerGroup({ label, children }) {
  return (
    <div style={{ marginBottom: 8 }}>
      <div style={{
        fontFamily: "var(--font-mono)", fontSize: 9,
        color: "var(--fg-4)", letterSpacing: "0.22em",
        textTransform: "uppercase", padding: "0 4px 8px",
      }}>{label}</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>{children}</div>
    </div>
  );
}

function DrawerDivider() {
  return <div style={{ height: 1, background: "var(--line)", margin: "12px 0" }} />;
}

function DrawerLink({ href, children, active, onClick }) {
  return (
    <a href={href} onClick={onClick} style={{
      fontFamily: "var(--font-display)", fontSize: 15, fontWeight: active ? 500 : 400,
      padding: "11px 12px", borderRadius: "var(--r-md)",
      color: active ? "var(--plasma-cyan)" : "var(--fg-2)",
      background: active ? "rgba(0,229,255,0.08)" : "transparent",
      display: "flex", alignItems: "center", gap: 10,
      textDecoration: "none",
      transition: "all 0.2s",
    }}>
      {active && (
        <span style={{
          width: 5, height: 5, borderRadius: "50%",
          background: "var(--plasma-cyan)",
          boxShadow: "0 0 8px var(--plasma-cyan)",
        }} />
      )}
      {children}
    </a>
  );
}

window.Nav = Nav;
