function SuperviseurManager() {
  const { notify } = useStore();
  const tr = (key) => typeof t !== 'undefined' ? t(key) : key;
  const [superviseurs, setSuperviseurs] = React.useState([]);
  const [loading, setLoading]           = React.useState(true);
  const [form, setForm]                 = React.useState({ nom:'', email:'', password:'' });

  const boutiqueId = localStorage.getItem('pos_boutique_id');
  const token      = localStorage.getItem('pos_auth_token');

  const SUPABASE_URL = 'https://avqhsomkexldzhsbzbss.supabase.co';
  const SUPABASE_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImF2cWhzb21rZXhsZHpoc2J6YnNzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Nzk5OTczMzQsImV4cCI6MjA5NTU3MzMzNH0.tEoQGoAdLwUW9hL-Zpd0_47s3rXZ1sqcjb068-0Fy44';

  async function sbFetch(table, options) {
    const { method='GET', body, params='' } = options || {};
    const url = SUPABASE_URL + '/rest/v1/' + table + '?select=*' + params;
    const res = await fetch(url, {
      method,
      headers: {
        'apikey':        SUPABASE_KEY,
        'Authorization': 'Bearer ' + token,
        'Content-Type':  'application/json',
        'Prefer':        method==='POST'||method==='PATCH' ? 'return=representation' : '',
      },
      body: body ? JSON.stringify(body) : undefined,
    });
    const text = await res.text();
    return text ? JSON.parse(text) : [];
  }

  async function authFetch(path, body) {
    const res = await fetch(SUPABASE_URL + '/auth/v1/' + path, {
      method: 'POST',
      headers: { 'apikey': SUPABASE_KEY, 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    });
    return res.json();
  }

  async function charger() {
    setLoading(true);
    try {
      const data = await sbFetch('roles', { params: '&boutique_id=eq.' + boutiqueId + '&role=eq.superviseur&order=created_at.asc' });
      setSuperviseurs(Array.isArray(data) ? data : []);
    } catch(e) { setSuperviseurs([]); }
    setLoading(false);
  }

  React.useEffect(() => { charger(); }, []);

  async function ajouterSuperviseur() {
    if (!form.nom || !form.email || !form.password) { notify(tr('champs_obligatoires')||'Champs obligatoires', 'err'); return; }
    if (form.password.length < 6) { notify(tr('mdp_min6')||'Mot de passe minimum 6 caractères', 'err'); return; }
    notify('⏳ Création...');
    const data = await authFetch('signup', {
      email:    form.email,
      password: form.password,
      data:     { boutique_nom: localStorage.getItem('pos_shop') ? JSON.parse(localStorage.getItem('pos_shop')).name : '' }
    });
    if (data.error || data.error_code) { notify(data.error_description || 'Erreur', 'err'); return; }
    await sbFetch('roles', {
      method: 'POST',
      body: { user_id:data.user?.id||null, boutique_id:boutiqueId, role:'superviseur', nom:form.nom.toUpperCase(), email:form.email, actif:true }
    });
    notify(tr('sup_ajoute')||'✅ Superviseur ajouté');
    setForm({ nom:'', email:'', password:'' });
    charger();
  }

  async function supprimerSuperviseur(id) {
    if (!window.confirm('Supprimer ce superviseur ?')) return;
    await sbFetch('roles', { method:'DELETE', params:'&id=eq.'+id });
    notify(tr('sup_supprime')||'Superviseur supprimé', 'err');
    charger();
  }

  return (
    <div>
      <div className="card">
        <div className="stitle">{tr('superviseurs_titre')||'👔 Superviseurs de la boutique'}</div>
        {loading ? (
          <div style={{textAlign:'center',color:'#94a3b8',padding:'20px 0'}}>⏳ {tr('chargement')||'Chargement...'}</div>
        ) : superviseurs.length === 0 ? (
          <div style={{textAlign:'center',color:'#94a3b8',padding:'20px 0',fontSize:13}}>
            <div style={{fontSize:40,marginBottom:10}}>👔</div>
            {tr('aucun_sup')||'Aucun superviseur — ajoutez-en un ci-dessous'}
          </div>
        ) : superviseurs.map(s => (
          <div key={s.id} style={{background:'#f8fafc',border:'1.5px solid #e2e8f0',borderRadius:12,padding:'14px 16px',marginBottom:10,display:'flex',alignItems:'center',gap:12}}>
            <div style={{width:44,height:44,borderRadius:22,background:'#eff6ff',display:'flex',alignItems:'center',justifyContent:'center',fontSize:20,flexShrink:0}}>👔</div>
            <div style={{flex:1}}>
              <div style={{fontSize:14,color:'#1e293b',fontWeight:700}}>{s.nom}</div>
              <div style={{fontFamily:"'DM Mono',monospace",fontSize:11,color:'#94a3b8',marginTop:2}}>{s.email}</div>
              {s.pin && s.pin_expire && new Date(s.pin_expire) > new Date() && (
                <div style={{fontSize:11,color:'#16a34a',marginTop:4,fontWeight:600}}>
                  🔐 PIN {tr('actif')||'actif'} · {new Date(s.pin_expire).toLocaleTimeString('fr-FR',{hour:'2-digit',minute:'2-digit'})}
                </div>
              )}
            </div>
            <button className="btn-danger btn-sm" onClick={()=>supprimerSuperviseur(s.id)}>🗑</button>
          </div>
        ))}
      </div>

      <div className="card">
        <div className="stitle">{tr('ajouter_sup')||'➕ Ajouter un superviseur'}</div>
        <div className="field">
          <label>{tr('nom_complet')||'Nom complet'}</label>
          <input value={form.nom} onChange={e=>setForm({...form,nom:e.target.value})} placeholder={tr('ex_nom')||'Ex: JEAN DUPONT'}/>
        </div>
        <div className="field">
          <label>{tr('email_sup')||'Email du superviseur'}</label>
          <input type="email" value={form.email} onChange={e=>setForm({...form,email:e.target.value})} placeholder={tr('ex_email_sup')||'superviseur@email.com'}/>
        </div>
        <div className="field">
          <label>{tr('mdp_provisoire')||'Mot de passe provisoire'}</label>
          <input type="password" value={form.password} onChange={e=>setForm({...form,password:e.target.value})} placeholder={tr('min_6')||'Minimum 6 caractères'}/>
        </div>
        <button className="btn-primary" onClick={ajouterSuperviseur} style={{width:'100%',padding:'12px',fontSize:14}}>
          {tr('creer_sup')||'✅ Créer le compte superviseur'}
        </button>
        <div style={{marginTop:12,background:'#eff6ff',border:'1px solid #bfdbfe',borderRadius:9,padding:'12px 16px',fontSize:12,color:'#1d4ed8',lineHeight:1.8}}>
          <div>{tr('comment_marche')||'💡 Comment ça marche :'}</div>
          <div>1. {tr('etape1_sup')||'Créez le compte avec email et mot de passe provisoire'}</div>
          <div>2. {tr('etape2_sup')||'Donnez ces identifiants au superviseur'}</div>
          <div>3. {tr('etape3_sup')||'Il se connecte sur superviseur.html'}</div>
          <div>4. {tr('etape4_sup')||'Il génère son PIN quand nécessaire'}</div>
        </div>
      </div>

      <div style={{background:'#fffbf0',border:'1px solid #fde68a',borderRadius:10,padding:'12px 16px',fontSize:12,color:'#92400e'}}>
        {tr('warning_sup')||'⚠️ Transmettez les identifiants de façon sécurisée — par message privé uniquement'}
      </div>
    </div>
  );
}
