// =============================================================================
// ÉCRANS PLEIN-PAGE — landing publique, authentification, sélection d'événement
// =============================================================================

// === LoadingScreen ===
function LoadingScreen({ label }) {
  return (
    <div className="min-h-screen flex items-center justify-center">
      <div className="text-center">
        <div className="font-display font-extrabold text-4xl text-stone-900 mb-2 tracking-tight">Caterii</div>
        <div className="text-stone-500 text-xs tracking-widest uppercase">{label || 'Chargement…'}</div>
      </div>
    </div>
  );
}

// === FirebaseErrorScreen ===
function FirebaseErrorScreen({ error }) {
  return (
    <div className="min-h-screen flex items-center justify-center px-6">
      <div className="text-center max-w-sm">
        <div className="font-display font-extrabold text-4xl text-stone-900 mb-3 tracking-tight">Caterii</div>
        <div className="text-rose-600 text-sm mb-3 flex items-center justify-center gap-2 font-semibold">
          <Icon name="AlertTriangle" className="w-4 h-4" /> Configuration Firebase manquante
        </div>
        <div className="text-stone-600 text-sm leading-relaxed">
          Édite ce fichier HTML et remplace la section <code className="text-orange-600 font-mono text-xs bg-orange-50 px-1 py-0.5 rounded">FIREBASE_CONFIG</code> par tes propres valeurs.
        </div>
        <div className="mt-4 text-xs text-stone-400 font-mono break-all">{error}</div>
      </div>
    </div>
  );
}

// === LandingPage (page publique vitrine) ===
function LandingPage({ onSignin }) {
  const features = [
    { icon: 'Users',     title: 'Multi-barmen temps réel',    body: 'Chaque téléphone enregistre les ventes, tout est synchronisé instantanément. Plus de tableurs partagés ou de comptes à rapprocher.' },
    { icon: 'Receipt',   title: 'Ardoises pour les habitués', body: 'Ouvre une ardoise par client ou par table, ajoute au fil de la soirée, encaisse à la fin. Sans calcul mental.' },
    { icon: 'CloudOff',  title: 'Hors-ligne robuste',         body: 'Wifi qui flanche ? Tu continues à vendre, tout se synchronise dès que ça revient. Aucune vente perdue.' },
    { icon: 'Package',   title: 'Recompte et clôture',        body: 'En fin de soirée, recompte le stock physique vs théorique, archive l\'événement, télécharge le CSV. Compta du dimanche : 5 minutes.' },
    { icon: 'ChartLine', title: 'Stats automatiques',         body: 'Top boissons, ventilation par paiement et par catégorie, performance par barman, heures de pic. Pas besoin de tableurs.' },
  ];
  const targets = ['Mariages', 'Bars éphémères', 'Festivals', 'Buvettes associatives', 'Brasseries pop-up', 'Clubs sportifs', 'Soirées d\'entreprise', 'Soirées étudiantes'];

  return (
    <div className="min-h-screen bg-stone-50">
      <header className="px-5 pt-5 pb-4 max-w-2xl mx-auto flex items-center justify-between">
        <div className="font-display font-extrabold text-2xl text-stone-900 tracking-tight leading-none">Caterii</div>
        <button onClick={onSignin} className="text-[10px] uppercase tracking-widest text-stone-700 hover:text-stone-900 px-3.5 py-2 rounded-full border border-stone-300 hover:border-stone-400 font-bold">
          Se connecter
        </button>
      </header>

      <section className="px-5 pt-8 pb-12 max-w-2xl mx-auto">
        <div className="text-[10px] uppercase tracking-widest text-orange-600 font-bold mb-3">Gratuit pendant la phase de lancement</div>
        <h1 className="font-display font-extrabold text-4xl sm:text-5xl text-stone-900 tracking-tight leading-[1.05] mb-4">
          La caisse événementielle simple, faite pour les vrais bars.
        </h1>
        <p className="text-stone-600 text-sm leading-relaxed mb-6 max-w-md">
          Caterii transforme tes téléphones en caisse synchronisée. Multi-barmen en temps réel, ardoises, mode hors-ligne, recompte de fin de soirée, stats automatiques. Tout ce qu\'il faut pour un événement, rien de plus.
        </p>
        <button onClick={onSignin} className="bg-stone-900 hover:bg-stone-700 text-white font-bold py-3.5 px-6 rounded-xl text-base">
          Créer mon premier comptoir
        </button>
      </section>

      <section className="px-5 pb-10 max-w-2xl mx-auto">
        <h3 className="text-[10px] uppercase tracking-widest text-stone-500 mb-3 font-bold">Pourquoi Caterii</h3>
        <div className="space-y-2">
          {features.map(f => (
            <div key={f.title} className="bg-white border border-stone-200 rounded-xl p-4 flex gap-3">
              <div className="w-9 h-9 rounded-lg bg-stone-100 text-stone-700 flex items-center justify-center shrink-0">
                <Icon name={f.icon} className="w-4 h-4" strokeWidth={2} />
              </div>
              <div className="min-w-0">
                <div className="text-sm font-bold text-stone-900 mb-0.5">{f.title}</div>
                <div className="text-xs text-stone-600 leading-relaxed">{f.body}</div>
              </div>
            </div>
          ))}
        </div>
      </section>

      <section className="px-5 pb-10 max-w-2xl mx-auto">
        <h3 className="text-[10px] uppercase tracking-widest text-stone-500 mb-3 font-bold">Pour qui</h3>
        <div className="bg-white border border-stone-200 rounded-xl p-4">
          <div className="grid grid-cols-2 gap-y-2.5 gap-x-3 text-xs text-stone-700">
            {targets.map(t => (
              <div key={t} className="flex items-center gap-1.5">
                <Icon name="Check" className="w-3 h-3 text-stone-400 shrink-0" strokeWidth={3} /> {t}
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="px-5 pb-10 max-w-2xl mx-auto">
        <h3 className="text-[10px] uppercase tracking-widest text-stone-500 mb-3 font-bold">Mise en place sur mesure</h3>
        <div className="bg-white border border-stone-200 rounded-xl p-5">
          <h4 className="font-display font-extrabold text-xl text-stone-900 mb-2 leading-tight">On configure ton premier événement avec toi.</h4>
          <p className="text-stone-600 text-sm leading-relaxed mb-4">
            Tu nous envoies ta carte (boissons, prix, catégories), on te livre une caisse prête à l\'emploi avec photos, recettes de cocktails et comptes barmen. Tu débriefes après ton premier événement, on ajuste.
          </p>
          <a href={`mailto:${CONTACT_EMAIL}?subject=Caterii%20-%20Mise%20en%20place%20sur%20mesure`}
             className="inline-flex items-center gap-2 bg-stone-900 hover:bg-stone-700 text-white text-sm font-bold py-2.5 px-4 rounded-lg">
            <Icon name="Settings" className="w-3.5 h-3.5" /> Demander un devis
          </a>
          <div className="text-[10px] text-stone-400 mt-3 font-mono">{CONTACT_EMAIL}</div>
        </div>
      </section>

      <footer className="px-5 pb-10 max-w-2xl mx-auto text-[10px] text-stone-400 font-mono">
        v1 · Caterii · Caisse événementielle
      </footer>
    </div>
  );
}

// === OwnerAuthScreen (login Firebase Auth pour le créateur d'événement) ===
function OwnerAuthScreen({ onBack }) {
  const [mode, setMode] = useState('signin'); // 'signin' | 'signup'
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const [resetSent, setResetSent] = useState(false);

  const friendlyError = (e) => {
    const c = e?.code || '';
    if (c === 'auth/invalid-email') return 'Email invalide';
    if (c === 'auth/email-already-in-use') return 'Cet email est déjà utilisé';
    if (c === 'auth/weak-password') return 'Mot de passe trop court (6 caractères minimum)';
    if (c === 'auth/wrong-password' || c === 'auth/user-not-found' || c === 'auth/invalid-credential') return 'Email ou mot de passe incorrect';
    if (c === 'auth/too-many-requests') return 'Trop de tentatives. Réessaie plus tard.';
    if (c === 'auth/popup-closed-by-user') return '';
    if (c === 'auth/network-request-failed') return 'Pas de connexion réseau';
    return e?.message || 'Erreur inconnue';
  };

  const handleSubmit = async (e) => {
    if (e) e.preventDefault();
    setError(''); setBusy(true);
    try {
      if (mode === 'signup') {
        await fbAuth.createUserWithEmailAndPassword(email.trim(), password);
      } else {
        await fbAuth.signInWithEmailAndPassword(email.trim(), password);
      }
      // L'écouteur d'auth dans App va détecter et rediriger
    } catch (err) {
      setError(friendlyError(err));
    } finally { setBusy(false); }
  };

  const handleGoogle = async () => {
    setError(''); setBusy(true);
    try { await fbAuth.signInWithPopup(googleProvider); }
    catch (err) {
      const msg = friendlyError(err);
      if (msg) setError(msg); // popup-closed = silencieux
    } finally { setBusy(false); }
  };

  const handleReset = async () => {
    if (!email.trim()) { setError('Saisis ton email pour recevoir le lien'); return; }
    setError(''); setBusy(true);
    try { await fbAuth.sendPasswordResetEmail(email.trim()); setResetSent(true); }
    catch (err) { setError(friendlyError(err)); }
    finally { setBusy(false); }
  };

  return (
    <div className="min-h-screen bg-stone-50 flex items-center justify-center px-6 py-12">
      <div className="w-full max-w-sm">
        <button onClick={onBack} className="flex items-center gap-1 text-xs font-semibold text-stone-500 hover:text-stone-900 mb-4">
          <Icon name="ChevronUp" className="w-4 h-4 rotate-[-90deg]" /> Retour
        </button>
        <div className="text-center mb-6">
          <div className="font-display font-extrabold text-4xl text-stone-900 tracking-tight leading-none">Caterii</div>
          <div className="text-stone-500 text-xs tracking-widest uppercase mt-2 font-semibold">{mode === 'signup' ? 'Créer un compte' : 'Connexion'}</div>
        </div>

        <div className="bg-white border border-stone-200 rounded-2xl p-5 shadow-sm space-y-3">
          <button onClick={handleGoogle} disabled={busy} className="w-full flex items-center justify-center gap-2 bg-white hover:bg-stone-50 border border-stone-300 disabled:opacity-50 text-stone-800 font-semibold py-3 rounded-lg">
            <svg className="w-4 h-4" viewBox="0 0 24 24"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>
            Continuer avec Google
          </button>

          <div className="flex items-center gap-2 my-3">
            <div className="flex-1 h-px bg-stone-200"></div>
            <div className="text-[10px] uppercase tracking-widest text-stone-400 font-bold">ou</div>
            <div className="flex-1 h-px bg-stone-200"></div>
          </div>

          <form onSubmit={handleSubmit} className="space-y-2">
            <input type="email" value={email} onChange={e => { setEmail(e.target.value); setError(''); }} placeholder="email@exemple.com" autoComplete="email" required
              className="w-full bg-stone-50 border border-stone-200 rounded-lg px-3 py-3 text-sm focus:border-orange-500 focus:outline-none" />
            <input type="password" value={password} onChange={e => { setPassword(e.target.value); setError(''); }} placeholder="Mot de passe" autoComplete={mode === 'signup' ? 'new-password' : 'current-password'} required
              className="w-full bg-stone-50 border border-stone-200 rounded-lg px-3 py-3 text-sm focus:border-orange-500 focus:outline-none" />
            {error && <div className="text-rose-600 text-xs flex items-start gap-1"><Icon name="AlertTriangle" className="w-3 h-3 mt-0.5 shrink-0" /> {error}</div>}
            {resetSent && <div className="text-emerald-700 text-xs flex items-start gap-1"><Icon name="Check" className="w-3 h-3 mt-0.5 shrink-0" /> Email de réinitialisation envoyé.</div>}
            <button type="submit" disabled={busy || !email || !password} className="w-full bg-stone-900 hover:bg-stone-700 disabled:opacity-40 text-white font-bold py-3 rounded-lg">
              {busy ? '…' : (mode === 'signup' ? 'Créer mon compte' : 'Se connecter')}
            </button>
          </form>

          {mode === 'signin' && (
            <button onClick={handleReset} disabled={busy} className="text-xs text-stone-500 hover:text-stone-900 underline disabled:opacity-50">
              Mot de passe oublié ?
            </button>
          )}
        </div>

        <div className="text-center mt-4 text-xs text-stone-600">
          {mode === 'signup' ? (
            <>Déjà un compte ?{' '}
              <button onClick={() => { setMode('signin'); setError(''); setResetSent(false); }} className="text-orange-600 hover:text-orange-700 font-bold underline">Se connecter</button>
            </>
          ) : (
            <>Pas encore de compte ?{' '}
              <button onClick={() => { setMode('signup'); setError(''); setResetSent(false); }} className="text-orange-600 hover:text-orange-700 font-bold underline">En créer un</button>
            </>
          )}
        </div>

        <div className="text-center text-[10px] text-stone-400 mt-6 font-mono">v1 · Caterii</div>
      </div>
    </div>
  );
}

// === EventPickerScreen (choisir un événement existant ou en créer un) ===
function EventPickerScreen({ user, events, onPick, onCreate, onSignout }) {
  return (
    <div className="min-h-screen bg-stone-50 px-6 py-10">
      <div className="max-w-md mx-auto">
        <div className="flex items-start justify-between mb-6">
          <div>
            <div className="font-display font-extrabold text-3xl text-stone-900 tracking-tight">Caterii</div>
            <div className="text-xs text-stone-500 mt-1">{user?.email || user?.displayName}</div>
          </div>
          <button onClick={onSignout} className="text-[10px] uppercase tracking-widest text-stone-500 hover:text-stone-900 font-bold flex items-center gap-1">
            Déconnexion <Icon name="X" className="w-3 h-3" strokeWidth={2.5} />
          </button>
        </div>

        <div className="mb-3">
          <h2 className="font-display font-bold text-xl text-stone-900 mb-1">Tes comptoirs</h2>
          <div className="text-xs text-stone-500">Sélectionne un événement ou crées-en un nouveau.</div>
        </div>

        {events.length > 0 ? (
          <div className="bg-white border border-stone-200 rounded-xl divide-y divide-stone-100 mb-3">
            {events.map(ev => (
              <button key={ev._key} onClick={() => onPick(ev._key)} className="w-full px-4 py-3.5 flex items-center justify-between hover:bg-stone-50 text-left">
                <div className="min-w-0">
                  <div className="text-sm font-bold text-stone-900 truncate">{ev.name}</div>
                  <div className="text-[10px] text-stone-500 font-mono mt-0.5">
                    Créé le {ev.createdAt ? new Date(ev.createdAt).toLocaleDateString('fr-BE') : '?'}
                  </div>
                </div>
                <Icon name="ChevronUp" className="w-4 h-4 text-stone-400 rotate-90 shrink-0" strokeWidth={2.5} />
              </button>
            ))}
          </div>
        ) : (
          <div className="bg-white border border-stone-200 border-dashed rounded-xl px-4 py-8 text-center mb-3">
            <Icon name="Receipt" className="w-10 h-10 text-stone-300 mx-auto mb-2" strokeWidth={1.5} />
            <div className="text-sm text-stone-500 mb-1">Aucun événement pour l'instant</div>
            <div className="text-xs text-stone-400">Crée ton premier comptoir ci-dessous.</div>
          </div>
        )}

        <button onClick={onCreate} className="w-full flex items-center justify-center gap-2 bg-orange-500 hover:bg-orange-600 text-white font-bold py-3.5 rounded-xl">
          <Icon name="Plus" className="w-4 h-4" strokeWidth={2.5} /> Créer un nouveau comptoir
        </button>
      </div>
    </div>
  );
}

// === EventCreateScreen (formulaire de création d'événement) ===
function EventCreateScreen({ user, onCreate, onCancel, busy }) {
  const [eventName, setEventName] = useState('');
  // Membres : la première ligne est pré-remplie avec le créateur
  const [members, setMembers] = useState([
    { name: user?.displayName || '', password: '', role: 'admin' },
  ]);
  const [error, setError] = useState('');

  const updateMember = (i, patch) => {
    setMembers(ms => ms.map((m, idx) => idx === i ? { ...m, ...patch } : m));
  };
  const addMember = () => setMembers(ms => [...ms, { name: '', password: '', role: 'barman' }]);
  const removeMember = (i) => setMembers(ms => ms.filter((_, idx) => idx !== i));

  const handleSubmit = async (e) => {
    if (e) e.preventDefault();
    setError('');
    const name = eventName.trim();
    if (!name) { setError('Donne un nom à ton comptoir'); return; }
    const cleaned = members
      .map(m => ({ name: m.name.trim(), password: m.password, role: m.role }))
      .filter(m => m.name && m.password);
    if (cleaned.length === 0) { setError('Ajoute au moins un membre avec mot de passe'); return; }
    if (!cleaned.some(m => m.role === 'admin')) { setError('Au moins un membre doit être admin'); return; }
    // Vérifier unicité des noms
    const lower = cleaned.map(m => m.name.toLowerCase());
    if (new Set(lower).size !== lower.length) { setError('Les noms de membres doivent être uniques'); return; }
    onCreate({ name, members: cleaned });
  };

  return (
    <div className="min-h-screen bg-stone-50 px-6 py-10">
      <div className="max-w-md mx-auto">
        <button onClick={onCancel} disabled={busy} className="flex items-center gap-1 text-xs font-semibold text-stone-500 hover:text-stone-900 mb-4 disabled:opacity-50">
          <Icon name="ChevronUp" className="w-4 h-4 rotate-[-90deg]" /> Retour
        </button>
        <h1 className="font-display font-extrabold text-3xl text-stone-900 tracking-tight mb-1">Nouveau comptoir</h1>
        <p className="text-xs text-stone-500 mb-5">Donne un nom à ton événement et crée les comptes pour ton équipe. Tu pourras tout modifier plus tard.</p>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="bg-white border border-stone-200 rounded-xl p-4">
            <label className="block text-[10px] uppercase tracking-widest text-stone-500 mb-2 font-bold">Nom de l'événement</label>
            <input type="text" value={eventName} onChange={e => setEventName(e.target.value)} placeholder="Ex: Mariage Pauline & Tom" autoFocus required
              className="w-full bg-stone-50 border border-stone-200 rounded-lg px-3 py-3 text-base focus:border-orange-500 focus:outline-none" />
          </div>

          <div className="bg-white border border-stone-200 rounded-xl p-4">
            <div className="flex items-center justify-between mb-3">
              <label className="text-[10px] uppercase tracking-widest text-stone-500 font-bold">Équipe ({members.length})</label>
              <button type="button" onClick={addMember} className="text-[10px] uppercase tracking-widest font-bold text-orange-600 flex items-center gap-1">
                <Icon name="Plus" className="w-3 h-3" strokeWidth={2.5} /> Ajouter
              </button>
            </div>
            <div className="text-[10px] text-stone-500 leading-relaxed mb-3">
              Le mot de passe est ce que chaque barman saisira sur son téléphone pour utiliser la caisse. <span className="font-bold">Garde-en une trace</span> pour pouvoir le redonner.
            </div>
            <div className="space-y-2">
              {members.map((m, i) => (
                <div key={i} className="bg-stone-50 border border-stone-200 rounded-lg p-2.5 space-y-2">
                  <div className="grid grid-cols-[1fr_auto] gap-2">
                    <input type="text" value={m.name} onChange={e => updateMember(i, { name: e.target.value })} placeholder="Prénom"
                      className="bg-white border border-stone-200 rounded-md px-2.5 py-2 text-sm focus:border-orange-500 focus:outline-none" />
                    <select value={m.role} onChange={e => updateMember(i, { role: e.target.value })}
                      className="bg-white border border-stone-200 rounded-md px-2 py-2 text-sm focus:border-orange-500 focus:outline-none">
                      <option value="admin">Admin</option>
                      <option value="barman">Barman</option>
                    </select>
                  </div>
                  <div className="flex gap-2">
                    <input type="text" value={m.password} onChange={e => updateMember(i, { password: e.target.value })} placeholder="Mot de passe (4+ caractères)"
                      className="flex-1 bg-white border border-stone-200 rounded-md px-2.5 py-2 text-sm font-mono focus:border-orange-500 focus:outline-none" />
                    {members.length > 1 && (
                      <button type="button" onClick={() => removeMember(i)} className="bg-white hover:bg-rose-50 border border-stone-200 text-rose-600 px-2 rounded-md">
                        <Icon name="Trash2" className="w-3.5 h-3.5" />
                      </button>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>

          {error && <div className="bg-rose-50 border border-rose-200 rounded-lg px-3 py-2 text-sm text-rose-700 flex items-start gap-2"><Icon name="AlertTriangle" className="w-4 h-4 mt-0.5 shrink-0" /> {error}</div>}

          <button type="submit" disabled={busy} className="w-full bg-stone-900 hover:bg-stone-700 disabled:opacity-50 text-white font-bold py-3.5 rounded-xl text-base">
            {busy ? 'Création…' : 'Créer le comptoir'}
          </button>
        </form>
      </div>
    </div>
  );
}

// === BarmanJoinScreen (login en tant que membre d'un événement) ===
// Utilisé à la fois par le créateur (qui doit aussi se "loguer" comme membre pour
// vendre) et par les barmen qui arrivent via un lien partagé.
function BarmanJoinScreen({ eventName, members, onLogin, onLeaveEvent, error: extError }) {
  const [step, setStep] = useState('name'); // 'name' | 'password'
  const [selectedName, setSelectedName] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);

  useEffect(() => { if (extError) setError(extError); }, [extError]);

  const handleNameClick = (name) => {
    setSelectedName(name);
    setStep('password');
    setError('');
  };

  const handlePasswordSubmit = async (e) => {
    if (e) e.preventDefault();
    setBusy(true); setError('');
    const member = members.find(m => m.name === selectedName);
    if (!member) { setError('Membre introuvable'); setBusy(false); return; }
    try {
      const hash = await hashPassword(password, member.salt || '');
      if (hash !== member.passwordHash) {
        setError('Mot de passe incorrect'); setPassword('');
      } else {
        onLogin({ name: member.name, role: member.role });
      }
    } catch (err) { setError('Erreur de vérification'); }
    finally { setBusy(false); }
  };

  return (
    <div className="min-h-screen bg-stone-50 flex items-center justify-center px-6 py-12">
      <div className="w-full max-w-sm">
        <div className="text-center mb-8">
          <div className="font-display font-extrabold text-5xl text-stone-900 tracking-tight leading-none">Caterii</div>
          {eventName && (
            <div className="text-base font-bold text-orange-700 mt-2">{eventName}</div>
          )}
          <div className="text-stone-500 text-xs tracking-widest uppercase mt-2 font-semibold">Connexion à la caisse</div>
        </div>

        <div className="bg-white border border-stone-200 rounded-2xl p-5 shadow-sm">
          {step === 'name' ? (
            <>
              <div className="text-[10px] uppercase tracking-widest text-stone-500 mb-3 font-bold">Choisis ton compte</div>
              {(!members || members.length === 0) ? (
                <div className="bg-stone-50 border border-stone-200 rounded-lg px-3 py-4 text-sm text-stone-500 text-center">
                  Aucun membre n'a été configuré pour cet événement.
                </div>
              ) : (
                <div className="space-y-1.5">
                  {members.map(m => (
                    <button key={m.name} onClick={() => handleNameClick(m.name)} className="w-full flex items-center justify-between px-3 py-3 bg-stone-50 hover:bg-stone-100 rounded-lg text-left">
                      <div className="flex items-center gap-2">
                        <div className={`w-8 h-8 rounded-full flex items-center justify-center font-bold text-white text-sm ${m.role === 'admin' ? 'bg-stone-900' : 'bg-stone-500'}`}>
                          {m.name[0]?.toUpperCase()}
                        </div>
                        <div>
                          <div className="text-sm font-bold text-stone-900">{m.name}</div>
                          <div className="text-[10px] uppercase tracking-widest text-stone-500 font-bold">{m.role === 'admin' ? 'Admin' : 'Barman'}</div>
                        </div>
                      </div>
                      <Icon name="ChevronUp" className="w-4 h-4 text-stone-400 rotate-90" strokeWidth={2.5} />
                    </button>
                  ))}
                </div>
              )}
              {onLeaveEvent && (
                <button onClick={onLeaveEvent} className="w-full text-[10px] uppercase tracking-widest text-stone-500 hover:text-stone-900 font-bold mt-4 text-center">
                  Quitter cet événement
                </button>
              )}
            </>
          ) : (
            <form onSubmit={handlePasswordSubmit}>
              <div className="text-sm text-stone-700 mb-3">
                Salut <span className="font-bold text-stone-900">{selectedName}</span> 👋
              </div>
              <input type="password" value={password} onChange={e => { setPassword(e.target.value); setError(''); }}
                autoFocus autoComplete="off" placeholder="Ton mot de passe"
                className="w-full bg-stone-50 border border-stone-200 rounded-lg px-3 py-3 text-base focus:border-orange-500 focus:outline-none mb-2" />
              {error && <div className="text-rose-600 text-xs mb-2 flex items-center gap-1"><Icon name="AlertTriangle" className="w-3 h-3" /> {error}</div>}
              <div className="grid grid-cols-2 gap-2 mt-3">
                <button type="button" onClick={() => { setStep('name'); setPassword(''); setError(''); }} disabled={busy} className="bg-stone-100 hover:bg-stone-200 text-stone-700 py-3 rounded-lg font-semibold disabled:opacity-50">Retour</button>
                <button type="submit" disabled={busy || !password} className="bg-orange-500 hover:bg-orange-600 disabled:opacity-40 text-white font-bold py-3 rounded-lg">{busy ? '…' : 'Entrer'}</button>
              </div>
            </form>
          )}
        </div>
        <div className="text-center text-[10px] text-stone-400 mt-4 font-mono">v1 · Caterii</div>
      </div>
    </div>
  );
}

// === EventNotFoundScreen (lien partagé invalide) ===
function EventNotFoundScreen({ onBack }) {
  return (
    <div className="min-h-screen flex items-center justify-center px-6 py-12">
      <div className="text-center max-w-sm">
        <div className="font-display font-extrabold text-4xl text-stone-900 mb-3 tracking-tight">Caterii</div>
        <div className="bg-rose-50 border border-rose-200 rounded-xl p-4 mb-4">
          <Icon name="AlertTriangle" className="w-8 h-8 text-rose-500 mx-auto mb-2" />
          <div className="text-sm font-bold text-stone-900 mb-1">Événement introuvable</div>
          <div className="text-xs text-stone-600">Ce lien n'est pas valide ou l'événement a été supprimé.</div>
        </div>
        <button onClick={onBack} className="text-sm font-bold text-orange-600 hover:text-orange-700 underline">
          Retour à l'accueil
        </button>
      </div>
    </div>
  );
}
