// GetContent — site navigation. Transparent over dark hero; solid on scroll.

function Nav({ onNav, view, solid, onSignup }) {
  const NS = window.GetContentDesignSystem_aa0f52;
  const { Button } = NS;
  // Synchroon initialiseren én direct na mount meten: na een reload halverwege de
  // pagina (scroll restoration) hoort de balk meteen gevuld te zijn, niet pas na
  // de eerstvolgende scroll-beweging.
  const [scrolled, setScrolled] = React.useState(() => {
    const s = document.querySelector('#gc-scroll');
    return ((s && s.scrollTop) || window.scrollY || 0) > 24;
  });
  const [open, setOpen] = React.useState(false);
  // Meteen synchroon bepalen op basis van de schermbreedte, zodat de eerste render
  // al klopt. Anders toont de eerste frame de desktop-nav (de paginatitel-links) en
  // springt 'ie daarna pas naar het hamburgermenu — een zichtbare glitch op mobiel.
  const [mobile, setMobile] = React.useState(() => window.matchMedia('(max-width: 820px)').matches);

  React.useEffect(() => {
    const root = document.querySelector('#gc-scroll') || window;
    const onScroll = () => setScrolled((root.scrollTop || window.scrollY || 0) > 24);
    onScroll(); // herstelde scrollpositie direct oppakken
    root.addEventListener('scroll', onScroll);
    return () => root.removeEventListener('scroll', onScroll);
  }, []);
  React.useEffect(() => {
    const mq = window.matchMedia('(max-width: 820px)');
    const apply = () => { setMobile(mq.matches); if (!mq.matches) setOpen(false); };
    apply();
    mq.addEventListener('change', apply);
    return () => mq.removeEventListener('change', apply);
  }, []);

  const filled = solid || scrolled || open;

  // bij paginawissel (solid verandert) moet de balk instant overschakelen, zonder
  // flits/fade — de vloeiende overgang is alleen bedoeld voor scrollen op de homepage.
  const prevSolidRef = React.useRef(solid);
  const pageJustChanged = prevSolidRef.current !== solid;
  React.useEffect(() => { prevSolidRef.current = solid; });

  const store = window.useStore();
  const auth = store.auth;
  const role = auth && auth.role;
  const [menuOpen, setMenuOpen] = React.useState(false);

  const publicLinks = [
    { id: 'how', label: 'Hoe het werkt' },
    { id: 'browse', label: 'Bekijk opdrachten' },
    { id: 'creators', label: 'Voor creators' },
    { id: 'about', label: 'Over ons' },
  ];
  const authLinks = role === 'creator'
    ? [{ id: 'browse', label: 'Bekijk opdrachten' }, { id: 'my-responses', label: 'Mijn reacties' }]
    : [{ id: 'my-jobs', label: 'Mijn opdrachten' }, { id: 'browse', label: 'Opdrachten' }];
  const links = auth ? authLinks : publicLinks;
  // actief = de link die overeenkomt met de huidige pagina (view)
  const isActive = (l) => l.id === view;
  const initials = auth ? auth.name.split(' ').map((w) => w[0]).slice(0, 2).join('').toUpperCase() : '';
  const menuItemStyle = { display: 'block', padding: '9px 12px', borderRadius: 'var(--radius-sm)', fontSize: 14.5, color: 'var(--text-body)', cursor: 'pointer' };

  const go = (l) => { setOpen(false); setMenuOpen(false); onNav(typeof l === 'string' ? l : l.id); };
  const logout = () => { setMenuOpen(false); setOpen(false); window.GC_STORE.logout(); onNav('home'); };

  // body-scroll blokkeren terwijl het fullscreen menu open is
  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, [open]);

  return (
    <React.Fragment>
    <header style={{
      position: 'sticky', top: 0, zIndex: 70,
      // geen backdrop-blur: de gevulde balk is volledig dekkend, dus blur is
      // onzichtbaar en kost alleen GPU (merkbaar op oudere telefoons)
      background: open ? 'transparent' : (filled ? 'rgba(18,24,38,1)' : 'transparent'),
      transition: pageJustChanged ? 'none' : 'background var(--dur-base) var(--ease-out)',
    }}>
      <div style={{ maxWidth: 'var(--container-wide)', margin: '0 auto', height: 76, padding: '0 var(--gutter)', display: 'flex', alignItems: 'center', gap: 28 }}>
        <a onClick={() => go(auth ? 'dashboard' : 'home')} style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', opacity: open ? 0 : 1, pointerEvents: open ? 'none' : 'auto', transition: 'opacity 0.2s var(--ease-out)', userSelect: 'none', WebkitUserSelect: 'none', WebkitTapHighlightColor: 'transparent' }} aria-label="getcontent home">
          {/* De SVG-viewBox is verticaal symmetrisch rond het optische midden
              (midden van de x-hoogte), zodat het centreren in de balk de tekst
              ook optisch centreert. Hoogte iets groter dan de zichtbare glyph
              omdat de viewBox extra ruimte boven de letters bevat.
              pointer-events:none op de img → een klik landt altijd op de <a>
              (navigeren), nooit op de afbeelding, en die kan niet meer geselecteerd
              of gesleept worden (de blauwe selectie-highlight bij dubbelklik). */}
          <img src="assets/logo/wordmark-warm-white-coral.svg" alt="getcontent" draggable={false} style={{ height: 25, display: 'block', userSelect: 'none', WebkitUserDrag: 'none', pointerEvents: 'none' }} />
        </a>

        {!mobile && (
          // alles rechts gegroepeerd (logo blijft links): paginatitels → verticale
          // separator → Inloggen + de creator-CTA
          <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 20 }}>
            <nav style={{ display: 'flex', gap: 4 }}>
              {links.map((l, i) => (
                <a key={i} onClick={() => go(l)} className="gc-nav-link" aria-current={isActive(l) ? 'page' : undefined} style={{
                  cursor: 'pointer', padding: '8px 14px', borderRadius: 'var(--radius-pill)', whiteSpace: 'nowrap',
                  fontSize: 15, fontWeight: isActive(l) ? 'var(--fw-bold)' : 'var(--fw-medium)', color: isActive(l) ? 'var(--text-on-dark)' : 'var(--text-on-dark-muted)',
                }}>
                  {l.label}
                </a>
              ))}
            </nav>
            <span aria-hidden style={{ width: 1, height: 24, flex: 'none', background: 'var(--border-on-dark)' }} />
            {auth ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                {role === 'opdrachtgever' && (
                  <Button variant="primary" style={{ fontWeight: 'var(--fw-medium)' }} onClick={() => go('post')}>Plaats opdracht</Button>
                )}
                <div style={{ position: 'relative' }}>
                  <button type="button" onClick={() => setMenuOpen((o) => !o)} aria-label="Account" style={{
                    width: 40, height: 40, flex: 'none', borderRadius: '50%', border: '1px solid var(--border-on-dark)',
                    background: 'rgba(245,243,239,0.10)', color: 'var(--text-on-dark)', cursor: 'pointer',
                    fontSize: 13, fontWeight: 'var(--fw-bold)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  }}>{initials}</button>
                  {menuOpen && (
                    <React.Fragment>
                      <div onClick={() => setMenuOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 1 }} />
                      <div style={{ position: 'absolute', top: 'calc(100% + 10px)', right: 0, zIndex: 2, minWidth: 214, background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-md)', boxShadow: 'var(--shadow-lg)', padding: 8, textAlign: 'left' }}>
                        <div style={{ padding: '8px 12px 10px' }}>
                          <div style={{ fontSize: 14, fontWeight: 'var(--fw-semibold)', color: 'var(--text-strong)' }}>{auth.name}</div>
                          <div style={{ fontSize: 12.5, color: 'var(--text-muted)', textTransform: 'capitalize' }}>{role}</div>
                        </div>
                        <div style={{ height: 1, background: 'var(--border-subtle)', margin: '2px 0 6px' }} />
                        {[{ id: 'dashboard', label: 'Dashboard' }, role === 'creator' ? { id: 'my-responses', label: 'Mijn reacties' } : { id: 'my-jobs', label: 'Mijn opdrachten' }, { id: 'account', label: 'Mijn profiel' }].map((it, i) => (
                          <a key={i} onClick={() => go(it.id)} className="gc-menu-item" style={menuItemStyle}>{it.label}</a>
                        ))}
                        <div style={{ height: 1, background: 'var(--border-subtle)', margin: '6px 0' }} />
                        <a onClick={logout} className="gc-menu-item" style={Object.assign({}, menuItemStyle, { color: 'var(--accent)', fontWeight: 'var(--fw-semibold)' })}>Uitloggen</a>
                      </div>
                    </React.Fragment>
                  )}
                </div>
              </div>
            ) : (
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <Button variant="ghost" style={{ color: 'var(--text-on-dark)' }} onClick={() => go('login')}>Inloggen</Button>
                <Button variant="primary" style={{ fontWeight: 'var(--fw-medium)' }} onClick={() => { setMenuOpen(false); onSignup && onSignup(); }}>Meld je gratis aan</Button>
              </div>
            )}
          </div>
        )}

        {mobile && (
          <button
            type="button"
            aria-label={open ? 'Menu sluiten' : 'Menu openen'}
            aria-expanded={open}
            onClick={() => setOpen((o) => !o)}
            style={{
              marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              width: 44, height: 44, flex: 'none', border: 'none', borderRadius: 'var(--radius-md)',
              background: 'transparent', cursor: 'pointer', padding: 0, position: 'relative', zIndex: 70,
            }}
          >
            <span style={{ position: 'relative', width: 26, height: 14, display: 'block' }}>
              {[0, 1].map((k) => (
                <span key={k} style={{
                  position: 'absolute', left: 0, height: 2, width: '100%', borderRadius: 2,
                  background: open ? 'var(--gc-ink-800)' : 'var(--gc-warm-white)',
                  top: open ? 6 : k * 12,
                  transform: open ? (k === 0 ? 'rotate(45deg)' : 'rotate(-45deg)') : 'none',
                  transformOrigin: 'center',
                  transition: 'top 0.3s var(--ease-out), transform 0.3s var(--ease-out)',
                }} />
              ))}
            </span>
          </button>
        )}
      </div>
    </header>

      {/* fullscreen mobiel menu — clean, links uitgelijnd, veel witruimte, geen kaarten/glass */}
      {mobile && (
        <div style={{
          position: 'fixed', inset: 0, zIndex: 60,
          background: 'var(--surface-page)',
          display: 'flex', flexDirection: 'column',
          padding: '88px var(--gutter) calc(env(safe-area-inset-bottom, 0px) + 32px)',
          opacity: open ? 1 : 0,
          visibility: open ? 'visible' : 'hidden',
          transform: open ? 'none' : 'translateY(-8px)',
          transition: open
            ? 'opacity 0.35s var(--ease-out), transform 0.35s var(--ease-out), visibility 0s'
            : 'opacity 0.3s var(--ease-out), transform 0.3s var(--ease-out), visibility 0s 0.3s',
        }}>
          <nav style={{ display: 'flex', flexDirection: 'column' }}>
            {links.map((l, i) => (
              <a key={i} onClick={() => go(l)} aria-current={isActive(l) ? 'page' : undefined} style={{
                cursor: 'pointer', padding: '8px 0',
                fontSize: isActive(l) ? 23 : 20, fontWeight: isActive(l) ? 'var(--fw-bold)' : 'var(--fw-medium)',
                letterSpacing: 'var(--ls-snug)', color: isActive(l) ? 'var(--text-strong)' : 'var(--text-muted)',
                opacity: open ? 1 : 0,
                transform: open ? 'none' : 'translateY(10px)',
                transition: `opacity 0.4s var(--ease-out) ${0.08 + i * 0.05}s, transform 0.4s var(--ease-out) ${0.08 + i * 0.05}s`,
              }}>{l.label}</a>
            ))}
          </nav>

          {auth ? (
            <div style={{ marginTop: 40, display: 'flex', flexDirection: 'column', gap: 12 }}>
              {role === 'opdrachtgever' && <Button variant="primary" fullWidth size="lg" onClick={() => go('post')}>Plaats opdracht</Button>}
              <Button variant="secondary" fullWidth size="lg" onClick={() => go('dashboard')}>Dashboard</Button>
              <Button variant="secondary" fullWidth size="lg" onClick={() => go('account')}>Mijn profiel</Button>
              <Button variant="ghost" fullWidth size="lg" onClick={logout}>Uitloggen</Button>
            </div>
          ) : (
            <div style={{ marginTop: 40, display: 'flex', flexDirection: 'column', gap: 12 }}>
              <Button variant="primary" fullWidth size="lg" onClick={() => { setOpen(false); onSignup && onSignup(); }}>Meld je gratis aan</Button>
              <Button variant="secondary" fullWidth size="lg" onClick={() => go('login')}>Inloggen</Button>
            </div>
          )}
        </div>
      )}
    </React.Fragment>
  );
}
window.Nav = Nav;
