// screens/CRM.jsx — clients list with status filter, plus drag-and-drop Kanban sales pipeline.

function CRM() {
  const [tab, setTab] = React.useState('clients'); // 'clients' | 'pipeline'
  const [filter, setFilter] = React.useState('Tous');
  const [search, setSearch] = React.useState('');
  const [selected, setSelected] = React.useState(null);

  const filtered = CLIENTS.filter(c =>
    (filter === 'Tous' || c.status === filter) &&
    (search === '' || c.name.toLowerCase().includes(search.toLowerCase()) || c.company.toLowerCase().includes(search.toLowerCase()))
  );

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1>CRM</h1>
          <div className="sub">Gestion de la relation client · {CLIENTS.length} clients · 8 deals actifs</div>
        </div>
        <div className="spacer"></div>
        <button className="btn btn-ghost"><i data-lucide="upload" style={{width:14,height:14}}></i> Importer CSV</button>
        <button className="btn btn-ghost"><i data-lucide="download" style={{width:14,height:14}}></i> Export PDF</button>
        <button className="btn btn-warm"><i data-lucide="plus" style={{width:14,height:14}}></i> Nouveau client</button>
      </div>

      {/* Tab strip */}
      <div style={{ display:'flex', gap:4, padding:4, background:'var(--app-surface)', border:'1px solid var(--app-border)', borderRadius:10, alignSelf:'flex-start' }}>
        {[
          { id:'clients',  label:'Clients',           icon:'users-round' },
          { id:'pipeline', label:'Pipeline de ventes',icon:'kanban' },
        ].map(t => (
          <button key={t.id} onClick={()=>setTab(t.id)} style={{
            display:'inline-flex', alignItems:'center', gap:8,
            height:36, padding:'0 14px', borderRadius:7,
            background: tab===t.id ? 'var(--app-warm-soft)' : 'transparent',
            color: tab===t.id ? '#C2410C' : 'var(--app-text-2)',
            font:'600 13px/1 var(--m-font-sans)',
            transition:'background 140ms ease-out, color 140ms ease-out'
          }}>
            <i data-lucide={t.icon} style={{ width:14, height:14 }}></i>{t.label}
          </button>
        ))}
      </div>

      {tab === 'clients' && (
        <Widget>
          <div style={{ display:'flex', gap:10, marginBottom:18, flexWrap:'wrap', alignItems:'center' }}>
            <div style={{ position:'relative', flex:'1 1 280px', minWidth:240 }}>
              <i data-lucide="search" style={{ position:'absolute', left:12, top:11, width:14, height:14, color:'var(--app-text-4)' }}></i>
              <input className="input" placeholder="Rechercher par nom, entreprise…" value={search} onChange={e=>setSearch(e.target.value)} style={{ paddingLeft:34 }} />
            </div>
            {['Tous','Prospect','Actif','Inactif'].map(c => (
              <button key={c} onClick={()=>setFilter(c)} style={{
                height:36, padding:'0 14px', borderRadius:8,
                border:'1px solid '+(filter===c?'var(--app-warm)':'var(--app-border)'),
                background: filter===c?'var(--app-warm-soft)':'var(--app-surface)',
                color: filter===c?'#C2410C':'var(--app-text-2)',
                font:'600 13px/1 var(--m-font-sans)'
              }}>{c}</button>
            ))}
            <button className="btn btn-ghost"><i data-lucide="filter" style={{width:14,height:14}}></i> Filtres</button>
          </div>

          <table className="m-table">
            <thead>
              <tr>
                <th><input type="checkbox" /></th>
                <th>Client</th><th>Ville</th><th>Téléphone</th><th>Commandes</th><th>CA total</th><th>Statut</th><th></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(c => (
                <tr key={c.id} onClick={()=>setSelected(c)} style={{ cursor:'pointer' }}>
                  <td onClick={e=>e.stopPropagation()}><input type="checkbox" /></td>
                  <td>
                    <div style={{ display:'flex', alignItems:'center', gap:12 }}>
                      <Avatar ini={c.ini} color={c.color} />
                      <div style={{ display:'flex', flexDirection:'column', gap:2 }}>
                        <span style={{ color:'var(--app-text)', fontWeight:700, fontSize:13 }}>{c.name}</span>
                        <span style={{ color:'var(--app-text-3)', fontSize:11, fontWeight:500 }}>{c.company}</span>
                      </div>
                    </div>
                  </td>
                  <td>
                    <span style={{ display:'inline-flex', alignItems:'center', gap:6 }}>
                      <i data-lucide="map-pin" style={{ width:12, height:12, color:'var(--app-text-4)' }}></i>
                      {c.city}
                    </span>
                  </td>
                  <td style={{ font:'500 12px/1 var(--m-font-mono)', color:'var(--app-text-2)' }}>{c.phone}</td>
                  <td style={{ color:'var(--app-text)', fontWeight:600 }}>{c.orders}</td>
                  <td style={{ color:'var(--app-text)', fontWeight:700 }}>{c.value === 0 ? '—' : fmtMAD(c.value, {compact:true})}</td>
                  <td><StatusBadge status={c.status} /></td>
                  <td onClick={e=>e.stopPropagation()} style={{ textAlign:'right' }}>
                    <button className="btn btn-ghost btn-icon" style={{ height:30, width:30 }}><i data-lucide="more-horizontal" style={{width:14,height:14}}></i></button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          <footer style={{ display:'flex', alignItems:'center', marginTop:18, font:'500 12px/1 var(--m-font-sans)', color:'var(--app-text-3)' }}>
            <span>1-{filtered.length} sur {CLIENTS.length} clients</span>
            <div style={{ flex:1 }}></div>
            <div style={{ display:'flex', gap:6 }}>
              {['‹','1','2','3','›'].map((p,i)=>(
                <button key={i} style={{
                  width:32, height:32,
                  border:'1px solid '+(p==='1'?'var(--app-warm)':'var(--app-border)'),
                  background: p==='1'?'var(--app-warm)':'var(--app-surface)',
                  color: p==='1'?'#fff':'var(--app-text-2)',
                  borderRadius:6, font:'600 12px/1 var(--m-font-sans)'
                }}>{p}</button>
              ))}
            </div>
          </footer>
        </Widget>
      )}

      {tab === 'pipeline' && <Pipeline />}

      {selected && <ClientDetail client={selected} onClose={()=>setSelected(null)} />}
    </div>
  );
}

function Pipeline() {
  const [board, setBoard] = React.useState(() => JSON.parse(JSON.stringify(PIPELINE)));
  const [drag, setDrag] = React.useState(null); // { from, deal }
  const stageColors = {
    'Nouveau':     '#78829D',
    'Qualifié':    '#1379F0',
    'Proposition': '#D97706',
    'Négociation': '#C2410C',
    'Gagné':       '#19C781',
  };

  const onDragStart = (from, deal) => setDrag({ from, deal });
  const onDrop = (to) => {
    if (!drag) return;
    if (drag.from === to) { setDrag(null); return; }
    setBoard(b => {
      const next = JSON.parse(JSON.stringify(b));
      next[drag.from] = next[drag.from].filter(d => d.id !== drag.deal.id);
      next[to].unshift(drag.deal);
      return next;
    });
    setDrag(null);
  };

  const totalAll = Object.values(board).flat().reduce((s,d)=>s+d.amount,0);

  return (
    <div>
      <div style={{ display:'flex', alignItems:'center', gap:14, marginBottom:18, flexWrap:'wrap' }}>
        <div style={{ display:'flex', flexDirection:'column' }}>
          <span className="eyebrow">Valeur du pipeline</span>
          <span style={{ font:'700 22px/1 var(--m-font-sans)', color:'var(--app-text)', letterSpacing:'-.02em', marginTop:6 }}>{fmtMAD(totalAll, {compact:true})}</span>
        </div>
        <div style={{ flex:1 }}></div>
        <button className="btn btn-ghost"><i data-lucide="filter" style={{width:14,height:14}}></i> Filtrer</button>
        <button className="btn btn-warm"><i data-lucide="plus" style={{width:14,height:14}}></i> Nouveau deal</button>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'repeat(5, minmax(240px, 1fr))', gap:14, overflowX:'auto', paddingBottom:8 }}>
        {Object.entries(board).map(([stage, deals]) => {
          const sum = deals.reduce((s,d)=>s+d.amount,0);
          const isOver = drag && drag.from !== stage;
          return (
            <div key={stage}
              onDragOver={e => { e.preventDefault(); }}
              onDrop={() => onDrop(stage)}
              style={{
                background: drag && drag.from !== stage && isOver ? 'var(--app-warm-soft)' : 'var(--app-surface-2)',
                border:'1px dashed var(--app-border-2)',
                borderRadius:10, padding:12, minHeight:300,
                transition:'background 140ms ease-out'
              }}>
              <header style={{ display:'flex', alignItems:'center', gap:8, marginBottom:12 }}>
                <span style={{ width:8, height:8, borderRadius:99, background: stageColors[stage] }}></span>
                <span style={{ font:'700 13px/1 var(--m-font-sans)', color:'var(--app-text)' }}>{stage}</span>
                <span style={{ font:'700 10px/1 var(--m-font-sans)', color:'var(--app-text-3)', background:'var(--app-surface)', border:'1px solid var(--app-border)', padding:'3px 7px', borderRadius:99 }}>{deals.length}</span>
                <div style={{ flex:1 }}></div>
                <span style={{ font:'700 11px/1 var(--m-font-sans)', color:'var(--app-text-2)' }}>{fmtMAD(sum, {compact:true})}</span>
              </header>

              <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
                {deals.map(d => (
                  <div key={d.id}
                    draggable
                    onDragStart={() => onDragStart(stage, d)}
                    style={{
                      background:'var(--app-surface)', border:'1px solid var(--app-border)', borderRadius:9,
                      padding:12, cursor:'grab', boxShadow:'0 1px 2px rgba(0,0,0,.03)',
                      opacity: drag?.deal.id === d.id ? .5 : 1
                    }}>
                    <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:8 }}>
                      <Avatar ini={d.ini} color={d.color} size={26} />
                      <span style={{ font:'700 12px/1.2 var(--m-font-sans)', color:'var(--app-text)' }}>{d.client}</span>
                    </div>
                    <div style={{ font:'500 11px/1.4 var(--m-font-sans)', color:'var(--app-text-3)', marginBottom:8 }}>{d.company}</div>
                    <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
                      <span style={{ font:'700 13px/1 var(--m-font-sans)', color:'#C2410C' }}>{fmtMAD(d.amount, {compact:true})}</span>
                      <span style={{ font:'500 10px/1 var(--m-font-sans)', color:'var(--app-text-3)', display:'inline-flex', alignItems:'center', gap:4 }}>
                        <i data-lucide="calendar" style={{ width:10, height:10 }}></i>{d.due}
                      </span>
                    </div>
                  </div>
                ))}
                <button style={{
                  height:32, borderRadius:8, border:'1px dashed var(--app-border-2)',
                  background:'transparent', color:'var(--app-text-3)',
                  font:'500 11px/1 var(--m-font-sans)'
                }}>+ Ajouter un deal</button>
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ font:'500 11px/1 var(--m-font-sans)', color:'var(--app-text-4)', marginTop:14, display:'flex', alignItems:'center', gap:6 }}>
        <i data-lucide="move" style={{ width:12, height:12 }}></i>
        Glissez-déposez les deals pour changer leur étape.
      </div>
    </div>
  );
}

function ClientDetail({ client, onClose }) {
  return (
    <div onClick={onClose} style={{
      position:'fixed', inset:0, zIndex:40, background:'rgba(7,20,55,.32)', display:'flex', justifyContent:'flex-end'
    }}>
      <div onClick={e=>e.stopPropagation()} style={{
        width:480, height:'100%', background:'var(--app-surface)',
        borderLeft:'1px solid var(--app-border)', overflowY:'auto'
      }}>
        <div style={{ padding:'20px 24px', borderBottom:'1px solid var(--app-border)', display:'flex', alignItems:'center', gap:12 }}>
          <Avatar ini={client.ini} color={client.color} size={48} />
          <div style={{ flex:1 }}>
            <div style={{ font:'700 16px/1.2 var(--m-font-sans)', color:'var(--app-text)' }}>{client.name}</div>
            <div style={{ font:'500 12px/1 var(--m-font-sans)', color:'var(--app-text-3)', marginTop:4 }}>{client.company} · {client.id}</div>
          </div>
          <button className="btn btn-ghost btn-icon" onClick={onClose}><i data-lucide="x" style={{width:16,height:16}}></i></button>
        </div>

        <div style={{ padding:24, display:'flex', flexDirection:'column', gap:18 }}>
          <div style={{ display:'flex', alignItems:'center', gap:8 }}>
            <StatusBadge status={client.status} />
            <span className="pill" style={{ background:'var(--app-warm-soft)', color:'#C2410C' }}>
              <i data-lucide="map-pin" style={{ width:11, height:11 }}></i>{client.city}
            </span>
          </div>

          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
            <div className="card" style={{ padding:14 }}>
              <div className="eyebrow">CA total</div>
              <div style={{ font:'700 18px/1 var(--m-font-sans)', color:'var(--app-text)', marginTop:8, letterSpacing:'-.02em' }}>{client.value === 0 ? '—' : fmtMAD(client.value, {compact:true})}</div>
            </div>
            <div className="card" style={{ padding:14 }}>
              <div className="eyebrow">Commandes</div>
              <div style={{ font:'700 18px/1 var(--m-font-sans)', color:'var(--app-text)', marginTop:8, letterSpacing:'-.02em' }}>{client.orders}</div>
            </div>
          </div>

          <div className="card" style={{ padding:18 }}>
            <div style={{ font:'700 13px/1 var(--m-font-sans)', color:'var(--app-text)', marginBottom:14 }}>Coordonnées</div>
            {[
              ['phone','Téléphone', client.phone],
              ['mail','Email', client.email],
              ['building-2','Entreprise', client.company],
              ['map-pin','Ville', client.city],
            ].map(([icon,label,val])=>(
              <div key={label} style={{ display:'flex', alignItems:'center', gap:12, padding:'10px 0', borderBottom:'1px solid var(--app-border)' }}>
                <i data-lucide={icon} style={{ width:14, height:14, color:'var(--app-text-3)' }}></i>
                <span style={{ font:'500 12px/1 var(--m-font-sans)', color:'var(--app-text-3)', width:90 }}>{label}</span>
                <span style={{ font:'600 13px/1 var(--m-font-sans)', color:'var(--app-text)' }}>{val}</span>
              </div>
            ))}
          </div>

          <div className="card" style={{ padding:18 }}>
            <div style={{ font:'700 13px/1 var(--m-font-sans)', color:'var(--app-text)', marginBottom:14 }}>Historique des interactions</div>
            {INTERACTIONS.filter(it=>it.client===client.name).length === 0 && (
              <div style={{ font:'500 12px/1.4 var(--m-font-sans)', color:'var(--app-text-3)' }}>Aucune interaction enregistrée pour ce client.</div>
            )}
            {INTERACTIONS.filter(it=>it.client===client.name).map((it,i)=>(
              <div key={i} style={{ display:'flex', gap:12, padding:'10px 0', borderBottom:'1px solid var(--app-border)' }}>
                <div style={{ width:30, height:30, borderRadius:8, background:'var(--app-warm-soft)', color:'#C2410C', display:'grid', placeItems:'center', flexShrink:0 }}>
                  <i data-lucide={it.icon} style={{ width:14, height:14 }}></i>
                </div>
                <div style={{ flex:1 }}>
                  <div style={{ display:'flex', gap:6, alignItems:'center' }}>
                    <span style={{ font:'700 12px/1 var(--m-font-sans)', color:'var(--app-text)' }}>{it.kind}</span>
                    <span style={{ font:'500 11px/1 var(--m-font-sans)', color:'var(--app-text-4)' }}>· {it.when}</span>
                  </div>
                  <div style={{ font:'500 12px/1.4 var(--m-font-sans)', color:'var(--app-text-3)', marginTop:4 }}>{it.note}</div>
                </div>
              </div>
            ))}
          </div>

          <div style={{ display:'flex', gap:8 }}>
            <button className="btn btn-warm" style={{ flex:1, justifyContent:'center' }}><i data-lucide="phone" style={{width:14,height:14}}></i> Appeler</button>
            <button className="btn btn-ghost" style={{ flex:1, justifyContent:'center' }}><i data-lucide="mail" style={{width:14,height:14}}></i> Email</button>
            <button className="btn btn-ghost btn-icon"><i data-lucide="more-horizontal" style={{width:16,height:16}}></i></button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CRM });
