// bha-rewards-parts.jsx — sub-components for the Rewards & Achievements screen.
// Top-level function declarations become global, so RewardsScreen (in bha-rewards.jsx)
// can reference them. Also mirrored onto window for safety.
const RWP_C = window.BHA_COLORS

// Shared style helpers (function declarations → visible to sibling rewards files)
function rwCard(extra) { return { background: '#fff', border: `1px solid ${RWP_C.border}`, borderRadius: 16, padding: 16, boxShadow: '0 1px 4px rgba(0,0,0,0.04)', ...(extra || {}) } }
function rwLabel() { return { color: RWP_C.muted, fontSize: 11, fontWeight: 700, letterSpacing: 1.2, textTransform: 'uppercase', fontFamily: 'DM Sans, sans-serif' } }

// ── OVERVIEW TAB ─────────────────────────────────────────────
function RWOverview({ RW, m, st, nav }) {
  const doseBtn = (active, bg, color, border, onClick, label, icon) => (
    <button onClick={onClick} disabled={!active} style={{
      flex: 1, padding: '9px 0', borderRadius: 10, cursor: active ? 'pointer' : 'default',
      background: bg, border: `1.5px solid ${border}`, color, opacity: active ? 1 : 0.5,
      fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 12.5,
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5,
    }}>{icon} {label}</button>
  )

  return (
    <>
      {/* Composite score hero */}
      <div style={{ background: `linear-gradient(135deg, #FFFFFF 0%, ${m.tier.color}10 100%)`, border: `1.5px solid ${m.tier.color}40`, borderRadius: 18, padding: 18, boxShadow: RWP_C.shadow }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
          <div>
            <p style={{ color: m.tier.color, fontSize: 11, fontWeight: 700, letterSpacing: 1.5, textTransform: 'uppercase' }}>Engagement Score</p>
            <p style={{ fontFamily: 'DM Serif Display, serif', fontSize: 30, color: RWP_C.text, lineHeight: 1, marginTop: 4 }}>
              <span style={{ color: m.tier.color }}>{m.score}</span><span style={{ color: RWP_C.muted, fontSize: 18 }}>/100</span>
            </p>
          </div>
          <div style={{ background: `${m.tier.color}15`, color: m.tier.color, padding: '6px 12px', borderRadius: 100, fontSize: 12, fontWeight: 700, fontFamily: 'DM Sans, sans-serif', display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <span>{m.tier.emoji}</span><span>{m.tier.name}</span>
          </div>
        </div>
        <div style={{ background: RWP_C.bg, borderRadius: 100, height: 8, overflow: 'hidden', marginBottom: 10 }}>
          <div style={{ width: `${m.score}%`, height: '100%', background: `linear-gradient(90deg, ${RWP_C.green}, ${RWP_C.gold})`, borderRadius: 100, transition: 'width 0.5s' }} />
        </div>
        <p style={{ color: RWP_C.muted, fontSize: 12, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif' }}>
          Adherence is <strong>{m.adherence}%</strong> and drives most of your score — so your tier and adherence move together.
        </p>
      </div>

      {/* Streak + adherence + rewards quick stats */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
        <div style={{ background: '#fff', border: `1px solid ${RWP_C.border}`, borderRadius: 12, padding: 12, textAlign: 'center' }}>
          <p style={{ fontSize: 20, marginBottom: 2 }}>{m.streak > 0 ? '🔥' : '💔'}</p>
          <p style={{ color: RWP_C.text, fontSize: 16, fontWeight: 800, fontFamily: 'DM Sans, sans-serif' }}>{m.streak}</p>
          <p style={{ color: RWP_C.muted, fontSize: 9, letterSpacing: 0.6, textTransform: 'uppercase', fontWeight: 700 }}>Day Streak</p>
        </div>
        <div style={{ background: '#fff', border: `1px solid ${RWP_C.border}`, borderRadius: 12, padding: 12, textAlign: 'center' }}>
          <p style={{ fontSize: 20, marginBottom: 2 }}>💊</p>
          <p style={{ color: RWP_C.text, fontSize: 16, fontWeight: 800, fontFamily: 'DM Sans, sans-serif' }}>{m.adherence}%</p>
          <p style={{ color: RWP_C.muted, fontSize: 9, letterSpacing: 0.6, textTransform: 'uppercase', fontWeight: 700 }}>Adherence</p>
        </div>
        <div style={{ background: '#fff', border: `1px solid ${RWP_C.border}`, borderRadius: 12, padding: 12, textAlign: 'center' }}>
          <p style={{ fontSize: 20, marginBottom: 2 }}>🎁</p>
          <p style={{ color: RWP_C.text, fontSize: 16, fontWeight: 800, fontFamily: 'DM Sans, sans-serif' }}>{m.rewardsCount}</p>
          <p style={{ color: RWP_C.muted, fontSize: 9, letterSpacing: 0.6, textTransform: 'uppercase', fontWeight: 700 }}>Rewards</p>
        </div>
      </div>

      {/* Pending points — loss-framed */}
      <div style={{ background: `linear-gradient(135deg, ${RWP_C.gold}14, ${RWP_C.gold}06)`, border: `1.5px solid ${RWP_C.gold}50`, borderRadius: 16, padding: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
          <p style={{ color: RWP_C.goldDk, fontSize: 11, fontWeight: 800, letterSpacing: 1, textTransform: 'uppercase', fontFamily: 'DM Sans, sans-serif' }}>Pending Points</p>
          <p style={{ fontFamily: 'DM Serif Display, serif', fontSize: 24, color: RWP_C.goldDk }}>{m.pending}</p>
        </div>
        <p style={{ color: RWP_C.muted, fontSize: 12.5, lineHeight: 1.55, fontFamily: 'DM Sans, sans-serif', marginBottom: 10 }}>
          We pre-loaded your <strong>{m.pendingWeekly}</strong> weekly + <strong>{m.pendingMonthly}</strong> monthly streak bonus. Keep logging to bank them — <strong>miss a dose and you lose {RW.POINTS ? 50 : 50} pending points.</strong>
        </p>
        <div style={{ display: 'flex', gap: 8 }}>
          <div style={{ flex: 1, background: 'rgba(255,255,255,0.6)', borderRadius: 10, padding: '8px 10px' }}>
            <p style={{ color: RWP_C.muted, fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.6 }}>Weekly</p>
            <p style={{ color: RWP_C.text, fontSize: 15, fontWeight: 800, fontFamily: 'DM Sans, sans-serif' }}>{m.pendingWeekly}</p>
          </div>
          <div style={{ flex: 1, background: 'rgba(255,255,255,0.6)', borderRadius: 10, padding: '8px 10px' }}>
            <p style={{ color: RWP_C.muted, fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.6 }}>Monthly</p>
            <p style={{ color: RWP_C.text, fontSize: 15, fontWeight: 800, fontFamily: 'DM Sans, sans-serif' }}>{m.pendingMonthly}</p>
          </div>
        </div>
      </div>

      {/* Today's doses — log or miss */}
      <div style={rwCard()}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
          <p style={rwLabel()}>Today's Doses</p>
          <button onClick={() => RW.resetToday()} style={{ background: 'none', border: 'none', color: RWP_C.muted, fontSize: 11, fontWeight: 700, cursor: 'pointer', fontFamily: 'DM Sans, sans-serif' }}>Reset day</button>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {st.today.doses.map(d => (
            <div key={d.id} style={{ border: `1px solid ${d.status === 'logged' ? RWP_C.green + '50' : d.status === 'missed' ? RWP_C.critical + '50' : RWP_C.border}`, borderRadius: 12, padding: 12, background: d.status === 'logged' ? `${RWP_C.green}08` : d.status === 'missed' ? `${RWP_C.critical}08` : '#fff' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: d.status === 'pending' ? 10 : 0 }}>
                <div>
                  <p style={{ color: RWP_C.text, fontWeight: 700, fontSize: 14, fontFamily: 'DM Sans, sans-serif' }}>{d.name} · {d.dose}</p>
                  <p style={{ color: RWP_C.muted, fontSize: 11, marginTop: 2, fontFamily: 'DM Sans, sans-serif' }}>Scheduled {d.time}</p>
                </div>
                {d.status === 'logged' && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <span style={{ color: RWP_C.green, fontSize: 11, fontWeight: 800, textTransform: 'uppercase' }}>✓ Logged +10</span>
                    <button onClick={() => RW.undoDose(d.id)} style={{ background: 'none', border: 'none', color: RWP_C.muted, fontSize: 11.5, fontWeight: 700, textDecoration: 'underline', cursor: 'pointer', fontFamily: 'DM Sans, sans-serif', padding: 0 }}>Undo</button>
                  </div>
                )}
                {d.status === 'missed' && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <span style={{ color: RWP_C.critical, fontSize: 11, fontWeight: 800, textTransform: 'uppercase' }}>Missed −50</span>
                    <button onClick={() => RW.undoDose(d.id)} style={{ background: 'none', border: 'none', color: RWP_C.critical, fontSize: 11.5, fontWeight: 700, textDecoration: 'underline', cursor: 'pointer', fontFamily: 'DM Sans, sans-serif', padding: 0 }}>Undo</button>
                  </div>
                )}
              </div>
              {d.status === 'pending' && (
                <div style={{ display: 'flex', gap: 8 }}>
                  {doseBtn(true, RWP_C.green, '#fff', RWP_C.green, () => RW.logDose(d.id), 'Log Dose', '✓')}
                  {doseBtn(true, '#fff', RWP_C.critical, RWP_C.critical + '60', () => RW.missDose(d.id), 'Mark Missed', '✕')}
                </div>
              )}
            </div>
          ))}
        </div>
      </div>

      {/* Weekly regret lottery */}
      <RWWeeklyDraw RW={RW} m={m} />

      {/* How to earn */}
      <div style={rwCard()}>
        <p style={{ ...rwLabel(), marginBottom: 12 }}>Ways to Earn</p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {[
            ['💊', 'Log a daily medication', '+10'],
            ['🩸', 'Log a biometric (BP, glucose, weight)', '+10'],
            ['📚', 'Finish an education module', '+50'],
            ['🔥', '7-day streak bonus', '+50'],
            ['🗓', 'Keep an appointment', '+200'],
            ['🔥', '30-day streak bonus', '+250'],
            ['🩺', 'Complete a preventive screening', '+500'],
            ['🤝', 'Referral that activates', '+300'],
          ].map(([ic, lbl, pts], i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{ fontSize: 16, width: 22, textAlign: 'center' }}>{ic}</span>
              <p style={{ flex: 1, color: RWP_C.text, fontSize: 13, fontFamily: 'DM Sans, sans-serif' }}>{lbl}</p>
              <span style={{ color: RWP_C.green, fontSize: 13, fontWeight: 800, fontFamily: 'DM Sans, sans-serif' }}>{pts}</span>
            </div>
          ))}
        </div>
        <p style={{ color: RWP_C.dim, fontSize: 11, marginTop: 12, textAlign: 'center', fontFamily: 'DM Sans, sans-serif' }}>100 points = $1 of redemption value</p>
      </div>
    </>
  )
}

// ── WEEKLY DRAW MODULE ───────────────────────────────────────
function RWWeeklyDraw({ RW, m }) {
  const prize = RW.WEEKLY_PRIZE
  const [preview, setPreview] = React.useState(false)
  const entered = preview ? false : m.drawEntered
  const shownWk = preview ? 62 : m.weekAdherence
  return (
    <div style={{ background: entered ? `linear-gradient(135deg, ${RWP_C.green}12, ${RWP_C.green}04)` : `linear-gradient(135deg, ${RWP_C.muted}12, ${RWP_C.muted}04)`, border: `1.5px solid ${entered ? RWP_C.green + '50' : RWP_C.border}`, borderRadius: 16, padding: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
        <p style={{ ...rwLabel(), color: entered ? RWP_C.green : RWP_C.muted }}>Weekly Draw</p>
        <span style={{ background: entered ? RWP_C.green : RWP_C.muted, color: '#fff', fontSize: 10, fontWeight: 800, padding: '3px 9px', borderRadius: 100, fontFamily: 'DM Sans, sans-serif', textTransform: 'uppercase', letterSpacing: 0.5 }}>{entered ? '✓ Entered' : 'Not entered'}</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
        <div style={{ width: 48, height: 48, borderRadius: 12, background: '#fff', border: `1px solid ${RWP_C.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 26, flexShrink: 0 }}>{prize.emoji}</div>
        <div style={{ flex: 1 }}>
          <p style={{ color: RWP_C.text, fontWeight: 800, fontSize: 15, fontFamily: 'DM Sans, sans-serif' }}>This week: {prize.name}</p>
          <p style={{ color: RWP_C.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif', marginTop: 2 }}>{prize.detail}</p>
        </div>
      </div>
      {/* threshold progress */}
      <div style={{ background: 'rgba(255,255,255,0.7)', borderRadius: 100, height: 8, overflow: 'hidden', marginBottom: 8 }}>
        <div style={{ width: `${Math.min(100, shownWk)}%`, height: '100%', background: entered ? RWP_C.green : RWP_C.gold, borderRadius: 100 }} />
      </div>
      {entered ? (
        <p style={{ color: RWP_C.green, fontSize: 12.5, fontWeight: 600, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif' }}>
          You hit {shownWk}% adherence this week — you're automatically entered. Good luck! 🍀
        </p>
      ) : (
        <p style={{ color: RWP_C.muted, fontSize: 12.5, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif' }}>
          You would have been entered this week. Hit {m.weeklyThreshold}% next week to qualify — you're at {shownWk}%. You've got this. 💛
        </p>
      )}
      <button onClick={() => setPreview(p => !p)} style={{ marginTop: 10, background: 'none', border: 'none', color: RWP_C.dim, fontSize: 11, fontWeight: 600, cursor: 'pointer', fontFamily: 'DM Sans, sans-serif', padding: 0 }}>
        {preview ? '← Back to my real status' : 'Preview: what a missed week looks like ›'}
      </button>
    </div>
  )
}

// ── CATALOG TAB ──────────────────────────────────────────────
function RWCatalog({ RW, m, payerLabels, onPick }) {
  const st = RW.get()
  const capped = RW.CAPPED_PAYERS.includes(m.payerType)
  const payers = ['medicaid', 'medicare', 'dual', 'commercial', 'uninsured']
  return (
    <>
      {/* Payer type selector */}
      <div style={rwCard()}>
        <p style={{ ...rwLabel(), marginBottom: 8 }}>Payer Type</p>
        <p style={{ color: RWP_C.muted, fontSize: 12, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif', marginBottom: 10 }}>
          Determines reward eligibility. Medicaid, Medicare & dual-eligible members have value caps on non-health rewards.
        </p>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {payers.map(p => {
            const on = m.payerType === p
            return (
              <button key={p} onClick={() => RW.setPayer(p)} style={{
                padding: '7px 12px', borderRadius: 100, cursor: 'pointer',
                border: `1.5px solid ${on ? RWP_C.blue : RWP_C.border}`, background: on ? `${RWP_C.blue}12` : '#fff',
                color: on ? RWP_C.blue : RWP_C.muted, fontFamily: 'DM Sans, sans-serif', fontSize: 12.5, fontWeight: on ? 700 : 500,
              }}>{payerLabels[p]}</button>
            )
          })}
        </div>
        {capped && (
          <div style={{ background: RWP_C.infoBg, border: `1px solid ${RWP_C.info}30`, borderRadius: 10, padding: 11, marginTop: 12, display: 'flex', gap: 8 }}>
            <span style={{ fontSize: 14, flexShrink: 0 }}>🛡️</span>
            <p style={{ color: RWP_C.infoText, fontSize: 12, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif' }}>
              {payerLabels[m.payerType]} caps: non-health rewards must be under ${RW.PER_ITEM_CAP} each and under ${RW.ANNUAL_CAP}/yr total. Connected devices & access-to-care rewards are exempt.
            </p>
          </div>
        )}
      </div>

      {/* Catalog items */}
      <p style={{ ...rwLabel(), paddingLeft: 4 }}>Reward Catalog · Balance {m.balance.toLocaleString()} pts</p>
      {RW.CATALOG.map(item => {
        const chk = RW.checkRedeem(item.id)
        const blocked = !chk.ok
        return (
          <div key={item.id} style={rwCard({ opacity: blocked ? 0.92 : 1 })}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10, marginBottom: 8 }}>
              <div style={{ flex: 1 }}>
                <p style={{ color: RWP_C.text, fontWeight: 800, fontSize: 15, fontFamily: 'DM Sans, sans-serif', lineHeight: 1.3 }}>{item.name}</p>
                <p style={{ color: RWP_C.muted, fontSize: 11.5, marginTop: 3, fontFamily: 'DM Sans, sans-serif' }}>{item.category}</p>
              </div>
              {item.qualifying && <span style={{ background: `${RWP_C.green}15`, color: RWP_C.green, fontSize: 9.5, fontWeight: 800, padding: '3px 8px', borderRadius: 100, fontFamily: 'DM Sans, sans-serif', textTransform: 'uppercase', letterSpacing: 0.4, flexShrink: 0 }}>Health-qualifying</span>}
            </div>
            <div style={{ background: `${RWP_C.gold}0C`, borderRadius: 8, padding: '7px 10px', marginBottom: 10 }}>
              <p style={{ color: RWP_C.goldDk, fontSize: 11.5, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif' }}><strong>Care nexus:</strong> {item.careNexus}</p>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <p style={{ color: RWP_C.text, fontSize: 15, fontWeight: 800, fontFamily: 'DM Sans, sans-serif' }}>{item.pointCost.toLocaleString()} pts</p>
                <p style={{ color: RWP_C.dim, fontSize: 11, fontFamily: 'DM Sans, sans-serif' }}>${item.retailValue} retail value</p>
              </div>
              <button onClick={() => onPick(item)} disabled={blocked && chk.reason && chk.reason.includes('Not enough')} style={{
                background: blocked ? '#fff' : RWP_C.gold, color: blocked ? RWP_C.muted : '#fff',
                border: blocked ? `1.5px solid ${RWP_C.border}` : 'none', borderRadius: 10, padding: '10px 18px',
                fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 13, cursor: 'pointer',
              }}>{blocked ? (chk.reason && chk.reason.includes('Not enough') ? 'Need more pts' : 'Check eligibility') : 'Redeem'}</button>
            </div>
            {blocked && chk.reason && !chk.reason.includes('Not enough') && (
              <p style={{ color: RWP_C.critical, fontSize: 11, marginTop: 8, lineHeight: 1.45, fontFamily: 'DM Sans, sans-serif' }}>🚫 Capped for {payerLabels[m.payerType]} — tap for details.</p>
            )}
          </div>
        )
      })}
      <p style={{ color: RWP_C.dim, fontSize: 10.5, textAlign: 'center', lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif', padding: '4px 8px' }}>
        All rewards are non-cash and tied to health or access to care. Compliance caps are a design safeguard — have counsel approve the final catalog and thresholds before launch.
      </p>
    </>
  )
}

// ── ACTIVITY TAB (append-only ledger + audit) ────────────────
function RWActivity({ st }) {
  const fmt = (ts) => new Date(ts).toLocaleDateString([], { month: 'short', day: 'numeric' })
  const earns = st.ledger.filter(l => l.type === 'earn')
  const losses = st.ledger.filter(l => l.type === 'pending_loss')
  const redeems = st.ledger.filter(l => l.type === 'redeem')
  const Row = ({ l, color }) => (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', borderBottom: `1px solid ${RWP_C.border}` }}>
      <div style={{ flex: 1, paddingRight: 10 }}>
        <p style={{ color: RWP_C.text, fontSize: 13, fontWeight: 600, fontFamily: 'DM Sans, sans-serif' }}>{l.reason}</p>
        <p style={{ color: RWP_C.dim, fontSize: 11, marginTop: 1, fontFamily: 'DM Sans, sans-serif' }}>{fmt(l.ts)}</p>
      </div>
      <p style={{ color, fontSize: 14, fontWeight: 800, fontFamily: 'DM Sans, sans-serif' }}>{l.points > 0 ? '+' : ''}{l.points}</p>
    </div>
  )
  return (
    <>
      <div style={rwCard()}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <p style={rwLabel()}>Points Balance</p>
          <p style={{ fontFamily: 'DM Serif Display, serif', fontSize: 26, color: RWP_C.text }}>{st.balance.toLocaleString()}</p>
        </div>
        <p style={{ color: RWP_C.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif' }}>≈ ${(st.balance / 100).toFixed(2)} redemption value · append-only ledger</p>
      </div>

      <div style={rwCard()}>
        <p style={{ ...rwLabel(), marginBottom: 4 }}>Earn History</p>
        {earns.length === 0 ? <p style={{ color: RWP_C.muted, fontSize: 13, padding: '8px 0' }}>No earnings yet.</p> : earns.slice().reverse().map(l => <Row key={l.id} l={l} color={RWP_C.green} />)}
        {losses.length > 0 && <>
          <p style={{ ...rwLabel(), color: RWP_C.critical, margin: '14px 0 4px' }}>Pending Losses</p>
          {losses.slice().reverse().map(l => <Row key={l.id} l={l} color={RWP_C.critical} />)}
        </>}
      </div>

      <div style={rwCard()}>
        <p style={{ ...rwLabel(), marginBottom: 4 }}>Redemption History & Audit</p>
        {st.redemptions.length === 0 ? <p style={{ color: RWP_C.muted, fontSize: 13, padding: '8px 0' }}>No redemptions yet.</p> : st.redemptions.slice().reverse().map(r => (
          <div key={r.id} style={{ padding: '10px 0', borderBottom: `1px solid ${RWP_C.border}` }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <p style={{ color: RWP_C.text, fontSize: 13, fontWeight: 700, fontFamily: 'DM Sans, sans-serif', flex: 1, paddingRight: 8 }}>{r.item}</p>
              <p style={{ color: RWP_C.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif' }}>${r.value}</p>
            </div>
            <p style={{ color: RWP_C.dim, fontSize: 11, marginTop: 3, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif' }}>
              {fmt(r.ts)} · {r.user} · payer: {r.payerType} · {r.capApplied}
            </p>
          </div>
        ))}
      </div>
    </>
  )
}

// ── REDEMPTION MODAL (cap check + audit confirmation) ────────
function RWRedeemModal({ RW, item, result, onConfirm, onClose }) {
  const done = item._done && result && result.ok
  const blocked = result && !result.ok
  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(26,26,46,0.6)', zIndex: 60, display: 'flex', alignItems: 'flex-end', backdropFilter: 'blur(3px)' }}>
      <div onClick={e => e.stopPropagation()} style={{ width: '100%', background: '#fff', borderRadius: '22px 22px 0 0', padding: '22px 20px 28px', animation: 'slideUp 0.25s ease-out' }}>
        <div style={{ width: 44, height: 4, borderRadius: 2, background: RWP_C.border, margin: '0 auto 18px' }} />
        {done ? (
          <div style={{ textAlign: 'center' }}>
            <div style={{ width: 60, height: 60, borderRadius: 30, background: `${RWP_C.green}15`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 30, margin: '0 auto 14px' }}>✓</div>
            <h2 style={{ fontFamily: 'DM Serif Display, serif', fontSize: 22, color: RWP_C.text, marginBottom: 8 }}>Redeemed!</h2>
            <p style={{ color: RWP_C.muted, fontSize: 14, lineHeight: 1.6, fontFamily: 'DM Sans, sans-serif', marginBottom: 16 }}>{item.name} is on its way. An audit record was written.</p>
            <div style={{ background: RWP_C.bg, borderRadius: 12, padding: 14, textAlign: 'left', marginBottom: 16 }}>
              <p style={{ ...rwLabel(), marginBottom: 8 }}>Audit Record</p>
              {[['User', RW.get().user], ['Item', item.name], ['Value', `$${item.retailValue}`], ['Payer type', RW.get().payerType], ['Cap / exemption', result.capApplied]].map(([k, v]) => (
                <div key={k} style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '3px 0' }}>
                  <span style={{ color: RWP_C.muted, fontSize: 12, fontFamily: 'DM Sans, sans-serif' }}>{k}</span>
                  <span style={{ color: RWP_C.text, fontSize: 12, fontWeight: 600, fontFamily: 'DM Sans, sans-serif', textAlign: 'right', flex: 1 }}>{v}</span>
                </div>
              ))}
            </div>
            <button onClick={onClose} style={{ width: '100%', background: RWP_C.gold, color: '#fff', border: 'none', borderRadius: 12, padding: 14, fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 15, cursor: 'pointer' }}>Done</button>
          </div>
        ) : (
          <>
            <p style={{ ...rwLabel(), marginBottom: 6 }}>Confirm Redemption</p>
            <h2 style={{ fontFamily: 'DM Serif Display, serif', fontSize: 22, color: RWP_C.text, lineHeight: 1.25, marginBottom: 12 }}>{item.name}</h2>
            <div style={{ display: 'flex', gap: 10, marginBottom: 16 }}>
              <div style={{ flex: 1, background: RWP_C.bg, borderRadius: 10, padding: 12 }}>
                <p style={{ color: RWP_C.muted, fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.6 }}>Cost</p>
                <p style={{ color: RWP_C.text, fontSize: 16, fontWeight: 800, fontFamily: 'DM Sans, sans-serif' }}>{item.pointCost.toLocaleString()} pts</p>
              </div>
              <div style={{ flex: 1, background: RWP_C.bg, borderRadius: 10, padding: 12 }}>
                <p style={{ color: RWP_C.muted, fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.6 }}>Retail value</p>
                <p style={{ color: RWP_C.text, fontSize: 16, fontWeight: 800, fontFamily: 'DM Sans, sans-serif' }}>${item.retailValue}</p>
              </div>
            </div>
            {blocked ? (
              <div style={{ background: RWP_C.criticalBg, border: `1.5px solid ${RWP_C.critical}40`, borderRadius: 12, padding: 14, marginBottom: 16, display: 'flex', gap: 10 }}>
                <span style={{ fontSize: 18, flexShrink: 0 }}>🚫</span>
                <div>
                  <p style={{ color: RWP_C.criticalText, fontSize: 13, fontWeight: 700, fontFamily: 'DM Sans, sans-serif', marginBottom: 4 }}>Not eligible</p>
                  <p style={{ color: RWP_C.criticalText, fontSize: 12.5, lineHeight: 1.55, fontFamily: 'DM Sans, sans-serif' }}>{result.reason}</p>
                </div>
              </div>
            ) : (
              <div style={{ background: RWP_C.infoBg, border: `1px solid ${RWP_C.info}25`, borderRadius: 10, padding: 11, marginBottom: 16, display: 'flex', gap: 8 }}>
                <span style={{ fontSize: 14, flexShrink: 0 }}>🛡️</span>
                <p style={{ color: RWP_C.infoText, fontSize: 12, lineHeight: 1.5, fontFamily: 'DM Sans, sans-serif' }}>{result && result.capApplied}</p>
              </div>
            )}
            <div style={{ display: 'flex', gap: 10 }}>
              <button onClick={onClose} style={{ flex: 1, background: 'transparent', color: RWP_C.muted, border: `1.5px solid ${RWP_C.border}`, borderRadius: 12, padding: 13, fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 14, cursor: 'pointer' }}>Cancel</button>
              {!blocked && <button onClick={onConfirm} style={{ flex: 1.4, background: RWP_C.gold, color: '#fff', border: 'none', borderRadius: 12, padding: 13, fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 14, cursor: 'pointer' }}>Confirm Redemption</button>}
            </div>
          </>
        )}
      </div>
    </div>
  )
}

window.RWOverview = RWOverview
window.RWWeeklyDraw = RWWeeklyDraw
window.RWCatalog = RWCatalog
window.RWActivity = RWActivity
window.RWRedeemModal = RWRedeemModal
