// screen-auth.jsx — Connexion et inscription Sauv'Moi

// ── Constantes de style partagées ─────────────────────────────────────────
const AUTH_INP = {
  width: '100%', border: 'none', outline: 'none',
  fontSize: 15, fontFamily: 'inherit', background: 'transparent', color: 'var(--sm-ink)',
};
const AUTH_BOX = {
  border: '1.5px solid var(--sm-line)', borderRadius: 12,
  padding: '12px 14px', background: 'white',
};

// ── Wrapper champ de formulaire ────────────────────────────────────────────
function FieldWrap({ label, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
      {label && (
        <label style={{ fontSize: 13, fontWeight: 600, color: 'var(--sm-ink-700)' }}>
          {label}
        </label>
      )}
      <div style={AUTH_BOX}>{children}</div>
    </div>
  );
}

// ── Icône Google (SVG inline — Lucide n'a pas de logo Google) ─────────────
function GoogleIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" style={{ flexShrink: 0 }}>
      <path 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" fill="#4285F4"/>
      <path 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" fill="#34A853"/>
      <path 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.93l3.66-2.84z" fill="#FBBC05"/>
      <path 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" fill="#EA4335"/>
    </svg>
  );
}

// ── Icône Apple (SVG inline) ───────────────────────────────────────────────
function AppleIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" style={{ flexShrink: 0 }}>
      <path d="M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.8-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z"/>
    </svg>
  );
}

// ── Utilitaire de connexion au backend ────────────────────────────────────
async function authFetch(path, body) {
  const base = (window.API && window.API.base) || '';
  const res = await fetch(base + path, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(body),
  });
  const data = await res.json();
  return { ok: res.ok, data };
}

function applySession(data, nav) {
  if (data.token) {
    window.SM.token = data.token;
    localStorage.setItem('sm_token', data.token);
  }
  if (data.refreshToken) localStorage.setItem('sm_refresh_token', data.refreshToken);
  if (data.expiresAt) localStorage.setItem('sm_expires_at', String(data.expiresAt));
  if (data.user) {
    window.SM.user = data.user;
    localStorage.setItem('sm_user', JSON.stringify(data.user));
    window.SM.emit();
  }
  nav.reset('home');
}

// ════════════════════════════════════════════════════════════════════════════
// ÉCRAN DE CONNEXION
// ════════════════════════════════════════════════════════════════════════════
function AuthScreen({ nav }) {
  useLucide();
  const t = useTranslation();
  const SM = window.useSM();
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');
  const [googleLoading, setGoogleLoading] = React.useState(false);

  // LOT 13b — le callback OAuth natif (lien profond) arrive via
  // supabase-client.js, hors de cet arbre de composants (appUrlOpen peut se
  // déclencher alors que cet écran n'est même plus monté si le retour a été
  // lent) : un échec y pose window.SM.oauthError plutôt que de rester
  // silencieux. Même mécanisme de remise à zéro immédiate que
  // SM.sessionExpired dans app-live.jsx — affiché une seule fois.
  React.useEffect(() => {
    if (SM.oauthError) {
      setError(SM.oauthError);
      window.SM.oauthError = null;
    }
  });

  async function handleLogin(e) {
    e.preventDefault();
    if (!email.trim() || !password) return setError(t('auth.error_fill_fields'));
    setLoading(true); setError('');
    try {
      const { ok, data } = await authFetch('/api/auth/login', { email: email.trim(), password });
      if (!ok) { setError(data.error || t('auth.error_invalid_credentials')); return; }
      applySession(data, nav);
    } catch {
      setError(t('auth.error_network'));
    } finally {
      setLoading(false);
    }
  }

  // Web : signInWithOAuth redirige immédiatement la page vers Google en cas
  // de succès — il n'y a rien à faire après (pas de nav.reset ici) : le
  // retour sur Sauv'Moi est géré par supabase-client.js (synchronisation
  // auto au chargement) avant même que ce composant ne soit remonté.
  //
  // Natif (lot 13b) : signInWithOAuth({ skipBrowserRedirect: true }) ne
  // navigue PAS la WebView embarquée — une navigation directe y serait
  // typiquement refusée par Google (Error 403: disallowed_useragent pour les
  // WebViews génériques). L'URL retournée est ouverte dans un vrai
  // navigateur système (Chrome Custom Tabs, @capacitor/browser) ; le retour
  // par lien profond (ci.sauvmoi.app://auth-callback) est traité entièrement
  // par supabase-client.js (appUrlOpen), pas ici — ce composant peut même
  // être démonté avant que ça n'arrive (voir le watcher SM.oauthError
  // ci-dessus, qui fonctionne indépendamment du montage de cet écran).
  async function handleGoogleLogin() {
    setError('');
    if (!window.getSupabaseClient) {
      setError(t('auth.google_unavailable'));
      return;
    }
    setGoogleLoading(true);
    try {
      const client = await window.getSupabaseClient();
      if (!client) {
        setError(t('auth.google_unavailable_retry'));
        return;
      }
      const isNativeApp = !!(window.Capacitor?.isNativePlatform?.());
      if (isNativeApp) {
        const Browser = window.Capacitor?.Plugins?.Browser;
        if (!Browser) {
          setError(t('auth.google_unavailable'));
          return;
        }
        const { data, error: oauthErr } = await client.auth.signInWithOAuth({
          provider: 'google',
          options: { redirectTo: 'ci.sauvmoi.app://auth-callback', skipBrowserRedirect: true },
        });
        if (oauthErr || !data?.url) { setError(t('auth.google_failed')); return; }
        await Browser.open({ url: data.url });
        // Pas de Browser.close() ICI : l'onglet doit rester ouvert tant que
        // l'utilisateur interagit avec Google. La fermeture a lieu une fois
        // le lien profond reçu, voir ci-dessous.
      } else {
        const { error: oauthErr } = await client.auth.signInWithOAuth({
          provider: 'google',
          options: { redirectTo: window.location.origin },
        });
        if (oauthErr) setError(oauthErr.message || t('auth.google_failed'));
      }
    } catch {
      setError(t('auth.network_error_check_connection'));
    } finally {
      setGoogleLoading(false);
    }
  }

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflowY: 'auto', background: 'var(--sm-paper)' }}>
      <div style={{ padding: '52px 28px 40px', display: 'flex', flexDirection: 'column' }}>

        {/* ── Logo ── */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: 42 }}>
          <img
            src="logo_80.png"
            alt="Sauv'Moi"
            style={{ width: 80, height: 80, objectFit: 'contain', marginBottom: 16, borderRadius: 22, boxShadow: '0 8px 28px rgba(10,22,40,.15)' }}
          />
          <h1 className="sm-serif" style={{ fontSize: 'clamp(26px, 7.5vw, 30px)', marginBottom: 6 }}>Sauv'Moi</h1>
          <p style={{ fontSize: 14, color: 'var(--sm-ink-500)', textAlign: 'center', lineHeight: 1.4 }}>
            {t('splash.tagline')}
          </p>
        </div>

        {/* ── Formulaire ── */}
        <form onSubmit={handleLogin} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <FieldWrap label={t('auth.email_label')}>
            <input
              type="email"
              placeholder={t('auth.email_placeholder')}
              value={email}
              onChange={e => setEmail(e.target.value)}
              autoComplete="email"
              style={AUTH_INP}
            />
          </FieldWrap>

          <FieldWrap label={t('auth.password_label')}>
            <input
              type="password"
              placeholder="••••••••"
              value={password}
              onChange={e => setPassword(e.target.value)}
              autoComplete="current-password"
              style={AUTH_INP}
            />
          </FieldWrap>

          <button
            type="submit"
            className="sm-btn sm-btn-primary"
            disabled={loading}
            style={{ width: '100%', marginTop: 4 }}
          >
            {loading ? t('auth.login_loading') : t('auth.login_button')}
          </button>
        </form>

        {/* Erreur partagée email/mdp et Google — affichée une seule fois,
            sous le formulaire, quelle que soit la méthode qui a échoué. */}
        {error && (
          <Banner variant="danger" icon="alert-circle" text={error} style={{ margin: '10px 0 0' }} />
        )}

        {/* ── Séparateur ── */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '22px 0' }}>
          <div style={{ flex: 1, height: 1, background: 'var(--sm-line)' }} />
          <span style={{ fontSize: 13, color: 'var(--sm-ink-400)', fontWeight: 500 }}>{t('common.or')}</span>
          <div style={{ flex: 1, height: 1, background: 'var(--sm-line)' }} />
        </div>

        {/* ── Boutons sociaux ── */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <button
            type="button"
            onClick={handleGoogleLogin}
            disabled={googleLoading}
            style={{
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
              padding: '13px 20px', borderRadius: 999, width: '100%',
              background: 'white', border: '1.5px solid var(--sm-line)',
              fontSize: 15, fontWeight: 600, fontFamily: 'inherit', color: 'var(--sm-ink)',
              cursor: googleLoading ? 'default' : 'pointer',
              opacity: googleLoading ? 0.7 : 1,
            }}
          >
            <GoogleIcon />
            {googleLoading ? t('auth.google_redirecting') : t('auth.continue_google')}
          </button>

          <button
            type="button"
            style={{
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
              padding: '13px 20px', borderRadius: 999, width: '100%',
              // #1A1A1A fixe (pas var(--sm-ink)) : bouton "Apple" toujours
              // noir avec texte blanc, quel que soit le thème — --sm-ink
              // est un token de TEXTE qui s'éclaircit en mode sombre, ce
              // qui rendait ce bouton blanc-sur-blanc une fois réutilisé
              // comme fond ici.
              background: '#1A1A1A', border: 'none',
              fontSize: 15, fontWeight: 600, fontFamily: 'inherit', color: 'white',
              cursor: 'pointer',
            }}
          >
            <AppleIcon />
            {t('auth.continue_apple')}
          </button>
        </div>

        {/* ── Lien inscription ── */}
        <p style={{ textAlign: 'center', marginTop: 32, fontSize: 14, color: 'var(--sm-ink-500)' }}>
          {t('auth.no_account_yet')}{' '}
          <button
            type="button"
            onClick={() => nav.go('register')}
            style={{ background: 'none', border: 'none', color: 'var(--sm-red)', fontWeight: 600, fontSize: 14, cursor: 'pointer', padding: 0 }}
          >
            {t('auth.signup_link')}
          </button>
        </p>
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════════════
// ÉCRAN D'INSCRIPTION EN 2 ÉTAPES
// ════════════════════════════════════════════════════════════════════════════
const BLOOD_TYPES = ['A+', 'A−', 'B+', 'B−', 'AB+', 'AB−', 'O+', 'O−'];
const GENDERS = ['Masculin', 'Féminin'];

function RegisterScreen({ nav }) {
  useLucide();
  const t = useTranslation();
  const [step, setStep] = React.useState(1);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');

  const [form, setForm] = React.useState({
    // Étape 1 — Infos personnelles
    name: '', birthdate: '', gender: '',
    email: '', phone: '', password: '', confirm: '',
    // Étape 2 — Profil médical
    bloodType: '', height: '', weight: '',
    conditions: '', allergies: '',
    ecName: '', ecPhone: '',
    website: '', // honeypot anti-bot — jamais rempli par un humain, voir plus bas
  });

  const set = k => e => setForm(f => ({ ...f, [k]: e.target.value }));
  const pick = (k, v) => setForm(f => ({ ...f, [k]: v }));

  // ── Validation étape 1 ────────────────────────────────────────────────────
  function validateStep1() {
    if (!form.name.trim())     return t('auth.error_name_required');
    if (!form.email.trim())    return t('auth.error_email_required');
    if (!form.password)        return t('auth.error_password_required');
    if (form.password.length < 6) return t('auth.error_password_min');
    if (form.password !== form.confirm) return t('auth.error_password_mismatch');
    // Une date de naissance dans le futur est toujours une erreur de saisie
    // (contrairement à une date très récente — un nourrisson est un profil
    // légitime, jamais à rejeter) — même règle que le serveur (routes/auth.js,
    // isNotFutureDate), vérifiée ici aussi pour un retour immédiat sans
    // aller-retour réseau. Comparaison de chaînes YYYY-MM-DD, BirthdateField
    // exposant toujours ce format au parent.
    if (form.birthdate && form.birthdate > new Date().toISOString().slice(0, 10)) {
      return t('auth.error_birthdate_future');
    }
    return null;
  }

  function goStep2(e) {
    e.preventDefault();
    const err = validateStep1();
    if (err) { setError(err); return; }
    setError('');
    setStep(2);
  }

  // ── Soumission finale ──────────────────────────────────────────────────────
  async function doRegister() {
    setLoading(true); setError('');
    try {
      const { ok, data } = await authFetch('/api/auth/register', {
        name:      form.name.trim(),
        email:     form.email.trim(),
        phone:     form.phone.trim(),
        password:  form.password,
        birthdate: form.birthdate,
        gender:    form.gender,
        bloodType: form.bloodType,
        height:    form.height   || null,
        weight:    form.weight   || null,
        conditions: form.conditions,
        allergies:  form.allergies,
        emergencyContact: form.ecName ? { name: form.ecName, phone: form.ecPhone } : null,
        website: form.website, // honeypot — doit toujours être vide
      });
      if (!ok) { setError(data.error || t('auth.error_register_generic')); return; }
      applySession(data, nav);
    } catch {
      setError(t('auth.error_network'));
    } finally {
      setLoading(false);
    }
  }

  // ── Rendu ─────────────────────────────────────────────────────────────────
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: 'var(--sm-paper)' }}>

      {/* ── En-tête avec progression ── */}
      <div style={{
        padding: '18px 24px 14px',
        display: 'flex', alignItems: 'center', gap: 12,
        borderBottom: '1px solid var(--sm-line)',
      }}>
        <button
          onClick={() => step === 1 ? nav.back() : (setStep(1), setError(''))}
          style={{ padding: 8, margin: -8, background: 'none', border: 'none', cursor: 'pointer', flexShrink: 0 }}
        >
          <Icon name="arrow-left" size={22} color="var(--sm-ink)" />
        </button>

        <div style={{ flex: 1 }}>
          <p style={{ fontSize: 11, color: 'var(--sm-ink-400)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 2 }}>
            {t('auth.step_of_2').replace('{n}', step)}
          </p>
          <h2 className="sm-serif" style={{ fontSize: 19 }}>
            {step === 1 ? t('auth.step1_title') : t('auth.step2_title')}
          </h2>
        </div>

        {/* Indicateur de progression */}
        <div style={{ display: 'flex', gap: 5, flexShrink: 0 }}>
          {[1, 2].map(n => (
            <div key={n} style={{
              height: 4, borderRadius: 2,
              width: n === step ? 22 : 8,
              background: n <= step ? 'var(--sm-red)' : 'var(--sm-line)',
              transition: 'all 250ms ease',
            }} />
          ))}
        </div>
      </div>

      {/* ── Corps scrollable ── */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '22px 24px 36px' }}>

        {/* ════ ÉTAPE 1 ════ */}
        {step === 1 && (
          <form onSubmit={goStep2} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

            {/* Honeypot anti-bot : masqué visuellement (pas display:none —
                certains robots l'évitent spécifiquement) plutôt que retiré
                du DOM, pour qu'un remplissage automatique aveugle des champs
                du formulaire le renseigne. Invisible et inaccessible au
                clavier pour un humain (aria-hidden + tabIndex -1 + hors
                écran), donc jamais rempli en usage normal. */}
            <input
              type="text"
              name="website"
              value={form.website}
              onChange={set('website')}
              tabIndex={-1}
              autoComplete="off"
              aria-hidden="true"
              style={{ position: 'absolute', left: -9999, top: -9999, width: 1, height: 1, opacity: 0, pointerEvents: 'none' }}
            />

            <FieldWrap label={t('auth.fullname_label')}>
              <input
                type="text" placeholder={t('auth.fullname_placeholder')}
                value={form.name} onChange={set('name')}
                style={AUTH_INP}
              />
            </FieldWrap>

            <BirthdateField
              value={form.birthdate}
              onChange={v => pick('birthdate', v)}
              inputStyle={AUTH_INP}
              boxStyle={AUTH_BOX}
            />

            {/* Sexe — sélection visuelle. Valeur stockée toujours en FR
                (GENDERS), seul le libellé affiché est traduit (genderLabel). */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <label style={{ fontSize: 13, fontWeight: 600, color: 'var(--sm-ink-700)' }}>{t('auth.gender_label')}</label>
              <div style={{ display: 'flex', gap: 10 }}>
                {GENDERS.map(g => (
                  <button
                    key={g} type="button"
                    onClick={() => pick('gender', g)}
                    style={{
                      flex: 1, padding: '11px', borderRadius: 12,
                      fontSize: 14, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer',
                      transition: 'all 150ms ease',
                      background: form.gender === g ? 'var(--sm-ink)' : 'white',
                      color: form.gender === g ? 'white' : 'var(--sm-ink)',
                      border: `1.5px solid ${form.gender === g ? 'var(--sm-ink)' : 'var(--sm-line)'}`,
                    }}
                  >
                    {genderLabel(g)}
                  </button>
                ))}
              </div>
            </div>

            <FieldWrap label={t('auth.email_label')}>
              <input
                type="email" placeholder={t('auth.email_placeholder')}
                value={form.email} onChange={set('email')}
                autoComplete="email" style={AUTH_INP}
              />
            </FieldWrap>

            <FieldWrap label={t('auth.phone_label')}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ fontSize: 14, color: 'var(--sm-ink-500)', fontWeight: 500, flexShrink: 0 }}>🇨🇮 +225</span>
                <input
                  type="tel" placeholder="07 00 00 00 00"
                  value={form.phone} onChange={set('phone')}
                  style={AUTH_INP}
                />
              </div>
            </FieldWrap>

            <FieldWrap label={t('auth.password_label')}>
              <input
                type="password" placeholder={t('auth.password_min_placeholder')}
                value={form.password} onChange={set('password')}
                autoComplete="new-password" style={AUTH_INP}
              />
            </FieldWrap>

            <FieldWrap label={t('auth.confirm_password_label')}>
              <input
                type="password" placeholder="••••••••"
                value={form.confirm} onChange={set('confirm')}
                autoComplete="new-password" style={AUTH_INP}
              />
            </FieldWrap>

            {error && <Banner variant="danger" icon="alert-circle" text={error} />}

            <button type="submit" className="sm-btn sm-btn-primary" style={{ width: '100%', marginTop: 4 }}>
              {t('auth.continue_button')}
            </button>

            <p style={{ textAlign: 'center', fontSize: 14, color: 'var(--sm-ink-500)', margin: 0 }}>
              {t('auth.already_account')}{' '}
              <button
                type="button"
                onClick={() => nav.back()}
                style={{ background: 'none', border: 'none', color: 'var(--sm-red)', fontWeight: 600, fontSize: 14, cursor: 'pointer', padding: 0 }}
              >
                {t('auth.login_button')}
              </button>
            </p>
          </form>
        )}

        {/* ════ ÉTAPE 2 ════ */}
        {step === 2 && (
          <form onSubmit={e => { e.preventDefault(); doRegister(); }} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            <p style={{ fontSize: 13, color: 'var(--sm-ink-500)', margin: 0 }}>
              {t('auth.step2_intro')}
            </p>

            {/* Groupe sanguin — chips */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <label style={{ fontSize: 13, fontWeight: 600, color: 'var(--sm-ink-700)' }}>{t('auth.blood_type_label')}</label>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {BLOOD_TYPES.map(bt => (
                  <button
                    key={bt} type="button"
                    onClick={() => pick('bloodType', bt)}
                    style={{
                      padding: '8px 16px', borderRadius: 999,
                      fontSize: 14, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer',
                      transition: 'all 150ms ease',
                      background: form.bloodType === bt ? 'var(--sm-red)' : 'white',
                      color: form.bloodType === bt ? 'white' : 'var(--sm-ink)',
                      border: `1.5px solid ${form.bloodType === bt ? 'var(--sm-red)' : 'var(--sm-line)'}`,
                    }}
                  >
                    {bt}
                  </button>
                ))}
              </div>
            </div>

            {/* Taille + Poids en colonne */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <FieldWrap label={t('auth.height_label')}>
                <input
                  type="number" placeholder="170"
                  value={form.height} onChange={set('height')}
                  min="50" max="250" style={AUTH_INP}
                />
              </FieldWrap>
              <FieldWrap label={t('auth.weight_label')}>
                <input
                  type="number" placeholder="65"
                  value={form.weight} onChange={set('weight')}
                  min="1" max="300" style={AUTH_INP}
                />
              </FieldWrap>
            </div>

            {/* Antécédents */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <label style={{ fontSize: 13, fontWeight: 600, color: 'var(--sm-ink-700)' }}>{t('auth.conditions_label')}</label>
              <div style={{ ...AUTH_BOX }}>
                <textarea
                  placeholder={t('auth.conditions_placeholder')}
                  value={form.conditions} onChange={set('conditions')}
                  rows={3} style={{ ...AUTH_INP, resize: 'none', lineHeight: 1.55 }}
                />
              </div>
            </div>

            {/* Allergies */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <label style={{ fontSize: 13, fontWeight: 600, color: 'var(--sm-ink-700)' }}>{t('auth.allergies_label')}</label>
              <div style={{ ...AUTH_BOX }}>
                <textarea
                  placeholder={t('auth.allergies_placeholder')}
                  value={form.allergies} onChange={set('allergies')}
                  rows={2} style={{ ...AUTH_INP, resize: 'none', lineHeight: 1.55 }}
                />
              </div>
            </div>

            {/* Contact d'urgence */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <label style={{ fontSize: 13, fontWeight: 600, color: 'var(--sm-ink-700)' }}>{t('auth.emergency_contact_label')}</label>
              <div style={{ ...AUTH_BOX }}>
                <input
                  type="text" placeholder={t('auth.emergency_contact_name_placeholder')}
                  value={form.ecName} onChange={set('ecName')}
                  style={AUTH_INP}
                />
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, ...AUTH_BOX }}>
                <span style={{ fontSize: 14, color: 'var(--sm-ink-500)', fontWeight: 500, flexShrink: 0 }}>🇨🇮 +225</span>
                <input
                  type="tel" placeholder="07 00 00 00 00"
                  value={form.ecPhone} onChange={set('ecPhone')}
                  style={AUTH_INP}
                />
              </div>
            </div>

            {error && <Banner variant="danger" icon="alert-circle" text={error} />}

            <button
              type="submit"
              className="sm-btn sm-btn-primary"
              disabled={loading}
              style={{ width: '100%', marginTop: 4 }}
            >
              {loading ? t('auth.create_account_loading') : t('auth.create_account_button')}
            </button>

            <button
              type="button"
              className="sm-btn sm-btn-outline"
              disabled={loading}
              onClick={doRegister}
              style={{ width: '100%' }}
            >
              {t('auth.skip_step')}
            </button>
          </form>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { AuthScreen, RegisterScreen });
