// easy-points.jsx — "Easy Points" daily game card (Home) + playable Wordle.
//
//   EasyPointsCard — compact Home card replacing the persona strip
//   WordleGame     — full-screen Wordle: 5 letters, 6 guesses, on-screen
//                    keyboard. Win pays +25 pts, a loss pays +5.
//                    Fresh state every open so it can be demoed repeatedly.

// Per-tenant five-letter answers — sports/tenant flavored.
const WORDLE_WORDS = {
  wvu:      'BRAWL',  // Backyard Brawl
  utah:     'SWOOP',  // mascot
  osu:      'BUCKS',
  kentucky: 'DERBY',
  rsl:      'ROYAL',
  royals:   'CROWN',
};

function _wordleAnswer() {
  return WORDLE_WORDS[WVU.id] || 'FIELD';
}

// ── Home card ────────────────────────────────────────────────────────
function EasyPointsCard({ onPlay }) {
  return (
    <div style={{ padding: '0 16px', marginBottom: 18 }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 14,
        padding: 14, borderRadius: DS.r.lg,
        background: WVU.ink2, border: `1px solid ${WVU.line}`,
      }}>
        {/* mini tile mark */}
        <div style={{
          width: 44, height: 44, borderRadius: DS.r.sm, flexShrink: 0,
          display: 'grid', gridTemplateColumns: '1fr 1fr', gridTemplateRows: '1fr 1fr', gap: 3,
          padding: 5, background: 'rgba(255,255,255,0.05)',
          border: `1px solid ${WVU.line}`,
        }}>
          <div style={{ borderRadius: 3, background: '#538D4E' }} />
          <div style={{ borderRadius: 3, background: '#B59F3B' }} />
          <div style={{ borderRadius: 3, background: 'rgba(255,255,255,0.18)' }} />
          <div style={{ borderRadius: 3, background: '#538D4E' }} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: DS.sans, fontSize: 15, fontWeight: 800, color: WVU.cream, letterSpacing: '-0.01em' }}>
            Easy Points
          </div>
          <div style={{ fontFamily: DS.sans, fontSize: 12, color: WVU.creamDim, marginTop: 2 }}>
            Today's word · solve it for 25 pts
          </div>
        </div>
        <button data-pulse="true" onClick={onPlay} style={{
          padding: '10px 20px', borderRadius: DS.r.pill, flexShrink: 0,
          background: WVU.gold, color: WVU.onPrimary || WVU.blueDim,
          border: 'none', cursor: 'pointer',
          fontFamily: DS.sans, fontSize: 13, fontWeight: 800, letterSpacing: '0.01em',
        }}>Play</button>
      </div>
    </div>
  );
}

// ── Wordle ───────────────────────────────────────────────────────────
const WD_GREEN = '#538D4E';
const WD_YELLOW = '#B59F3B';
const WD_GRAY = '#3A3A3C';

function _scoreGuess(guess, answer) {
  // standard two-pass wordle scoring
  const res = Array(5).fill('absent');
  const remaining = {};
  for (let i = 0; i < 5; i++) {
    if (guess[i] === answer[i]) res[i] = 'correct';
    else remaining[answer[i]] = (remaining[answer[i]] || 0) + 1;
  }
  for (let i = 0; i < 5; i++) {
    if (res[i] === 'correct') continue;
    if (remaining[guess[i]] > 0) { res[i] = 'present'; remaining[guess[i]]--; }
  }
  return res;
}

function WordleGame({ onClose }) {
  const answer = React.useMemo(() => _wordleAnswer(), []);
  const [guesses, setGuesses] = React.useState([]); // [{word, marks}]
  const [current, setCurrent] = React.useState('');
  const [status, setStatus] = React.useState('playing'); // playing | won | lost
  const [shake, setShake] = React.useState(false);

  // key colors aggregated from guesses
  const keyMarks = React.useMemo(() => {
    const m = {};
    const rank = { absent: 0, present: 1, correct: 2 };
    guesses.forEach(g => g.word.split('').forEach((ch, i) => {
      const mark = g.marks[i];
      if (!m[ch] || rank[mark] > rank[m[ch]]) m[ch] = mark;
    }));
    return m;
  }, [guesses]);

  const submit = () => {
    if (status !== 'playing') return;
    if (current.length !== 5) { setShake(true); setTimeout(() => setShake(false), 400); return; }
    const marks = _scoreGuess(current, answer);
    const next = [...guesses, { word: current, marks }];
    setGuesses(next);
    setCurrent('');
    if (current === answer) {
      setStatus('won');
      window.fireRewardEvent && window.fireRewardEvent({ pts: 25, reason: 'Easy Points · solved the word', label: '+25 · Daily game' });
      setTimeout(() => onClose && onClose(), 2600);
    } else if (next.length >= 6) {
      setStatus('lost');
      window.fireRewardEvent && window.fireRewardEvent({ pts: 5, reason: 'Easy Points · nice try', label: '+5 · Play again tomorrow' });
      setTimeout(() => onClose && onClose(), 2800);
    }
  };
  const type = (ch) => {
    if (status !== 'playing') return;
    if (ch === 'ENTER') return submit();
    if (ch === 'DEL') return setCurrent(c => c.slice(0, -1));
    if (current.length < 5) setCurrent(c => c + ch);
  };

  const ROWS = [['Q','W','E','R','T','Y','U','I','O','P'],['A','S','D','F','G','H','J','K','L'],['ENTER','Z','X','C','V','B','N','M','DEL']];

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 270,
      background: '#101014', color: WVU.cream,
      display: 'flex', flexDirection: 'column',
    }}>
      <style>{`
        @keyframes wdShake { 0%,100%{transform:translateX(0)} 25%{transform:translateX(-6px)} 75%{transform:translateX(6px)} }
        @keyframes wdPop { 0%{transform:scale(0.85)} 60%{transform:scale(1.08)} 100%{transform:scale(1)} }
      `}</style>

      {/* header */}
      <div style={{
        paddingTop: 58, paddingBottom: 12, paddingLeft: 14, paddingRight: 14,
        display: 'flex', alignItems: 'center', gap: 12,
        borderBottom: `1px solid ${WVU.line}`,
      }}>
        <button onClick={onClose} style={{
          width: 34, height: 34, borderRadius: 17, flexShrink: 0,
          background: 'rgba(255,255,255,0.07)', border: `1px solid ${WVU.lineBold}`,
          color: WVU.cream, cursor: 'pointer', padding: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="13" height="13" viewBox="0 0 14 14" fill="none"><path d="M2 2l10 10M12 2L2 12" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>
        </button>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: DS.display, fontSize: 19, fontWeight: 900, letterSpacing: '0.02em' }}>
            {(WVU.short || 'TEAM')} WORDLE
          </div>
          <div style={{ fontFamily: DS.sans, fontSize: 11.5, color: WVU.creamDim, marginTop: 1 }}>Guess the 5-letter word in 6 tries</div>
        </div>
        <div style={{
          padding: '5px 11px', borderRadius: DS.r.pill, flexShrink: 0,
          background: hexA(WVU.gold, 0.14), border: `1px solid ${hexA(WVU.gold, 0.4)}`,
          fontFamily: DS.sans, fontSize: 12, fontWeight: 800, color: WVU.gold,
        }}>+25 pts</div>
      </div>

      {/* board */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 6, padding: '12px 0', position: 'relative' }}>
        {Array.from({ length: 6 }).map((_, r) => {
          const done = guesses[r];
          const isCur = r === guesses.length && status === 'playing';
          const word = done ? done.word : (isCur ? current : '');
          return (
            <div key={r} style={{ display: 'flex', gap: 6, animation: isCur && shake ? 'wdShake 0.4s' : 'none' }}>
              {Array.from({ length: 5 }).map((_, c) => {
                const ch = word[c] || '';
                const mark = done ? done.marks[c] : null;
                const bg = mark === 'correct' ? WD_GREEN : mark === 'present' ? WD_YELLOW : mark === 'absent' ? WD_GRAY : 'transparent';
                return (
                  <div key={c} style={{
                    width: 52, height: 52, borderRadius: 5,
                    background: bg,
                    border: mark ? 'none' : `2px solid ${ch ? 'rgba(255,255,255,0.4)' : 'rgba(255,255,255,0.16)'}`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontFamily: DS.sans, fontSize: 24, fontWeight: 800, color: '#fff',
                    animation: ch && !mark ? 'wdPop 120ms ease-out' : 'none',
                    transition: 'background 200ms ease',
                  }}>{ch}</div>
                );
              })}
            </div>
          );
        })}

        {/* result overlay */}
        {status !== 'playing' && (
          <div style={{
            position: 'absolute', left: 24, right: 24, top: '50%', transform: 'translateY(-50%)',
            padding: '20px 18px', borderRadius: DS.r.lg, textAlign: 'center',
            background: status === 'won'
              ? `linear-gradient(150deg, ${WVU.gold}, ${WVU.goldDim})`
              : '#1C1C22',
            border: status === 'won' ? 'none' : `1px solid ${WVU.lineBold}`,
            boxShadow: '0 18px 48px rgba(0,0,0,0.6)',
            animation: 'mtnFade 240ms ease-out',
          }}>
            {status === 'won' && <ConfettiBurst originY={0.2} count={40} />}
            <div style={{ fontFamily: DS.display, fontSize: 24, fontWeight: 900, color: status === 'won' ? (WVU.onPrimary || WVU.blueDim) : WVU.cream }}>
              {status === 'won' ? 'Solved it!' : 'Out of guesses'}
            </div>
            <div style={{ fontFamily: DS.sans, fontSize: 13.5, fontWeight: status === 'won' ? 700 : 400, color: status === 'won' ? (WVU.onPrimary || WVU.blueDim) : WVU.creamDim, marginTop: 6 }}>
              {status === 'won' ? '+25 pts added to your account' : <>The word was <span style={{ color: WVU.gold, fontWeight: 800 }}>{answer}</span> · +5 for playing</>}
            </div>
          </div>
        )}
      </div>

      {/* keyboard */}
      <div style={{ padding: '0 6px 12px', display: 'flex', flexDirection: 'column', gap: 6 }}>
        {ROWS.map((row, ri) => (
          <div key={ri} style={{ display: 'flex', gap: 5, justifyContent: 'center' }}>
            {row.map(k => {
              const mark = keyMarks[k];
              const wide = k === 'ENTER' || k === 'DEL';
              const bg = mark === 'correct' ? WD_GREEN : mark === 'present' ? WD_YELLOW : mark === 'absent' ? '#232328' : 'rgba(255,255,255,0.12)';
              return (
                <button key={k} onClick={() => type(k)} style={{
                  flex: wide ? 1.5 : 1, maxWidth: wide ? 58 : 34, height: 50,
                  borderRadius: 5, border: 'none', cursor: 'pointer', padding: 0,
                  background: bg, color: '#fff',
                  fontFamily: DS.sans, fontSize: wide ? 10 : 14.5, fontWeight: 800,
                }}>{k === 'DEL' ? '⌫' : k}</button>
              );
            })}
          </div>
        ))}
      </div>

      {/* sponsor strip */}
      <div style={{ padding: '0 12px 30px' }}>
        <AdGatoradeSlim label="Daily game fuel" onClick={() => {}} />
      </div>
    </div>
  );
}

Object.assign(window, { EasyPointsCard, WordleGame });
