/* global React */

/* Single source of truth for the nav. Desktop splits this list either side of
   the centered brand mark; tablet/phone shows all of it in the drawer. */
const NAV_LINKS = [
  { id: 'home',       label: 'Home' },
  { id: 'portfolio',  label: 'Portfolio' },
  { id: 'about',      label: 'About' },
  { id: 'investment', label: 'Investment' },
  { id: 'journal',    label: 'Journal' },
  { id: 'contact',    label: 'Contact' },
];
const NAV_SPLIT = 3;                       // first 3 left of the logo, rest right
const DRAWER_BREAKPOINT = 1024;            // matches the @media in kit.css

function Header({ activePage, onNav }) {
  // Overlay mode: transparent nav, cream links, primary logo — active while
  // the home hero is still underneath the nav; flips solid once scrolled past.
  const [overlay, setOverlay] = React.useState(activePage === 'home');
  const [menuOpen, setMenuOpen] = React.useState(false);
  const navRef = React.useRef(null);

  React.useEffect(() => {
    const update = () => {
      const hero = document.querySelector('.hero-bleed');
      // Measured, not hard-coded — the nav is shorter on tablet and phone.
      const navH = navRef.current ? navRef.current.offsetHeight : 113;
      setOverlay(!!hero && hero.getBoundingClientRect().bottom > navH);
    };
    update();
    window.addEventListener('scroll', update, { passive: true });
    window.addEventListener('resize', update);
    return () => {
      window.removeEventListener('scroll', update);
      window.removeEventListener('resize', update);
    };
  }, [activePage]);

  // Navigating away always closes the drawer.
  React.useEffect(() => { setMenuOpen(false); }, [activePage]);

  React.useEffect(() => {
    if (!menuOpen) return;
    // Freeze the page behind the drawer, and bail out of the drawer entirely if
    // the window grows past the breakpoint where the full nav reappears.
    // html is the scroll container here (colors_and_type.css sets
    // overflow-x: hidden on it, which computes overflow-y to auto), so locking
    // body alone left the page scrollable and its scrollbar on screen.
    const html = document.documentElement;
    const prevBodyOverflow = document.body.style.overflow;
    const prevHtmlOverflow = html.style.overflow;
    const scrollY = window.scrollY;
    // Hiding a classic scrollbar widens the viewport; reserve its width so the
    // pinned bar and drawer do not jump sideways as the drawer opens.
    const barW = window.innerWidth - html.clientWidth;
    html.style.setProperty('--scrollbar-w', `${barW}px`);
    html.style.overflow = 'hidden';
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') setMenuOpen(false); };
    const onResize = () => { if (window.innerWidth > DRAWER_BREAKPOINT) setMenuOpen(false); };
    window.addEventListener('keydown', onKey);
    window.addEventListener('resize', onResize);
    return () => {
      document.body.style.overflow = prevBodyOverflow;
      html.style.overflow = prevHtmlOverflow;
      html.style.removeProperty('--scrollbar-w');
      // .kit-nav--menu-open took the bar out of flow, so the document was a nav
      // height shorter while the drawer was open. Put the reader back exactly
      // where they were. When the drawer closed because of a navigation, App's
      // route effect runs after this and scrolls to the top instead.
      window.scrollTo(0, scrollY);
      window.removeEventListener('keydown', onKey);
      window.removeEventListener('resize', onResize);
    };
  }, [menuOpen]);

  const left = NAV_LINKS.slice(0, NAV_SPLIT);
  const right = NAV_LINKS.slice(NAV_SPLIT);

  // The cream-on-photo treatment would be unreadable against the open drawer.
  const isOverlay = overlay && !menuOpen;

  const navLink = (l) => (
    <button
      key={l.id}
      className={`kit-nav__link ${activePage === l.id ? 'is-active' : ''}`}
      onClick={() => onNav(l.id)}
    >
      {l.label}
    </button>
  );

  return (
    <header
      ref={navRef}
      className={`kit-nav ${isOverlay ? 'kit-nav--overlay' : ''} ${menuOpen ? 'kit-nav--menu-open' : ''}`}
    >
      <button
        className={`kit-nav__burger ${menuOpen ? 'is-open' : ''}`}
        aria-label={menuOpen ? 'Close menu' : 'Open menu'}
        aria-expanded={menuOpen}
        aria-controls="site-menu"
        onClick={() => setMenuOpen(o => !o)}
      >
        <span /><span /><span />
      </button>

      <div className="kit-nav__left">{left.map(navLink)}</div>

      <div className="kit-brand" onClick={() => onNav('home')}>
        <img
          src={asset(isOverlay ? 'assets/ahp-logo/Primary-cream.png' : 'assets/ahp-logo/AH-green.png')}
          alt="Abby Harper Photography"
        />
      </div>

      <div className="kit-nav__right">{right.map(navLink)}</div>

      <div id="site-menu" className={`nav-drawer ${menuOpen ? 'is-open' : ''}`} aria-hidden={!menuOpen}>
        <nav className="nav-drawer__links">
          {NAV_LINKS.map((l, i) => (
            <button
              key={l.id}
              className={`nav-drawer__link ${activePage === l.id ? 'is-active' : ''}`}
              tabIndex={menuOpen ? 0 : -1}
              onClick={() => { setMenuOpen(false); onNav(l.id); }}
            >
              <span className="nav-drawer__num">{String(i + 1).padStart(2, '0')}</span>
              {l.label}
            </button>
          ))}
        </nav>
        <div className="nav-drawer__foot">
          <a href="mailto:abbyharperphoto@gmail.com" tabIndex={menuOpen ? 0 : -1}>
            abbyharperphoto@gmail.com
          </a>
          <span>Athens · Georgia</span>
        </div>
      </div>
    </header>
  );
}

window.Header = Header;
