// Chart Growth Hub — Student "Refer & Earn" panel. Open to ALL students (Free Trial + VIP),
// not VIP-only — the bonus is tiered by the REFERRER's own membership: VIP members earn
// ₱4,000 per successful referral, Free Trial members earn ₱1,000. Whole panel is hidden
// while the $88 VIP promo is running (see REFERRAL_ACTIVE in config.js) and auto-activates
// the moment the promo ends and price reverts to $499.
// Reads students.referral_code (auto-generated at signup) and the referrals table
// (status: pending is informational only right now, earned = referred person became VIP,
// paid = admin has sent the money manually). Exposes window.ReferralPanel.
(function(){
const { useState, useEffect } = React;

const STATUS_META = {
  earned: { label:'Earned — payout pending', color:'#fbbf24', bg:'rgba(251,191,36,.12)' },
  paid:   { label:'Paid', color:'var(--green)', bg:'rgba(52,211,153,.12)' },
};

function ReferralPanel({client, session, isVIP}){
  const [code,setCode]=useState(null);
  const [refs,setRefs]=useState(null);
  const [copied,setCopied]=useState(false);

  async function load(){
    const { data:stu } = await client.from('students').select('referral_code').eq('id',session.user.id).maybeSingle();
    setCode(stu&&stu.referral_code||null);
    const { data:r } = await client.from('referrals').select('*').eq('referrer_student_id',session.user.id).order('created_at',{ascending:false});
    setRefs(r||[]);
  }
  useEffect(()=>{ load(); /* eslint-disable-next-line */ },[]);

  if(code===null || refs===null) return null;

  const link = code ? (location.origin + location.pathname.replace(/[^/]*$/,'') + 'Sign Up.html?ref=' + code) : '';
  const earned = refs.filter(r=>r.status==='earned').reduce((s,r)=>s+Number(r.reward_php||0),0);
  const paid = refs.filter(r=>r.status==='paid').reduce((s,r)=>s+Number(r.reward_php||0),0);
  const CFG = window.CG_CONFIG||{};
  const vipBonus = CFG.REFERRAL_BONUS_VIP_PHP||4000;
  const trialBonus = CFG.REFERRAL_BONUS_TRIAL_PHP||1000;
  const bonusCopy = isVIP
    ? `Earn ₱${vipBonus.toLocaleString('en-US')} for every friend who becomes a VIP member using your link.`
    : `Earn ₱${trialBonus.toLocaleString('en-US')} for every friend who becomes a VIP member using your link — upgrade to VIP to earn ₱${vipBonus.toLocaleString('en-US')} per referral instead.`;

  function copy(){
    navigator.clipboard.writeText(link).then(()=>{ setCopied(true); setTimeout(()=>setCopied(false),2000); });
  }

  return <div style={{background:'linear-gradient(165deg,var(--surface-2),var(--surface))',border:'1px solid var(--border-gold)',borderRadius:'var(--radius)',padding:'24px 26px',marginBottom:34}}>
    <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:16,flexWrap:'wrap',marginBottom:16}}>
      <div>
        <h2 style={{fontSize:'1.3rem',margin:'0 0 4px'}}>Refer &amp; Earn</h2>
        <p style={{color:'var(--ink-dim)',fontSize:'.88rem',margin:0}}>{bonusCopy}</p>
      </div>
      <div style={{display:'flex',gap:18,fontFamily:'var(--font-mono)',fontSize:'.8rem'}}>
        <div style={{textAlign:'right'}}><div style={{color:'var(--gold-2)',fontSize:'1.2rem',fontWeight:600}}>₱{earned.toLocaleString('en-US')}</div><div style={{color:'var(--ink-faint)',fontSize:'.7rem'}}>pending payout</div></div>
        <div style={{textAlign:'right'}}><div style={{color:'var(--green)',fontSize:'1.2rem',fontWeight:600}}>₱{paid.toLocaleString('en-US')}</div><div style={{color:'var(--ink-faint)',fontSize:'.7rem'}}>paid out</div></div>
      </div>
    </div>

    <div style={{display:'flex',gap:10,alignItems:'center',flexWrap:'wrap',marginBottom:refs.length?18:0}}>
      <input readOnly value={link} onClick={e=>e.target.select()} style={{flex:1,minWidth:220,padding:'11px 14px',borderRadius:'var(--radius-sm)',background:'var(--navy-950)',border:'1px solid var(--border)',color:'var(--ink)',fontFamily:'var(--font-mono)',fontSize:'.82rem'}}/>
      <button className="btn btn-primary" style={{width:'auto'}} onClick={copy}>{copied?'Copied ✓':'Copy link'}</button>
    </div>

    {refs.length>0 && <div style={{display:'grid',gap:8}}>
      {refs.map(r=>{ const m=STATUS_META[r.status]||{label:r.status,color:'var(--ink-faint)',bg:'var(--surface)'};
        return <div key={r.id} style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:10,flexWrap:'wrap',padding:'10px 12px',borderRadius:9,background:'var(--surface)',border:'1px solid var(--border)'}}>
          <span style={{fontFamily:'var(--font-mono)',fontSize:'.78rem',color:'var(--ink-dim)'}}>{new Date(r.created_at).toLocaleDateString(undefined,{month:'short',day:'numeric',year:'numeric'})}</span>
          <span style={{fontFamily:'var(--font-mono)',fontSize:'.8rem'}}>₱{Number(r.reward_php).toLocaleString('en-US')}</span>
          <span style={{fontFamily:'var(--font-mono)',fontSize:'.68rem',padding:'3px 10px',borderRadius:999,color:m.color,background:m.bg,border:'1px solid var(--border-gold)'}}>{m.label}</span>
        </div>; })}
    </div>}
  </div>;
}

window.ReferralPanel = ReferralPanel;
})();
