// commissions.jsx — Commissions page + Tier levels page
function CommissionsPage({ mobile, go, leads, openDoc, showToast }) {
  const comm = leads.filter(l => ['accepte','effectue','verse'].includes(l.status));
  const paidAll = leads.filter(l=>l.status==='verse').reduce((s,l)=>s+l.commission,0);
  const paidMonth = leads.filter(l=>l.status==='verse' && /mai 2026/.test(l.dates.paid)).reduce((s,l)=>s+l.commission,0);
  const pending = leads.filter(l=>['accepte','effectue'].includes(l.status)).reduce((s,l)=>s+(l.commission||0),0);

  const csMeta = { verse:{l:'Versé',c:'b-verse'}, valide:{l:'Validé',c:'b-effectue'}, attente:{l:'En attente',c:'b-accepte'} };
  const metrics = [
    { label:'Total gagné', value:euro(paidAll + pending), sub:'depuis le début', icon:'euroCircle' },
    { label:'Versé ce mois', value:euro(paidMonth), sub:'mai 2026', icon:'check' },
    { label:'En attente', value:euro(pending), sub:`${comm.filter(l=>l.commissionStatus!=='verse').length} déménagements`, icon:'clock' },
    { label:'Prochain versement', value:'5 juin', sub:'2026', icon:'calendar' },
  ];

  const rows = comm.map(l=>{
    const cs = csMeta[l.commissionStatus];
    const date = l.status==='verse'? l.dates.paid : (l.status==='effectue'?'~ juin 2026':'~ août 2026');
    return { l, cs, date };
  });

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
      <div style={{ display:'grid', gridTemplateColumns: mobile?'1fr 1fr':'repeat(4,1fr)', gap: mobile?12:18 }}>
        {metrics.map((m,i)=><KPICard key={i} {...m} delay={i*55} />)}
      </div>

      <div className="card" style={{ overflow:'hidden' }}>
        <div style={{ padding: mobile?'16px 18px':'18px 20px', borderBottom:'1px solid var(--border)', display:'flex', justifyContent:'space-between', alignItems:'center', gap:12 }}>
          <span className="section-title" style={{ fontSize: mobile?16:18 }}>Historique des commissions</span>
          {!mobile && <button className="btn btn-ghost btn-sm" onClick={()=>{ window.exportCommissionsCSV(rows); showToast&&showToast('Export CSV téléchargé'); }}><Icon name="download" size={15} />CSV</button>}
        </div>
        {mobile ? (
          <div>
            {rows.map(({l,cs,date})=>(
              <div key={l.id} onClick={()=>go('lead-detail',{id:l.id})} style={{ padding:'14px 18px', borderBottom:'1px solid var(--border)', display:'flex', justifyContent:'space-between', alignItems:'center', gap:10 }}>
                <div>
                  <div style={{ fontWeight:600, fontSize:14, color:'var(--ink)' }}>{l.first} {l.last}</div>
                  <div style={{ fontSize:12, color:'var(--muted)', marginTop:4 }}><Route from={l.from} to={l.to} /></div>
                </div>
                <div style={{ textAlign:'right' }}>
                  <div className="tnum" style={{ fontWeight:700, fontSize:14.5, color:'var(--ink)' }}>{euro(l.commission)}</div>
                  <span className={`badge ${cs.c}`} style={{ marginTop:5, fontSize:11 }}>{cs.l}</span>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div style={{ padding:'8px 4px' }}>
            <table className="tbl">
              <thead><tr>
                <th>Client</th><th>Déménagement</th><th>Valeur</th><th>Taux</th><th>Commission</th><th>Statut</th><th>Date versement</th><th></th>
              </tr></thead>
              <tbody>
                {rows.map(({l,cs,date})=>(
                  <tr key={l.id} onClick={()=>go('lead-detail',{id:l.id})}>
                    <td className="cell-client">{l.first} {l.last}</td>
                    <td><Route from={l.from} to={l.to} /></td>
                    <td className="tnum">{euro(l.value)}</td>
                    <td className="tnum" style={{ color:'var(--muted)' }}>{l.rate}%</td>
                    <td className="tnum" style={{ fontWeight:700, color:'var(--ink)' }}>{euro(l.commission)}</td>
                    <td><span className={`badge ${cs.c}`}>{cs.l}</span></td>
                    <td style={{ color:'var(--muted)' }}>{date}</td>
                    <td style={{ textAlign:'right', width:50 }}>
                      {l.commissionStatus==='verse' && <button onClick={(e)=>{ e.stopPropagation(); openDoc&&openDoc('invoice', l); }} title="Télécharger la facture" style={{ color:'var(--verse)', display:'inline-flex', padding:6, borderRadius:8 }}
                        onMouseEnter={e=>e.currentTarget.style.background='var(--verse-bg)'} onMouseLeave={e=>e.currentTarget.style.background='transparent'}><Icon name="receipt" size={17} /></button>}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
        <div style={{ padding:'16px 20px', borderTop:'1px solid var(--border)', display:'flex', justifyContent: mobile?'center':'flex-end' }}>
          <button className="btn btn-ghost btn-sm" style={{ height:40 }} onClick={()=>openDoc&&openDoc('statement')}><Icon name="download" size={16} />Télécharger mon relevé mensuel (PDF)</button>
        </div>
      </div>
    </div>
  );
}

/* ============== TIER LEVELS ============== */
function TiersPage({ mobile, go, leads, partner }) {
  const tiers = window.LBC_DATA.TIERS;
  const leadsThisMonth = leads.filter(l=>/mai 2026/.test(l.submitted)).length;
  const toSilver = Math.max(0, 5 - leadsThisMonth);

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:22, maxWidth:1080, margin:'0 auto' }}>
      <div style={{ display:'grid', gridTemplateColumns: mobile?'1fr':'repeat(3,1fr)', gap:18, alignItems:'stretch' }}>
        {tiers.map((t,i)=>{
          const current = t.key===partner.tier;
          return (
            <div key={t.key} className="fade-up" style={{ animationDelay:`${i*70}ms`, position:'relative',
              background:'var(--card)', borderRadius:'var(--r-lg)',
              border: current?'2px solid var(--brand)':'1px solid var(--border)',
              boxShadow: current?'0 12px 34px rgba(182,61,36,.16)':'var(--shadow-card)',
              padding:'26px 24px', display:'flex', flexDirection:'column' }}>
              {current && <span style={{ position:'absolute', top:-11, left:24, background:'var(--brand)', color:'#fff',
                fontSize:11, fontWeight:700, letterSpacing:'.06em', textTransform:'uppercase', padding:'4px 11px', borderRadius:999, whiteSpace:'nowrap' }}>Votre niveau</span>}
              <div style={{ display:'flex', alignItems:'center', gap:11, marginBottom:18 }}>
                <span style={{ width:40, height:40, borderRadius:11, background:t.color+'22', display:'flex', alignItems:'center', justifyContent:'center', color:t.color }}>
                  <Icon name="award" size={22} /></span>
                <span style={{ fontSize:20, fontWeight:700, color:'var(--ink)' }}>{t.key}</span>
              </div>
              <div style={{ display:'flex', alignItems:'baseline', gap:6, marginBottom:4 }}>
                <span className="tnum" style={{ fontSize:38, fontWeight:700, color:'var(--ink)', letterSpacing:'-.02em' }}>{t.rate}%</span>
                <span style={{ fontSize:14, color:'var(--muted)' }}>de commission</span>
              </div>
              <div style={{ fontSize:13, color:'var(--muted)', paddingBottom:18, borderBottom:'1px solid var(--border)' }}>{t.range}</div>
              <div style={{ display:'flex', flexDirection:'column', gap:12, marginTop:18, flex:1 }}>
                {t.perks.map((p,j)=>(
                  <div key={j} style={{ display:'flex', gap:10, alignItems:'flex-start', fontSize:13.5, color:'var(--ink-2)' }}>
                    <span style={{ color:t.color, display:'flex', marginTop:1, flexShrink:0 }}><Icon name="check" size={16} stroke={2.4} /></span>{p}
                  </div>
                ))}
              </div>
            </div>
          );
        })}
      </div>

      <div className="card card-pad" style={{ display:'flex', flexDirection: mobile?'column':'row', gap:20, alignItems: mobile?'stretch':'center', justifyContent:'space-between' }}>
        <div style={{ flex:1 }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:10 }}>
            <span style={{ fontSize:14.5, fontWeight:600, color:'var(--ink)' }}>Vous êtes à {toSilver} lead{toSilver>1?'s':''} de Silver — continuez comme ça&nbsp;!</span>
            <span className="tnum" style={{ fontSize:13, color:'var(--muted)' }}>{leadsThisMonth}/5</span>
          </div>
          <ProgressBar value={leadsThisMonth} max={5} height={9} />
        </div>
        <button className="btn btn-primary" onClick={()=>go('new-lead')} style={{ flexShrink:0 }}>
          <Icon name="plus" size={17} />Envoyer un lead maintenant</button>
      </div>
    </div>
  );
}

Object.assign(window, { CommissionsPage, TiersPage });
