// reward-popup.jsx — Lightweight points-earned toast.
//
// Usage: in any screen,
//   const fireReward = useRewardPopup();
//   fireReward({ pts: 100, label: 'for watching', reason: 'Highlight reel' });
//
// The popup auto-mounts a portal at #mtn-reward-portal and is shared across
// every render — only one toast appears at a time. Auto-dismisses in 2.6s.

const _rewardListeners = new Set();
let _rewardSeq = 0;

function fireRewardEvent(payload) {
  _rewardSeq += 1;
  const evt = { id: _rewardSeq, ts: Date.now(), ...payload };
  _rewardListeners.forEach(fn => fn(evt));
  // Also persist running points total in localStorage (fan-side accumulator)
  try {
    const cur = Number(localStorage.getItem('mtn.bonusPts') || 0);
    localStorage.setItem('mtn.bonusPts', String(cur + (payload.pts || 0)));
  } catch (e) {}
}

function useRewardPopup() {
  return React.useCallback((payload) => fireRewardEvent(payload), []);
}

function RewardPopupHost() {
  const [evt, setEvt] = React.useState(null);
  React.useEffect(() => {
    const onEvt = (e) => {
      setEvt(e);
      // auto-dismiss
      setTimeout(() => {
        setEvt(prev => (prev && prev.id === e.id) ? null : prev);
      }, 2600);
    };
    _rewardListeners.add(onEvt);
    return () => _rewardListeners.delete(onEvt);
  }, []);

  if (!evt) return null;
  return (
    <div style={{
      position: 'absolute', top: 92, left: 16, right: 16, zIndex: 200,
      pointerEvents: 'none',
      animation: 'mtnRewardIn 480ms cubic-bezier(0.22,1,0.36,1)',
    }}>
      <div style={{
        position: 'relative', overflow: 'hidden',
        background: `linear-gradient(135deg, ${WVU.blue}, ${WVU.blueDim})`,
        border: `1px solid ${hexA(WVU.gold, 0.55)}`,
        borderRadius: DS.r.lg,
        padding: '14px 14px 14px 16px',
        boxShadow: `0 18px 50px rgba(0,0,0,0.55), 0, 0 6px 20px ${hexA(WVU.gold, 0.32)}`,
        display: 'flex', alignItems: 'center', gap: 14,
      }}>
        {/* sparkle burst */}
        <div style={{
          position: 'absolute', top: -20, right: -20, width: 110, height: 110,
          background: 'transparent',
          pointerEvents: 'none',
        }} />
        {/* trophy / +pts mark */}
        <div style={{
          width: 46, height: 46, borderRadius: 23, flexShrink: 0,
          background: `linear-gradient(135deg, ${WVU.goldLite}, ${WVU.gold} 60%, ${WVU.goldDim})`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: `0 6px 18px ${hexA(WVU.gold, 0.65)}, inset 0 1px 0 rgba(255,255,255,0.4)`,
          position: 'relative',
          animation: 'mtnRewardPop 700ms 80ms cubic-bezier(0.34,1.56,0.64,1) both',
        }}>
          <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
            <path d="M5 3h12v5a6 6 0 01-12 0V3z" fill={WVU.blueDim} stroke={WVU.blueDim} strokeWidth="1.4" strokeLinejoin="round"/>
            <rect x="9.5" y="13" width="3" height="3" fill={WVU.blueDim}/>
            <rect x="6" y="16" width="10" height="2" rx="0.5" fill={WVU.blueDim}/>
          </svg>
        </div>
        <div style={{ flex: 1, minWidth: 0, position: 'relative' }}>
          <div style={{
            display: 'flex', alignItems: 'baseline', gap: 6,
            fontFamily: DS.display, fontWeight: 900,
            color: WVU.cream, letterSpacing: '-0.02em', lineHeight: 1,
            fontVariantNumeric: 'tabular-nums',
          }}>
            <span style={{
              fontSize: 26,
              background: `linear-gradient(135deg, ${WVU.goldLite}, ${WVU.gold})`,
              WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent',
              backgroundClip: 'text',
            }}>+{(evt.pts || 0).toLocaleString()}</span>
            <span style={{ fontSize: 11, color: WVU.creamDim, fontWeight: 600, letterSpacing: 0 }}>pts</span>
          </div>
          <div style={{
            marginTop: 4,
            fontFamily: DS.sans, fontSize: 12, fontWeight: 600,
            color: WVU.cream, letterSpacing: '-0.005em', lineHeight: 1.25,
          }}>
            {evt.reason || 'Nice move'} {evt.label ? <span style={{ color: WVU.creamDim, fontWeight: 500 }}>· {evt.label}</span> : null}
          </div>
          <div style={{
            marginTop: 5,
            fontFamily: DS.mono, fontSize: 9, color: hexA(WVU.gold, 0.85),
            letterSpacing: '0.14em', textTransform: 'uppercase',
          }}>★ Keep earning</div>
        </div>
      </div>
    </div>
  );
}

// Inject keyframes once
if (!document.getElementById('__mtn_reward_kf')) {
  const el = document.createElement('style');
  el.id = '__mtn_reward_kf';
  el.textContent = `
    @keyframes mtnRewardIn {
      from { opacity: 0; transform: translateY(-14px) scale(0.96); }
      to   { opacity: 1; transform: translateY(0) scale(1); }
    }
    @keyframes mtnRewardPop {
      0%   { transform: scale(0.4) rotate(-12deg); }
      60%  { transform: scale(1.18) rotate(6deg); }
      100% { transform: scale(1) rotate(0); }
    }
  `;
  document.head.appendChild(el);
}

Object.assign(window, { useRewardPopup, RewardPopupHost, fireRewardEvent });
