function Logo() {
  const goHome = (e) => {
    e.preventDefault();
    const el = document.getElementById("accueil");
    if (!el) return;
    const headerOffset = 110;
    const y = el.getBoundingClientRect().top + window.pageYOffset - headerOffset;
    window.scrollTo({ top: Math.max(y, 0), behavior: "smooth" });
  };

  return (
    <a href="#accueil" className="logo" onClick={goHome}>
      <img src="logo.svg" alt="Discover Studio" style={{ height: 38, marginTop: 6 }} />
    </a>
  );
}

const NAV_LINKS = [
  { label: "Accueil",  id: "accueil"  },
  { label: "Projets",  id: "projets"  },
  { label: "Services", id: "services" },
  { label: "Sur nous", id: "sur-nous" },
  { label: "FAQ",      id: "faq"      },
];

function NavLink({ label, id, active, onClick }) {
  const scrollToSection = (targetId) => {
    const el = document.getElementById(targetId);
    if (!el) return;
    const headerOffset = 110;
    const y = el.getBoundingClientRect().top + window.pageYOffset - headerOffset;
    window.scrollTo({ top: Math.max(y, 0), behavior: "smooth" });
  };

  return (
    <a
      href={`#${id}`}
      className={`nav-link${active ? " nav-link--active" : ""}`}
      onClick={(e) => {
        e.preventDefault();
        onClick && onClick(id);
        scrollToSection(id);
      }}
    >
      {label}
    </a>
  );
}

function Nav() {
  const [scrolled, setScrolled] = React.useState(false);
  const [active, setActive]     = React.useState("accueil");
  const [drawerOpen, setDrawerOpen] = React.useState(false);
  const pendingTargetRef = React.useRef(null);

  const scrollToSection = React.useCallback((targetId) => {
    const el = document.getElementById(targetId);
    if (!el) return;
    const headerOffset = 110;
    const y = el.getBoundingClientRect().top + window.pageYOffset - headerOffset;
    window.scrollTo({ top: Math.max(y, 0), behavior: "smooth" });
  }, []);

  const startProgrammaticNav = React.useCallback((targetId) => {
    pendingTargetRef.current = targetId;
    setActive(targetId);
  }, []);

  React.useEffect(() => {
    const onScroll = () => {
      setScrolled(window.scrollY > 30);

      // Keep the clicked tab active while smooth scrolling to that section.
      if (pendingTargetRef.current) {
        const targetEl = document.getElementById(pendingTargetRef.current);
        if (!targetEl) {
          pendingTargetRef.current = null;
        } else {
          const targetY = Math.max(targetEl.offsetTop - 110, 0);
          if (Math.abs(window.scrollY - targetY) > 18) {
            setActive(pendingTargetRef.current);
            return;
          }
          pendingTargetRef.current = null;
        }
      }

      // Highlight active section based on the nearest section above viewport.
      let current = "accueil";
      let bestTop = -Infinity;
      NAV_LINKS.forEach(({ id }) => {
        const el = document.getElementById(id);
        if (!el) return;
        const top = el.offsetTop - 120;
        if (window.scrollY >= top && top > bestTop) {
          bestTop = top;
          current = id;
        }
      });
      setActive(current);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <>
      <div className={`nav-wrap${scrolled ? " scrolled" : ""}`}>
        <div className="container">
          <div className="nav">
            <Logo />
            <div className="nav-links">
              {NAV_LINKS.map(({ label, id }) => (
                <NavLink
                  key={id}
                  label={label}
                  id={id}
                  active={active === id}
                  onClick={startProgrammaticNav}
                />
              ))}
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <button
                className="btn btn-primary nav-cta-btn"
                onClick={() => {
                  window.dispatchEvent(new CustomEvent("openContactModal"));
                }}
              >
                Démarrer un projet
              </button>
              <button className="mobile-toggle" onClick={() => setDrawerOpen(true)} aria-label="Menu">
                <Icon.Menu />
              </button>
            </div>
          </div>
        </div>
      </div>

      <div className={`mobile-drawer${drawerOpen ? " open" : ""}`} onClick={() => setDrawerOpen(false)}>
        <div className="mobile-drawer-inner" onClick={(e) => e.stopPropagation()}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
            <Logo />
            <button onClick={() => setDrawerOpen(false)} style={{ width: 36, height: 36, borderRadius: 10, background: "var(--bg-soft)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
              <Icon.X />
            </button>
          </div>
          {NAV_LINKS.map(({ label, id }) => (
            <NavLink
              key={id}
              label={label}
              id={id}
              active={active === id}
              onClick={(targetId) => {
                startProgrammaticNav(targetId);
                setDrawerOpen(false);
              }}
            />
          ))}
          <button 
            className="btn btn-primary" 
            style={{ marginTop: 18 }}
            onClick={() => {
              setDrawerOpen(false);
              window.dispatchEvent(new CustomEvent("openContactModal"));
            }}
          >
            Démarrer un projet
          </button>
        </div>
      </div>
    </>
  );
}

window.Nav = Nav;
