// wager-system.jsx — Sponsored coin toss + prop bet wagers, quizzes, and
// win/loss reveal modals. Plugs into the Game Day Rewards tab.
//
// Exposes:
//   WAGER_SPONSORS           — catalog of sponsor brand styling
//   WagerSheet               — sponsor-skinned action sheet for picking a side
//   WagerResultModal         — instant win/loss reveal with confetti or sad-face
//   QuizSheet                — one-question or multi-question trivia modal
//   QuizResultModal          — score summary at end of multi-question quiz

// ─────────────────────────────────────────────────────────────────────
// SPONSOR CATALOG
// Each entry: bg color (modal bg), accent color, wordmark text, font, mark SVG.
// These are placeholder visual identities — for a pitch demo. Real generated
// images can be dropped at the prizeImage path on the wager config to swap in.
// ─────────────────────────────────────────────────────────────────────
const WAGER_SPONSORS = {
  chickfila: {
    name: 'Chick-fil-A',
    wordmark: 'CHICK-FIL-A',
    superscript: '\u00A9',
    color: '#DD0031', accent: '#FFFFFF',
    font: '"Caecilia", "Georgia", serif',
    weight: 800, tracking: '-0.005em',
    bgDark: '#8E001E',
  },
  sheetz: {
    name: 'Sheetz', wordmark: 'SHEETZ', color: '#E51737', accent: '#FFE100',
    font: '"Inter", Helvetica, Arial, sans-serif',
    weight: 900, tracking: '-0.02em',
    bgDark: '#8E0E25',
  },
  pizzahut: {
    name: 'Pizza Hut', wordmark: 'PIZZA HUT', color: '#EE3124', accent: '#FFFFFF',
    font: '"Helvetica Neue", Helvetica, Arial, sans-serif',
    weight: 900, tracking: '-0.01em',
    bgDark: '#8E1D16',
  },
  cocacola: {
    name: 'Coca-Cola', wordmark: 'Coca-Cola', color: '#E61A27', accent: '#FFFFFF',
    font: '"Georgia", serif',
    weight: 700, italic: true, tracking: '0',
    bgDark: '#8E0F18',
  },
  innout: {
    name: 'In-N-Out', wordmark: 'IN-N-OUT', color: '#D6022B', accent: '#FFE43F',
    font: '"Helvetica Neue", Helvetica, Arial, sans-serif',
    weight: 900, italic: true, tracking: '-0.005em',
    bgDark: '#8E0119',
  },
  caferio: {
    name: 'Cafe Rio', wordmark: 'CAFE RIO', color: '#176A3B', accent: '#F1BC2A',
    font: '"Inter", Helvetica, Arial, sans-serif',
    weight: 800, tracking: '0.02em',
    bgDark: '#0D4225',
  },
  maverik: {
    name: 'Maverik', wordmark: 'Maverik', color: '#F36F21', accent: '#FFFFFF',
    font: '"Inter", Helvetica, Arial, sans-serif',
    weight: 900, italic: true, tracking: '-0.01em',
    bgDark: '#9E4814',
  },
  wendys: {
    name: "Wendy's", wordmark: "Wendy's", color: '#E2203B', accent: '#FFFFFF',
    font: '"Georgia", "Times New Roman", serif',
    weight: 700, italic: false, tracking: '-0.005em',
    bgDark: '#8E1426',
  },
  whitecastle: {
    name: 'White Castle', wordmark: 'WHITE CASTLE', color: '#1A4FA0', accent: '#FFFFFF',
    font: '"Inter", Helvetica, Arial, sans-serif',
    weight: 900, tracking: '0.04em',
    bgDark: '#0F3066',
  },
  skyline: {
    name: 'Skyline Chili', wordmark: 'SKYLINE CHILI', color: '#003E7E', accent: '#F0B400',
    font: '"Inter", Helvetica, Arial, sans-serif',
    weight: 800, tracking: '0.02em',
    bgDark: '#00254D',
  },
  kfc: {
    name: 'KFC', wordmark: 'KFC', color: '#E4002B', accent: '#FFFFFF',
    font: '"Helvetica Neue", Helvetica, Arial, sans-serif',
    weight: 900, tracking: '0',
    bgDark: '#8E001A',
  },
  ale8: {
    name: 'Ale-8', wordmark: 'ALE-8-ONE', color: '#0A6638', accent: '#F0B400',
    font: '"Georgia", serif',
    weight: 800, tracking: '0.02em',
    bgDark: '#063D22',
  },
  bourbon: {
    name: 'Bourbon Barrel', wordmark: 'BOURBON BARREL CO.', color: '#5B341A', accent: '#F0B400',
    font: '"Georgia", "Times New Roman", serif',
    weight: 800, italic: true, tracking: '0.02em',
    bgDark: '#3A2110',
  },
  pepsi: {
    name: 'Pepsi', wordmark: 'pepsi', color: '#004B93', accent: '#E32934',
    font: '"Helvetica Neue", Helvetica, Arial, sans-serif',
    weight: 900, italic: true, tracking: '-0.02em',
    bgDark: '#002D5A',
  },
};

function getSponsor(id) { return WAGER_SPONSORS[id] || WAGER_SPONSORS.chickfila; }

// Sponsor wordmark element — pulls from the catalog and renders in brand font/color.
function WagerSponsorMark({ sponsorId, size = 'lg', light = false }) {
  const s = getSponsor(sponsorId);
  const px = size === 'lg' ? 22 : (size === 'md' ? 16 : 13);
  return (
    <span style={{
      fontFamily: s.font, fontWeight: s.weight,
      fontStyle: s.italic ? 'italic' : 'normal',
      color: light ? '#FFFFFF' : s.color,
      fontSize: px, lineHeight: 1,
      letterSpacing: s.tracking || '0',
      whiteSpace: 'nowrap',
    }}>
      {s.wordmark}{s.superscript ? <sup style={{ fontSize: '0.55em', verticalAlign: 'super', marginLeft: 1 }}>{s.superscript}</sup> : null}
    </span>
  );
}

// ─────────────────────────────────────────────────────────────────────
// WAGER SHEET — sponsor-branded coin toss / prop bet picker
// Props:
//   wager:    { sponsor, prize, prizeImage, prizeEmoji, question?, teamA?, teamB?, optionLabels? }
//             — `question` + yes/no options for prop bets, or teamA/teamB for coin toss
//   stake:    number of points being wagered (default 100)
//   onPick:   (option) => void   — fires on selection
//   onCancel: () => void
// ─────────────────────────────────────────────────────────────────────
function WagerSheet({ wager, stake = 100, onPick, onCancel, isCoinToss = false }) {
  const s = getSponsor(wager.sponsor);
  const bg = s.color;
  const dark = s.bgDark || _darken(bg, 0.25);
  const [posterOk, setPosterOk] = React.useState(true);

  const options = isCoinToss
    ? [
        { id: 'A', label: wager.teamA || 'Team A' },
        { id: 'B', label: wager.teamB || 'Team B' },
      ]
    : [
        { id: 'yes', label: 'Yes — Lock it in' },
        { id: 'no',  label: 'No — I\'ll pass' },
      ];

  const title = isCoinToss
    ? `${s.wordmark} COIN TOSS`
    : `${s.wordmark} PROP BET`;

  const description = isCoinToss
    ? `If you are correct, you will win a ${wager.prize}.`
    : wager.question;

  return (
    <div onClick={onCancel} style={{
      position: 'absolute', inset: 0, zIndex: 240,
      background: 'rgba(0,0,0,0.5)',
      backdropFilter: 'blur(5px)', WebkitBackdropFilter: 'blur(5px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 16,
      animation: 'mtnFade 220ms ease-out',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', maxWidth: 340,
        borderRadius: 22, overflow: 'hidden',
        boxShadow: '0 28px 70px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.06)',
        background: `linear-gradient(180deg, ${bg}, ${dark})`,
      }}>
        {/* Header — sponsor wordmark in brand font */}
        <div style={{
          padding: '22px 20px 14px',
          textAlign: 'center',
          borderBottom: '0.5px solid rgba(255,255,255,0.12)',
        }}>
          <div style={{
            fontFamily: s.font, fontWeight: 900,
            fontStyle: s.italic ? 'italic' : 'normal',
            color: '#fff', fontSize: 16,
            letterSpacing: '0.04em', textTransform: 'uppercase',
            lineHeight: 1.15,
            textShadow: '0 1px 2px rgba(0,0,0,0.25)',
          }}>{title}{s.superscript ? <sup style={{ fontSize: '0.55em' }}>{s.superscript}</sup> : null}</div>
          <div style={{
            fontFamily: DS.sans, fontSize: 13, fontWeight: 500,
            color: 'rgba(255,255,255,0.88)', marginTop: 8,
            lineHeight: 1.4, letterSpacing: '-0.005em',
          }}>{description}</div>

          {/* Prize image / emoji */}
          {wager.prize && (
            <div style={{ marginTop: 14, display: 'flex', justifyContent: 'center' }}>
              {posterOk && wager.prizeImage ? (
                <img
                  src={wager.prizeImage}
                  alt={wager.prize}
                  onError={() => setPosterOk(false)}
                  style={{
                    width: 96, height: 96, objectFit: 'contain',
                    filter: 'drop-shadow(0 6px 14px rgba(0,0,0,0.45))',
                  }}
                />
              ) : (
                <div style={{
                  width: 96, height: 96, borderRadius: 48,
                  background: 'rgba(255,255,255,0.12)',
                  border: '0.5px solid rgba(255,255,255,0.18)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 48,
                  filter: 'drop-shadow(0 6px 14px rgba(0,0,0,0.45))',
                }}>{wager.prizeEmoji || '\u{1F3C6}'}</div>
              )}
            </div>
          )}

          {/* Wager amount — wrap in a flex container so the pill centers reliably */}
          <div style={{ marginTop: 14, display: 'flex', justifyContent: 'center' }}>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '5px 11px', borderRadius: 999,
              background: 'rgba(0,0,0,0.32)',
              border: '0.5px solid rgba(255,255,255,0.18)',
            }}>
              <span style={{
                fontFamily: DS.mono, fontSize: 10, fontWeight: 700,
                color: 'rgba(255,255,255,0.85)', letterSpacing: '0.16em',
                textTransform: 'uppercase',
              }}>Wager</span>
              <span style={{
                fontFamily: DS.sans, fontSize: 13, fontWeight: 800,
                color: '#fff', letterSpacing: '-0.005em',
                fontVariantNumeric: 'tabular-nums',
              }}>{stake} pts</span>
            </div>
          </div>
        </div>

        {/* Prompt + options */}
        <div style={{ padding: '16px 0 0' }}>
          <div style={{
            fontFamily: DS.sans, fontSize: 15.5, fontWeight: 700,
            color: '#fff', textAlign: 'center', letterSpacing: '-0.005em',
            padding: '0 18px 12px',
          }}>{isCoinToss ? 'Who will win the coin toss?' : 'Place your wager'}</div>

          {options.map((opt, i) => (
            <button
              key={opt.id}
              onClick={(e) => { e.stopPropagation(); onPick && onPick(opt.id); }}
              style={{
                display: 'block', width: '100%',
                padding: '17px 16px',
                background: _shade(dark, -0.04 - i * 0.08),
                border: 'none',
                borderTop: '0.5px solid rgba(255,255,255,0.14)',
                fontFamily: DS.sans, fontSize: 16, fontWeight: 700,
                color: '#fff', letterSpacing: '-0.005em',
                cursor: 'pointer', textAlign: 'center',
                transition: 'background 120ms ease',
              }}
              onMouseDown={(e) => { e.currentTarget.style.filter = 'brightness(0.92)'; }}
              onMouseUp={(e) => { e.currentTarget.style.filter = 'brightness(1)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.filter = 'brightness(1)'; }}
            >{opt.label}</button>
          ))}

          {/* Cancel */}
          <button
            onClick={(e) => { e.stopPropagation(); onCancel && onCancel(); }}
            style={{
              display: 'block', width: '100%',
              padding: '14px 16px',
              background: 'rgba(0,0,0,0.55)',
              border: 'none',
              borderTop: '0.5px solid rgba(255,255,255,0.12)',
              fontFamily: DS.sans, fontSize: 15, fontWeight: 600,
              color: s.accent || '#fff', letterSpacing: '-0.005em',
              cursor: 'pointer', textAlign: 'center',
            }}
          >Cancel</button>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// WAGER SUSPENSE → RESULT MODAL
// Renders a brief 1.5s "spinner" then the win/loss reveal.
// Props:
//   wager:   the same wager config used in WagerSheet
//   pick:    'A' | 'B' | 'yes' | 'no'
//   isCoinToss: bool
//   stake:   points wagered
//   onClose: () => void  — fires after user dismisses the result
//   onResult: (didWin: bool) => void  — fires once when result settles
// ─────────────────────────────────────────────────────────────────────
function WagerResultModal({ wager, pick, isCoinToss = false, stake = 100, onClose, onResult }) {
  const s = getSponsor(wager.sponsor);
  const winningSide = wager.winnerHint || 'A';
  const didWin = pick === winningSide;
  const [phase, setPhase] = React.useState('suspense'); // 'suspense' | 'result'

  React.useEffect(() => {
    const t = setTimeout(() => {
      setPhase('result');
      if (onResult) onResult(didWin);
    }, 1500);
    return () => clearTimeout(t);
  }, [didWin]);

  // Auto-dismiss result after a beat
  React.useEffect(() => {
    if (phase !== 'result') return;
    const t = setTimeout(() => onClose && onClose(), 4400);
    return () => clearTimeout(t);
  }, [phase]);

  const bg = didWin ? s.color : '#1F1F28';
  const dark = didWin ? (s.bgDark || _darken(bg, 0.25)) : '#0B0B12';

  return (
    <div onClick={phase === 'result' ? onClose : undefined} style={{
      position: 'absolute', inset: 0, zIndex: 245,
      background: 'rgba(0,0,0,0.6)',
      backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 16,
      animation: 'mtnFade 240ms ease-out',
    }}>
      {phase === 'suspense' ? (
        <SuspenseSpinner isCoinToss={isCoinToss} sponsor={s} />
      ) : (
        <div onClick={(e) => e.stopPropagation()} style={{
          position: 'relative',
          width: '100%', maxWidth: 300,
          borderRadius: 22, overflow: 'visible',
          background: `linear-gradient(170deg, ${bg}, ${dark})`,
          boxShadow: `0 28px 70px rgba(0,0,0,0.65), 0 0 0 1px rgba(255,255,255,0.08), inset 0 1px 0 rgba(255,255,255,0.18)`,
          padding: '36px 24px 28px',
          textAlign: 'center',
          animation: 'mtnTrophyPop 480ms cubic-bezier(0.34, 1.56, 0.64, 1) both',
        }}>
          {didWin && <ConfettiBurst originY={0.28} count={48} />}

          {/* Big result mark */}
          <div style={{
            width: 84, height: 84, borderRadius: 42,
            background: didWin ? 'rgba(255,255,255,0.16)' : 'rgba(255,255,255,0.08)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            marginBottom: 14,
            boxShadow: didWin
              ? '0 6px 22px rgba(0,0,0,0.35), inset 0 1px 0 rgba(255,255,255,0.25)'
              : '0 4px 14px rgba(0,0,0,0.4)',
          }}>
            {didWin ? (
              <svg width="44" height="44" viewBox="0 0 44 44" fill="none">
                <path d="M5 22l10 10L40 8" stroke="#fff" strokeWidth="4.5" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
              </svg>
            ) : (
              <svg width="42" height="42" viewBox="0 0 42 42" fill="none">
                <circle cx="21" cy="21" r="17" stroke="rgba(255,255,255,0.45)" strokeWidth="2.5" fill="none"/>
                <path d="M14 26q7-5 14 0" stroke="rgba(255,255,255,0.6)" strokeWidth="2.5" strokeLinecap="round" fill="none"/>
                <circle cx="15" cy="17" r="1.6" fill="rgba(255,255,255,0.6)"/>
                <circle cx="27" cy="17" r="1.6" fill="rgba(255,255,255,0.6)"/>
              </svg>
            )}
          </div>

          <div style={{
            fontFamily: DS.sans, fontSize: 19, fontWeight: 900,
            color: '#fff', letterSpacing: '-0.015em', lineHeight: 1.15,
            textShadow: '0 1px 4px rgba(0,0,0,0.25)',
          }}>
            {didWin ? 'You won!' : 'Tough luck.'}
          </div>

          {didWin ? (
            <>
              <div style={{
                fontFamily: DS.sans, fontSize: 14, fontWeight: 600,
                color: 'rgba(255,255,255,0.9)', marginTop: 10, lineHeight: 1.4,
              }}>You won a {wager.prize}</div>
              <div style={{
                fontFamily: DS.mono, fontSize: 10.5, fontWeight: 700,
                color: 'rgba(255,255,255,0.7)', letterSpacing: '0.14em',
                marginTop: 8, textTransform: 'uppercase',
              }}>+{stake * 2} pts · prize added to Inventory</div>
            </>
          ) : (
            <>
              <div style={{
                fontFamily: DS.sans, fontSize: 14, fontWeight: 500,
                color: 'rgba(255,255,255,0.78)', marginTop: 8, lineHeight: 1.4,
              }}>You'll get 'em next time.</div>
              <div style={{
                fontFamily: DS.mono, fontSize: 10.5, fontWeight: 700,
                color: 'rgba(255,90,90,0.95)', letterSpacing: '0.14em',
                marginTop: 8, textTransform: 'uppercase',
              }}>-{stake} pts</div>
            </>
          )}
        </div>
      )}
    </div>
  );
}

// 1.5s suspense — coin flip (for coin toss) or simple "Tallying…" spinner (for props)
function SuspenseSpinner({ isCoinToss, sponsor }) {
  return (
    <div style={{
      width: 200, height: 200, position: 'relative',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <style>{`
        @keyframes mtnCoinFlip {
          0%   { transform: rotateY(0)   translateY(0); }
          50%  { transform: rotateY(720deg) translateY(-30px); }
          100% { transform: rotateY(1440deg) translateY(0); }
        }
        @keyframes mtnSpinnerRing {
          to { transform: rotate(360deg); }
        }
      `}</style>
      {isCoinToss ? (
        <>
          <div style={{
            width: 92, height: 92, borderRadius: 46,
            background: `radial-gradient(circle at 35% 30%, #FFE490, ${sponsor.accent === '#FFE100' ? '#F0B400' : '#D49B00'} 70%, #8E6800)`,
            border: `2px solid ${sponsor.color}`,
            boxShadow: `0 0 0 4px rgba(255,255,255,0.08), 0 18px 32px rgba(0,0,0,0.55)`,
            animation: 'mtnCoinFlip 1.4s cubic-bezier(0.4, 0, 0.6, 1)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: sponsor.color,
            fontFamily: sponsor.font, fontWeight: 900, fontSize: 28,
            letterSpacing: '-0.02em',
          }}>{(sponsor.wordmark || 'C')[0]}</div>
        </>
      ) : (
        <>
          <div style={{
            width: 64, height: 64, borderRadius: 32,
            border: `4px solid rgba(255,255,255,0.18)`,
            borderTopColor: '#fff',
            animation: 'mtnSpinnerRing 0.9s linear infinite',
          }} />
          <div style={{
            position: 'absolute',
            fontFamily: DS.mono, fontSize: 10, fontWeight: 700,
            color: '#fff', letterSpacing: '0.18em',
            textTransform: 'uppercase', marginTop: 96,
          }}>Tallying</div>
        </>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// QUIZ SHEET — single or multi-question trivia
// Props:
//   quiz:    [{ question, choices: [...], correct: idx }]  or  { question, choices, correct }
//   onClose: ({ correctCount, total, reward }) => void
//   accentBg: optional override
// ─────────────────────────────────────────────────────────────────────
function QuizSheet({ quiz, rewardPerQuestion = 50, onClose, accentBg }) {
  const questions = Array.isArray(quiz) ? quiz : [quiz];
  const [idx, setIdx] = React.useState(0);
  const [pickedIdx, setPickedIdx] = React.useState(null);
  const [correctCount, setCorrectCount] = React.useState(0);
  const [done, setDone] = React.useState(false);

  const bg = accentBg || pickBoldTenantColor();
  const dark = _darken(bg, 0.15);
  const q = questions[idx];

  const handlePick = (i) => {
    if (pickedIdx !== null) return;
    setPickedIdx(i);
    const right = i === q.correct;
    if (right) setCorrectCount(c => c + 1);
    setTimeout(() => {
      if (idx + 1 < questions.length) {
        setIdx(idx + 1);
        setPickedIdx(null);
      } else {
        setDone(true);
      }
    }, 1100);
  };

  if (done) {
    return (
      <QuizResultModal
        correctCount={correctCount}
        total={questions.length}
        reward={correctCount * rewardPerQuestion}
        onClose={() => onClose && onClose({ correctCount, total: questions.length, reward: correctCount * rewardPerQuestion })}
      />
    );
  }

  return (
    <div onClick={() => onClose && onClose({ aborted: true })} style={{
      position: 'absolute', inset: 0, zIndex: 240,
      background: 'rgba(0,0,0,0.55)',
      backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 16,
      animation: 'mtnFade 220ms ease-out',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', maxWidth: 340,
        borderRadius: 22, overflow: 'hidden',
        background: `linear-gradient(180deg, ${bg}, ${dark})`,
        boxShadow: `0 28px 70px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.06)`,
      }}>
        <div style={{
          padding: '18px 20px 14px',
          textAlign: 'center',
          borderBottom: '0.5px solid rgba(255,255,255,0.12)',
        }}>
          <div style={{
            fontFamily: DS.mono, fontSize: 10.5, fontWeight: 700,
            color: 'rgba(255,255,255,0.7)', letterSpacing: '0.18em',
            textTransform: 'uppercase',
          }}>{questions.length > 1 ? `Question ${idx + 1} of ${questions.length}` : 'Quick Quiz'}</div>
          <div style={{
            fontFamily: DS.sans, fontSize: 17, fontWeight: 800,
            color: '#fff', letterSpacing: '-0.01em', marginTop: 8,
            lineHeight: 1.25,
            textShadow: '0 1px 2px rgba(0,0,0,0.25)',
          }}>{q.question}</div>
        </div>

        <div style={{ padding: '8px 0' }}>
          {q.choices.map((choice, i) => {
            const isPicked = pickedIdx === i;
            const isCorrect = pickedIdx !== null && i === q.correct;
            const isWrong = isPicked && i !== q.correct;
            const showFeedback = pickedIdx !== null;
            return (
              <button
                key={i}
                onClick={() => handlePick(i)}
                disabled={pickedIdx !== null}
                style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  width: '100%', padding: '14px 18px',
                  background: showFeedback
                    ? (isCorrect ? 'rgba(34,197,94,0.28)' : (isWrong ? 'rgba(220,30,30,0.25)' : 'transparent'))
                    : 'transparent',
                  border: 'none',
                  borderTop: i > 0 ? '0.5px solid rgba(255,255,255,0.10)' : 'none',
                  fontFamily: DS.sans, fontSize: 15, fontWeight: 600,
                  color: '#fff', letterSpacing: '-0.005em',
                  cursor: pickedIdx === null ? 'pointer' : 'default',
                  textAlign: 'left',
                  transition: 'background 200ms ease',
                  opacity: showFeedback && !isCorrect && !isWrong ? 0.5 : 1,
                }}
              >
                <span style={{
                  width: 24, height: 24, borderRadius: 12,
                  background: showFeedback
                    ? (isCorrect ? '#22C55E' : (isWrong ? '#DC2626' : 'rgba(255,255,255,0.10)'))
                    : 'rgba(255,255,255,0.10)',
                  border: '0.5px solid rgba(255,255,255,0.2)',
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  flexShrink: 0,
                  fontFamily: DS.sans, fontSize: 11, fontWeight: 800,
                  color: '#fff',
                }}>
                  {isCorrect ? (
                    <svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M2 6.5l3 3 5-7" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  ) : isWrong ? (
                    <svg width="10" height="10" viewBox="0 0 10 10" fill="none"><path d="M1 1l8 8M9 1l-8 8" stroke="#fff" strokeWidth="1.8" strokeLinecap="round"/></svg>
                  ) : (
                    String.fromCharCode(65 + i)
                  )}
                </span>
                {choice}
              </button>
            );
          })}
        </div>

        {/* Progress bar for multi-question */}
        {questions.length > 1 && (
          <div style={{
            height: 4, background: 'rgba(255,255,255,0.12)',
          }}>
            <div style={{
              width: `${((idx + (pickedIdx !== null ? 1 : 0)) / questions.length) * 100}%`,
              height: '100%', background: '#22C55E',
              transition: 'width 320ms ease',
            }} />
          </div>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// QUIZ RESULT — score summary at end of multi-question quiz
// ─────────────────────────────────────────────────────────────────────
function QuizResultModal({ correctCount, total, reward, onClose }) {
  const bg = pickBoldTenantColor();
  const passed = correctCount >= Math.ceil(total / 2);

  React.useEffect(() => {
    const t = setTimeout(() => onClose && onClose(), 4400);
    return () => clearTimeout(t);
  }, []);

  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 245,
      background: 'rgba(0,0,0,0.55)',
      backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 16,
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        position: 'relative',
        width: '100%', maxWidth: 300,
        borderRadius: 22, overflow: 'visible',
        background: `linear-gradient(170deg, ${bg}, ${_darken(bg, 0.15)})`,
        boxShadow: `0 28px 70px rgba(0,0,0,0.65), 0 0 0 1px rgba(255,255,255,0.08), inset 0 1px 0 rgba(255,255,255,0.18)`,
        padding: '36px 24px 28px',
        textAlign: 'center',
        animation: 'mtnTrophyPop 480ms cubic-bezier(0.34, 1.56, 0.64, 1) both',
      }}>
        {passed && <ConfettiBurst originY={0.28} count={36} />}

        <div style={{
          width: 84, height: 84, borderRadius: 42,
          background: 'rgba(255,255,255,0.14)',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          marginBottom: 14,
          boxShadow: '0 6px 22px rgba(0,0,0,0.35), inset 0 1px 0 rgba(255,255,255,0.25)',
        }}>
          <svg width="44" height="44" viewBox="0 0 44 44" fill="none">
            <path d="M12 6h20v8a10 10 0 01-20 0V6z" fill="#fff"/>
            <rect x="20" y="20" width="4" height="6" fill="#fff"/>
            <rect x="14" y="26" width="16" height="4" rx="1" fill="#fff"/>
          </svg>
        </div>

        <div style={{
          fontFamily: DS.sans, fontSize: 18, fontWeight: 900,
          color: '#fff', letterSpacing: '-0.015em',
        }}>{passed ? 'Nice work!' : 'Better luck next time'}</div>
        <div style={{
          fontFamily: DS.display, fontSize: 42, fontWeight: 900,
          color: '#fff', letterSpacing: '-0.03em', marginTop: 8,
          lineHeight: 1,
        }}>{correctCount}/{total}</div>
        <div style={{
          fontFamily: DS.mono, fontSize: 11, fontWeight: 700,
          color: 'rgba(255,255,255,0.78)', letterSpacing: '0.16em',
          marginTop: 8, textTransform: 'uppercase',
        }}>+{reward} pts earned</div>
      </div>
    </div>
  );
}

// Helper: darken a hex toward black by factor t in [0,1]
function _darken(hex, t) {
  const h = (hex || '#000').replace('#', '');
  const n = parseInt(h.length === 3 ? h.split('').map(c => c + c).join('') : h, 16);
  const r = ((n >> 16) & 255) * (1 - t);
  const g = ((n >>  8) & 255) * (1 - t);
  const b = ((n)       & 255) * (1 - t);
  return '#' + [r, g, b].map(v => Math.round(v).toString(16).padStart(2, '0')).join('');
}

Object.assign(window, {
  WAGER_SPONSORS, WagerSheet, WagerResultModal, QuizSheet, QuizResultModal, WagerSponsorMark, getSponsor,
});
