// bha-rewards.jsx — Rewards & Achievements screen (uses window.BHA_RW engine)
const RW_C = window.BHA_COLORS

function useRW() {
  const RW = window.BHA_RW
  const [, force] = React.useState(0)
  React.useEffect(() => RW.subscribe(() => force(n => n + 1)), [])
  return RW
}

// Small styled helpers shared in this file
const rwCardX = null // (helpers live in bha-rewards-parts.jsx as global functions)

function RewardsScreen({ nav }) {
  const RW = useRW()
  const m = RW.compute()
  const st = RW.get()
  const [redeemItem, setRedeemItem] = React.useState(null)
  const [redeemResult, setRedeemResult] = React.useState(null)
  const [showLedger, setShowLedger] = React.useState(false)
  const [tab, setTab] = React.useState('overview') // overview | catalog | activity

  // auto-dismiss the pending-loss flash
  React.useEffect(() => {
    if (m.lastLoss) {
      const t = setTimeout(() => RW.clearLoss(), 4200)
      return () => clearTimeout(t)
    }
  }, [m.lastLoss && m.lastLoss.ts])

  const payerLabels = { medicaid: 'Medicaid', medicare: 'Medicare', dual: 'Dual-eligible', commercial: 'Commercial', uninsured: 'Uninsured / self-pay' }

  return (
    <div style={{ height: '100%', overflowY: 'auto', background: RW_C.bg, paddingBottom: 90 }}>
      <SectionHeader title="Rewards & Achievements" sub="Earn by staying on your medications" onBack={() => nav('home')} backLabel="Home" />

      {/* Pending-loss flash (loss-framing) */}
      {m.lastLoss && (
        <div style={{ position: 'sticky', top: 0, zIndex: 30, padding: '0 16px', marginBottom: 12 }}>
          <div style={{ background: RW_C.criticalBg, border: `1.5px solid ${RW_C.critical}`, borderRadius: 12, padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10, animation: 'rwFlash 0.5s ease-out' }}>
            <span style={{ fontSize: 20 }}>📉</span>
            <p style={{ color: RW_C.criticalText, fontSize: 13.5, fontWeight: 600, lineHeight: 1.45, fontFamily: 'DM Sans, sans-serif' }}>
              You just lost <strong>{m.lastLoss.points} pending points</strong> by missing today's dose.
            </p>
          </div>
        </div>
      )}

      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        {/* Tab switcher */}
        <div style={{ display: 'flex', gap: 8 }}>
          {[['overview', 'Overview'], ['catalog', 'Catalog'], ['activity', 'Activity']].map(([k, lbl]) => {
            const on = tab === k
            return (
              <button key={k} onClick={() => setTab(k)} style={{
                flex: 1, padding: '10px 6px', borderRadius: 100, cursor: 'pointer',
                background: on ? RW_C.gold : '#fff', border: `1.5px solid ${on ? RW_C.gold : RW_C.border}`,
                color: on ? '#fff' : RW_C.muted, fontFamily: 'DM Sans, sans-serif', fontWeight: 700, fontSize: 13,
              }}>{lbl}</button>
            )
          })}
        </div>

        {tab === 'overview' && <RWOverview RW={RW} m={m} st={st} nav={nav} />}
        {tab === 'catalog' && <RWCatalog RW={RW} m={m} payerLabels={payerLabels} onPick={(it) => { setRedeemItem(it); setRedeemResult(RW.checkRedeem(it.id)) }} />}
        {tab === 'activity' && <RWActivity st={st} />}
      </div>

      {/* Redemption modal */}
      {redeemItem && (
        <RWRedeemModal
          RW={RW} item={redeemItem} result={redeemResult}
          onConfirm={() => { const r = RW.redeem(redeemItem.id); setRedeemResult(r); if (r.ok) setRedeemItem({ ...redeemItem, _done: true }) }}
          onClose={() => { setRedeemItem(null); setRedeemResult(null) }}
        />
      )}

      <style>{`@keyframes rwFlash { from { transform: translateY(-8px); opacity: 0 } to { transform: translateY(0); opacity: 1 } }`}</style>
    </div>
  )
}

window.RewardsScreen = RewardsScreen
