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

  /* GameHUD — Duolingo-style XP layer:
     · level chip + striped XP bar (lives in the nav)
     · floating "+N XP" pops (top-right)
     · full-screen level-up celebration with confetti           */
  function GameHUD() {
    var _gs   = useState(window.CBGame.state()); var gs = _gs[0], setGs = _gs[1];
    var _pops = useState([]);                    var pops = _pops[0], setPops = _pops[1];
    var _lvl  = useState(null);                  var levelUp = _lvl[0], setLevelUp = _lvl[1];
    var _pulse = useState(false);                var pulse = _pulse[0], setPulse = _pulse[1];
    var _muted = useState(window.CBSfx ? window.CBSfx.muted() : false);
    var muted = _muted[0], setMuted = _muted[1];
    var popId = useRef(0);

    var toggleSound = function() {
      // CBSfx is the source of truth — avoids stale-closure flips on rapid clicks
      var next = !(window.CBSfx && window.CBSfx.muted());
      window.CBSfx && window.CBSfx.setMuted(next);
      setMuted(next);
      // Confirmation ding only when turning sound ON
      if (!next) window.CBSfx && window.CBSfx.play('xp');
    };

    useEffect(function() {
      var off = window.CBGame.on(function(ev) {
        setGs(window.CBGame.state());
        if (ev.type === 'xp') {
          var id = ++popId.current;
          setPops(function(p) { return p.concat([{ id: id, amount: ev.amount, label: ev.label }]); });
          setPulse(true);
          setTimeout(function() { setPulse(false); }, 500);
          setTimeout(function() {
            setPops(function(p) { return p.filter(function(x) { return x.id !== id; }); });
          }, 2400);
        }
        if (ev.type === 'levelup') {
          setLevelUp({ level: ev.level, title: ev.title });
          window.CBConfetti && window.CBConfetti.burst({ count: 180, power: 15 });
          setTimeout(function() { setLevelUp(null); }, 3200);
        }
      });
      // First-visit welcome XP (one-shot — no-op on later visits)
      var t = setTimeout(function() {
        window.CBGame.award('welcome', 10, 'Welcome to the City');
      }, 1600);
      return function() { off(); clearTimeout(t); };
    }, []);

    return (
      <React.Fragment>
        <div className={'xp-hud' + (pulse ? ' pulse' : '')} title={'Level ' + gs.level + ' — ' + gs.title + ' · ' + gs.xp + ' XP'}
          onMouseEnter={function(){ document.body.classList.add('hov'); }}
          onMouseLeave={function(){ document.body.classList.remove('hov'); }}>
          <div className="xp-badge">{gs.level}</div>
          <div className="xp-meta">
            <div className="xp-title">{gs.title}</div>
            <div className="xp-track"><div className="xp-fill" style={{ width: gs.pct + '%' }} /></div>
          </div>
        </div>

        <button className="sfx-toggle" aria-label={muted ? 'Unmute sound effects' : 'Mute sound effects'}
          title={muted ? 'Sound off' : 'Sound on'}
          onMouseEnter={function(){ document.body.classList.add('hov'); }}
          onMouseLeave={function(){ document.body.classList.remove('hov'); }}
          onClick={toggleSound}>
          <Icon name={muted ? 'volume-off' : 'volume'} size={14} />
        </button>

        <div className="xp-pop-stack" aria-live="polite">
          {pops.map(function(p) {
            return (
              <div key={p.id} className="xp-pop">
                <Icon name="sparkles" size={13} />
                <span className="xp-pop-amt">+{p.amount} XP</span>
                {p.label ? <span className="xp-pop-label">{p.label}</span> : null}
              </div>
            );
          })}
        </div>

        {levelUp && (
          <div className="levelup-overlay" onClick={function(){ setLevelUp(null); }}>
            <div className="levelup-card">
              <div className="levelup-rays" />
              <div className="levelup-badge">{levelUp.level}</div>
              <div className="levelup-heading">Level Up!</div>
              <div className="levelup-title">{levelUp.title}</div>
              <div className="levelup-sub">Keep exploring the city to earn XP</div>
            </div>
          </div>
        )}
      </React.Fragment>
    );
  }

  window.CBGameHUD = GameHUD;
})();
