(function() {
  var useState  = React.useState;
  var useEffect = React.useEffect;
  var useRef    = React.useRef;

  var GlassNavBar  = window.GlassNavBar;
  var GlassMenu    = window.GlassMenu;
  var GlassButton  = window.GlassButton;
  var Ico          = window.GlassIcons;

  /* Screens that should NOT keep Explore highlighted (they have their own tabs or are secondary) */
  var HOME_SCREENS = [
    'projects', 'project-detail', 'city-map', 'ar-demo', 'funding', 'community', 'quests',
    'submit', 'profile', 'opportunities', 'opportunity-detail', 'owner-dashboard',
    'wallet', 'marketplace', 'inventory', 'messages', 'feed'
  ];

  /* Rank tiers, lowest → highest. Reputation is the only progression
     signal the User model carries, so it drives the tier. */
  var TIERS = [
    { name: 'Bronze',   min: 0,     c: '#C08457' },
    { name: 'Silver',   min: 100,   c: '#B8C4D0' },
    { name: 'Gold',     min: 500,   c: '#F5B942' },
    { name: 'Platinum', min: 1500,  c: '#7FD8D8' },
    { name: 'Diamond',  min: 3500,  c: '#5CE1E6' },
    { name: 'Crown',    min: 7500,  c: '#A78BFA' },
    { name: 'Ace',      min: 15000, c: '#FF6B9D' },
  ];

  function tierFor(rep) {
    var r = Math.max(0, Number(rep) || 0);
    var i = 0;
    for (var k = 0; k < TIERS.length; k++) if (r >= TIERS[k].min) i = k;
    var cur = TIERS[i], next = TIERS[i + 1] || null;
    // Top tier has no ceiling — show the bar full rather than dividing by zero.
    var pct = next ? Math.min(100, Math.round(((r - cur.min) / (next.min - cur.min)) * 100)) : 100;
    return { cur: cur, next: next, pct: pct, rep: r };
  }

  function compact(n) {
    var v = Number(n) || 0;
    if (v >= 1e6) return (v / 1e6).toFixed(v % 1e6 === 0 ? 0 : 1) + 'M';
    if (v >= 1e4) return (v / 1e3).toFixed(0) + 'K';
    return v.toLocaleString();
  }

  function ProfileMenu(props) {
    var user = props.user;
    var _open = useState(false);
    var open = _open[0], setOpen = _open[1];
    var _wallet = useState(null);
    var wallet = _wallet[0], setWallet = _wallet[1];
    var anchorRef = useRef(null);

    // Fetch the wallet lazily — only once the menu is actually opened.
    useEffect(function() {
      if (!open || wallet || !window.ApiClient) return;
      var cancelled = false;
      window.ApiClient.get('/buildcoins/wallet')
        .then(function(res) { if (!cancelled) setWallet(res && res.wallet ? res.wallet : null); })
        .catch(function() { /* stats are non-essential — leave them blank */ });
      return function() { cancelled = true; };
    }, [open, wallet]);

    var hover = function() { document.body.classList.add('hov'); };
    var leave = function() { document.body.classList.remove('hov'); };

    var initials = (user.name || '?').split(' ').map(function(n) { return n[0] || ''; }).join('').slice(0, 2).toUpperCase();
    var tier = tierFor(user.reputation);

    function go(screen, params) {
      setOpen(false);
      window.navigate(screen, params || {});
    }

    // AI-generated nav art (Vertex, --set nav). Rendered at 26px inside
    // GlassMenu's 28px slot — these are deliberately bold, low-detail
    // forms so they still read once shrunk this far.
    function ico(name) {
      return <img src={'/assets/gamification/nav/nav-' + name + '.png'} alt="" className="nav-ico" loading="lazy" />;
    }

    var ITEMS = [
      { icon:ico('generate'),  label:'Create vision',    hint:'Photo → enhance → 3D',     run:function(){ go('submit'); } },
      { icon:ico('projects'),  label:'My projects',      hint:'Visions and 3D models',    run:function(){ go('profile', { userId: user._id }); } },
      { icon: window.CBIcon ? React.createElement(window.CBIcon, { name: 'mail', size: 18 }) : '✉',
        label:'Messages', hint:'Direct chats', run:function(){ go('messages'); } },
      { divider: true },
      { icon:ico('wallet'),    label:'Wallet',           hint:'BuildCoins balance',       run:function(){ go('wallet'); } },
      { icon:ico('inventory'), label:'Inventory',        hint:'Purchases and gifts',      run:function(){ go('inventory'); } },
      { icon:ico('fund'),      label:'Funding',          hint:'Back community visions',   run:function(){ go('funding'); } },
      { icon:ico('citymap'),   label:'City Map',         hint:'Explore the city in 3D',   run:function(){ go('city-map'); } },
      { icon:ico('owner'),     label:'Owner dashboard',  hint:'Publish and review sites', run:function(){ go('owner-dashboard'); } },
    ];

    if (user.role === 'admin') {
      ITEMS.push({ divider: true });
      ITEMS.push({ icon:ico('admin'), label:'Admin', hint:'Intelligence platform', run:function(){ setOpen(false); window.open('admin.html', '_blank'); } });
    }

    return (
      <div className="nav-profile" ref={anchorRef}>
        <button type="button" className={'nav-avatar' + (open ? ' open' : '')}
          data-tour="nav-avatar"
          title={user.name + ' · profile & settings'}
          onMouseEnter={hover} onMouseLeave={leave}
          onClick={function(){ setOpen(!open); }}
          aria-expanded={open} aria-haspopup="menu">
          {initials}
        </button>

        <GlassMenu
          open={open}
          onClose={function(){ setOpen(false); }}
          anchor={anchorRef.current}
          className="profile-dropdown"
          style={{ position:'absolute', top:'calc(100% + 12px)', right:0, width:'min(280px, calc(100vw - 24px))', maxWidth:'calc(100vw - 24px)', zIndex:1000 }}
          items={ITEMS.concat([{ divider:true }, {
            icon: ico('signout'),
            label:'Sign Out',
            run: function(){ props.onLogout(); }
          }])}
        >
          <div className="profile-dropdown-head">
            <div className="profile-dropdown-avatar">{initials}</div>
            <div className="profile-dropdown-meta">
              <div className="profile-dropdown-name">{user.name}</div>
              <div className="profile-dropdown-email">{user.email}</div>
              <div className="profile-dropdown-badges">
                <span className="pstat-tier-chip" style={{ '--tier': tier.cur.c }}>{tier.cur.name}</span>
                <span className={'chip ' + (user.role==='admin'?'c-a':user.role==='business'?'c-l':user.role==='government'?'c-c':'c-v')}>
                  {(window.CBRoles&&window.CBRoles.label(user.role))||'Builder'}
                </span>
              </div>
            </div>
          </div>

          <div className="pstat pstat--slim">
            <div className="pstat-bar" role="progressbar" aria-valuenow={tier.pct} aria-valuemin={0} aria-valuemax={100}>
              <span className="pstat-bar-fill" style={{ width: tier.pct + '%', '--tier': tier.cur.c }} />
            </div>
            <div className="pstat-slim-row">
              <span className="pstat-slim-item">
                <strong>{compact(tier.rep)}</strong> rep
              </span>
              <span className="pstat-slim-item pstat-slim-item--coin">
                <Ico.Wallet size={14} />
                <strong>{wallet ? compact(wallet.balance) : '—'}</strong>
              </span>
              <span className="pstat-slim-item">
                <strong>{compact((user.projects || []).length)}</strong> builds
              </span>
            </div>
          </div>
        </GlassMenu>
      </div>
    );
  }

  function HeaderNav(props) {
    var active = props.active;
    var authUser = props.authUser;
    var onLoginClick = props.onLoginClick;
    var onLogout = props.onLogout;

    var tabs = window.USER_NAV_TABS || [];

    var _progress = useState(0);
    var progress = _progress[0], setProgress = _progress[1];
    var _questPending = useState(window.CBQuests ? window.CBQuests.pendingCount() : 0);
    var questPending = _questPending[0], setQuestPending = _questPending[1];
    /* Mobile: keep a solid docked header — no scroll-morph reflow/jitter. */
    var isMobile = typeof window !== 'undefined' && window.matchMedia
      ? window.matchMedia('(max-width: 768px)').matches
      : false;
    /* Rules of Hooks: useScrollMorph MUST be called unconditionally and in the
       same order every render. Gating the CALL on isMobile (which flips on
       resize) changed the hook order and crashed the whole app. Call it always,
       then ignore the result on mobile. */
    var morphRaw = window.useScrollMorph ? window.useScrollMorph(40) : { scrolled: false };
    var morph = isMobile ? { scrolled: false } : morphRaw;

    var trackRef = useRef(null);
    var pillRef  = useRef(null);
    var lastActiveKey = useRef(null);

    useEffect(function() {
      if (!window.CBQuests) return;
      return window.CBQuests.on(function() { setQuestPending(window.CBQuests.pendingCount()); });
    }, []);

    useEffect(function() {
      function onScroll() {
        var max = document.documentElement.scrollHeight - window.innerHeight;
        setProgress(max > 0 ? Math.min(1, window.scrollY / max) : 0);
      }
      window.addEventListener('scroll', onScroll, { passive: true });
      return function() { window.removeEventListener('scroll', onScroll); };
    }, []);

    useEffect(function() {
      var track = trackRef.current;
      var pill = pillRef.current;
      if (!track || !pill) return;

      function layoutPill(scrollActive) {
        var activeBtn = track.querySelector('.nav-tab.act');
        if (!activeBtn) {
          pill.style.opacity = '0';
          return;
        }
        if (scrollActive && track.scrollWidth > track.clientWidth + 4) {
          activeBtn.scrollIntoView({ inline: 'center', block: 'nearest' });
        }
        pill.style.left = activeBtn.offsetLeft + 'px';
        pill.style.top = activeBtn.offsetTop + 'px';
        pill.style.width = activeBtn.offsetWidth + 'px';
        pill.style.height = activeBtn.offsetHeight + 'px';
        pill.style.opacity = '1';
      }

      function onResize() { layoutPill(false); }

      var scrollActive = lastActiveKey.current !== active;
      lastActiveKey.current = active;
      layoutPill(scrollActive);
      window.addEventListener('resize', onResize);
      var ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(onResize) : null;
      if (ro) ro.observe(track);

      return function() {
        window.removeEventListener('resize', onResize);
        if (ro) ro.disconnect();
      };
    }, [active, questPending, morph.scrolled]);

    var hover = function() { document.body.classList.add('hov'); };
    var leave = function() { document.body.classList.remove('hov'); };

    function isTabActive(tab) {
      if (tab.screen === 'home') {
        return active === 'home' || HOME_SCREENS.indexOf(active) === -1;
      }
      if (tab.screen === 'opportunities') {
        return active === 'opportunities' || active === 'opportunity-detail' || active === 'owner-dashboard';
      }
      if (tab.screen === 'projects') {
        return active === 'projects' || active === 'project-detail' || active === 'profile';
      }
      return active === tab.screen;
    }

    return (
      <>
        <div id="scroll-progress" style={{ transform: 'scaleX(' + progress + ')' }} />
        <GlassNavBar scrolled={morph.scrolled}>
          <div className="nav-shell">
            <div className="nav-zone-brand">
              <button type="button" className="nav-brand" aria-label="CityBuildRR home"
                onMouseEnter={hover} onMouseLeave={leave}
                onClick={function(){ window.navigate('home'); }}>
                {window.BrandLogo
                  ? React.createElement(window.BrandLogo, { size: 'md' })
                  : <span className="nav-brand-text">CityBuildRR</span>}
              </button>
            </div>

            <div className="nav-zone-tabs">
              <nav className="nav-tab-track" ref={trackRef} aria-label="Primary" data-tour="nav-tabs">
                <span className="nav-link-pill" ref={pillRef} aria-hidden="true" />
                {tabs.map(function(tab) {
                  var pending = tab.badge && tab.screen === 'quests' ? questPending : 0;
                  var act = isTabActive(tab);
                  return (
                    <button key={tab.key} type="button"
                      className={'nav-tab' + (act ? ' act' : '')}
                      data-tour={'nav-tab-' + tab.key}
                      aria-current={act ? 'page' : undefined}
                      onMouseEnter={hover} onMouseLeave={leave}
                      onClick={function(){ window.navigate(tab.screen); }}>
                      <span className="nav-tab-label nav-tab-label--full">{tab.label}</span>
                      <span className="nav-tab-label nav-tab-label--short">{tab.short || tab.label}</span>
                      {pending > 0 ? <span className="quest-nav-dot">{pending}</span> : null}
                    </button>
                  );
                })}
              </nav>
            </div>

            <div className="nav-zone-actions" data-tour="nav-actions">
              {window.CBDemo && window.CBDemo.on ? (
                <button type="button" className="demo-pill" title="Demo mode — click to exit"
                  onMouseEnter={hover} onMouseLeave={leave}
                  onClick={function(){ window.CBDemo.disable(); }}>
                  <span className="demo-pill-dot" />Demo
                </button>
              ) : null}

              {window.CBGameHUD ? (
                <div className="nav-hud" title="Level and XP">
                  <window.CBGameHUD />
                </div>
              ) : null}

              <div className="nav-action-sep" aria-hidden="true" />

              <button type="button" className="nav-icon-btn" aria-label="Messages"
                title="Messages"
                onMouseEnter={hover} onMouseLeave={leave}
                onClick={function(){ window.navigate('messages'); }}>
                {window.CBIcon
                  ? React.createElement(window.CBIcon, { name: 'mail', size: 17 })
                  : '✉'}
              </button>

              <button type="button" className="nav-cta"
                onMouseEnter={hover} onMouseLeave={leave}
                onClick={function(){ window.navigate('submit'); }}>
                Create
              </button>

              {authUser ? (
                <ProfileMenu user={authUser} onLogout={onLogout} />
              ) : (
                <button type="button" className="nav-signin"
                  onMouseEnter={hover} onMouseLeave={leave}
                  onClick={onLoginClick}>
                  Sign In
                </button>
              )}
            </div>
          </div>
        </GlassNavBar>
      </>
    );
  }

  window.HeaderNav = HeaderNav;
})();
