/* global React, Wordmark */

function smoothScrollToCenter(id) {
  const target = document.getElementById(id);
  if (!target) return;
  // Find the nearest scrollable ancestor (defaults to window if none)
  let scrollEl = target.parentElement;
  while (scrollEl && scrollEl !== document.body) {
    const cs = getComputedStyle(scrollEl);
    const overflows = /(auto|scroll|overlay)/.test(cs.overflowY);
    if (overflows && scrollEl.scrollHeight > scrollEl.clientHeight) break;
    scrollEl = scrollEl.parentElement;
  }
  const useWindow = !scrollEl || scrollEl === document.body;
  const viewportHeight = useWindow ? window.innerHeight : scrollEl.clientHeight;
  const currentTop = useWindow ? window.scrollY : scrollEl.scrollTop;
  const rect = target.getBoundingClientRect();
  const containerRect = useWindow ? { top: 0 } : scrollEl.getBoundingClientRect();
  const targetTop = currentTop + rect.top - containerRect.top;
  const targetCenter = targetTop + rect.height / 2 - viewportHeight / 2;
  if (useWindow) {
    window.scrollTo({ top: Math.max(0, targetCenter), behavior: 'smooth' });
  } else {
    scrollEl.scrollTo({ top: Math.max(0, targetCenter), behavior: 'smooth' });
  }
}
window.smoothScrollToCenter = smoothScrollToCenter;

function Nav({ active = "Home", transparent = false }) {
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const [isSolid, setIsSolid] = React.useState(false);

  // When nav floats over the hero, switch to a solid PCB-green bar once the
  // user scrolls past the hero. The scroll listener walks the DOM up from #home
  // to find the actual scrolling ancestor (window or an overflow:auto parent).
  React.useEffect(() => {
    if (!transparent) return;
    const hero = document.getElementById('home');
    if (!hero) return;

    let scrollEl = hero.parentElement;
    while (scrollEl && scrollEl !== document.body) {
      const cs = getComputedStyle(scrollEl);
      if (/(auto|scroll|overlay)/.test(cs.overflowY) && scrollEl.scrollHeight > scrollEl.clientHeight) break;
      scrollEl = scrollEl.parentElement;
    }
    const useWindow = !scrollEl || scrollEl === document.body;
    const target = useWindow ? window : scrollEl;

    const check = () => {
      const r = hero.getBoundingClientRect();
      // Anchor to the scroll container's viewport top, not the window's
      const containerTop = useWindow ? 0 : scrollEl.getBoundingClientRect().top;
      setIsSolid((r.bottom - containerTop) < 80);
    };
    target.addEventListener('scroll', check, { passive: true });
    check();
    return () => target.removeEventListener('scroll', check);
  }, [transparent]);

  const items = [
    { k: 'Home', href: '#home' },
    { k: 'Products & Services', href: '#services' },
    { k: 'About', href: '#about' },
    { k: 'Community', href: '#community' },
  ];

  const handleClick = (e, href) => {
    if (!href || !href.startsWith('#')) return;
    e.preventDefault();
    setMobileOpen(false);
    smoothScrollToCenter(href.slice(1));
  };

  return (
    <nav className={"nav" + (transparent ? " nav-over-hero" : "") + (isSolid ? " is-solid" : "") + (mobileOpen ? " mobile-open" : "")}>
      <div className="nav-inner">
        <Wordmark onDark={transparent || isSolid} />
        <ul className="nav-items">
          {items.map((it) => (
            <li key={it.k} style={{ position: 'relative' }}>
              <a
                href={it.href}
                onClick={(e) => handleClick(e, it.href)}
                className={active === it.k ? "is-active" : ""}
              >
                {it.k}
              </a>
            </li>
          ))}
        </ul>
        <div className="nav-cta">
          <a href="#contact" onClick={(e) => handleClick(e, '#contact')}>
            <button className="btn btn-primary">Contact us</button>
          </a>
        </div>
        <button
          className="nav-burger"
          aria-label={mobileOpen ? 'Close menu' : 'Open menu'}
          aria-expanded={mobileOpen}
          onClick={() => setMobileOpen((v) => !v)}>
          <span className="nav-burger-line" />
          <span className="nav-burger-line" />
          <span className="nav-burger-line" />
        </button>
      </div>
    </nav>
  );
}

window.Nav = Nav;
