function ClientSelector({ onSelect, onClose }) {
 const { notify } = useStore();
 const [search, setSearch]   = React.useState('');
 const [clients, setClients] = React.useState(() => {
   try { return JSON.parse(localStorage.getItem('pos_clients') || '[]'); }
   catch(e) { return []; }
 });
 const [form, setForm] = React.useState({ nom:'', prenom:'', telephone:'' });
 const [addMode, setAddMode] = React.useState(false);

 function niveau(pts) {
   if (pts >= 5000) return { label:'Platine', color:'#8b5cf6', icon:'💎', reduction:15 };
   if (pts >= 2000) return { label:'Or',      color:'#f59e0b', icon:'🥇', reduction:10 };
   if (pts >= 500)  return { label:'Argent',  color:'#64748b', icon:'🥈', reduction:5  };
   return                  { label:'Bronze',  color:'#b45309', icon:'🥉', reduction:2  };
 }

 const filtered = clients.filter(c =>
   search.length >= 2 && (
     c.nom.toLowerCase().includes(search.toLowerCase()) ||
     c.prenom.toLowerCase().includes(search.toLowerCase()) ||
     c.telephone.includes(search)
   )
 );

 function createAndSelect() {
   if (!form.nom || !form.telephone) { notify('Nom et téléphone obligatoires', 'err'); return; }
   const newClient = {
     id:          'cli_' + Date.now(),
     nom:         form.nom.toUpperCase(),
     prenom:      form.prenom.toUpperCase(),
     telephone:   form.telephone,
     email:       '',
     points:      0,
     totalAchats: 0,
     nbVisites:   0,
     dateInscription: new Date().toLocaleDateString('fr-FR'),
     historique:  [],
   };
   const updated = [newClient, ...clients];
   setClients(updated);
   localStorage.setItem("pos_clients", JSON.stringify(updated));
    const bid = localStorage.getItem("pos_boutique_id");
    if (bid) window.SupaBase.saveClient(bid, newClient);
   notify('✅ Client créé');
   onSelect(newClient);
 }

 return (
   <div style={{position:'fixed',inset:0,background:'#00000060',zIndex:1000,display:'flex',alignItems:'center',justifyContent:'center',padding:20}}>
     <div style={{background:'#fff',borderRadius:16,width:'100%',maxWidth:500,maxHeight:'80vh',display:'flex',flexDirection:'column',boxShadow:'0 20px 60px #00000030'}}>

       {/* Header */}
       <div style={{padding:'18px 20px',borderBottom:'1px solid #e2e8f0',display:'flex',alignItems:'center',justifyContent:'space-between',flexShrink:0}}>
         <div style={{fontFamily:"'Playfair Display',serif",fontSize:18,color:'#1e293b',fontWeight:700}}>👥 Client fidélité</div>
         <button className="btn-ghost btn-sm" onClick={onClose}>✕</button>
       </div>

       <div style={{flex:1,overflowY:'auto',padding:18}}>
         {!addMode ? (
           <div>
             {/* Recherche */}
             <input value={search} onChange={e=>setSearch(e.target.value)} autoFocus
               placeholder="Tapez nom ou téléphone…"
               style={{marginBottom:14,fontSize:15}}/>

             {search.length < 2 && (
               <div style={{textAlign:'center',color:'#94a3b8',padding:'20px 0',fontSize:13}}>
                 Tapez au moins 2 caractères pour rechercher
               </div>
             )}

             {search.length >= 2 && filtered.length === 0 && (
               <div style={{textAlign:'center',padding:'20px 0'}}>
                 <div style={{color:'#94a3b8',fontSize:13,marginBottom:14}}>Aucun client trouvé</div>
                 <button className="btn-primary" onClick={()=>{ setAddMode(true); setForm({nom:'',prenom:'',telephone:search}); }}>
                   ➕ Créer ce client
                 </button>
               </div>
             )}

             {filtered.map(c => {
               const niv = niveau(c.points);
               return (
                 <div key={c.id} onClick={() => onSelect(c)}
                   style={{display:'flex',alignItems:'center',gap:14,padding:'13px 16px',borderRadius:12,marginBottom:8,border:'1.5px solid #e2e8f0',cursor:'pointer',transition:'all .15s',background:'#fafafa'}}
                   onMouseEnter={e=>e.currentTarget.style.borderColor='#2563eb'}
                   onMouseLeave={e=>e.currentTarget.style.borderColor='#e2e8f0'}>
                   <div style={{width:44,height:44,borderRadius:22,background:niv.color+'22',display:'flex',alignItems:'center',justifyContent:'center',fontSize:20,flexShrink:0}}>
                     {niv.icon}
                   </div>
                   <div style={{flex:1}}>
                     <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:3}}>
                       <span style={{fontSize:14,color:'#1e293b',fontWeight:700}}>{c.prenom} {c.nom}</span>
                       <span style={{background:niv.color+'22',color:niv.color,borderRadius:5,fontSize:10,padding:'2px 7px',fontWeight:700}}>{niv.label}</span>
                     </div>
                     <div style={{fontSize:11,color:'#94a3b8',fontFamily:"'DM Mono',monospace"}}>{c.telephone}</div>
                   </div>
                   <div style={{textAlign:'right',flexShrink:0}}>
                     <div style={{fontFamily:"'Playfair Display',serif",fontSize:18,color:niv.color,fontWeight:700}}>{c.points}</div>
                     <div style={{fontSize:10,color:'#94a3b8'}}>points · {niv.reduction}% réd.</div>
                   </div>
                 </div>
               );
             })}

             <div style={{marginTop:16,textAlign:'center'}}>
               <button className="btn-ghost" style={{fontSize:12}} onClick={()=>setAddMode(true)}>
                 ➕ Nouveau client
               </button>
             </div>
           </div>
         ) : (
           <div>
             <button className="btn-ghost btn-sm" style={{marginBottom:16}} onClick={()=>setAddMode(false)}>← Retour</button>
             <div className="field">
               <label>Nom *</label>
               <input value={form.nom} onChange={e=>setForm({...form,nom:e.target.value})} placeholder="DUPONT" autoFocus/>
             </div>
             <div className="field">
               <label>Prénom</label>
               <input value={form.prenom} onChange={e=>setForm({...form,prenom:e.target.value})} placeholder="Jean"/>
             </div>
             <div className="field">
               <label>Téléphone *</label>
               <input value={form.telephone} onChange={e=>setForm({...form,telephone:e.target.value})}
                 placeholder="07 XX XX XX XX" style={{fontFamily:"'DM Mono',monospace"}}/>
             </div>
             <button className="btn-success" style={{width:'100%',padding:'12px',fontSize:14,marginTop:8}} onClick={createAndSelect}>
               ✅ Créer et sélectionner
             </button>
           </div>
         )}
       </div>

       {/* Vente sans client */}
       <div style={{padding:'14px 20px',borderTop:'1px solid #e2e8f0',flexShrink:0}}>
         <button className="btn-ghost" style={{width:'100%',fontSize:13,padding:'10px'}} onClick={onClose}>
           Continuer sans client
         </button>
       </div>
     </div>
   </div>
 );
}
