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

  /* Blip — the CityBuildR guide bot. Bobs in the corner, reacts to
     the section you're viewing (Duolingo-owl style), awards XP for
     exploring, and wiggles when clicked.                          */

  var SECTIONS = [
    { sel: '#hero',          id: 'hero',      msg: "Hey! I'm Blip. Scroll down — I'll show you around." },
    { sel: '.pipeline-grid', id: 'pipeline',  msg: 'Photo in, live AR out. Ten minutes. Watch the steps!' },
    { sel: '.proj-grid',     id: 'projects',  msg: 'Real ideas from real citizens. Tap one to dive in!' },
    { sel: '.ar-wrap',       id: 'slider',    msg: 'Ooh — drag that slider. Before and after. Trust me.' },
    { sel: '.fund-card',     id: 'funding',   msg: 'Every dollar here reshapes a real street.' },
    { sel: '.contrib-row',   id: 'community', msg: 'The city legends leaderboard. You could be on it.' },
    { sel: '.upload-zone',   id: 'submit',    msg: 'Your turn! Got a photo and a wild idea?' },
    { sel: '#footer',        id: 'footer',    msg: 'You explored the whole city. Absolute legend!' },
  ];

  var CLICK_LINES = [
    'Beep! That tickles.',
    'I run on civic optimism.',
    'Fun fact: I was rendered, not built.',
    'Keep scrolling, keep earning XP!',
    'One day this will all be AR…',
  ];

  function Mascot() {
    var _msg    = useState(SECTIONS[0].msg); var msg = _msg[0], setMsg = _msg[1];
    var _bump   = useState(0);               var bump = _bump[0], setBump = _bump[1];
    var _wiggle = useState(false);           var wiggle = _wiggle[0], setWiggle = _wiggle[1];
    var clickIdx = useRef(0);

    useEffect(function() {
      var obs = new IntersectionObserver(function(entries) {
        entries.forEach(function(e) {
          if (!e.isIntersecting) return;
          var s = e.target.__cbSect;
          if (!s) return;
          setMsg(s.msg);
          setBump(function(b) { return b + 1; });
          window.CBGame && window.CBGame.award('visit-' + s.id, 5, 'Explorer');
        });
      }, { threshold: 0.4 });

      // Content arrives async (API-fed cards) — scan a few times
      var observed = {};
      function scan() {
        SECTIONS.forEach(function(s) {
          if (observed[s.id]) return;
          var el = document.querySelector(s.sel);
          if (el) { el.__cbSect = s; obs.observe(el); observed[s.id] = true; }
        });
      }
      scan();
      var t1 = setTimeout(scan, 1500);
      var t2 = setTimeout(scan, 4000);
      return function() { obs.disconnect(); clearTimeout(t1); clearTimeout(t2); };
    }, []);

    var onPoke = function() {
      setWiggle(true);
      setTimeout(function() { setWiggle(false); }, 700);
      setMsg(CLICK_LINES[clickIdx.current++ % CLICK_LINES.length]);
      setBump(function(b) { return b + 1; });
      window.CBGame && window.CBGame.award('poke-blip', 5, 'Made a Friend');
    };

    return (
      <div className="mascot-wrap">
        <div key={bump} className="mascot-bubble">{msg}</div>
        <button className={'mascot' + (wiggle ? ' wiggle' : '')} aria-label="Blip, your city guide"
          onMouseEnter={function(){ document.body.classList.add('hov'); }}
          onMouseLeave={function(){ document.body.classList.remove('hov'); }}
          onClick={onPoke}>
          <svg viewBox="0 0 64 64" width="56" height="56" aria-hidden="true">
            <defs>
              <linearGradient id="blip-g" x1="0" y1="0" x2="1" y2="1">
                <stop offset="0%" stopColor="#8d4bf6" />
                <stop offset="100%" stopColor="#22d3ee" />
              </linearGradient>
            </defs>
            {/* antenna */}
            <line x1="32" y1="10" x2="32" y2="16" stroke="#8d4bf6" strokeWidth="2.5" strokeLinecap="round" />
            <circle className="mascot-antenna" cx="32" cy="7" r="3.4" fill="#a3e635" />
            {/* body */}
            <rect x="14" y="16" width="36" height="34" rx="11" fill="url(#blip-g)" />
            <rect x="14" y="16" width="36" height="34" rx="11" fill="none" stroke="rgba(255,255,255,.25)" strokeWidth="1.5" />
            {/* eyes */}
            <g className="mascot-eyes">
              <circle cx="25" cy="31" r="4.2" fill="#0b0716" />
              <circle cx="39" cy="31" r="4.2" fill="#0b0716" />
              <circle cx="26.4" cy="29.6" r="1.5" fill="#fff" />
              <circle cx="40.4" cy="29.6" r="1.5" fill="#fff" />
            </g>
            {/* smile */}
            <path d="M26 41 Q32 46 38 41" stroke="#0b0716" strokeWidth="2.6" fill="none" strokeLinecap="round" />
            {/* arms */}
            <line className="mascot-arm-l" x1="14" y1="34" x2="7" y2="28" stroke="#8d4bf6" strokeWidth="3.4" strokeLinecap="round" />
            <line x1="50" y1="34" x2="57" y2="38" stroke="#22d3ee" strokeWidth="3.4" strokeLinecap="round" />
          </svg>
        </button>
      </div>
    );
  }

  window.CBMascot = Mascot;
})();
