// Helper-side Referral pages — Wallet hub + /r/:code landing
// Exports: HelperReferralWallet, ReferralLandingPage, shared UI bits

// ========================================================================
// Shared formatters
// ========================================================================
const fmtUsd = (cents) => '$' + (cents / 100).toFixed(cents % 100 === 0 ? 0 : 2);
const fmtLocal = (cents, cur) => {
  const major = cents / 100;
  if (cur === 'IDR' || cur === 'VND') return new Intl.NumberFormat('en-US', { maximumFractionDigits: 0 }).format(major) + ' ' + cur;
  return cur + ' ' + new Intl.NumberFormat('en-US', { maximumFractionDigits: 2 }).format(major);
};
const fmtRelDays = (date) => {
  if (!date) return '—';
  const d = Math.round((date.getTime() - Date.now()) / 86400000);
  if (d === 0) return 'today';
  if (d > 0) return `in ${d}d`;
  return `${-d}d ago`;
};
const fmtDate = (d) => d ? new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', year: 'numeric' }).format(d) : '—';

// ========================================================================
// Status badges
// ========================================================================
const REFERRAL_STATUS_META = {
  PENDING:   { label: 'In progress',    bg: '#FFF7E6', fg: '#8A5A00', dot: '#F59E0B' },
  QUALIFIED: { label: 'On track',       bg: '#E7F3FD', fg: '#1F5EAD', dot: '#2563EB' },
  HOLD:      { label: 'Hold period',    bg: '#F0F4F8', fg: '#4A5568', dot: '#718096' },
  PAID:      { label: 'Completed',      bg: '#E6F4EA', fg: '#1E6B3A', dot: '#2F8F4E' },
  VOID:      { label: 'Not eligible',   bg: '#FCEDEA', fg: '#9A2820', dot: '#D2392D' },
};
const ReferralStatusBadge = ({ status }) => {
  const m = REFERRAL_STATUS_META[status] || { label: status, bg: '#EEE', fg: '#444', dot: '#888' };
  return (
    <span style={{
      display:'inline-flex', alignItems:'center', gap:6, padding:'3px 10px', borderRadius:99,
      background:m.bg, color:m.fg, fontSize:11, fontWeight:600, letterSpacing:'0.02em'
    }}>
      <span style={{width:6, height:6, borderRadius:99, background:m.dot}}/>{m.label}
    </span>
  );
};

// ========================================================================
// Step mini-timeline — 4 dots showing the new referral flow:
//   1. Sign up → 2. Complete resume → 3. Approved → 4. 14-day HOLD ends
// Stays in sync with helper-referral-data.js field names.
// ========================================================================
const GatesTimeline = ({ r, compact = false }) => {
  const now = new Date();
  const holdEnded = r.holdEndAt && r.holdEndAt < now;
  const steps = [
    { label: 'Signed up',       at: r.signupAt,          done: !!r.signupAt,          icon: 'user' },
    { label: 'Resume submitted', at: r.resumeSubmittedAt, done: !!r.resumeSubmittedAt, icon: 'check' },
    { label: 'Approved',         at: r.approvedAt,        done: !!r.approvedAt,        icon: 'verified' },
    { label: '14-day HOLD ends', at: r.holdEndAt,         done: !!holdEnded,           icon: 'clock' },
  ];
  if (compact) {
    return (
      <div style={{display:'flex', alignItems:'center', gap:3}}>
        {steps.map((g, i) => (
          <React.Fragment key={i}>
            <div style={{
              width:12, height:12, borderRadius:99,
              background: g.done ? 'var(--trust)' : 'var(--t-line)',
              border: g.done ? 'none' : '1.5px dashed var(--t-line-strong, #CDD5DC)',
              boxShadow: g.done ? '0 0 0 2px var(--trust-bg)' : 'none',
              transition:'all 0.2s',
            }} title={g.label + (g.done ? ': ' + fmtDate(g.at) : ': pending')}/>
            {i < steps.length - 1 && <div style={{width:14, height:1.5, background: steps[i+1].done ? 'var(--trust)' : 'var(--t-line)'}}/>}
          </React.Fragment>
        ))}
      </div>
    );
  }
  return (
    <div style={{display:'flex', alignItems:'center', padding:'8px 0'}}>
      {steps.map((g, i) => (
        <React.Fragment key={i}>
          <div style={{display:'flex', flexDirection:'column', alignItems:'center', flex:1, minWidth:60}}>
            <div style={{
              width:28, height:28, borderRadius:99,
              background: g.done ? 'var(--trust)' : '#F7F8FA',
              border: g.done ? 'none' : '2px dashed #D5DBE2',
              display:'grid', placeItems:'center', flexShrink:0,
              color: g.done ? 'white' : '#A0A7B0',
              transition:'all 0.2s',
            }}>
              <Icon name={g.icon} size={12}/>
            </div>
            <div style={{fontSize:10, fontWeight: g.done ? 600 : 400, color: g.done ? 'var(--t-ink)' : 'var(--t-ink-muted)', marginTop:6, textAlign:'center'}}>{g.label}</div>
            <div style={{fontSize:10, color:'var(--t-ink-muted)', marginTop:1}}>{g.at ? fmtRelDays(g.at) : '—'}</div>
          </div>
          {i < steps.length - 1 && (
            <div style={{flex:1, height:2, background: steps[i+1].done ? 'var(--trust)' : '#E5E9EE', marginBottom:28, minWidth:20}}/>
          )}
        </React.Fragment>
      ))}
    </div>
  );
};

// ========================================================================
// HELPER REFERRAL WALLET — replaces old HelperEarnings
// ========================================================================
const HelperReferralWallet = () => {
  const data = window.HELPER_REFERRAL;
  if (!data) return <div style={{padding:40, textAlign:'center', color:'var(--t-ink-muted)'}}>Loading wallet…</div>;

  const { ME, referrals, payouts, payoutMethod, totals, stats, usdToLocal } = data;
  const [tab, setTab] = React.useState('overview');
  const [copied, setCopied] = React.useState(false);
  const [openRef, setOpenRef] = React.useState(null);

  const refLink = `https://helpermatch.com/r/${ME.referralCode}`;
  const copyLink = () => {
    navigator.clipboard.writeText(refLink).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2200);
    }).catch(() => {});
  };
  const shareWA = () => {
    const msg = encodeURIComponent(`Hi! Aku pakai HelperMatch untuk cari kerja di luar negeri, no agency fee. Kamu daftar pake kode aku, kita berdua dapet bonus 🎁 ${refLink}`);
    window.open(`https://wa.me/?text=${msg}`, '_blank');
  };
  const shareFB = () => {
    window.open(`https://facebook.com/sharer/sharer.php?u=${encodeURIComponent(refLink)}`, '_blank');
  };

  return (
    <div>
      <div className="dash-header">
        <h1>🎁 Earnings & referrals</h1>
        <p>Earn <strong>$5</strong> ({fmtLocal(usdToLocal(500, ME.localCurrency), ME.localCurrency)}) for every friend who completes the full HelperMatch sign-up flow and clears the 14-day safety hold.</p>
      </div>

      {/* ─── Wallet summary card ────────────────────────────────────── */}
      <div className="card-flat" style={{padding:0, marginBottom:20, overflow:'hidden', background:'linear-gradient(135deg, var(--trust-ink) 0%, #2A4668 100%)', color:'white'}}>
        <div style={{padding:'26px 28px 22px'}}>
          <div style={{display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:20}}>
            <div>
              <div style={{fontSize:11, fontWeight:600, letterSpacing:'0.12em', textTransform:'uppercase', opacity:0.7, marginBottom:8}}>Total earned</div>
              <div style={{display:'flex', alignItems:'baseline', gap:10, marginBottom:6}}>
                <span style={{fontSize:42, fontWeight:700, letterSpacing:'-0.02em', lineHeight:1}}>{fmtUsd(totals.totalEarnedUsdCents)}</span>
                <span style={{fontSize:15, opacity:0.75}}>USD</span>
              </div>
              <div style={{fontSize:13, opacity:0.75}}>
                ≈ {fmtLocal(usdToLocal(totals.totalEarnedUsdCents, ME.localCurrency), ME.localCurrency)}
                <span style={{margin:'0 8px', opacity:0.4}}>·</span>
                from {stats.paidReferrals} completed referral{stats.paidReferrals === 1 ? '' : 's'}
              </div>
            </div>
            <div style={{textAlign:'right'}}>
              <div style={{fontSize:11, fontWeight:600, letterSpacing:'0.12em', textTransform:'uppercase', opacity:0.7, marginBottom:8}}>Last payout</div>
              {payouts[0] ? (
                <>
                  <div style={{fontSize:16, fontWeight:600}}>{fmtUsd(payouts[0].amountUsdCents)}</div>
                  <div style={{fontSize:12, opacity:0.75, marginTop:2}}>{fmtRelDays(payouts[0].paidAt)} to {payoutMethod.label}</div>
                </>
              ) : (
                <div style={{fontSize:13, opacity:0.75}}>No payouts yet</div>
              )}
            </div>
          </div>
        </div>
        <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', borderTop:'1px solid rgba(255,255,255,0.12)'}}>
          {[
            { label: 'In progress',   value: fmtUsd(totals.pendingUsdCents), sub: `${stats.pendingReferrals} referrals` },
            { label: 'In hold period', value: fmtUsd(totals.holdUsdCents),    sub: '14-day confirmation' },
            { label: 'Paid out',       value: fmtUsd(totals.paidOutUsdCents), sub: `${payouts.length} transaction${payouts.length === 1 ? '' : 's'}` },
          ].map((s, i) => (
            <div key={i} style={{padding:'14px 22px', borderRight: i < 2 ? '1px solid rgba(255,255,255,0.12)' : 'none'}}>
              <div style={{fontSize:10, fontWeight:600, letterSpacing:'0.1em', textTransform:'uppercase', opacity:0.65, marginBottom:4}}>{s.label}</div>
              <div style={{fontSize:18, fontWeight:700, letterSpacing:'-0.01em'}}>{s.value}</div>
              <div style={{fontSize:11, opacity:0.7, marginTop:1}}>{s.sub}</div>
            </div>
          ))}
        </div>
      </div>

      {/* ─── Tabs ─────────────────────────────────────────────────── */}
      <div style={{display:'flex', gap:4, borderBottom:'1px solid var(--t-line)', marginBottom:22}}>
        {[
          { id: 'overview', label: 'Share & invite' },
          { id: 'referrals', label: `My referrals (${referrals.length})` },
          { id: 'payouts', label: `Payouts (${payouts.length})` },
          { id: 'how', label: 'How it works' },
        ].map(t => (
          <button key={t.id} onClick={()=>setTab(t.id)} style={{
            padding:'12px 16px', border:'none', background:'transparent',
            fontSize:13, fontWeight: tab === t.id ? 600 : 500,
            color: tab === t.id ? 'var(--trust-ink)' : 'var(--t-ink-muted)',
            borderBottom: tab === t.id ? '2px solid var(--trust)' : '2px solid transparent',
            marginBottom:-1, cursor:'pointer', fontFamily:'inherit',
          }}>{t.label}</button>
        ))}
      </div>

      {/* ─── Tab: Share & invite ─────────────────────────────────── */}
      {tab === 'overview' && (
        <div style={{display:'grid', gridTemplateColumns:'1.3fr 1fr', gap:20}}>
          <div>
            {/* Code card */}
            <div className="card-flat" style={{padding:26, marginBottom:20, borderColor:'var(--trust)'}}>
              <div style={{fontSize:11, fontWeight:700, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--trust)', marginBottom:8}}>Your referral code</div>
              <div style={{display:'flex', alignItems:'center', gap:14, padding:'16px 18px', background:'var(--trust-bg)', border:'1.5px dashed var(--trust-soft)', borderRadius:12, marginBottom:14}}>
                <div style={{flex:1, fontFamily:'JetBrains Mono, monospace', fontSize:22, fontWeight:700, letterSpacing:'0.04em', color:'var(--trust-ink)'}}>{ME.referralCode}</div>
                <button className="btn btn-trust btn-sm" onClick={copyLink}>
                  <Icon name={copied ? 'check' : 'copy'} size={13}/> {copied ? 'Copied!' : 'Copy link'}
                </button>
              </div>
              <div style={{fontSize:12, color:'var(--t-ink-muted)', marginBottom:16, lineHeight:1.6}}>
                Share this link with friends who are also helpers. When they sign up and get hired, you both earn.
              </div>
              <div style={{display:'flex', gap:10}}>
                <button className="btn btn-outline btn-sm" onClick={shareWA} style={{flex:1, justifyContent:'center', gap:8}}>
                  <span style={{fontSize:16}}>💬</span> Share on WhatsApp
                </button>
                <button className="btn btn-outline btn-sm" onClick={shareFB} style={{flex:1, justifyContent:'center', gap:8}}>
                  <span style={{fontSize:16}}>📘</span> Share on Facebook
                </button>
              </div>
            </div>

            {/* Reward breakdown — single $5 bonus paid only after the
                referee completes ALL 4 steps (sign up → resume → approved →
                14-day HOLD). Steps 1-3 are progress milestones with no
                cash; the bonus releases as a single payment at step 4. */}
            <div className="card-flat" style={{padding:24}}>
              <h3 style={{fontSize:15, fontWeight:700, marginBottom:4}}>How you earn $5 per friend</h3>
              <p style={{fontSize:12, color:'var(--t-ink-muted)', marginBottom:18}}>Single $5 bonus paid as one transfer once your friend clears every step. Protects both of you from fraud.</p>
              <div style={{display:'flex', flexDirection:'column', gap:0}}>
                {[
                  { step: 1, label: 'Friend signs up',     sub: 'They create an account using your link or code',           done: 'Tracked automatically' },
                  { step: 2, label: 'Friend completes resume', sub: 'They fill the resume form and hit Publish',             done: 'Submitted to admin queue' },
                  { step: 3, label: 'Friend gets approved',    sub: 'Our team reviews and approves their profile',           done: 'Profile goes live' },
                  { step: 4, label: '14-day HOLD ends',        sub: 'Profile stays active for 14 days · then bonus releases', done: 'You earn $5' },
                ].map((m, i) => (
                  <div key={i} style={{display:'flex', gap:14, padding:'14px 0', borderBottom: i < 3 ? '1px solid var(--t-line)' : 'none'}}>
                    <div style={{
                      width:34, height:34, borderRadius:99,
                      background: i === 3 ? 'var(--trust)' : 'var(--trust-bg)',
                      color: i === 3 ? 'white' : 'var(--trust-ink)',
                      display:'grid', placeItems:'center', fontWeight:700, fontSize:13, flexShrink:0,
                    }}>{m.step}</div>
                    <div style={{flex:1}}>
                      <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:2}}>
                        <span style={{fontSize:14, fontWeight:600}}>{m.label}</span>
                        {i === 3 && <span style={{fontSize:14, fontWeight:700, color:'var(--trust-ink)'}}>{fmtUsd(500)}</span>}
                      </div>
                      <div style={{fontSize:12, color:'var(--t-ink-muted)', marginBottom:2}}>{m.sub}</div>
                      <div style={{fontSize:11, color:'var(--trust)', fontWeight:600}}>{m.done}</div>
                    </div>
                  </div>
                ))}
              </div>
              <div style={{marginTop:16, padding:'12px 14px', background:'var(--sand)', borderRadius:8, fontSize:12, color:'var(--t-ink-muted)', lineHeight:1.55}}>
                🎁 <strong style={{color:'var(--t-ink)'}}>Your friend gets $20 credit</strong> toward their first month once their profile is approved.
              </div>
            </div>
          </div>

          {/* Funnel + payout method */}
          <div>
            <div className="card-flat" style={{padding:24, marginBottom:16}}>
              <h3 style={{fontSize:14, fontWeight:700, marginBottom:4}}>Your conversion</h3>
              <p style={{fontSize:11, color:'var(--t-ink-muted)', marginBottom:18}}>How your referrals progress through the funnel.</p>
              {[
                { label: 'Signed up',         pct: 100,                  count: stats.totalReferrals },
                { label: 'Resume submitted',  pct: stats.resumeRate,     count: referrals.filter(r => r.resumeSubmittedAt).length },
                { label: 'Approved',          pct: stats.approvedRate,   count: referrals.filter(r => r.approvedAt).length },
                { label: 'HOLD ended',        pct: stats.holdEndedRate,  count: referrals.filter(r => r.holdEndAt && r.holdEndAt < new Date()).length },
              ].map((row, i) => (
                <div key={i} style={{marginBottom: i < 3 ? 14 : 0}}>
                  <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:4}}>
                    <span style={{fontSize:12, fontWeight:500}}>{row.label}</span>
                    <span style={{fontSize:11, color:'var(--t-ink-muted)'}}>{row.count} · {row.pct}%</span>
                  </div>
                  <div style={{height:6, background:'var(--t-line)', borderRadius:99, overflow:'hidden'}}>
                    <div style={{height:'100%', width:`${row.pct}%`, background:'var(--trust)', borderRadius:99, transition:'width 0.4s'}}/>
                  </div>
                </div>
              ))}
            </div>

            <div className="card-flat" style={{padding:24}}>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:14}}>
                <h3 style={{fontSize:14, fontWeight:700}}>Payout method</h3>
                <button className="btn btn-ghost btn-sm" style={{fontSize:11, padding:'3px 8px'}}>Change</button>
              </div>
              <div style={{display:'flex', alignItems:'center', gap:12, padding:'12px 14px', background:'var(--t-paper)', border:'1px solid var(--t-line)', borderRadius:10, marginBottom:10}}>
                <div style={{width:36, height:36, borderRadius:8, background:'#118EEA', color:'white', display:'grid', placeItems:'center', fontSize:18, fontWeight:700}}>D</div>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{fontSize:13, fontWeight:600}}>{payoutMethod.label}</div>
                  <div style={{fontSize:11, color:'var(--t-ink-muted)'}}>{payoutMethod.accountNumber}</div>
                </div>
                {payoutMethod.kycVerified && (
                  <div title="Verified" style={{color:'var(--trust)'}}><Icon name="verified" size={14}/></div>
                )}
              </div>
              <div style={{fontSize:11, color:'var(--t-ink-muted)', lineHeight:1.5}}>
                Payouts are sent automatically on the 1st and 15th of each month for any amount over {fmtUsd(1000)}.
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ─── Tab: My referrals ────────────────────────────────────── */}
      {tab === 'referrals' && (
        referrals.length === 0 ? (
          <div className="card-flat" style={{padding:60, textAlign:'center'}}>
            <div style={{fontSize:40, marginBottom:10}}>🎁</div>
            <div style={{fontSize:15, fontWeight:600, marginBottom:4}}>No referrals yet</div>
            <div style={{fontSize:12, color:'var(--t-ink-muted)', marginBottom:16}}>Share your code with friends to start earning.</div>
            <button className="btn btn-trust btn-sm" onClick={()=>setTab('overview')}>Get your link</button>
          </div>
        ) : (
          <div className="card-flat" style={{padding:0, overflow:'hidden'}}>
            <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
              <thead>
                <tr style={{background:'var(--sand)', borderBottom:'1px solid var(--t-line)'}}>
                  <th style={{textAlign:'left', padding:'12px 16px', fontSize:11, fontWeight:600, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--t-ink-muted)'}}>Friend</th>
                  <th style={{textAlign:'left', padding:'12px 16px', fontSize:11, fontWeight:600, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--t-ink-muted)'}}>Progress</th>
                  <th style={{textAlign:'right', padding:'12px 16px', fontSize:11, fontWeight:600, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--t-ink-muted)'}}>Earned</th>
                  <th style={{textAlign:'center', padding:'12px 16px', fontSize:11, fontWeight:600, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--t-ink-muted)'}}>Status</th>
                </tr>
              </thead>
              <tbody>
                {referrals.map((r, i) => (
                  <tr key={r.id}
                    style={{borderBottom: i < referrals.length - 1 ? '1px solid var(--t-line)' : 'none', cursor:'pointer', transition:'background 0.15s'}}
                    onClick={()=>setOpenRef(r)}
                    onMouseEnter={e=>e.currentTarget.style.background='var(--sand)'}
                    onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
                    <td style={{padding:'14px 16px'}}>
                      <div style={{display:'flex', alignItems:'center', gap:10}}>
                        <div style={{width:32, height:32, borderRadius:99, background:'var(--sand)', display:'grid', placeItems:'center', fontWeight:600, fontSize:13, color:'var(--t-ink-muted)'}}>
                          {r.refereeName.split(' ').map(w => w[0]).slice(0,2).join('')}
                        </div>
                        <div>
                          <div style={{fontWeight:600, fontSize:13}}>{r.refereeName}</div>
                          <div style={{fontSize:11, color:'var(--t-ink-muted)'}}>{r.refereeFlag} {r.refereeCity} · signed up {fmtRelDays(r.signupAt)}</div>
                        </div>
                      </div>
                    </td>
                    <td style={{padding:'14px 16px'}}>
                      <GatesTimeline r={r} compact={true}/>
                    </td>
                    <td style={{padding:'14px 16px', textAlign:'right'}}>
                      <div style={{fontWeight:700, fontSize:14}}>{fmtUsd(r.status === 'PAID' ? r.bonusUsdCents : 0)}</div>
                      <div style={{fontSize:11, color:'var(--t-ink-muted)'}}>of {fmtUsd(r.bonusUsdCents)}</div>
                    </td>
                    <td style={{padding:'14px 16px', textAlign:'center'}}>
                      <ReferralStatusBadge status={r.status}/>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )
      )}

      {/* ─── Tab: Payouts ─────────────────────────────────────────── */}
      {tab === 'payouts' && (
        payouts.length === 0 ? (
          <div className="card-flat" style={{padding:60, textAlign:'center'}}>
            <div style={{fontSize:40, marginBottom:10}}>💳</div>
            <div style={{fontSize:15, fontWeight:600, marginBottom:4}}>No payouts yet</div>
            <div style={{fontSize:12, color:'var(--t-ink-muted)'}}>Your first payout will appear here once a friend completes their profile.</div>
          </div>
        ) : (
          <div className="card-flat" style={{padding:0, overflow:'hidden'}}>
            <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
              <thead>
                <tr style={{background:'var(--sand)', borderBottom:'1px solid var(--t-line)'}}>
                  <th style={{textAlign:'left', padding:'12px 16px', fontSize:11, fontWeight:600, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--t-ink-muted)'}}>Date</th>
                  <th style={{textAlign:'left', padding:'12px 16px', fontSize:11, fontWeight:600, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--t-ink-muted)'}}>Transaction</th>
                  <th style={{textAlign:'left', padding:'12px 16px', fontSize:11, fontWeight:600, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--t-ink-muted)'}}>Method</th>
                  <th style={{textAlign:'right', padding:'12px 16px', fontSize:11, fontWeight:600, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--t-ink-muted)'}}>Amount</th>
                  <th style={{textAlign:'center', padding:'12px 16px', fontSize:11, fontWeight:600, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--t-ink-muted)'}}>Status</th>
                </tr>
              </thead>
              <tbody>
                {payouts.map((p, i) => (
                  <tr key={p.id} style={{borderBottom: i < payouts.length - 1 ? '1px solid var(--t-line)' : 'none'}}>
                    <td style={{padding:'14px 16px', color:'var(--t-ink-muted)', fontSize:12}}>{fmtDate(p.paidAt || p.requestedAt)}</td>
                    <td style={{padding:'14px 16px'}}>
                      <div style={{fontSize:12, fontFamily:'JetBrains Mono, monospace', fontWeight:500}}>{p.externalTxId || p.id}</div>
                      <div style={{fontSize:11, color:'var(--t-ink-muted)', marginTop:1}}>
                        {p.items.length} referral{p.items.length === 1 ? '' : 's'}
                        {p.note && <> · {p.note}</>}
                      </div>
                    </td>
                    <td style={{padding:'14px 16px'}}>
                      <div style={{display:'flex', alignItems:'center', gap:8}}>
                        <div style={{width:20, height:20, borderRadius:4, background:'#118EEA', color:'white', display:'grid', placeItems:'center', fontSize:11, fontWeight:700}}>D</div>
                        <span style={{fontSize:12, color:'var(--t-ink-muted)'}}>{p.maskedAccount}</span>
                      </div>
                    </td>
                    <td style={{padding:'14px 16px', textAlign:'right'}}>
                      <div style={{fontWeight:700, fontSize:14}}>{fmtUsd(p.amountUsdCents)}</div>
                      <div style={{fontSize:11, color:'var(--t-ink-muted)'}}>{fmtLocal(p.amountLocalCents, p.currency)}</div>
                    </td>
                    <td style={{padding:'14px 16px', textAlign:'center'}}>
                      <ReferralStatusBadge status={p.status === 'PAID' ? 'PAID' : 'PENDING'}/>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )
      )}

      {/* ─── Tab: How it works ──────────────────────────────────── */}
      {tab === 'how' && (
        <div style={{maxWidth:720}}>
          <div className="card-flat" style={{padding:28, marginBottom:16}}>
            <h3 style={{fontSize:16, fontWeight:700, marginBottom:14}}>The short version</h3>
            <ol style={{margin:0, paddingLeft:0, listStyle:'none', counterReset:'step', display:'flex', flexDirection:'column', gap:14}}>
              {[
                { t: 'Share your unique link', s: `Send your link (${refLink}) to friends who are helpers looking for jobs abroad.` },
                { t: 'They sign up with your code', s: 'We track who referred them with a cookie — no action needed from them.' },
                { t: 'They complete the full sign-up flow', s: 'Friend signs up, finishes their resume, gets approved by our team, and stays active for 14 days. You earn nothing until all four steps are done — keeps the program fair and fraud-free.' },
                { t: 'You earn $5 per successful referral', s: `We transfer the $5 bonus to your ${payoutMethod.label} (${payoutMethod.accountNumber}) on the next 1st or 15th of the month.` },
              ].map((step, i) => (
                <li key={i} style={{display:'flex', gap:14, counterIncrement:'step'}}>
                  <div style={{width:28, height:28, borderRadius:99, background:'var(--trust-ink)', color:'white', display:'grid', placeItems:'center', fontWeight:700, fontSize:13, flexShrink:0}}>{i + 1}</div>
                  <div>
                    <div style={{fontSize:14, fontWeight:600, marginBottom:2}}>{step.t}</div>
                    <div style={{fontSize:12, color:'var(--t-ink-muted)', lineHeight:1.55}}>{step.s}</div>
                  </div>
                </li>
              ))}
            </ol>
          </div>

          <div className="card-flat" style={{padding:28, marginBottom:16}}>
            <h3 style={{fontSize:15, fontWeight:700, marginBottom:14}}>Why the 14-day hold?</h3>
            <p style={{fontSize:13, color:'var(--t-ink-muted)', lineHeight:1.65, marginBottom:10}}>
              Once our team approves your friend's profile, we wait 14 days before paying the $5 bonus. This catches profiles that get suspended or removed shortly after approval — which unfortunately sometimes happens.
            </p>
            <p style={{fontSize:13, color:'var(--t-ink-muted)', lineHeight:1.65, marginBottom:0}}>
              If the profile stays active for the full 14 days, the bonus becomes payable on the next 1st or 15th. If the profile is suspended or voided during the hold, the bonus is cancelled — you only earn from referrals that genuinely make it through.
            </p>
          </div>

          <div className="card-flat" style={{padding:28}}>
            <h3 style={{fontSize:15, fontWeight:700, marginBottom:14}}>What counts as a valid referral?</h3>
            <div style={{fontSize:13, color:'var(--t-ink-muted)', lineHeight:1.7}}>
              <p style={{marginBottom:10}}><strong style={{color:'var(--t-ink)'}}>✓ Real friends</strong> who sign up from your link, complete their profile themselves, and get hired through HelperMatch.</p>
              <p style={{marginBottom:10}}><strong style={{color:'var(--coral)'}}>✗ Self-referrals</strong> (signing up yourself with a different number) — automatically detected via device fingerprint.</p>
              <p style={{margin:0}}><strong style={{color:'var(--coral)'}}>✗ Fake accounts</strong> or accounts that never become real job-seekers.</p>
            </div>
          </div>
        </div>
      )}

      {/* Referral detail drawer */}
      {openRef && <ReferralDetailDrawer referral={openRef} onClose={()=>setOpenRef(null)} usdToLocal={usdToLocal} localCur={ME.localCurrency}/>}
    </div>
  );
};

// ========================================================================
// Drawer for one referral
// ========================================================================
const ReferralDetailDrawer = ({ referral: r, onClose, usdToLocal, localCur }) => {
  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);
  return (
    <div onClick={onClose} style={{position:'fixed', inset:0, background:'rgba(15,22,34,0.45)', zIndex:2000, display:'flex', justifyContent:'flex-end'}}>
      <div onClick={e=>e.stopPropagation()} style={{width:'min(560px, 100vw)', height:'100%', background:'white', overflow:'auto', boxShadow:'-20px 0 60px rgba(0,0,0,0.15)'}}>
        {/* Header */}
        <div style={{padding:'20px 26px 16px', borderBottom:'1px solid var(--t-line)', position:'sticky', top:0, background:'white', zIndex:1}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
            <div style={{display:'flex', alignItems:'center', gap:12}}>
              <div style={{width:44, height:44, borderRadius:99, background:'var(--sand)', display:'grid', placeItems:'center', fontWeight:700, fontSize:16, color:'var(--t-ink-muted)'}}>
                {r.refereeName.split(' ').map(w => w[0]).slice(0,2).join('')}
              </div>
              <div>
                <div style={{fontSize:16, fontWeight:700}}>{r.refereeName}</div>
                <div style={{fontSize:12, color:'var(--t-ink-muted)'}}>{r.refereeFlag} {r.refereeCity} · {r.refereeNat}</div>
              </div>
            </div>
            <button onClick={onClose} style={{width:32, height:32, borderRadius:99, border:'none', background:'var(--sand)', cursor:'pointer', display:'grid', placeItems:'center'}}>
              <Icon name="close" size={14}/>
            </button>
          </div>
        </div>

        <div style={{padding:'22px 26px'}}>
          {/* Total — single $5 bonus, paid only after step 4 (HOLD ends).
              Earned shows $5 only if status is PAID, $0 otherwise. */}
          {(() => {
            const earned = r.status === 'PAID' ? r.bonusUsdCents : 0;
            return (
              <div style={{padding:20, background:'var(--trust-bg)', borderRadius:12, marginBottom:22, display:'flex', alignItems:'center', justifyContent:'space-between'}}>
                <div>
                  <div style={{fontSize:11, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'var(--trust-ink)', marginBottom:4}}>Earned from this referral</div>
                  <div style={{fontSize:28, fontWeight:700, letterSpacing:'-0.01em', lineHeight:1}}>{fmtUsd(earned)} <span style={{fontSize:14, fontWeight:500, color:'var(--t-ink-muted)'}}>of {fmtUsd(r.bonusUsdCents)}</span></div>
                  <div style={{fontSize:12, color:'var(--t-ink-muted)', marginTop:4}}>≈ {fmtLocal(usdToLocal(earned, localCur), localCur)}</div>
                </div>
                <ReferralStatusBadge status={r.status}/>
              </div>
            );
          })()}

          {/* Timeline */}
          <h4 style={{fontSize:12, fontWeight:700, letterSpacing:'0.08em', textTransform:'uppercase', color:'var(--t-ink-muted)', marginBottom:12}}>Progress</h4>
          <GatesTimeline r={r}/>

          {/* Bonus status — single $5 bonus tied to the referral's overall
              status. Released as one transfer once step 4 completes. */}
          <h4 style={{fontSize:12, fontWeight:700, letterSpacing:'0.08em', textTransform:'uppercase', color:'var(--t-ink-muted)', marginBottom:12, marginTop:24}}>Bonus</h4>
          {(() => {
            const isPaid    = r.status === 'PAID';
            const isHold    = r.status === 'HOLD';
            const isPayable = r.status === 'PAYABLE';
            const isVoid    = r.status === 'VOID';
            const subtitle =
              isPaid    ? `Paid ${fmtRelDays(r.paidAt)}` :
              isPayable ? 'Ready to pay · in next batch' :
              isHold    ? `In 14-day hold · releases ${fmtRelDays(r.holdEndAt)}` :
              isVoid    ? 'Cancelled — referral voided' :
                          'Not yet earned · friend still working through the flow';
            return (
              <div style={{display:'flex', alignItems:'center', gap:14, padding:'14px 16px', border:'1px solid var(--t-line)', borderRadius:10, background: isPaid ? 'var(--trust-bg)' : 'white'}}>
                <div style={{width:36, height:36, borderRadius:99, background: isPaid ? 'var(--trust)' : isVoid ? 'var(--coral, #E66A4F)' : 'var(--t-line)', color:'white', display:'grid', placeItems:'center', fontSize:14, fontWeight:700, flexShrink:0}}>
                  {isPaid ? <Icon name="check" size={14}/> : isVoid ? <Icon name="x" size={14}/> : '$'}
                </div>
                <div style={{flex:1}}>
                  <div style={{fontSize:13, fontWeight:600}}>Full referral bonus</div>
                  <div style={{fontSize:11, color:'var(--t-ink-muted)'}}>{subtitle}</div>
                </div>
                <div style={{textAlign:'right'}}>
                  <div style={{fontSize:16, fontWeight:700, color: isPaid ? 'var(--trust-ink)' : isVoid ? 'var(--coral, #E66A4F)' : 'var(--t-ink-muted)'}}>{fmtUsd(r.bonusUsdCents)}</div>
                  <div style={{fontSize:11, color:'var(--t-ink-muted)'}}>{fmtLocal(r.bonusLocalCents, localCur)}</div>
                </div>
              </div>
            );
          })()}

          {/* Attribution */}
          <h4 style={{fontSize:12, fontWeight:700, letterSpacing:'0.08em', textTransform:'uppercase', color:'var(--t-ink-muted)', marginBottom:10, marginTop:24}}>Details</h4>
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, fontSize:13}}>
            <div><div style={{fontSize:11, color:'var(--t-ink-muted)', marginBottom:2}}>Signed up via</div>
              <div style={{fontWeight:500}}>{{cookie:'Your link', manual_input:'Manual code entry', qr:'QR code'}[r.attributionSource]}</div>
            </div>
            <div><div style={{fontSize:11, color:'var(--t-ink-muted)', marginBottom:2}}>Signup date</div>
              <div style={{fontWeight:500}}>{fmtDate(r.signupAt)}</div>
            </div>
            {r.paidAt && (
              <div><div style={{fontSize:11, color:'var(--t-ink-muted)', marginBottom:2}}>Paid out</div>
                <div style={{fontWeight:500}}>{fmtDate(r.paidAt)}</div>
              </div>
            )}
            {r.holdEndAt && r.status === 'HOLD' && (
              <div><div style={{fontSize:11, color:'var(--t-ink-muted)', marginBottom:2}}>Hold ends</div>
                <div style={{fontWeight:500, color:'var(--trust)'}}>{fmtDate(r.holdEndAt)}</div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

// ========================================================================
// REFERRAL LANDING PAGE — /r/:CODE
// ========================================================================
const ReferralLandingPage = ({ code, go }) => {
  // Look up referrer (for demo, match against HELPER_REFERRAL.ME)
  const me = window.HELPER_REFERRAL?.ME;
  const isMe = me && me.referralCode === code;
  const referrer = isMe ? me : { name: code.split('-')[0].replace(/^./, c => c.toUpperCase()).toLowerCase().replace(/^./, c => c.toUpperCase()), nationality: 'Indonesia', flag: '🇮🇩' };

  // Set cookie on mount
  React.useEffect(() => {
    document.cookie = `hm_ref=${encodeURIComponent(code)}; path=/; max-age=2592000`; // 30d
    try { localStorage.setItem('hm_ref', code); localStorage.setItem('hm_ref_at', String(Date.now())); } catch {}
  }, [code]);

  return (
    <div style={{background:'linear-gradient(180deg, var(--trust-bg) 0%, white 60%)', minHeight:'100vh'}}>
      <div className="container" style={{maxWidth:920, padding:'48px 24px 60px'}}>
        {/* Referrer card */}
        <div style={{
          background:'white', border:'1px solid var(--t-line)', borderRadius:16,
          padding:'22px 28px', marginBottom:28,
          display:'flex', alignItems:'center', gap:16,
          boxShadow:'0 4px 16px rgba(30,40,60,0.06)',
        }}>
          <div style={{width:56, height:56, borderRadius:99, background:'var(--trust-bg)', display:'grid', placeItems:'center', fontSize:22, fontWeight:700, color:'var(--trust-ink)', flexShrink:0}}>
            {referrer.name.split(' ').map(w => w[0]).slice(0,2).join('')}
          </div>
          <div style={{flex:1}}>
            <div style={{fontSize:11, fontWeight:700, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--trust)', marginBottom:4}}>You were invited by</div>
            <div style={{fontSize:20, fontWeight:700, letterSpacing:'-0.01em', marginBottom:2}}>{referrer.name}</div>
            <div style={{fontSize:13, color:'var(--t-ink-muted)'}}>{referrer.flag} {referrer.nationality} · helper on HelperMatch</div>
          </div>
          <div style={{textAlign:'right', flexShrink:0}}>
            <div style={{fontFamily:'JetBrains Mono, monospace', fontSize:13, fontWeight:600, color:'var(--t-ink-muted)', marginBottom:4}}>{code}</div>
            <div style={{fontSize:11, color:'var(--trust)', fontWeight:600}}>Code applied ✓</div>
          </div>
        </div>

        {/* Hero */}
        <div style={{textAlign:'center', marginBottom:36}}>
          <div style={{fontSize:48, marginBottom:10}}>🎁</div>
          <h1 style={{fontSize:40, fontWeight:700, letterSpacing:'-0.02em', lineHeight:1.15, maxWidth:640, margin:'0 auto 14px'}}>
            Welcome! Your first month is <span style={{color:'var(--trust)'}}>$20 off</span>.
          </h1>
          <p style={{fontSize:17, color:'var(--t-ink-muted)', lineHeight:1.55, maxWidth:560, margin:'0 auto 28px'}}>
            HelperMatch connects helpers with families directly — <strong style={{color:'var(--t-ink)'}}>no agency fees</strong>, no long contracts, just real matches.
          </p>
          <div style={{display:'inline-flex', gap:10}}>
            <button className="btn btn-trust" style={{fontSize:15, padding:'14px 26px'}} onClick={()=>go('auth:signup')}>
              Create your helper profile <Icon name="arrow" size={14}/>
            </button>
            <button className="btn btn-outline" style={{fontSize:15, padding:'14px 22px'}} onClick={()=>go('candidates')}>
              Browse helpers first
            </button>
          </div>
        </div>

        {/* Perks */}
        <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:16, marginBottom:32}}>
          {[
            { ic: '💰', t: 'No agency fees', s: 'Zero commissions on salary. You keep 100%.' },
            { ic: '🎯', t: 'Direct matching', s: 'Employers message you. You decide who to reply to.' },
            { ic: '📱', t: 'Profile in your language', s: 'Bahasa, Tagalog, 繁中, English — auto-translated.' },
          ].map((p, i) => (
            <div key={i} style={{padding:22, background:'white', border:'1px solid var(--t-line)', borderRadius:12}}>
              <div style={{fontSize:26, marginBottom:10}}>{p.ic}</div>
              <div style={{fontSize:15, fontWeight:700, marginBottom:4}}>{p.t}</div>
              <div style={{fontSize:13, color:'var(--t-ink-muted)', lineHeight:1.55}}>{p.s}</div>
            </div>
          ))}
        </div>

        {/* What you get */}
        <div style={{padding:28, background:'var(--sand)', borderRadius:14, marginBottom:28}}>
          <h3 style={{fontSize:16, fontWeight:700, marginBottom:14, display:'flex', alignItems:'center', gap:8}}>
            <Icon name="verified" size={15} style={{color:'var(--trust)'}}/> What you get with {referrer.name.split(' ')[0]}'s invite
          </h3>
          <div style={{display:'flex', flexDirection:'column', gap:10}}>
            {[
              '$20 credit toward your first premium month (applied automatically)',
              'Priority profile review — we check your videos within 24 hours',
              'Access to jobs in Taiwan, Hong Kong, and Singapore',
              'Free profile translation in all 4 supported languages',
            ].map((b, i) => (
              <div key={i} style={{display:'flex', gap:10, alignItems:'flex-start', fontSize:14}}>
                <div style={{color:'var(--trust)', marginTop:2, flexShrink:0}}><Icon name="check" size={14}/></div>
                <span>{b}</span>
              </div>
            ))}
          </div>
        </div>

        {/* CTA */}
        <div style={{textAlign:'center', padding:'28px 20px', background:'white', border:'2px solid var(--trust)', borderRadius:14}}>
          <div style={{fontSize:15, fontWeight:600, marginBottom:10}}>Ready to find your next family?</div>
          <button className="btn btn-trust" style={{fontSize:15, padding:'14px 32px'}} onClick={()=>go('auth:signup')}>
            Sign up with code {code}
          </button>
          <div style={{fontSize:11, color:'var(--t-ink-muted)', marginTop:14}}>Takes about 10 minutes · Free · No credit card needed</div>
        </div>
      </div>
    </div>
  );
};

// Expose globally
Object.assign(window, { HelperReferralWallet, ReferralLandingPage, GatesTimeline, ReferralStatusBadge, ReferralDetailDrawer });
