/* Central Rewards Club — Rewards catalog, detail, redemption, vouchers. */

function tierRank(t) { return ['classic', 'gold', 'platinum', 'black'].indexOf(t); }

function Rewards({ ctx }) {
  const C = ctx.C;
  const [cat, setCat] = React.useState('Semua');
  const list = C.rewards.filter((r) => cat === 'Semua' || r.cat === cat);
  return (
    <div style={{ paddingBottom: 24 }}>
      {/* Header */}
      <div style={{ padding: '60px 20px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 23, fontWeight: 700 }}>Hadiah</h1>
          <p style={{ margin: '2px 0 0', fontSize: 13.5, color: 'var(--crc-ink-2)' }}>Tukarkan poinmu</p>
        </div>
        <button onClick={() => ctx.push('vouchers')} style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '9px 14px', borderRadius: 999, border: 'none', background: 'var(--crc-primary-soft)', color: 'var(--crc-primary)', fontWeight: 600, fontSize: 13, fontFamily: 'var(--crc-font)', cursor: 'pointer' }}>
          <CRCIcon name="ticket" size={17} />Voucher
        </button>
      </div>

      {/* Balance strip */}
      <div style={{ padding: '4px 20px 0' }}>
        <div style={{ background: 'var(--crc-ink)', color: '#fff', borderRadius: 16, padding: '14px 18px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ width: 38, height: 38, borderRadius: 11, background: 'linear-gradient(135deg,var(--crc-gold),var(--crc-gold-deep))', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><CRCIcon name="sparkle" size={20} color="#3a2c0a" /></span>
            <div><div style={{ fontSize: 11.5, color: 'rgba(255,255,255,.6)', fontWeight: 600, whiteSpace: 'nowrap' }}>POIN AKTIF</div><div className="crc-display" style={{ fontSize: 22, fontWeight: 800, lineHeight: 1.1 }}>{ctx.fmt.pts(ctx.points)}</div></div>
          </div>
          <span style={{ fontSize: 12, color: 'var(--crc-gold)', fontWeight: 600 }}>{ctx.tierObj.name} · {ctx.tierObj.mult}</span>
        </div>
      </div>

      {/* Filter chips */}
      <div style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: '16px 20px 4px' }}>
        {C.rewardCats.map((c) => <Chip key={c} label={c} active={cat === c} onClick={() => setCat(c)} />)}
      </div>

      {/* Grid */}
      <div style={{ padding: '12px 20px 0', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        {list.map((r) => {
          const locked = r.tier && tierRank(ctx.tier) < tierRank(r.tier);
          const afford = ctx.points >= r.cost;
          return (
            <div key={r.id} onClick={() => ctx.push('rewardDetail', { id: r.id })} style={{ borderRadius: 16, overflow: 'hidden', background: '#fff', boxShadow: 'var(--crc-sh-sm)', cursor: 'pointer', position: 'relative' }}>
              <div style={{ position: 'relative', height: 112 }}>
                <Img slot={r.slot} placeholder="Produk" radius={0} />
                {r.hot && <span style={{ position: 'absolute', top: 10, left: 10, display: 'flex', alignItems: 'center', gap: 4, padding: '3px 8px', borderRadius: 999, background: 'var(--crc-coral)', color: '#fff', fontSize: 10.5, fontWeight: 700 }}><CRCIcon name="flame" size={12} />HOT</span>}
                {locked && <div style={{ position: 'absolute', inset: 0, background: 'rgba(26,8,12,.55)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 5, color: '#fff' }}><CRCIcon name="lock" size={22} color="var(--crc-gold)" /><span style={{ fontSize: 11, fontWeight: 700 }}>{C.TIERS[r.tier].name}</span></div>}
              </div>
              <div style={{ padding: '11px 12px 13px' }}>
                <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--crc-ink-2)', letterSpacing: '.04em', textTransform: 'uppercase' }}>{r.cat}</div>
                <div style={{ fontWeight: 600, fontSize: 13, lineHeight: 1.3, marginTop: 3, minHeight: 34 }}>{r.name}</div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 8 }}>
                  <span style={{ display: 'flex', alignItems: 'center', gap: 4, color: 'var(--crc-gold-deep)', fontWeight: 700, fontSize: 13.5 }}><CRCIcon name="sparkle" size={14} />{ctx.fmt.pts(r.cost)}</span>
                  {!locked && !afford && <span style={{ fontSize: 10.5, color: 'var(--crc-ink-2)', fontWeight: 600 }}>kurang {ctx.fmt.pts(r.cost - ctx.points)}</span>}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function RewardDetail({ ctx, params }) {
  const C = ctx.C;
  const r = C.rewards.find((x) => x.id === params.id);
  const locked = r.tier && tierRank(ctx.tier) < tierRank(r.tier);
  const afford = ctx.points >= r.cost;
  return (
    <div style={{ paddingBottom: 110 }}>
      <div style={{ height: 280, position: 'relative' }}>
        <Img slot={r.slot} placeholder="Foto hadiah" radius={0} />
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg,rgba(0,0,0,.25),transparent 30%)' }} />
      </div>
      <div style={{ marginTop: -22, position: 'relative', background: 'var(--crc-bg)', borderRadius: '22px 22px 0 0', padding: '22px 20px 0' }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '4px 11px', borderRadius: 999, background: 'var(--crc-primary-soft)', color: 'var(--crc-primary)', fontSize: 11.5, fontWeight: 700, letterSpacing: '.04em' }}>{r.cat.toUpperCase()}</div>
        <h1 style={{ margin: '12px 0 8px', fontSize: 23, fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1.2 }}>{r.name}</h1>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--crc-gold-deep)', fontWeight: 800, fontSize: 22 }} className="crc-display"><CRCIcon name="sparkle" size={20} color="var(--crc-gold-deep)" />{ctx.fmt.pts(r.cost)} <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--crc-ink-2)', fontFamily: 'var(--crc-font)' }}>poin</span></div>

        <div style={{ marginTop: 18 }}>
          <h3 style={{ margin: '0 0 6px', fontSize: 15, fontWeight: 700 }}>Deskripsi</h3>
          <p style={{ margin: 0, fontSize: 14, color: 'var(--crc-ink-2)', lineHeight: 1.6 }}>Tukarkan poinmu dengan {r.name.toLowerCase()}. Hadiah dapat digunakan di seluruh gerai Central Department Store Grand Indonesia. Voucher dikirim langsung ke dompet digitalmu setelah penukaran.</p>
        </div>
        <div style={{ marginTop: 18 }}>
          <h3 style={{ margin: '0 0 8px', fontSize: 15, fontWeight: 700 }}>Syarat & ketentuan</h3>
          {['Berlaku 30 hari sejak penukaran', 'Tidak dapat digabung dengan promo lain', 'Tunjukkan voucher digital ke kasir'].map((t, i) => (
            <div key={i} style={{ display: 'flex', gap: 9, alignItems: 'flex-start', marginBottom: 8, fontSize: 13.5, color: 'var(--crc-ink-2)' }}><CRCIcon name="check" size={16} color="var(--crc-success)" style={{ marginTop: 1 }} />{t}</div>
          ))}
        </div>
      </div>

      {/* Sticky CTA */}
      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '14px 20px 26px', background: 'linear-gradient(180deg,transparent,var(--crc-bg) 24%)' }}>
        {locked ? (
          <CRCButton variant="dark" size="lg" icon="lock" full onClick={() => ctx.toast('Naik ke tier ' + C.TIERS[r.tier].name + ' untuk membuka', 'warning')}>Khusus member {C.TIERS[r.tier].name}</CRCButton>
        ) : (
          <CRCButton variant={afford ? 'gold' : 'outline'} size="lg" full disabled={!afford} onClick={() => ctx.openSheet(<RedeemSheet ctx={ctx} reward={r} />)}>
            {afford ? 'Tukar sekarang' : `Kurang ${ctx.fmt.pts(r.cost - ctx.points)} poin`}
          </CRCButton>
        )}
      </div>
    </div>
  );
}

function RedeemSheet({ ctx, reward }) {
  const [stage, setStage] = React.useState('confirm'); // confirm | done
  const [voucher, setVoucher] = React.useState(null);
  if (stage === 'done') {
    return (
      <div style={{ padding: '20px 24px 34px', textAlign: 'center', position: 'relative' }}>
        <Confetti show={true} />
        <div style={{ width: 72, height: 72, borderRadius: '50%', margin: '8px auto 0', background: 'var(--crc-gold-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><CRCIcon name="ticket" size={34} color="var(--crc-gold-deep)" /></div>
        <h2 style={{ margin: '18px 0 6px', fontSize: 20, fontWeight: 700 }}>Voucher kamu siap!</h2>
        <p style={{ margin: '0 0 16px', fontSize: 13.5, color: 'var(--crc-ink-2)' }}>{reward.name}</p>
        <div style={{ background: '#fff', borderRadius: 16, padding: 18, boxShadow: 'var(--crc-sh-sm)' }}>
          <QRBlock size={140} seed={(voucher && voucher.code) || reward.id} />
          <div style={{ marginTop: 12, letterSpacing: '.16em', fontWeight: 700, fontSize: 15 }}>{(voucher && voucher.code) || 'CRC-' + reward.id.toUpperCase()}</div>
          <div style={{ fontSize: 12, color: 'var(--crc-ink-2)', marginTop: 4 }}>Berlaku hingga {(voucher && voucher.expires) || '30 hari'}</div>
        </div>
        <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
          <CRCButton variant="outline" size="md" full onClick={() => ctx.closeSheet()}>Tutup</CRCButton>
          <CRCButton variant="primary" size="md" full onClick={() => { ctx.closeSheet(); ctx.push('vouchers'); }}>Lihat voucher</CRCButton>
        </div>
      </div>
    );
  }
  return (
    <div style={{ padding: '8px 20px 30px' }}>
      <h2 style={{ margin: '4px 0 14px', fontSize: 19, fontWeight: 700 }}>Konfirmasi penukaran</h2>
      <Surface pad={16} style={{ display: 'flex', alignItems: 'center', gap: 13 }}>
        <div style={{ width: 56, height: 56, borderRadius: 12, overflow: 'hidden', flexShrink: 0 }}><Img slot={reward.slot} placeholder="" radius={0} /></div>
        <div style={{ flex: 1 }}><div style={{ fontWeight: 600, fontSize: 14 }}>{reward.name}</div><div style={{ fontSize: 12.5, color: 'var(--crc-ink-2)' }}>{reward.cat}</div></div>
        <span style={{ display: 'flex', alignItems: 'center', gap: 3, color: 'var(--crc-gold-deep)', fontWeight: 700 }}><CRCIcon name="sparkle" size={15} />{ctx.fmt.pts(reward.cost)}</span>
      </Surface>
      <div style={{ marginTop: 14, padding: '14px 16px', background: '#fff', borderRadius: 14, boxShadow: 'var(--crc-sh-sm)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5, marginBottom: 8 }}><span style={{ color: 'var(--crc-ink-2)' }}>Poin saat ini</span><b>{ctx.fmt.pts(ctx.points)}</b></div>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5, marginBottom: 8 }}><span style={{ color: 'var(--crc-ink-2)' }}>Biaya penukaran</span><b style={{ color: 'var(--crc-coral)' }}>−{ctx.fmt.pts(reward.cost)}</b></div>
        <div style={{ height: 1, background: 'var(--crc-line)', margin: '4px 0 8px' }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14, fontWeight: 700 }}><span>Sisa poin</span><span>{ctx.fmt.pts(ctx.points - reward.cost)}</span></div>
      </div>
      <div style={{ marginTop: 18 }}><CRCButton variant="gold" size="lg" full onClick={() => { const v = ctx.actions.redeemReward(reward); if (v) { setVoucher(v); ctx.celebrate(); setStage('done'); } else { ctx.toast('Poin tidak cukup', 'warning'); } }}>Tukar {ctx.fmt.pts(reward.cost)} poin</CRCButton></div>
    </div>
  );
}

function Vouchers({ ctx }) {
  const C = ctx.C;
  const [tab, setTab] = React.useState('active');
  const list = ctx.store.vouchers.filter((v) => tab === 'active' ? v.status === 'active' : v.status === 'used');
  return (
    <div style={{ paddingBottom: 24 }}>
      <div style={{ display: 'flex', gap: 8, padding: '8px 20px 4px' }}>
        {[['active', 'Aktif'], ['used', 'Terpakai']].map(([k, l]) => <Chip key={k} label={l} active={tab === k} onClick={() => setTab(k)} />)}
      </div>
      <div style={{ padding: '12px 20px 0', display: 'flex', flexDirection: 'column', gap: 14 }}>
        {list.length === 0 && <EmptyState icon="ticket" title="Belum ada voucher" sub="Tukar poinmu untuk dapat voucher." />}
        {list.map((v) => {
          const used = v.status === 'used';
          return (
            <div key={v.id} style={{ position: 'relative', display: 'flex', background: '#fff', borderRadius: 16, overflow: 'hidden', boxShadow: 'var(--crc-sh-sm)', opacity: used ? .55 : 1 }}>
              <div style={{ width: 92, flexShrink: 0 }}><Img slot={v.slot} placeholder="" radius={0} /></div>
              <div style={{ position: 'absolute', left: 84, top: 0, bottom: 0, width: 16, background: 'radial-gradient(circle at left,transparent 7px,#fff 7px)' }} />
              <div style={{ flex: 1, padding: '13px 16px' }}>
                <div style={{ fontWeight: 600, fontSize: 14, lineHeight: 1.3 }}>{v.name}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 7, fontSize: 12.5 }}><span style={{ fontFamily: 'var(--crc-mono,monospace)', letterSpacing: '.06em', fontWeight: 700, color: 'var(--crc-primary)' }}>{v.code}</span></div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 8 }}>
                  <span style={{ fontSize: 12, color: 'var(--crc-ink-2)' }}>{used ? 'Terpakai' : 'Berlaku s/d ' + v.expires}</span>
                  {!used && <button onClick={() => ctx.openSheet(<VoucherUse ctx={ctx} v={v} />)} style={{ padding: '6px 13px', borderRadius: 999, border: 'none', background: 'var(--crc-primary)', color: '#fff', fontWeight: 600, fontSize: 12, fontFamily: 'var(--crc-font)', cursor: 'pointer' }}>Gunakan</button>}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function VoucherUse({ ctx, v }) {
  return (
    <div style={{ padding: '8px 24px 34px', textAlign: 'center' }}>
      <h2 style={{ margin: '4px 0 4px', fontSize: 19, fontWeight: 700 }}>{v.name}</h2>
      <p style={{ margin: '0 0 18px', fontSize: 13.5, color: 'var(--crc-ink-2)' }}>Tunjukkan ke kasir untuk digunakan</p>
      <div style={{ background: '#fff', borderRadius: 18, padding: 22, boxShadow: 'var(--crc-sh-sm)', display: 'inline-block' }}>
        <QRBlock size={180} seed={v.code} />
        <div style={{ marginTop: 12, letterSpacing: '.16em', fontWeight: 700, fontSize: 15, color: 'var(--crc-primary)' }}>{v.code}</div>
      </div>
      <p style={{ margin: '16px 0 0', fontSize: 12.5, color: 'var(--crc-ink-2)' }}>Berlaku hingga {v.expires}</p>
    </div>
  );
}

function EmptyState({ icon, title, sub, cta, onCta }) {
  return (
    <div style={{ textAlign: 'center', padding: '40px 24px' }}>
      <div style={{ width: 72, height: 72, borderRadius: '50%', margin: '0 auto', background: 'var(--crc-line-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><CRCIcon name={icon} size={32} color="var(--crc-ink-2)" /></div>
      <h3 style={{ margin: '16px 0 5px', fontSize: 16, fontWeight: 700 }}>{title}</h3>
      <p style={{ margin: 0, fontSize: 13.5, color: 'var(--crc-ink-2)' }}>{sub}</p>
      {cta && <div style={{ marginTop: 16 }}><CRCButton variant="primary" size="md" onClick={onCta}>{cta}</CRCButton></div>}
    </div>
  );
}

Object.assign(window, { Rewards, RewardDetail, RedeemSheet, Vouchers, VoucherUse, EmptyState, tierRank });
