// dashboard.jsx — Partner overview
const { useState: useStateD } = React;

function computeKPIs(leads) {
  const accepted = leads.filter(l => ['accepte','effectue','verse'].includes(l.status));
  const thisMonth = leads.filter(l => /mai 2026/.test(l.submitted));
  const prevMonth = leads.filter(l => /avr\. 2026/.test(l.submitted));
  const volume = accepted.reduce((s,l)=> s + (l.value||0), 0);
  const earned = leads.filter(l=>['effectue','verse'].includes(l.status)).reduce((s,l)=> s+(l.commission||0),0);
  const paid = leads.filter(l=>l.status==='verse').reduce((s,l)=> s+(l.commission||0),0);
  const pending = earned - paid;
  const conv = leads.length ? Math.round(accepted.length / leads.length * 100) : 0;
  return { leadsThisMonth: thisMonth.length, leadsPrevMonth: prevMonth.length, accepted: accepted.length, volume, earned, paid, pending, conv };
}

function TierCard({ partner, leads, go, compact, tw }) {
  const k = computeKPIs(leads);
  const next = window.LBC_DATA.TIERS[1];
  const need = 5;
  const done = Math.min(need, k.leadsThisMonth);
  const solid = tw && tw.tierStyle === 'solid';
  return (
    <div className="fade-up" style={{ position:'relative', overflow:'hidden', borderRadius:'var(--r-lg)',
      background: solid ? 'var(--brand)' : 'linear-gradient(120deg, #C24527 0%, #B63D24 42%, #8E2E18 100%)', color:'#fff',
      padding: compact?'20px':'26px 28px', boxShadow:'0 10px 30px rgba(142,46,24,.3)' }}>
      <div style={{ position:'absolute', top:-40, right:-30, width:200, height:200, borderRadius:'50%',
        background:'radial-gradient(circle, rgba(255,255,255,.14), transparent 65%)' }} />
      <div style={{ position:'absolute', bottom:-60, right:90, width:160, height:160, borderRadius:'50%',
        background:'radial-gradient(circle, rgba(0,0,0,.12), transparent 65%)' }} />
      <div style={{ position:'relative', display:'flex', flexWrap:'wrap', gap:24, alignItems:'center', justifyContent:'space-between' }}>
        <div style={{ minWidth:200 }}>
          <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:14 }}>
            <span style={{ width:9, height:9, borderRadius:'50%', background:'#E8B873' }} />
            <span style={{ fontSize:11.5, fontWeight:600, letterSpacing:'.14em', textTransform:'uppercase', opacity:.86 }}>Niveau actuel</span>
          </div>
          <div style={{ display:'flex', alignItems:'baseline', gap:14 }}>
            <span style={{ fontSize:34, fontWeight:700, letterSpacing:'-.02em' }}>Bronze</span>
            <span style={{ fontSize:15, fontWeight:600, padding:'4px 11px', borderRadius:999, background:'rgba(255,255,255,.18)', whiteSpace:'nowrap' }}>{partner.rate}% de commission</span>
          </div>
        </div>
        <button onClick={()=>go('tiers')} style={{ display:'inline-flex', alignItems:'center', gap:7, fontSize:13.5,
          fontWeight:600, color:'#fff', background:'rgba(255,255,255,.15)', padding:'9px 15px', borderRadius:9,
          border:'1px solid rgba(255,255,255,.22)', transition:'.16s', backdropFilter:'blur(4px)' }}
          onMouseEnter={e=>e.currentTarget.style.background='rgba(255,255,255,.26)'}
          onMouseLeave={e=>e.currentTarget.style.background='rgba(255,255,255,.15)'}>
          Voir tous les niveaux <Icon name="arrowR" size={15} /></button>
      </div>
      <div style={{ position:'relative', marginTop:22 }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', gap:12, fontSize:13, marginBottom:9, opacity:.95 }}>
          <span style={{ whiteSpace:'nowrap' }}><strong style={{ fontWeight:700 }}>{done} leads</strong> sur {need} pour passer <strong style={{ fontWeight:700 }}>Silver ({next.rate}%)</strong></span>
          <span style={{ opacity:.8, whiteSpace:'nowrap' }}>{need - done} restant{need-done>1?'s':''}</span>
        </div>
        <ProgressBar value={done} max={need} color="#F5EFE3" track="rgba(0,0,0,.18)" height={9} />
      </div>
    </div>
  );
}

function RecentLeads({ leads, go, mobile }) {
  const rows = leads.slice(0, mobile ? 6 : 6);
  if (mobile) {
    return (
      <div className="card" style={{ overflow:'hidden' }}>
        <div style={{ padding:'16px 18px', borderBottom:'1px solid var(--border)', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
          <span className="section-title" style={{ fontSize:16 }}>Leads récents</span>
          <a onClick={()=>go('leads')} style={{ fontSize:13, color:'var(--brand)', fontWeight:600 }}>Tout voir</a>
        </div>
        {rows.map(l => (
          <div key={l.id} onClick={()=>go('lead-detail',{id:l.id})}
            style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'14px 18px', borderBottom:'1px solid var(--border)', gap:10 }}>
            <div style={{ minWidth:0 }}>
              <div style={{ fontWeight:600, fontSize:14, color:'var(--ink)' }}>{l.first} {l.last}</div>
              <div style={{ marginTop:5 }}><StatusBadge status={l.status} pulse /></div>
            </div>
            <div className="tnum" style={{ fontWeight:600, fontSize:14, color: l.commission?'var(--ink)':'var(--faint)', whiteSpace:'nowrap' }}>
              {l.commission ? euro(l.commission) : '—'}</div>
          </div>
        ))}
      </div>
    );
  }
  return (
    <div className="card" style={{ overflow:'hidden' }}>
      <div style={{ padding:'18px 20px', borderBottom:'1px solid var(--border)', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
        <span className="section-title">Leads récents</span>
        <a onClick={()=>go('leads')} style={{ fontSize:13.5, color:'var(--brand)', fontWeight:600, display:'inline-flex', alignItems:'center', gap:5 }}>
          Voir tous mes leads <Icon name="arrowR" size={15} /></a>
      </div>
      <div style={{ padding:'16px 4px 4px' }}>
        <table className="tbl">
          <thead><tr>
            <th>Client</th><th>Trajet</th><th>Date</th><th>Valeur estimée</th><th>Statut</th><th style={{ textAlign:'right' }}>Commission</th>
          </tr></thead>
          <tbody>
            {rows.map(l=>(
              <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 style={{ color:'var(--muted)' }}>{l.submitted}</td>
                <td className="tnum" style={{ fontWeight:500 }}>{l.estValue ? euro(l.estValue) : <span style={{ color:'var(--faint)' }}>En attente</span>}</td>
                <td><StatusBadge status={l.status} pulse /></td>
                <td className="tnum" style={{ textAlign:'right', fontWeight:600, color: l.commission?'var(--ink)':'var(--faint)' }}>
                  {l.commission ? euro(l.commission) : '—'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function Dashboard({ mobile, go, leads, partner, tw }) {
  const k = computeKPIs(leads);
  const diff = k.leadsThisMonth - k.leadsPrevMonth;
  const kpis = [
    { label:'Leads ce mois', value:k.leadsThisMonth, trend: diff>0?`+${diff} vs avril`:null, trendDir:'up', sub: diff>0?null:'nouveaux clients recommandés', icon:'inbox' },
    { label:'Devis acceptés', value:k.accepted, sub:`Taux de conversion ${k.conv}%`, icon:'check' },
    { label:'Volume généré', value:euro(k.volume), sub:'Valeur des déménagements acceptés', icon:'package' },
    { label:'Commissions gagnées', value:euro(k.earned), sub:`${euro0(k.paid)} € versé · ${euro0(k.pending)} € en attente`, icon:'euroCircle' },
  ];
  const palette = { recu:'#8A96A0', devis:'#2563EB', accepte:'#C77A0A', effectue:'#16965A', verse:'#A9791F', perdu:'#C2C8CD' };
  const dist = ['recu','devis','accepte','effectue','verse','perdu']
    .map(s=>({ label:window.LBC_DATA.STATUS[s].label, value:leads.filter(l=>l.status===s).length, color:palette[s] }))
    .filter(s=>s.value>0);

  return (
    <div style={{ display:'flex', flexDirection:'column', gap: mobile?16:22 }}>
      <TierCard partner={partner} leads={leads} go={go} compact={mobile} tw={tw} />
      <div style={{ display:'grid', gridTemplateColumns: mobile?'1fr 1fr':'repeat(4,1fr)', gap: mobile?12:18 }}>
        {kpis.map((kp,i)=><KPICard key={i} {...kp} delay={i*60} />)}
      </div>
      <div style={{ display:'grid', gridTemplateColumns: mobile?'1fr':'1.5fr 1fr', gap: mobile?16:18 }}>
        <div className="card card-pad">
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:6 }}>
            <span className="section-title" style={{ fontSize:16 }}>Commissions gagnées</span>
            <span style={{ fontSize:12.5, color:'var(--muted)' }}>6 derniers mois</span>
          </div>
          <AreaChart data={window.LBC_DATA.MONTHLY} color="var(--brand)" />
        </div>
        <div className="card card-pad">
          <span className="section-title" style={{ fontSize:16, display:'block', marginBottom:16 }}>Mes leads par statut</span>
          <Donut segments={dist} />
        </div>
      </div>
      <RecentLeads leads={leads} go={go} mobile={mobile} />
    </div>
  );
}

Object.assign(window, { Dashboard, computeKPIs });
