// rewards.jsx — Tukar Poin: katalog voucher, redeem, kode, dompet warga. Global.

function discountLabel(v) {
  if (!v) return '';
  if (v.discount_type === 'amount') return '-Rp' + Math.round(v.discount_value || 0).toLocaleString('id-ID');
  if (v.discount_type === 'percent') return '-' + (v.discount_value || 0) + '%';
  return '';
}
function fmtDateID(d) {
  if (!d) return '';
  try { return new Date(d).toLocaleDateString('id-ID', { day: '2-digit', month: 'short', year: 'numeric' }); } catch (e) { return d; }
}
function copyText(t) {
  try {
    if (navigator.clipboard && navigator.clipboard.writeText) return navigator.clipboard.writeText(t);
  } catch (e) {}
  try {
    var ta = document.createElement('textarea'); ta.value = t; ta.style.position = 'fixed'; ta.style.opacity = '0';
    document.body.appendChild(ta); ta.select(); document.execCommand('copy'); document.body.removeChild(ta);
  } catch (e) {}
  return Promise.resolve();
}

// ---------- copy button (kode) ----------
function CopyBtn({ code, style, big }) {
  const [done, setDone] = React.useState(false);
  const onCopy = () => { copyText(code); setDone(true); setTimeout(() => setDone(false), 1600); };
  return (
    <button onClick={onCopy} className="gs-press" style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: big ? '12px 18px' : '6px 12px', borderRadius: 'var(--r-chip)', border: 'none', cursor: 'pointer', fontFamily: 'var(--font)', fontWeight: 800, fontSize: big ? 14.5 : 12, background: done ? 'var(--lime)' : (big ? '#fff' : 'var(--surface-2)'), color: done ? '#fff' : (big ? 'var(--primary)' : 'var(--text-2)'), ...(style || {}) }}>
      <Icon name={done ? 'check' : 'doc'} size={big ? 17 : 13} color={done ? '#fff' : (big ? 'var(--primary)' : 'var(--text-3)')} sw={2.4} />
      {done ? 'Tersalin' : 'Salin kode'}
    </button>
  );
}

// ---------- voucher card (photo-forward) ----------
function VoucherCard({ v, points, onRedeem }) {
  const dc = DIR_CATS.find(d => d.key === v.category) || DIR_CATS[0];
  const afford = points >= v.points_cost;
  const kurang = v.points_cost - points;
  return (
    <button onClick={() => onRedeem(v)} className="gs-press" style={{ position: 'relative', width: '100%', textAlign: 'left', border: 'none', borderRadius: 'var(--r-card)', overflow: 'hidden', cursor: 'pointer', boxShadow: 'var(--sh-2)', fontFamily: 'var(--font)', padding: 0, height: 150, background: dc.color, opacity: afford ? 1 : 0.72 }}>
      {v.photo
        ? <img src={v.photo} alt="" loading="lazy" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', filter: afford ? 'none' : 'grayscale(0.4)' }} />
        : <span style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', background: dc.color }}><Icon name={dc.icon} size={44} color="rgba(255,255,255,0.5)" /></span>}
      <span className="gs-scrim" />
      {/* biaya poin */}
      <span style={{ position: 'absolute', top: 10, right: 10, display: 'inline-flex', alignItems: 'center', gap: 4, padding: '5px 11px', borderRadius: 'var(--r-chip)', background: 'rgba(255,255,255,0.95)', color: 'var(--s-900)', fontSize: 13, fontWeight: 800, boxShadow: '0 2px 8px rgba(0,0,0,0.25)' }}>
        <Icon name="bolt" size={14} color="var(--amber)" /> <span className="mono">{v.points_cost}</span>
      </span>
      {/* diskon */}
      {discountLabel(v) && (
        <span style={{ position: 'absolute', top: 10, left: 10, padding: '4px 11px', borderRadius: 'var(--r-chip)', background: 'var(--coral)', color: '#fff', fontSize: 13, fontWeight: 800, boxShadow: '0 2px 8px rgba(0,0,0,0.25)' }}>{discountLabel(v)}</span>
      )}
      <span style={{ position: 'absolute', left: 13, right: 13, bottom: 11 }}>
        <span style={{ display: 'block', fontSize: 16, fontWeight: 800, color: '#fff', lineHeight: 1.2, textShadow: '0 1px 6px rgba(0,0,0,0.45)' }}>{v.title}</span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 4, flexWrap: 'wrap' }}>
          {v.place_name && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 11.5, color: 'rgba(255,255,255,0.9)' }}><Icon name="pin" size={11} color="rgba(255,255,255,0.85)" /> {v.place_name}</span>}
          {v.remaining != null && <span className="mono" style={{ fontSize: 10.5, fontWeight: 700, color: 'rgba(255,255,255,0.85)', padding: '2px 7px', borderRadius: 'var(--r-chip)', background: 'rgba(0,0,0,0.28)' }}>sisa {v.remaining}</span>}
          {v.valid_until && <span style={{ fontSize: 10.5, color: 'rgba(255,255,255,0.8)' }}>s/d {fmtDateID(v.valid_until)}</span>}
        </span>
        {!afford && <span style={{ display: 'inline-block', marginTop: 6, padding: '3px 10px', borderRadius: 'var(--r-chip)', background: 'rgba(15,23,42,0.66)', color: '#FFD9DB', fontSize: 11, fontWeight: 800 }}>Kurang {kurang} poin</span>}
      </span>
    </button>
  );
}

// ---------- redeem confirm sheet ----------
function RedeemSheet({ v, points, busy, err, onConfirm, onClose }) {
  const after = points - v.points_cost;
  const afford = after >= 0;
  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 130, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', background: 'rgba(15,23,42,0.5)', animation: 'gsFade 160ms var(--ease)' }}>
      <div onClick={e => e.stopPropagation()} style={{ background: 'var(--surface)', borderTopLeftRadius: 'var(--r-lg)', borderTopRightRadius: 'var(--r-lg)', padding: '10px 20px', paddingBottom: 'max(22px, env(safe-area-inset-bottom))', boxShadow: 'var(--sh-3)', animation: 'gsSheetUp 280ms var(--ease)' }}>
        <div style={{ width: 40, height: 4, borderRadius: 3, background: 'var(--border-strong)', margin: '0 auto 16px' }} />
        <h3 style={{ fontSize: 19, fontWeight: 800, color: 'var(--text-1)', letterSpacing: '-0.02em' }}>Tukar voucher?</h3>
        <p style={{ fontSize: 14, color: 'var(--text-2)', marginTop: 4, marginBottom: 16 }}>{v.title}{v.place_name ? ' · ' + v.place_name : ''}</p>

        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px', borderRadius: 'var(--r-card)', background: 'var(--surface-2)', border: '1px solid var(--border)' }}>
          <span style={{ flex: 1 }}>
            <span style={{ display: 'block', fontSize: 11.5, color: 'var(--text-3)', fontWeight: 700 }}>Saldo sekarang</span>
            <span className="mono" style={{ fontSize: 18, fontWeight: 800, color: 'var(--text-1)' }}>{points.toLocaleString('id-ID')}</span>
          </span>
          <Icon name="arrow" size={20} color="var(--text-3)" sw={2.2} />
          <span style={{ flex: 1, textAlign: 'right' }}>
            <span style={{ display: 'block', fontSize: 11.5, color: 'var(--text-3)', fontWeight: 700 }}>Sesudah</span>
            <span className="mono" style={{ fontSize: 18, fontWeight: 800, color: afford ? 'var(--lime-700)' : 'var(--coral-700)' }}>{after.toLocaleString('id-ID')}</span>
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, padding: '5px 10px', borderRadius: 'var(--r-chip)', background: 'var(--amber-50)', color: 'var(--amber-700)', fontWeight: 800, fontSize: 13 }}>
            <Icon name="bolt" size={14} color="var(--amber)" /> <span className="mono">-{v.points_cost}</span>
          </span>
        </div>

        {err && <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12, padding: '11px 14px', borderRadius: 'var(--r-md)', background: 'var(--coral-50)', color: 'var(--coral-700)', fontSize: 13, fontWeight: 600 }}><Icon name="shield" size={16} color="var(--coral-700)" /> {err}</div>}

        <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
          <button onClick={onClose} disabled={busy} className="gs-press" style={{ flex: 1, padding: 15, borderRadius: 'var(--r-chip)', border: '1px solid var(--border)', background: 'var(--surface)', color: 'var(--text-2)', fontWeight: 800, fontSize: 15, cursor: 'pointer', fontFamily: 'var(--font)' }}>Batal</button>
          <button onClick={onConfirm} disabled={busy || !afford} className="gs-press" style={{ flex: 1.6, padding: 15, borderRadius: 'var(--r-chip)', border: 'none', background: afford ? 'var(--cta)' : 'var(--border-strong)', color: '#fff', fontWeight: 800, fontSize: 15, cursor: (busy || !afford) ? 'default' : 'pointer', opacity: busy ? 0.7 : 1, fontFamily: 'var(--font)', boxShadow: afford ? 'var(--sh-cta)' : 'none' }}>{busy ? 'Memproses...' : (afford ? 'Tukar sekarang' : 'Poin belum cukup')}</button>
        </div>
      </div>
    </div>
  );
}

// ---------- redeem success (kode besar) ----------
function RedeemSuccess({ result, onClose }) {
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 135, background: 'var(--grad-hero)', display: 'flex', flexDirection: 'column', animation: 'gsFade 200ms var(--ease)' }}>
      <Confetti n={36} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', padding: 26, position: 'relative', zIndex: 2 }}>
        <div style={{ width: 84, height: 84, borderRadius: '50%', background: 'rgba(255,255,255,0.2)', display: 'grid', placeItems: 'center', animation: 'gsPop 420ms var(--ease)' }}>
          <span style={{ fontSize: 44 }}>🎁</span>
        </div>
        <h2 style={{ fontSize: 23, fontWeight: 800, color: '#fff', marginTop: 20, letterSpacing: '-0.02em' }}>Voucher ditukar!</h2>
        <p style={{ fontSize: 14.5, color: 'rgba(255,255,255,0.92)', marginTop: 4 }}>{result.title}{result.place_name ? ' · ' + result.place_name : ''}</p>

        <div style={{ marginTop: 24, width: '100%', maxWidth: 320, background: 'var(--surface)', borderRadius: 'var(--r-lg)', padding: '22px 20px', boxShadow: 'var(--sh-3)' }}>
          <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: '0.1em', color: 'var(--text-3)' }}>KODE VOUCHER</div>
          <div className="mono" style={{ fontSize: 34, fontWeight: 800, letterSpacing: '0.14em', color: 'var(--primary)', margin: '8px 0 6px' }}>{result.code}</div>
          <div style={{ fontSize: 12.5, color: 'var(--text-2)', marginBottom: 16 }}>Tunjukkan kode ini ke kasir</div>
          <CopyBtn code={result.code} big style={{ width: '100%', justifyContent: 'center', border: '1px solid var(--border)', background: 'var(--surface-2)', color: 'var(--primary)' }} />
        </div>

        <div style={{ marginTop: 16, display: 'inline-flex', alignItems: 'center', gap: 6, color: 'rgba(255,255,255,0.9)', fontSize: 13.5, fontWeight: 700 }}>
          <Icon name="bolt" size={15} color="#FFD9A8" /> Sisa poinmu: <span className="mono" style={{ fontWeight: 800 }}>{(result.sisa_poin || 0).toLocaleString('id-ID')}</span>
        </div>
      </div>
      <div style={{ padding: '16px 20px', paddingBottom: 'max(24px, env(safe-area-inset-bottom))', position: 'relative', zIndex: 2 }}>
        <button onClick={onClose} className="gs-press" style={{ width: '100%', padding: 15, borderRadius: 'var(--r-chip)', border: 'none', background: '#fff', color: 'var(--primary)', fontWeight: 800, fontSize: 15, cursor: 'pointer', fontFamily: 'var(--font)' }}>Selesai</button>
      </div>
    </div>
  );
}

// ---------- wallet row (Voucherku) ----------
function WalletRow({ r }) {
  const active = r.status === 'active';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 14px', borderRadius: 'var(--r-card)', background: 'var(--surface)', border: '1px solid ' + (active ? 'var(--border)' : 'var(--border)'), boxShadow: active ? 'var(--sh-1)' : 'none', opacity: active ? 1 : 0.62 }}>
      <span style={{ width: 42, height: 42, borderRadius: 12, background: active ? 'var(--primary-soft)' : 'var(--surface-2)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
        <span style={{ fontSize: 22 }}>{active ? '🎟️' : (r.status === 'used' ? '✅' : '⌛')}</span>
      </span>
      <span style={{ flex: 1, minWidth: 0 }}>
        <span style={{ display: 'block', fontSize: 14.5, fontWeight: 800, color: 'var(--text-1)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.title}</span>
        <span style={{ display: 'block', fontSize: 12, color: 'var(--text-3)' }}>{r.place_name || 'gs.town'} · {discountLabel(r) || (r.points_cost + ' poin')}</span>
        {active
          ? <span className="mono" style={{ display: 'inline-block', marginTop: 5, fontSize: 15, fontWeight: 800, letterSpacing: '0.12em', color: 'var(--primary)' }}>{r.code}</span>
          : <span className="mono" style={{ display: 'inline-block', marginTop: 4, fontSize: 11, fontWeight: 700, color: 'var(--text-3)', textDecoration: r.status === 'used' ? 'none' : 'line-through' }}>{r.code}</span>}
      </span>
      {active
        ? <CopyBtn code={r.code} />
        : <span style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-3)', letterSpacing: '0.06em' }}>{r.status === 'used' ? 'DIPAKAI' : 'HANGUS'}</span>}
    </div>
  );
}

// ---------- rewards screen (list + wallet) ----------
function RewardsScreen({ profile, authed, onRequireAuth, onClose }) {
  const [tab, setTab] = React.useState('katalog');
  const [rows, setRows] = React.useState(null);
  const [notReady, setNotReady] = React.useState(false);
  const [wallet, setWallet] = React.useState(null);
  const [sel, setSel] = React.useState(null);        // voucher yang mau ditukar
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [success, setSuccess] = React.useState(null); // hasil redeem
  const [points, setPoints] = React.useState((profile && profile.points) || 0);

  const loadCatalog = React.useCallback(() => {
    setRows(null);
    gsData.loadVouchers().then(r => { if (r.notReady) { setNotReady(true); setRows([]); } else { setNotReady(false); setRows(r.rows); } });
  }, []);
  const loadWallet = React.useCallback(() => {
    setWallet(null);
    gsData.myWallet().then(w => { if (w.notReady) { setNotReady(true); setWallet({ points: points, redemptions: [] }); } else { setWallet(w); setPoints(w.points); } });
  }, [points]);

  React.useEffect(() => { loadCatalog(); }, []);
  React.useEffect(() => { if (authed) gsData.myWallet().then(w => { if (!w.notReady) setPoints(w.points); }); }, [authed]);
  React.useEffect(() => { if (tab === 'dompet' && wallet === null) loadWallet(); }, [tab]);

  const onRedeem = (v) => {
    if (!authed) { onRequireAuth && onRequireAuth(); return; }
    setErr(''); setSel(v);
  };
  const confirmRedeem = async () => {
    setBusy(true); setErr('');
    const res = await gsData.redeemVoucher(sel.id);
    setBusy(false);
    if (res.notReady) { setErr('Fitur tukar poin segera aktif.'); return; }
    if (res.error) { setErr(res.error); return; }
    setPoints(res.data.sisa_poin);
    setSel(null);
    setSuccess(res.data);
    setWallet(null);       // paksa reload dompet nanti
    loadCatalog();         // sisa kuota bisa berubah
  };
  const closeSuccess = () => { setSuccess(null); setTab('dompet'); };

  const empty = rows && rows.length === 0 && !notReady;

  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 92, background: 'var(--bg)', display: 'flex', flexDirection: 'column', animation: 'gsFade 180ms var(--ease)' }}>
      {/* header */}
      <div style={{ paddingTop: 'max(12px, env(safe-area-inset-top))', background: 'var(--grad-hero)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '6px 16px 12px' }}>
          <button onClick={onClose} className="gs-press" style={{ width: 36, height: 36, borderRadius: '50%', border: 'none', background: 'rgba(255,255,255,0.2)', display: 'grid', placeItems: 'center', cursor: 'pointer' }}><Icon name="chevL" size={20} color="#fff" /></button>
          <h2 style={{ fontSize: 20, fontWeight: 800, color: '#fff', letterSpacing: '-0.02em' }}>Tukar Poin</h2>
          <span style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 5, padding: '6px 13px', borderRadius: 'var(--r-chip)', background: 'rgba(255,255,255,0.94)' }}>
            <Icon name="bolt" size={15} color="var(--amber)" /><span className="mono" style={{ fontSize: 14.5, fontWeight: 800, color: 'var(--text-1)' }}>{points.toLocaleString('id-ID')}</span>
          </span>
        </div>
        <div style={{ display: 'flex', gap: 8, padding: '0 16px 14px' }}>
          {[['katalog', 'Voucher'], ['dompet', 'Voucherku']].map(([k, l]) => (
            <button key={k} onClick={() => setTab(k)} className="gs-press" style={{ flex: 1, padding: '10px', borderRadius: 'var(--r-chip)', cursor: 'pointer', fontFamily: 'var(--font)', fontWeight: 800, fontSize: 13.5, border: 'none', background: tab === k ? '#fff' : 'rgba(255,255,255,0.18)', color: tab === k ? 'var(--primary)' : '#fff' }}>{l}</button>
          ))}
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '16px 16px 30px', scrollbarWidth: 'none' }}>
        {tab === 'katalog' ? (
          rows === null ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>{[0, 1, 2].map(i => <Skeleton key={i} h={150} r={16} />)}</div>
          ) : notReady ? (
            <EmptyState icon="tag" grad="var(--grad-coral)" title="Tukar poin segera aktif" sub="Fitur reward sedang disiapkan. Cek lagi sebentar lagi ya." />
          ) : empty ? (
            <EmptyState icon="tag" grad="var(--grad-coral)" title="Belum ada voucher" sub="Kumpulkan poin dari check-in & laporan — voucher menarik akan hadir di sini." />
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {rows.map(v => <VoucherCard key={v.id} v={v} points={points} onRedeem={onRedeem} />)}
            </div>
          )
        ) : (
          !authed ? (
            <EmptyState icon="user" grad="var(--grad-blue)" title="Masuk dulu" sub="Login untuk melihat voucher yang kamu tukar." cta="Masuk / Daftar" onCta={() => onRequireAuth && onRequireAuth()} />
          ) : wallet === null ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>{[0, 1, 2].map(i => <Skeleton key={i} h={68} r={16} />)}</div>
          ) : wallet.redemptions.length === 0 ? (
            <EmptyState icon="tag" grad="var(--grad-violet)" title="Dompet masih kosong" sub="Tukar poinmu jadi voucher dulu, nanti muncul di sini." cta="Lihat voucher" onCta={() => setTab('katalog')} />
          ) : (
            (() => {
              const act = wallet.redemptions.filter(r => r.status === 'active');
              const hist = wallet.redemptions.filter(r => r.status !== 'active');
              return (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                  {act.length > 0 && (
                    <div>
                      <div style={{ fontSize: 12.5, fontWeight: 800, color: 'var(--text-2)', letterSpacing: '0.04em', marginBottom: 10 }}>AKTIF · {act.length}</div>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>{act.map(r => <WalletRow key={r.id} r={r} />)}</div>
                    </div>
                  )}
                  {hist.length > 0 && (
                    <div>
                      <div style={{ fontSize: 12.5, fontWeight: 800, color: 'var(--text-3)', letterSpacing: '0.04em', marginBottom: 10 }}>RIWAYAT</div>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>{hist.map(r => <WalletRow key={r.id} r={r} />)}</div>
                    </div>
                  )}
                </div>
              );
            })()
          )
        )}
      </div>

      {sel && <RedeemSheet v={sel} points={points} busy={busy} err={err} onConfirm={confirmRedeem} onClose={() => { if (!busy) { setSel(null); setErr(''); } }} />}
      {success && <RedeemSuccess result={success} onClose={closeSuccess} />}
    </div>
  );
}

Object.assign(window, { RewardsScreen, VoucherCard, RedeemSheet, RedeemSuccess, WalletRow, CopyBtn, discountLabel });
