// Nav.jsx — Tiber Course sticky navigation (desktop + mobile drawer)
const Nav = ({ page, onNav }) => {
  const [scrolled, setScrolled]   = React.useState(false);
  const [logoFailed, setLogoFailed] = React.useState(false);
  const [isNarrow, setIsNarrow]   = React.useState(false);
  const [drawerOpen, setDrawerOpen] = React.useState(false);
  const hamburgerRef = React.useRef(null);
  const firstLinkRef = React.useRef(null);
  const wasOpenRef   = React.useRef(false);

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    const mql = window.matchMedia('(max-width: 820px)');
    const onMql = () => setIsNarrow(mql.matches);
    onScroll();
    onMql();
    window.addEventListener('scroll', onScroll, { passive: true });
    mql.addEventListener ? mql.addEventListener('change', onMql) : mql.addListener(onMql);
    return () => {
      window.removeEventListener('scroll', onScroll);
      mql.removeEventListener ? mql.removeEventListener('change', onMql) : mql.removeListener(onMql);
    };
  }, []);

  // Lock body scroll when drawer is open
  React.useEffect(() => {
    document.body.style.overflow = drawerOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [drawerOpen]);

  // Move focus into the drawer on open; return it to the hamburger on close
  React.useEffect(() => {
    if (drawerOpen) {
      wasOpenRef.current = true;
      if (firstLinkRef.current) firstLinkRef.current.focus();
    } else if (wasOpenRef.current) {
      if (hamburgerRef.current) hamburgerRef.current.focus();
    }
  }, [drawerOpen]);

  // Escape closes the drawer
  React.useEffect(() => {
    if (!drawerOpen) return;
    const onKey = (e) => { if (e.key === 'Escape') setDrawerOpen(false); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [drawerOpen]);

  const links = [
    { label: 'Courses',      p: 'courses' },
    { label: 'How it works', p: 'how-it-works' },
    { label: 'Pricing',      p: 'pricing' },
    { label: 'Lockdubh',     p: 'lockdubh' },
    { label: 'Contact',      p: 'contact' },
  ];

  const goAndClose = (p) => { setDrawerOpen(false); onNav(p); };

  const navHeight = isNarrow ? 64 : 84;
  const logoHeight = isNarrow ? 44 : 64;

  return (
    <React.Fragment>
      <nav style={{
        position: 'fixed', top: 40, left: 0, right: 0, zIndex: 200,
        background: scrolled ? 'rgba(237,232,223,0.97)' : 'rgba(237,232,223,0.85)',
        backdropFilter: 'blur(20px)',
        WebkitBackdropFilter: 'blur(20px)',
        borderBottom: `1px solid ${scrolled ? C.border : C.borderSubtle}`,
        transition: 'all 0.35s ease',
        padding: isNarrow ? '0 20px' : '0 40px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        height: navHeight,
      }}>
        <button onClick={() => goAndClose('home')} aria-label="Tiber Course — home" style={{
          background: 'none', border: 'none', cursor: 'pointer', padding: 0,
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          {!logoFailed ? (
            <img
              src="assets/logo.png"
              alt="Tiber Course"
              onError={() => setLogoFailed(true)}
              style={{ height: logoHeight, width: 'auto', display: 'block' }}
            />
          ) : (
            <span style={{
              fontFamily: F.display, fontStyle: 'italic',
              fontSize: isNarrow ? 20 : 24, color: C.ink, letterSpacing: '0.5px',
            }}>Tiber Course</span>
          )}
        </button>

        {/* Desktop nav */}
        {!isNarrow && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 30 }}>
            {links.map(({ label, p }) => (
              <NavLink key={p} label={label} active={page === p} onClick={() => onNav(p)} />
            ))}
            <div style={{ width: 1, height: 18, background: C.border, marginLeft: 4 }} />
            <button
              onClick={() => onNav('contact')}
              aria-label="Book a demo"
              style={{
                background: C.ink, color: C.textInverse,
                border: 'none', borderRadius: 9999,
                fontFamily: F.sans, fontSize: 11, fontWeight: 500,
                letterSpacing: '1.6px', textTransform: 'uppercase',
                padding: '10px 22px', cursor: 'pointer',
                transition: 'opacity 0.2s',
                outline: 'none',
              whiteSpace: 'nowrap' }}
              onFocus={e => e.currentTarget.style.boxShadow = `0 0 0 2px ${C.parchment}, 0 0 0 4px ${C.ink}`}
              onBlur={e => e.currentTarget.style.boxShadow = 'none'}
              onMouseEnter={e => e.currentTarget.style.opacity = '0.82'}
              onMouseLeave={e => e.currentTarget.style.opacity = '1'}
            >Book a demo</button>
          </div>
        )}

        {/* Mobile hamburger */}
        {isNarrow && (
          <button
            ref={hamburgerRef}
            onClick={() => setDrawerOpen(o => !o)}
            aria-label={drawerOpen ? 'Close menu' : 'Open menu'}
            aria-expanded={drawerOpen}
            aria-controls="mobile-menu"
            style={{
              background: 'none', border: `1px solid ${C.borderStrong}`,
              borderRadius: 9999, width: 42, height: 42, cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              padding: 0,
              transition: 'background 0.2s',
            }}
          >
            <svg width="18" height="14" viewBox="0 0 18 14" fill="none" aria-hidden="true">
              {drawerOpen ? (
                <React.Fragment>
                  <line x1="2" y1="2"  x2="16" y2="12" stroke={C.ink} strokeWidth="1.8" strokeLinecap="round" />
                  <line x1="2" y1="12" x2="16" y2="2"  stroke={C.ink} strokeWidth="1.8" strokeLinecap="round" />
                </React.Fragment>
              ) : (
                <React.Fragment>
                  <line x1="1" y1="2"  x2="17" y2="2"  stroke={C.ink} strokeWidth="1.6" strokeLinecap="round" />
                  <line x1="1" y1="7"  x2="17" y2="7"  stroke={C.ink} strokeWidth="1.6" strokeLinecap="round" />
                  <line x1="1" y1="12" x2="17" y2="12" stroke={C.ink} strokeWidth="1.6" strokeLinecap="round" />
                </React.Fragment>
              )}
            </svg>
          </button>
        )}
      </nav>

      {/* Mobile drawer */}
      {isNarrow && (
        <React.Fragment>
          <div
            onClick={() => setDrawerOpen(false)}
            aria-hidden="true"
            style={{
              position: 'fixed', inset: 0, zIndex: 198,
              background: 'rgba(26,25,23,0.45)',
              opacity: drawerOpen ? 1 : 0,
              pointerEvents: drawerOpen ? 'auto' : 'none',
              transition: 'opacity 0.25s ease',
            }}
          />
          <aside
            id="mobile-menu"
            role={drawerOpen ? 'dialog' : undefined}
            aria-modal={drawerOpen ? 'true' : undefined}
            aria-hidden={!drawerOpen}
            aria-label="Site navigation"
            style={{
              position: 'fixed', top: 0, right: 0, bottom: 0, zIndex: 199,
              width: 'min(86vw, 360px)',
              background: C.parchment,
              borderLeft: `1px solid ${C.border}`,
              padding: '128px 28px 32px',
              display: 'flex', flexDirection: 'column',
              transform: drawerOpen ? 'translateX(0)' : 'translateX(100%)',
              // visibility flips to hidden only after the slide-out finishes,
              // and removes the drawer's buttons from the tab order while closed
              visibility: drawerOpen ? 'visible' : 'hidden',
              transition: 'transform 0.32s cubic-bezier(0.22, 1, 0.36, 1), visibility 0.3s',
              boxShadow: drawerOpen ? '-12px 0 32px rgba(26,25,23,0.18)' : 'none',
            }}
          >
            <nav style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              {links.map(({ label, p }, i) => (
                <button
                  key={p}
                  ref={i === 0 ? firstLinkRef : undefined}
                  onClick={() => goAndClose(p)}
                  style={{
                    background: page === p ? C.linen : 'transparent',
                    border: 'none', borderRadius: 10,
                    fontFamily: F.sans, fontSize: 15, fontWeight: 500,
                    color: C.ink, textAlign: 'left',
                    padding: '14px 16px', cursor: 'pointer',
                    transition: 'background 0.18s',
                    outline: 'none',
                  }}
                  onFocus={e => e.currentTarget.style.background = C.linen}
                  onBlur={e => e.currentTarget.style.background = page === p ? C.linen : 'transparent'}
                >{label}</button>
              ))}
            </nav>
            <div style={{ marginTop: 'auto', display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div style={{ height: 1, background: C.border }} />
              <button
                onClick={() => goAndClose('contact')}
                style={{
                  background: C.ink, color: C.textInverse,
                  border: 'none', borderRadius: 9999,
                  fontFamily: F.sans, fontSize: 12, fontWeight: 500,
                  letterSpacing: '1.6px', textTransform: 'uppercase',
                  padding: '14px 24px', cursor: 'pointer',
                  outline: 'none',
                whiteSpace: 'nowrap' }}
              >Book a demo</button>
              <div style={{ fontFamily: F.body, fontSize: 12.5, color: C.dust, textAlign: 'center' }}>
                accounts@tibercourse.com
              </div>
            </div>
          </aside>
        </React.Fragment>
      )}
    </React.Fragment>
  );
};

const NavLink = ({ label, active, onClick }) => {
  const [hov, setHov] = React.useState(false);
  return (
    <button onClick={onClick}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      onFocus={e => e.currentTarget.style.boxShadow = `0 0 0 2px ${C.parchment}, 0 0 0 4px ${C.ink}`}
      onBlur={e => e.currentTarget.style.boxShadow = 'none'}
      style={{
        position: 'relative',
        background: 'none', border: 'none', cursor: 'pointer', padding: 0,
        fontFamily: F.sans, fontSize: 12, fontWeight: 500,
        letterSpacing: '1.4px', textTransform: 'uppercase',
        color: active || hov ? C.ink : C.ash,
        paddingBottom: 6,
        transition: 'color 0.2s',
        outline: 'none',
      }}>
      {label}
      {active && (
        // Underline expands from a centered dot to a full bar on each activation.
        // Re-mounting (active flag flipping) re-triggers the CSS animation.
        <span
          aria-hidden="true"
          style={{
            position: 'absolute',
            left: '50%', bottom: 0,
            transform: 'translateX(-50%)',
            height: 1.5, background: C.ink, borderRadius: 1,
            width: '100%',
            animation: 'navUnderlineExpand 0.42s cubic-bezier(0.22, 1, 0.36, 1) both',
          }}
        />
      )}
    </button>
  );
};

Object.assign(window, { Nav });
