// leads.jsx — New Lead, Leads List, Lead Detail
const { useState: useStateL, useMemo } = React;

const CITIES = ['Nice','Paris','Lyon','Marseille','Milan','Genève','Bordeaux','Toulouse','Annecy','Monaco','Cannes','Antibes','La Rochelle','Lille','Nantes','Strasbourg'];

/* ============== NEW LEAD ============== */
function NewLead({ mobile, go, addLead }) {
  const [done, setDone] = useStateL(false);
  const [f, setF] = useStateL({ first:'', last:'', phone:'', email:'', from:'Nice', to:'', date:'', formule:'', notes:'' });
  const [err, setErr] = useStateL({});
  const set = (k,v)=> setF(s=>({ ...s, [k]:v }));

  const submit = () => {
    const e = {};
    ['first','last','phone','to'].forEach(k => { if(!f[k]?.trim()) e[k]=true; });
    if(Object.keys(e).length){ setErr(e); return; }
    addLead(f);
    setDone(true);
  };

  if (done) {
    return (
      <div style={{ maxWidth:560, margin:'0 auto', paddingTop: mobile?20:40 }}>
        <div className="card fade-up" style={{ padding: mobile?'40px 24px':'56px 48px', textAlign:'center' }}>
          <svg width="92" height="92" viewBox="0 0 92 92" style={{ margin:'0 auto' }}>
            <circle cx="46" cy="46" r="42" fill="none" stroke="var(--effectue)" strokeWidth="3" className="check-circle" style={{ transformOrigin:'center', transform:'rotate(-90deg)' }} />
            <circle cx="46" cy="46" r="42" fill="rgba(22,150,90,.07)" />
            <path d="M30 47 l11 11 l22 -24" fill="none" stroke="var(--effectue)" strokeWidth="4.5" strokeLinecap="round" strokeLinejoin="round" className="check-tick" />
          </svg>
          <h2 style={{ fontSize:22, fontWeight:600, margin:'22px 0 8px', color:'var(--ink)' }}>Lead envoyé avec succès</h2>
          <p style={{ fontSize:14.5, color:'var(--muted)', lineHeight:1.55, maxWidth:380, margin:'0 auto 28px' }}>
            Nous contactons <strong style={{ color:'var(--ink)' }}>{f.first || 'votre client'}</strong> sous 24h. Vous recevrez une notification à chaque évolution.</p>
          <div style={{ display:'flex', gap:12, justifyContent:'center', flexWrap:'wrap' }}>
            <button className="btn btn-ghost" onClick={()=>{ setF({ first:'',last:'',phone:'',email:'',from:'Nice',to:'',date:'',formule:'',notes:'' }); setErr({}); setDone(false); }}>
              <Icon name="plus" size={17} />Envoyer un autre lead</button>
            <button className="btn btn-primary" onClick={()=>go('leads')}>Voir mes leads</button>
          </div>
        </div>
      </div>
    );
  }

  const fieldCls = (k)=> 'field' + (err[k] ? ' field-error' : '');
  return (
    <div style={{ maxWidth:600, margin:'0 auto' }}>
      <datalist id="cities">{CITIES.map(c=><option key={c} value={c} />)}</datalist>
      <div style={{ marginBottom:24 }}>
        <h1 className="page-title">Envoyer un nouveau lead</h1>
        <p style={{ fontSize:14, color:'var(--muted)', margin:'8px 0 0', lineHeight:1.5 }}>
          Nous contactons votre client sous 24h et vous tenons informé à chaque étape.</p>
      </div>
      <div className="card card-pad" style={{ display:'flex', flexDirection:'column', gap:18 }}>
        <div style={{ display:'grid', gridTemplateColumns: mobile?'1fr':'1fr 1fr', gap:16 }}>
          <div className={fieldCls('first')}><label className="label">Prénom du client</label>
            <div className="input-wrap"><span className="lead-icon"><Icon name="user" size={17} /></span>
              <input className="input has-icon" value={f.first} onChange={e=>set('first',e.target.value)} placeholder="Martin" /></div></div>
          <div className={fieldCls('last')}><label className="label">Nom du client</label>
            <input className="input" value={f.last} onChange={e=>set('last',e.target.value)} placeholder="Dupont" /></div>
          <div className={fieldCls('phone')}><label className="label">Téléphone</label>
            <div className="input-wrap"><span className="lead-icon"><Icon name="phone" size={17} /></span>
              <input className="input has-icon" value={f.phone} onChange={e=>set('phone',e.target.value)} placeholder="06 12 34 56 78" /></div></div>
          <div className="field"><label className="label">Email <span style={{ color:'var(--faint)', fontWeight:400 }}>· optionnel</span></label>
            <div className="input-wrap"><span className="lead-icon"><Icon name="mail" size={17} /></span>
              <input className="input has-icon" value={f.email} onChange={e=>set('email',e.target.value)} placeholder="client@email.fr" /></div></div>
          <div className="field"><label className="label">Ville de départ</label>
            <div className="input-wrap"><span className="lead-icon"><Icon name="pin" size={17} /></span>
              <input className="input has-icon" list="cities" value={f.from} onChange={e=>set('from',e.target.value)} placeholder="Nice" /></div></div>
          <div className={fieldCls('to')}><label className="label">Ville d'arrivée</label>
            <div className="input-wrap"><span className="lead-icon"><Icon name="pin" size={17} /></span>
              <input className="input has-icon" list="cities" value={f.to} onChange={e=>set('to',e.target.value)} placeholder="Paris" /></div></div>
          <div className="field"><label className="label">Date souhaitée</label>
            <div className="input-wrap"><span className="lead-icon"><Icon name="calendar" size={17} /></span>
              <input className="input has-icon" type="date" value={f.date} onChange={e=>set('date',e.target.value)} style={{ color: f.date?'var(--ink)':'var(--faint)' }} /></div></div>
          <div className="field"><label className="label">Formule souhaitée</label>
            <select className="select" value={f.formule} onChange={e=>set('formule',e.target.value)} style={{ color:f.formule?'var(--ink)':'var(--faint)' }}>
              <option value="" disabled>Sélectionner…</option>
              <option value="simple">Formule Simple</option>
              <option value="complete">Formule Complète (montage, démontage, protection)</option>
              <option value="unknown">Je ne sais pas encore</option>
            </select></div>
        </div>
        <div className="field"><label className="label">Notes complémentaires <span style={{ color:'var(--faint)', fontWeight:400 }}>· optionnel</span></label>
          <textarea className="textarea" value={f.notes} onChange={e=>set('notes',e.target.value)} placeholder="Étage, ascenseur, objets fragiles, contraintes d'accès…" /></div>

        <div style={{ display:'flex', gap:13, alignItems:'flex-start', background:'linear-gradient(180deg,#FCF3DF,#FBEFD3)',
          border:'1px solid #F0DcB0', borderRadius:12, padding:'15px 17px' }}>
          <span style={{ color:'var(--accepte)', display:'flex', marginTop:1 }}><Icon name="euroCircle" size={22} /></span>
          <div style={{ fontSize:13.5, color:'#7A5410', lineHeight:1.5 }}>
            <strong style={{ color:'#5E400A' }}>Commission estimée : entre 90 € et 250 €</strong> selon la valeur finale du déménagement.</div>
        </div>
        <button className="btn btn-primary btn-block btn-lg" onClick={submit}>
          <Icon name="arrowR" size={18} />Envoyer le lead</button>
      </div>
    </div>
  );
}

/* ============== LEADS LIST ============== */
const TABS = [
  { key:'all', label:'Tous' },
  { key:'cours', label:'En cours' },
  { key:'acceptes', label:'Acceptés' },
  { key:'effectues', label:'Effectués' },
  { key:'perdus', label:'Perdus' },
];
function matchTab(l, tab) {
  if (tab==='all') return true;
  if (tab==='cours') return ['recu','devis'].includes(l.status);
  if (tab==='acceptes') return l.status==='accepte';
  if (tab==='effectues') return ['effectue','verse'].includes(l.status);
  if (tab==='perdus') return l.status==='perdu';
}

function LeadsList({ mobile, go, leads, showToast }) {
  const [tab, setTab] = useStateL('all');
  const [q, setQ] = useStateL('');
  const [sort, setSort] = useStateL({ key:'date', dir:'desc' });
  const [page, setPage] = useStateL(1);
  const PER = 8;
  const filtered = useMemo(()=> {
    const order = { recu:0, devis:1, accepte:2, effectue:3, verse:4, perdu:5 };
    const val = (l)=>({ client:`${l.first} ${l.last}`, date:l.id, value:l.estValue||0, commission:l.commission||0, status:order[l.status] }[sort.key]);
    return leads.filter(l => matchTab(l,tab) && (`${l.first} ${l.last} ${l.from} ${l.to}`.toLowerCase().includes(q.toLowerCase())))
      .sort((a,b)=>{ const av=val(a), bv=val(b); const r = av<bv?-1:av>bv?1:0; return sort.dir==='asc'?r:-r; });
  }, [leads,tab,q,sort]);
  React.useEffect(()=>{ setPage(1); }, [tab,q,sort]);
  const pages = Math.max(1, Math.ceil(filtered.length/PER));
  const pageRows = mobile ? filtered : filtered.slice((page-1)*PER, page*PER);
  const toggleSort = (key)=> setSort(s=> s.key===key ? { key, dir: s.dir==='asc'?'desc':'asc' } : { key, dir:'asc' });
  const SortTh = ({ k, children, right })=>(
    <th className="th-sort" onClick={()=>toggleSort(k)} style={{ textAlign: right?'right':'left' }}>
      <span style={{ display:'inline-flex', alignItems:'center', gap:4 }}>{children}
        <Icon name="chevronD" size={12} style={{ opacity: sort.key===k?1:.25, transform: sort.key===k&&sort.dir==='asc'?'rotate(180deg)':'none', transition:'.15s' }} /></span></th>
  );
  const exportCSV = ()=>{ window.exportLeadsCSV(filtered); showToast && showToast('Export CSV téléchargé · '+filtered.length+' leads'); };

  const tabs = (
    <div style={{ display:'flex', gap:4, overflowX:'auto', flexShrink:0 }} className="scroll">
      {TABS.map(t=>{
        const n = leads.filter(l=>matchTab(l,t.key)).length;
        return (
          <button key={t.key} onClick={()=>setTab(t.key)} style={{ display:'inline-flex', alignItems:'center', gap:7,
            fontSize:13.5, fontWeight:600, padding:'8px 14px', borderRadius:9, whiteSpace:'nowrap',
            color: tab===t.key?'var(--ink)':'var(--muted)', background: tab===t.key?'var(--card)':'transparent',
            border:'1px solid', borderColor: tab===t.key?'var(--border-2)':'transparent', boxShadow: tab===t.key?'var(--shadow-xs)':'none', transition:'.14s' }}>
            {t.label}<span style={{ fontSize:11.5, fontWeight:600, padding:'1px 7px', borderRadius:999,
              background: tab===t.key?'var(--bg)':'rgba(20,56,78,.06)', color:'var(--muted)' }}>{n}</span>
          </button>
        );
      })}
    </div>
  );

  if (leads.length === 0) {
    return <div className="card"><EmptyState title="Vous n'avez pas encore soumis de lead."
      body="Recommandez LBC à un client qui déménage et suivez sa progression jusqu'au versement de votre commission."
      cta="Envoyer mon premier lead" onCta={()=>go('new-lead')} /></div>;
  }

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
      <div style={{ display:'flex', flexDirection: mobile?'column':'row', gap:12, justifyContent:'space-between', alignItems: mobile?'stretch':'center' }}>
        {tabs}
        <div style={{ display:'flex', gap:10, flexShrink:0 }}>
          <div className="input-wrap" style={{ flex:1 }}>
            <span className="lead-icon"><Icon name="search" size={16} /></span>
            <input className="input has-icon" value={q} onChange={e=>setQ(e.target.value)} placeholder="Rechercher…" style={{ height:40, width: mobile?'100%':220 }} />
          </div>
          {!mobile && <button className="btn btn-ghost btn-sm" style={{ height:40 }} onClick={exportCSV}><Icon name="download" size={16} />Exporter CSV</button>}
        </div>
      </div>

      {filtered.length === 0 ? (
        <div className="card" style={{ padding:'48px 24px', textAlign:'center', color:'var(--muted)' }}>
          <div style={{ color:'var(--faint)', display:'flex', justifyContent:'center', marginBottom:10 }}><Icon name="search" size={28} /></div>
          Aucun lead ne correspond à votre recherche.</div>
      ) : mobile ? (
        <div className="card" style={{ overflow:'hidden' }}>
          {filtered.map(l=>(
            <div key={l.id} onClick={()=>go('lead-detail',{id:l.id})} style={{ padding:'15px 18px', borderBottom:'1px solid var(--border)', display:'flex', flexDirection:'column', gap:9 }}>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
                <span style={{ fontWeight:600, fontSize:14.5, color:'var(--ink)' }}>{l.first} {l.last}</span>
                <StatusBadge status={l.status} pulse />
              </div>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', fontSize:13 }}>
                <Route from={l.from} to={l.to} />
                <span className="tnum" style={{ fontWeight:600, color: l.commission?'var(--ink)':'var(--faint)' }}>{l.commission?euro(l.commission):'—'}</span>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="card" style={{ overflow:'hidden', padding:'8px 4px' }}>
          <table className="tbl">
            <thead><tr>
              <SortTh k="client">Client</SortTh><th>Trajet</th><th>Formule</th>
              <SortTh k="date">Date soumis</SortTh><SortTh k="value">Valeur devis</SortTh>
              <SortTh k="status">Statut</SortTh><SortTh k="commission" right>Commission</SortTh><th></th>
            </tr></thead>
            <tbody>
              {pageRows.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>{l.formule==='unknown'? <span style={{ color:'var(--faint)' }}>—</span> : <FormuleBadge formule={l.formule} />}</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>
                  <td style={{ textAlign:'right', width:60 }}><span style={{ color:'var(--brand)', fontWeight:600, fontSize:13, display:'inline-flex', alignItems:'center', gap:3 }}>Voir<Icon name="chevronR" size={14} /></span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {!mobile && filtered.length > 0 && (
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', fontSize:13, color:'var(--muted)' }}>
          <span>{filtered.length} lead{filtered.length>1?'s':''} · page {page}/{pages}</span>
          <div style={{ display:'flex', gap:6, alignItems:'center' }}>
            <button className="btn btn-ghost btn-sm" disabled={page<=1} style={{ opacity:page<=1?.4:1 }} onClick={()=>setPage(p=>Math.max(1,p-1))}><Icon name="chevronL" size={15} /></button>
            {Array.from({length:pages}).map((_,i)=>(
              <button key={i} className="btn btn-sm" onClick={()=>setPage(i+1)}
                style={{ width:34, background: page===i+1?'var(--brand)':'var(--card)', color: page===i+1?'#fff':'var(--ink-2)', border: page===i+1?'none':'1px solid var(--border-2)' }}>{i+1}</button>
            ))}
            <button className="btn btn-ghost btn-sm" disabled={page>=pages} style={{ opacity:page>=pages?.4:1 }} onClick={()=>setPage(p=>Math.min(pages,p+1))}><Icon name="chevronR" size={15} /></button>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { NewLead, LeadsList });
