function CaissierManager() {
  const { notify } = useStore();
  const [cashiers, setCashiers] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('pos_cashiers') || '[]'); }
    catch(e) { return []; }
  });
  const [newId, setNewId]     = React.useState('');
  const [newName, setNewName] = React.useState('');
  const [newPin, setNewPin]   = React.useState('');
  const [activeId, setActiveId] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('pos_default_cashier') || '{}').id || ''; }
    catch(e) { return ''; }
  });

  function save(list) {
    setCashiers(list);
    localStorage.setItem('pos_cashiers', JSON.stringify(list));
    // Sync Supabase
    const bid = localStorage.getItem('pos_boutique_id');
    if (bid && window.SupaBase) {
      list.forEach(c => window.SupaBase.saveCaissier(bid, c).catch(e=>console.error(e)));
    }
  }

  function addCashier() {
    if (!newId || !newName) { notify('Matricule et nom obligatoires', 'err'); return; }
    if (!newPin || newPin.length !== 4 || isNaN(newPin)) { notify('PIN doit être 4 chiffres', 'err'); return; }
    if (cashiers.find(c => c.id === newId)) { notify('Ce matricule existe déjà', 'err'); return; }
    const list = [...cashiers, { id:newId, name:newName.toUpperCase(), pin:newPin }];
    save(list);
    setNewId(''); setNewName(''); setNewPin('');
    notify('✅ Caissier ajouté');
  }

  function setDefault(c) {
    setActiveId(c.id);
    localStorage.setItem('pos_default_cashier', JSON.stringify(c));
    notify('✅ ' + c.name + ' défini comme caissier par défaut');
  }

  function resetPin(id) {
   var newPin = prompt('Nouveau PIN (4 chiffres) :');
   if (!newPin || newPin.length !== 4 || isNaN(newPin)) { notify('PIN doit etre 4 chiffres', 'err'); return; }
   var list = cashiers.map(function(c) { return c.id === id ? Object.assign({}, c, {pin: newPin}) : c; });
   save(list);
   var bid = localStorage.getItem('pos_boutique_id');
   if (bid && window.SupaBase) {
     var ca = list.find(function(x) { return x.id === id; });
     if (ca) window.SupaBase.saveCaissier(bid, ca).catch(function(){});
   }
   notify('PIN reinitialise !');
 }

  function deleteCashier(id) {
    var toDelete = cashiers.find(function(c) { return c.id === id; });
    save(cashiers.filter(function(c) { return c.id !== id; }));
    if (toDelete && toDelete.supabase_id) {
      var bid = localStorage.getItem('pos_boutique_id');
      if (bid && window.SupaBase) window.SupaBase.deleteCaissier ? window.SupaBase.deleteCaissier(toDelete.supabase_id) : fetch('https://avqhsomkexldzhsbzbss.supabase.co/rest/v1/caissiers?id=eq.'+toDelete.supabase_id, {method:'DELETE', headers:{'apikey':'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImF2cWhzb21rZXhsZHpoc2J6YnNzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Nzk5OTczMzQsImV4cCI6MjA5NTU3MzMzNH0.tEoQGoAdLwUW9hL-Zpd0_47s3rXZ1sqcjb068-0Fy44','Authorization':'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImF2cWhzb21rZXhsZHpoc2J6YnNzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Nzk5OTczMzQsImV4cCI6MjA5NTU3MzMzNH0.tEoQGoAdLwUW9hL-Zpd0_47s3rXZ1sqcjb068-0Fy44'}}).catch(()=>{});
    }
    notify('Caissier supprime', 'err');
    notify('Caissier supprimé', 'err');
  }

  return (
    <div>
      <div className="card">
        <div className="stitle">👥 Liste des caissiers</div>
        {cashiers.length === 0 ? (
          <div style={{textAlign:'center',color:'#94a3b8',padding:'20px 0',fontSize:13}}>
            <div style={{fontSize:40,marginBottom:10}}>🧾</div>
            Aucun caissier — ajoutez-en un ci-dessous
          </div>
        ) : cashiers.map(c => {
          const isActive = activeId === c.id;
          return (
            <div key={c.id} style={{display:'flex',alignItems:'center',gap:12,padding:'13px 16px',borderRadius:11,marginBottom:8,border:isActive?'2px solid #2563eb':'1.5px solid #e2e8f0',background:isActive?'#eff6ff':'#f8fafc',transition:'all .18s'}}>
              <div style={{width:42,height:42,borderRadius:21,background:isActive?'#bfdbfe':'#e2e8f0',display:'flex',alignItems:'center',justifyContent:'center',fontSize:16,fontWeight:700,color:isActive?'#2563eb':'#64748b',flexShrink:0}}>
                {c.name.charAt(0)}
              </div>
              <div style={{flex:1}}>
                <div style={{fontSize:14,color:'#1e293b',fontWeight:isActive?700:500}}>{c.name}</div>
                <div style={{fontFamily:"'DM Mono',monospace",fontSize:11,color:'#94a3b8',marginTop:2}}>Matricule : {c.id} · PIN : ••••</div>
              </div>
              <div style={{display:'flex',gap:8,alignItems:'center'}}>
                {isActive
                  ? <span style={{background:'#2563eb',color:'#fff',borderRadius:6,fontSize:11,padding:'3px 10px',fontWeight:700}}>PAR DÉFAUT</span>
                  : <button className="btn-ghost btn-sm" onClick={()=>setDefault(c)}>⭐ Défaut</button>
                }
                <button onClick={()=>resetPin(c.id)} style={{background:"#fff7ed",border:"1.5px solid #fed7aa",borderRadius:8,padding:"6px 10px",fontSize:11,fontWeight:700,color:"#c2410c",cursor:"pointer",marginRight:6}}>🔄 PIN</button><button className="btn-danger btn-sm" onClick={()=>deleteCashier(c.id)}>✕</button>
              </div>
            </div>
          );
        })}
      </div>

      <div className="card">
        <div className="stitle">➕ Ajouter un caissier</div>
        <div style={{display:'grid',gridTemplateColumns:'120px 1fr 120px',gap:12,alignItems:'end',marginBottom:12}}>
          <div>
            <label>Matricule</label>
            <input value={newId} onChange={e=>setNewId(e.target.value)} placeholder="0001"/>
          </div>
          <div>
            <label>Nom complet</label>
            <input value={newName} onChange={e=>setNewName(e.target.value)} placeholder="PRÉNOM NOM"/>
          </div>
          <div>
            <label>PIN (4 chiffres)</label>
            <input type="password" maxLength={4} value={newPin}
              onChange={e=>setNewPin(e.target.value.replace(/\D/g,''))}
              placeholder="••••" style={{fontFamily:"'DM Mono',monospace",fontSize:18,letterSpacing:4,textAlign:'center'}}
              onKeyDown={e=>e.key==='Enter'&&addCashier()}/>
          </div>
        </div>
        <button className="btn-primary" onClick={addCashier} style={{width:'100%',padding:'11px',fontSize:14}}>+ Ajouter</button>
      </div>

      <div style={{background:'#eff6ff',border:'1px solid #bfdbfe',borderRadius:11,padding:'14px 18px',fontSize:12,color:'#1d4ed8',lineHeight:1.9}}>
        <div>💡 <strong>Comment ça marche :</strong></div>
        <div>• Ajoutez chaque caissier avec son matricule et son PIN</div>
        <div>• Définissez un caissier par défaut avec ⭐</div>
        <div>• Les caissiers se connectent depuis leur poste via l'onglet <strong>🧾 Caissier</strong></div>
        <div>• Votre session propriétaire n'est pas affectée</div>
      </div>
    </div>
  );
}
