// Top navigation

function useViewport() {
  const getState = () => {
    const width = window.innerWidth;
    return {
      width,
      isMobile: width <= 720,
      isTablet: width <= 960,
    };
  };

  const [viewport, setViewport] = React.useState(getState);

  React.useEffect(() => {
    const onResize = () => setViewport(getState());
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);

  return viewport;
}

function Nav() {
  const [scrolled, setScrolled] = React.useState(false);
  const [currentPath, setCurrentPath] = React.useState("");
  const [menuOpen, setMenuOpen] = React.useState(false);
  const { isMobile, isTablet } = useViewport();

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener("scroll", onScroll, { passive: true });
    // Get current page filename
    const path = window.location.pathname.split("/").pop() || "index.html";
    setCurrentPath(path);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  React.useEffect(() => {
    if (!isTablet) setMenuOpen(false);
  }, [isTablet]);

  React.useEffect(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
    return () => {
      document.body.style.overflow = "";
    };
  }, [menuOpen]);

  const links = [
    { label: "Accueil", href: "index.html", match: ["index.html", ""] },
    { label: "Services", href: "services.html", match: ["services.html"] },
    { label: "Portfolio", href: "portfolio.html", match: ["portfolio.html"] },
    { label: "À propos", href: "about.html", match: ["about.html"] },
    { label: "Processus", href: "index.html#processus", match: [] },
  ];

  const isActive = (l) => l.match.includes(currentPath);
  const showDesktopNav = !isTablet;

  return (
    <header
      style={{
        position: "fixed",
        top: 0, left: 0, right: 0,
        zIndex: 50,
        padding: "14px 0",
        backdropFilter: "blur(14px)",
        background: scrolled ? "oklch(1 0 0 / 0.78)" : "transparent",
        borderBottom: scrolled ? "1px solid var(--hairline)" : "1px solid transparent",
        transition: "background .25s ease, border-color .25s ease",
      }}
    >
      <div
        className="container"
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: isMobile ? 12 : 20,
        }}
      >
        <a href="index.html" aria-label="InfinitDev — accueil">
          <img src="assets/infinitdev-logo-horizontal.png" alt="InfinitDev" style={{ height: isMobile ? 44 : 60, width: "auto", display: "block", maxWidth: isMobile ? 210 : "none" }} />
        </a>
        {showDesktopNav ? (
          <>
            <nav
              style={{
                display: "flex",
                gap: 4,
                alignItems: "center",
                fontSize: 14,
                color: "var(--ink-muted)",
              }}
              className="nav-links"
            >
              {links.map((l) => {
                const active = isActive(l);
                return (
                  <a
                    key={l.label}
                    href={l.href}
                    data-active={active || undefined}
                    style={{
                      padding: "8px 14px",
                      borderRadius: "var(--r-pill)",
                      transition: "color .2s, background .2s",
                      color: active ? "var(--ink)" : "var(--ink-muted)",
                      fontWeight: active ? 500 : 400,
                      background: active ? "var(--cyan-wash)" : "transparent",
                      position: "relative",
                    }}
                    onMouseEnter={(e) => {
                      if (active) return;
                      e.currentTarget.style.color = "var(--ink)";
                      e.currentTarget.style.background = "var(--bg-alt)";
                    }}
                    onMouseLeave={(e) => {
                      if (active) return;
                      e.currentTarget.style.color = "var(--ink-muted)";
                      e.currentTarget.style.background = "transparent";
                    }}
                  >
                    {l.label}
                    {active && (
                      <span
                        aria-hidden
                        style={{
                          position: "absolute",
                          left: "50%",
                          bottom: -6,
                          transform: "translateX(-50%)",
                          width: 4,
                          height: 4,
                          borderRadius: "50%",
                          background: "var(--cyan)",
                        }}
                      />
                    )}
                  </a>
                );
              })}
            </nav>
            <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
              <a href="contact.html" className="btn btn-primary" style={{ padding: "10px 18px", fontSize: 13.5, width: "auto" }}>
                Démarrer un projet
                <span className="arr">→</span>
              </a>
            </div>
          </>
        ) : (
          <>
            <button
              aria-label={menuOpen ? "Fermer le menu" : "Ouvrir le menu"}
              aria-expanded={menuOpen}
              onClick={() => setMenuOpen((open) => !open)}
              style={{
                width: 46,
                height: 46,
                borderRadius: "50%",
                border: "1px solid var(--hairline-strong)",
                background: "var(--surface)",
                display: "grid",
                placeItems: "center",
                flexShrink: 0,
              }}
            >
              <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                {[0, 1, 2].map((line) => (
                  <span
                    key={line}
                    style={{
                      width: 18,
                      height: 1.5,
                      borderRadius: 999,
                      background: "var(--ink)",
                      transform:
                        menuOpen && line === 0 ? "translateY(5.5px) rotate(45deg)"
                        : menuOpen && line === 1 ? "scaleX(0)"
                        : menuOpen && line === 2 ? "translateY(-5.5px) rotate(-45deg)"
                        : "none",
                      transition: "transform .2s ease, opacity .2s ease",
                      opacity: menuOpen && line === 1 ? 0 : 1,
                    }}
                  />
                ))}
              </div>
            </button>
            <div
              style={{
                position: "fixed",
                top: 76,
                left: 12,
                right: 12,
                background: "oklch(1 0 0 / 0.96)",
                backdropFilter: "blur(16px)",
                border: "1px solid var(--hairline)",
                borderRadius: "22px",
                boxShadow: "var(--shadow-md)",
                padding: 16,
                display: menuOpen ? "flex" : "none",
                flexDirection: "column",
                gap: 10,
                maxHeight: "calc(100vh - 96px)",
                overflowY: "auto",
              }}
            >
              {links.map((l) => {
                const active = isActive(l);
                return (
                  <a
                    key={l.label}
                    href={l.href}
                    onClick={() => setMenuOpen(false)}
                    style={{
                      padding: "14px 16px",
                      borderRadius: 16,
                      background: active ? "var(--cyan-wash)" : "transparent",
                      color: active ? "var(--ink)" : "var(--ink-muted)",
                      fontWeight: active ? 600 : 500,
                      border: "1px solid " + (active ? "var(--cyan)" : "var(--hairline)"),
                    }}
                  >
                    {l.label}
                  </a>
                );
              })}
              <a href="contact.html" className="btn btn-primary" onClick={() => setMenuOpen(false)} style={{ marginTop: 6 }}>
                Démarrer un projet
                <span className="arr">→</span>
              </a>
            </div>
          </>
        )}
      </div>
    </header>
  );
}

Object.assign(window, { Nav, useViewport });
