// Header.jsx - TBS Digital Labs Website (dark theme only)
function dsReadInitialScrolled() {
  if (typeof window === 'undefined') return false;
  try {
    return window.scrollY > 20;
  } catch (e) {
    return false;
  }
}
function dsReadInitialNarrow() {
  if (typeof window === 'undefined') return false;
  try {
    return window.matchMedia('(max-width: 880px)').matches;
  } catch (e) {
    return false;
  }
}

function dsIsServicePage(activePage) {
  return typeof SERVICE_SLUGS !== 'undefined' && SERVICE_SLUGS.indexOf(activePage) >= 0;
}

Object.assign(window, {
  SiteHeader: function({ activePage, onNavigate }) {
    const t = darkTheme;
    const [scrolled, setScrolled] = React.useState(dsReadInitialScrolled);
    const [mobileOpen, setMobileOpen] = React.useState(false);
    const [servicesOpen, setServicesOpen] = React.useState(false);
    const [mobileServicesOpen, setMobileServicesOpen] = React.useState(false);
    const [isNarrow, setIsNarrow] = React.useState(dsReadInitialNarrow);
    const servicesRef = React.useRef(null);

    var serviceNav = typeof SERVICE_NAV !== 'undefined' ? SERVICE_NAV : [];

    var links = [
      { label: 'Work', key: 'work' },
      { label: 'About', key: 'about' },
      { label: 'Insights', key: 'insights' },
    ];

    var servicesActive = activePage === 'services' || dsIsServicePage(activePage);

    React.useLayoutEffect(function syncScrolledWithScrollPosition() {
      setScrolled(window.scrollY > 20);
    }, [activePage]);

    React.useEffect(function () {
      const onScroll = function () { setScrolled(window.scrollY > 20); };
      window.addEventListener('scroll', onScroll, { passive: true });
      return function () { window.removeEventListener('scroll', onScroll); };
    }, []);

    React.useEffect(function () {
      const mq = window.matchMedia('(max-width: 880px)');
      const apply = function () { setIsNarrow(mq.matches); };
      apply();
      mq.addEventListener('change', apply);
      return function () { mq.removeEventListener('change', apply); };
    }, []);

    React.useEffect(function () {
      if (!mobileOpen) return;
      const onKey = function (e) { if (e.key === 'Escape') setMobileOpen(false); };
      window.addEventListener('keydown', onKey);
      return function () { window.removeEventListener('keydown', onKey); };
    }, [mobileOpen]);

    React.useEffect(function () {
      if (typeof document === 'undefined') return undefined;
      const prev = document.body.style.overflow;
      if (mobileOpen) document.body.style.overflow = 'hidden';
      else document.body.style.overflow = prev || '';
      return function () {
        document.body.style.overflow = prev || '';
      };
    }, [mobileOpen]);

    React.useEffect(function () {
      if (!servicesOpen) return undefined;
      function onDocClick(e) {
        if (servicesRef.current && !servicesRef.current.contains(e.target)) {
          setServicesOpen(false);
        }
      }
      document.addEventListener('mousedown', onDocClick);
      return function () { document.removeEventListener('mousedown', onDocClick); };
    }, [servicesOpen]);

    const nav = function (key) {
      setMobileOpen(false);
      setMobileServicesOpen(false);
      setServicesOpen(false);
      onNavigate(key);
    };

    const navBtn = {
      fontFamily: "'Rethink Sans', sans-serif",
      fontSize: 16,
      fontWeight: 400,
      background: 'none',
      border: 'none',
      cursor: 'pointer',
      padding: '10px 4px',
      minHeight: 44,
      color: t.fg2,
      textAlign: 'left',
    };

    const ctaPrimary = {
      background: t.a1,
      color: t.onAccent,
      border: 'none',
      cursor: 'pointer',
      fontFamily: "'Rethink Sans', sans-serif",
      fontWeight: 600,
      fontSize: 16,
      lineHeight: 1.25,
      padding: '12px 22px',
      borderRadius: 2,
      minHeight: 44,
      boxSizing: 'border-box',
    };

    return (
      <header className="ds-site-header" style={{
        position: 'fixed', top: 0, left: 0, right: 0, zIndex: 5000,
        background: scrolled ? t.navBg : t.navBackdropIdle,
        backdropFilter: 'blur(16px)',
        borderBottom: scrolled ? '1px solid ' + t.border2 : '1px solid transparent',
        minHeight: 76,
        boxSizing: 'border-box',
        display: 'flex', alignItems: 'center',
        padding: '0 var(--ds-page-gutter)',
        justifyContent: 'space-between',
        transition: 'background 0.3s ease, border-color 0.3s ease',
        paddingTop: 'calc(env(safe-area-inset-top, 0px) + 10px)',
        paddingBottom: 10,
        overflow: 'visible',
      }}>
        <span className={'ds-header-glow ' + (scrolled ? 'is-visible' : '')} aria-hidden="true" />
        <button
          type="button"
          onClick={function () { nav('home'); }}
          style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'flex-start', background: 'none', border: 'none', padding: '6px 4px', minWidth: 44, minHeight: 44, overflow: 'visible' }}
          aria-label="TBS Digital Labs home"
        >
          <img src={t.logo} alt="" loading="eager" decoding="sync" fetchPriority="high" style={{ height: t.logoHeight, width: 'auto', maxWidth: 'min(200px, 42vw)', display: 'block', objectFit: 'contain', objectPosition: 'left center', transition: 'opacity 240ms ease' }} />
        </button>

        {isNarrow ? (
          <button
            type="button"
            className={'ds-btn ds-btn--secondary ds-header-menu-icon' + (mobileOpen ? ' is-open' : '')}
            onClick={function () { setMobileOpen(function (o) { return !o; }); }}
            aria-expanded={mobileOpen}
            aria-controls="site-mobile-nav"
            aria-label={mobileOpen ? 'Close menu' : 'Open menu'}
          >
            <span className="ds-header-menu-icon-bars" aria-hidden="true">
              <span />
              <span />
              <span />
            </span>
          </button>
        ) : (
          <nav style={{ display: 'flex', alignItems: 'center', gap: 28 }} aria-label="Primary">
            <div ref={servicesRef} style={{ position: 'relative' }}>
              <button
                type="button"
                onClick={function () { setServicesOpen(function (o) { return !o; }); }}
                className="ds-nav-btn"
                data-active={servicesActive ? 'true' : 'false'}
                aria-expanded={servicesOpen}
                aria-haspopup="true"
                style={{
                  ...navBtn,
                  color: servicesActive ? t.fg : t.fg2,
                  paddingBottom: 14,
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: 6,
                }}
              >
                Services
                <span aria-hidden="true" style={{ fontSize: 12, opacity: 0.8 }}>{servicesOpen ? '\u25B4' : '\u25BE'}</span>
              </button>
              {servicesOpen ? (
                <div
                  role="menu"
                  style={{
                    position: 'absolute',
                    top: '100%',
                    left: 0,
                    marginTop: 8,
                    minWidth: 280,
                    background: t.navBg,
                    border: '1px solid ' + t.border2,
                    borderRadius: 2,
                    padding: '8px 0',
                    boxShadow: t.elevatedShadow,
                    zIndex: 6000,
                  }}
                >
                  <button type="button" role="menuitem" onClick={function () { nav('services'); }} style={{ ...navBtn, width: '100%', padding: '12px 20px', color: activePage === 'services' ? t.fg : t.fg2, fontWeight: activePage === 'services' ? 600 : 400 }}>
                    All services
                  </button>
                  {serviceNav.map(function (svc) {
                    return (
                      <button
                        key={svc.slug}
                        type="button"
                        role="menuitem"
                        onClick={function () { nav(svc.slug); }}
                        style={{ ...navBtn, width: '100%', padding: '10px 20px', color: activePage === svc.slug ? t.fg : t.fg2, fontWeight: activePage === svc.slug ? 600 : 400 }}
                      >
                        {svc.label}
                      </button>
                    );
                  })}
                </div>
              ) : null}
            </div>
            {links.map(function (l) {
              return (
                <button
                  key={l.key}
                  type="button"
                  onClick={function () { nav(l.key); }}
                  className="ds-nav-btn"
                  data-active={activePage === l.key ? 'true' : 'false'}
                  style={{
                    ...navBtn,
                    color: activePage === l.key ? t.fg : t.fg2,
                    paddingBottom: 14,
                  }}
                >
                  {l.label}
                </button>
              );
            })}
            <button
              type="button"
              onClick={function () { nav('contact'); }}
              className="ds-btn-primary"
              style={ctaPrimary}
            >
              <span>Let&apos;s Talk</span>
            </button>
          </nav>
        )}

        {isNarrow && mobileOpen ? (
          <div
            id="site-mobile-nav"
            style={{
              position: 'absolute',
              top: '100%',
              left: 0,
              right: 0,
              background: t.navBg,
              borderBottom: '1px solid ' + t.border2,
              padding: '8px var(--ds-page-gutter) 20px',
              display: 'flex',
              flexDirection: 'column',
              gap: 4,
              backdropFilter: 'blur(20px)',
              maxHeight: 'calc(100dvh - var(--ds-header-offset))',
              overflowY: 'auto',
            }}
          >
            <button
              type="button"
              onClick={function () { setMobileServicesOpen(function (o) { return !o; }); }}
              aria-expanded={mobileServicesOpen}
              style={{
                ...navBtn,
                color: servicesActive ? t.fg : t.fg2,
                padding: '14px 8px',
                borderBottom: '1px solid ' + t.border2,
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                width: '100%',
              }}
            >
              <span>Services</span>
              <span aria-hidden="true">{mobileServicesOpen ? '\u2212' : '+'}</span>
            </button>
            {mobileServicesOpen ? (
              <div style={{ paddingLeft: 12, paddingBottom: 8 }}>
                <button type="button" onClick={function () { nav('services'); }} style={{ ...navBtn, color: activePage === 'services' ? t.fg : t.fg2, padding: '10px 8px', width: '100%' }}>All services</button>
                {serviceNav.map(function (svc) {
                  return (
                    <button key={svc.slug} type="button" onClick={function () { nav(svc.slug); }} style={{ ...navBtn, color: activePage === svc.slug ? t.fg : t.fg2, padding: '10px 8px', width: '100%' }}>{svc.label}</button>
                  );
                })}
              </div>
            ) : null}
            {links.map(function (l) {
              return (
                <button
                  key={l.key}
                  type="button"
                  onClick={function () { nav(l.key); }}
                  style={{
                    ...navBtn,
                    color: activePage === l.key ? t.fg : t.fg2,
                    padding: '14px 8px',
                    borderBottom: '1px solid ' + t.border2,
                  }}
                >
                  {l.label}
                </button>
              );
            })}
            <button
              type="button"
              onClick={function () { nav('contact'); }}
              className="ds-btn-primary"
              style={{ ...ctaPrimary, marginTop: 12, width: '100%' }}
            >
              <span>Let&apos;s Talk</span>
            </button>
          </div>
        ) : null}
      </header>
    );
  }
});
