// ─────────────────────────────────────────────────────────────
// auth.jsx — Login / cadastro por e-mail+senha e "Continuar com Google"
// (Google é simulado localmente — protótipo sem backend real.)
// ─────────────────────────────────────────────────────────────
const { LedgerIcon, LedgerButton } = window;

// Google "G" 4-cores oficial
function GoogleG({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 48 48" aria-hidden="true">
      <path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z" />
      <path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z" />
      <path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z" />
      <path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z" />
    </svg>);

}

// Demo Google accounts shown in the picker (prototype)
const DEMO_GOOGLE_ACCOUNTS = [
{ email: 'ana.melecaron@gmail.com', name: 'Ana Melecaron', color: '#B00369' },
{ email: 'voce@gmail.com', name: 'Você', color: '#3B6FF1' }];


function LedgerAuthScreen({ existingUser, onAuthenticated, onResetData }) {
  const S = window.LedgerStore;
  const [mode, setMode] = React.useState(existingUser ? 'signin' : 'signup');
  React.useEffect(() => {setMode(existingUser ? 'signin' : 'signup');}, [existingUser]);

  const [email, setEmail] = React.useState(existingUser ? existingUser.email : '');
  const [password, setPassword] = React.useState('');
  const [confirm, setConfirm] = React.useState('');
  const [showPw, setShowPw] = React.useState(false);
  const [focus, setFocus] = React.useState(null);
  const [error, setError] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [googleOpen, setGoogleOpen] = React.useState(false);



  const fieldStyle = (id, hasError) => ({
    fontFamily: 'var(--font-body)', fontSize: 14, padding: '12px 14px', width: '100%', boxSizing: 'border-box',
    border: `1px solid ${hasError ? 'var(--brand-magenta)' : focus === id ? 'var(--slate-400)' : 'var(--border)'}`,
    borderRadius: 'var(--r-3)',
    background: 'var(--bg-elevated)', color: 'var(--fg)', outline: 'none',
    boxShadow: hasError ? 'var(--shadow-error)' : focus === id ? 'var(--shadow-focus)' : 'none',
    transition: 'all var(--dur-fast) var(--ease-out)'
  });

  // Build a fresh authenticated state, seeding sample data only for brand-new vaults.
  function buildAuthedState(userObj) {
    const state = S.loadState();
    const isSameUser = state.user && state.user.email === userObj.email;
    state.user = userObj;
    state.session = { startedAt: new Date().toISOString() };
    if (!isSameUser && (state.transactions || []).length === 0) {
      S.seedSampleData(state);
    } else if (!isSameUser) {
      // different account on this device → start clean but keep settings
      const fresh = S.defaultState();
      fresh.user = userObj;
      fresh.session = state.session;
      fresh.settings = state.settings;
      S.seedSampleData(fresh);
      S.saveState(fresh);
      return fresh;
    }
    S.saveState(state);
    return state;
  }

  async function handleSignup(e) {
    e.preventDefault();
    setError('');
    if (!email.match(/^[^@\s]+@[^@\s]+\.[^@\s]+$/)) {setError('Informe um e-mail válido.');return;}
    if (password.length < 8) {setError('A senha precisa ter pelo menos 8 caracteres.');return;}
    if (password !== confirm) {setError('As senhas não conferem.');return;}
    setBusy(true);
    try {
      // Cria o usuário no Firebase Authentication
      const cred = await window.firebaseAuth.createUserWithEmailAndPassword(
        email.toLowerCase().trim(), password
      );
      const fbUser = cred.user;
      const userObj = {
        uid: fbUser.uid,
        email: fbUser.email,
        name: fbUser.displayName || fbUser.email.split('@')[0],
        provider: 'password',
        createdAt: new Date().toISOString(),
      };
      // Prepara o estado inicial com dados de exemplo
      const state = S.defaultState();
      state.user = userObj;
      state.session = { startedAt: new Date().toISOString() };
      S.saveState(state); // salva local + Firestore
      onAuthenticated(state);
    } catch (err) {
      const msgs = {
        'auth/email-already-in-use': 'Este e-mail já está cadastrado. Faça login.',
        'auth/weak-password': 'Senha muito fraca. Use pelo menos 8 caracteres.',
        'auth/invalid-email': 'E-mail inválido.',
      };
      setError(msgs[err.code] || 'Não foi possível criar a conta. ' + err.message);
    } finally {setBusy(false);}
  }

  async function handleSignin(e) {
    e.preventDefault();
    setError('');
    setBusy(true);
    try {
      // Login real no Firebase Authentication
      const cred = await window.firebaseAuth.signInWithEmailAndPassword(
        email.toLowerCase().trim(), password
      );
      const fbUser = cred.user;
      await loadUserAndEnter(fbUser, 'password');
    } catch (err) {
      const msgs = {
        'auth/user-not-found':  'Nenhuma conta encontrada para este e-mail.',
        'auth/wrong-password':  'Senha incorreta.',
        'auth/invalid-email':   'E-mail inválido.',
        'auth/too-many-requests': 'Muitas tentativas. Aguarde alguns minutos.',
        'auth/invalid-credential': 'E-mail ou senha incorretos.',
      };
      setError(msgs[err.code] || 'Não foi possível entrar. ' + err.message);
    } finally {setBusy(false);}
  }

  // Carrega os dados do Firestore e entra no app
  async function loadUserAndEnter(fbUser, provider) {
    const userObj = {
      uid: fbUser.uid,
      email: fbUser.email,
      name: fbUser.displayName || fbUser.email.split('@')[0],
      provider,
      createdAt: new Date().toISOString(),
    };
    // Tenta carregar dados salvos no Firestore
    const cloudData = await S.loadFromFirestore(fbUser.uid);
    let state;
    if (cloudData) {
      // Usuário já tem dados na nuvem — carrega eles
      state = S.defaultState();
      state.user = userObj;
      state.session = { startedAt: new Date().toISOString() };
      state.transactions    = cloudData.transactions    || [];
      state.monthlyBalances = cloudData.monthlyBalances || {};
      state.forecasts       = cloudData.forecasts       || [];
      state.goals           = cloudData.goals           || [];
      state.customSubs      = cloudData.customSubs      || {};
      state.settings        = { ...state.settings, ...(cloudData.settings || {}) };
    } else {
      // Primeiro login — começa com app limpo
      state = S.defaultState();
      state.user = userObj;
      state.session = { startedAt: new Date().toISOString() };
    }
    S.saveState(state);
    onAuthenticated(state);
  }

  async function handleGoogle() {
    setGoogleOpen(false);
    setBusy(true);
    setError('');
    try {
      const result = await window.firebaseAuth.signInWithPopup(window.googleProvider);
      if (result && result.user) {
        await loadUserAndEnter(result.user, 'google');
      }
    } catch (err) {
      if (err.code === 'auth/popup-blocked') {
        setError('Popup bloqueado pelo navegador. Permita popups para este site e tente novamente.');
      } else if (err.code !== 'auth/popup-closed-by-user') {
        setError('Não foi possível entrar com Google. ' + (err.message || err.code));
      }
    } finally { setBusy(false); }
  }

  return (
    <div style={{
      minHeight: '100vh', background: 'var(--bg)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 48,
      position: 'relative', overflow: 'hidden', boxSizing: 'border-box'
    }}>
      <div style={{ position: 'absolute', right: -200, top: -100, width: 640, height: 512, borderRadius: '50%', background: 'rgba(176,3,105,0.06)', filter: 'blur(40px)' }} />
      <div style={{ position: 'absolute', left: -180, bottom: -120, width: 480, height: 380, borderRadius: '50%', background: 'rgba(15,23,42,0.04)', filter: 'blur(40px)' }} />

      <div style={{ width: 448, maxWidth: '100%', position: 'relative', display: 'flex', flexDirection: 'column', gap: 40 }}>
        {/* Brand */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
          <div style={{
            width: 48, height: 48, borderRadius: 'var(--r-4)', background: 'var(--bg-inverse)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: 'var(--shadow-xs)'
          }}>
            <LedgerIcon name="wallet-minimal" size={22} color="var(--fg-on-inverse)" />
          </div>
          <h1 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 26, lineHeight: '32px', letterSpacing: '-0.6px', color: 'var(--fg-strong)' }}>The Ledger</h1>
          <div className="meta" style={{ color: 'var(--fg-2)' }}>SEU APP FINANCEIRO</div>
        </div>

        {/* Card */}
        <form onSubmit={mode === 'signup' ? handleSignup : handleSignin} style={{
          background: 'var(--bg-elevated)', border: '1px solid var(--border)', borderRadius: 'var(--r-5)',
          padding: 36, boxShadow: 'var(--shadow-xs)',
          display: 'flex', flexDirection: 'column', gap: 20
        }}>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, lineHeight: '28px', color: 'var(--fg-strong)' }}>
              {mode === 'signup' ? 'Crie Sua Conta' : 'Acesso Seguro'}
            </div>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--fg-2)', marginTop: 6 }}>
              {mode === 'signup' ?
              'Crie sua conta com e-mail ou com o Google.' :
              'Entre com seu e-mail ou com o Google.'}
            </div>
          </div>

          {error &&
          <div style={{
            padding: '10px 12px', borderRadius: 'var(--r-3)', display: 'flex', alignItems: 'center', gap: 10,
            background: 'var(--brand-magenta-100)', border: '1px solid rgba(176,3,105,0.22)',
            color: 'var(--brand-magenta-700)', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 12
          }}>
              <LedgerIcon name="alert-circle" size={16} color="var(--brand-magenta-700)" />
              {error}
            </div>
          }

          {/* Google button — topo, como nos apps modernos */}
          <button
            type="button"
            disabled={busy}
            onClick={handleGoogle}
            style={{
              all: 'unset', boxSizing: 'border-box', cursor: busy ? 'default' : 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 12,
              width: '100%', padding: '12px 16px', borderRadius: 'var(--r-3)',
              border: '1px solid var(--border-strong)', background: 'var(--bg-elevated)',
              fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14, color: 'var(--fg-strong)',
              transition: 'background var(--dur-fast)'
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-muted)'}
            onMouseLeave={(e) => e.currentTarget.style.background = 'var(--bg-elevated)'}>
            
            <GoogleG size={18} />
            Continuar com Google
          </button>

          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
            <span className="meta" style={{ color: 'var(--fg-3)' }}>OU COM E-MAIL</span>
            <div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 10, letterSpacing: '1px', textTransform: 'uppercase', color: 'var(--fg-2)' }}>E-mail</span>
              <div style={{ position: 'relative' }}>
                <span style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', display: 'flex' }}>
                  <LedgerIcon name="mail" size={15} color="var(--slate-400)" />
                </span>
                <input
                  type="email"
                  autoComplete="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  onFocus={() => setFocus('em')} onBlur={() => setFocus(null)}
                  placeholder="voce@exemplo.com"
                  style={{ ...fieldStyle('em'), paddingLeft: 40 }} />
                
              </div>
            </label>

            <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <span style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 10, letterSpacing: '1px', textTransform: 'uppercase', color: 'var(--fg-2)' }}>Senha</span>
                <button type="button" onClick={() => setShowPw((s) => !s)} style={{ all: 'unset', cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--fg-2)', textDecoration: 'underline' }}>
                  {showPw ? 'Esconder' : 'Mostrar'}
                </button>
              </span>
              <div style={{ position: 'relative' }}>
                <span style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', display: 'flex' }}>
                  <LedgerIcon name="lock" size={15} color="var(--slate-400)" />
                </span>
                <input
                  type={showPw ? 'text' : 'password'}
                  autoComplete={mode === 'signup' ? 'new-password' : 'current-password'}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  onFocus={() => setFocus('pw')} onBlur={() => setFocus(null)}
                  placeholder={mode === 'signup' ? 'Pelo menos 8 caracteres' : '••••••••'}
                  style={{ ...fieldStyle('pw'), paddingLeft: 40 }} />
                
              </div>
            </label>

            {mode === 'signup' &&
            <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 10, letterSpacing: '1px', textTransform: 'uppercase', color: 'var(--fg-2)' }}>Confirme a senha</span>
                <div style={{ position: 'relative' }}>
                  <span style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', display: 'flex' }}>
                    <LedgerIcon name="lock" size={15} color="var(--slate-400)" />
                  </span>
                  <input
                  type={showPw ? 'text' : 'password'}
                  autoComplete="new-password"
                  value={confirm}
                  onChange={(e) => setConfirm(e.target.value)}
                  onFocus={() => setFocus('cf')} onBlur={() => setFocus(null)}
                  style={{ ...fieldStyle('cf', confirm && confirm !== password), paddingLeft: 40 }} />
                
                </div>
              </label>
            }
          </div>

          <LedgerButton type="submit" variant="primary" full disabled={busy} icon={mode === 'signup' ? 'lock' : 'log-in'}>
            {busy ? 'Aguarde…' : mode === 'signup' ? 'Criar Conta' : 'Entrar'}
          </LedgerButton>

          {/* Toggle entre cadastro e login */}
          <div style={{ textAlign: 'center', fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--fg-2)' }}>
            {mode === 'signup' ?
            <>Já tem uma conta?{' '}
                <button type="button" onClick={() => {setMode('signin');setError('');}} style={{ all: 'unset', cursor: 'pointer', color: 'var(--brand-magenta)', fontWeight: 700 }}>Entrar</button>
              </> :

            <>Ainda não tem conta?{' '}
                <button type="button" onClick={() => {setMode('signup');setError('');}} style={{ all: 'unset', cursor: 'pointer', color: 'var(--brand-magenta)', fontWeight: 700 }}>Criar conta</button>
              </>
            }
          </div>

          {mode === 'signin' && existingUser && existingUser.provider !== 'google' &&
          <button type="button" onClick={onResetData} style={{
            all: 'unset', textAlign: 'center', cursor: 'pointer',
            fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--fg-2)'
          }}>Esqueceu a senha? <span style={{ color: 'var(--brand-magenta)', fontWeight: 700, textDecoration: 'underline' }}>Resetar esta conta</span></button>
          }
        </form>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 18, alignItems: 'center' }}>
          <div style={{ textAlign: 'center', fontFamily: 'var(--font-body)', fontStyle: 'italic', fontSize: 11, color: 'var(--fg-3)' }}>
            Seus dados são salvos com segurança no Firebase. Acesse de qualquer dispositivo.
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, width: '100%', opacity: 0.5 }}>
            <div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
            <div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
            <div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
          </div>
          <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 9, letterSpacing: '2.7px', color: 'var(--slate-400)' }}>
            PRECISÃO · SEGURANÇA · AUTORIDADE
          </div>
        </div>
      </div>

      {/* Login com Google agora usa popup real do Firebase */}
    </div>);

}

// ── GOOGLE ACCOUNT PICKER (simulado) ─────────────────────────
function GoogleSignInModal({ onClose, onPick }) {
  const [adding, setAdding] = React.useState(false);
  const [email, setEmail] = React.useState('');
  const [name, setName] = React.useState('');
  const [focus, setFocus] = React.useState(null);
  const [err, setErr] = React.useState('');

  function submitNew(e) {
    e.preventDefault();
    const m = email.trim().toLowerCase();
    if (!m.match(/^[^@\s]+@[^@\s]+\.[^@\s]+$/)) {setErr('Informe um e-mail Google válido.');return;}
    onPick({ email: m, name: name.trim() || m.split('@')[0] });
  }

  const fld = (id) => ({
    fontFamily: 'arial, sans-serif', fontSize: 15, padding: '13px 15px', width: '100%', boxSizing: 'border-box',
    border: `1px solid ${focus === id ? '#1a73e8' : '#dadce0'}`, borderRadius: 4,
    background: '#fff', color: '#202124', outline: 'none',
    boxShadow: focus === id ? '0 0 0 1px #1a73e8' : 'none'
  });

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 200, padding: 24
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: 400, maxWidth: '100%', background: '#fff', borderRadius: 12, overflow: 'hidden',
        boxShadow: '0 12px 40px rgba(0,0,0,0.28)', fontFamily: 'arial, sans-serif'
      }}>
        {/* Google header */}
        <div style={{ padding: '24px 24px 12px', display: 'flex', flexDirection: 'column', gap: 16 }}>
          <svg width="60" height="20" viewBox="0 0 74 24" aria-label="Google">
            <path fill="#4285F4" d="M9.24 8.19v2.46h5.88c-.18 1.38-.64 2.39-1.34 3.1-.86.86-2.2 1.8-4.54 1.8-3.62 0-6.45-2.92-6.45-6.54s2.83-6.54 6.45-6.54c1.95 0 3.38.77 4.43 1.76L15.4 2.5C13.94 1.08 11.98 0 9.24 0 4.28 0 .11 4.04.11 9s4.17 9 9.13 9c2.68 0 4.7-.88 6.28-2.52 1.62-1.62 2.13-3.91 2.13-5.75 0-.57-.04-1.1-.13-1.54H9.24z" />
            <path fill="#EA4335" d="M25 6.19c-3.21 0-5.83 2.44-5.83 5.81 0 3.34 2.62 5.81 5.83 5.81s5.83-2.46 5.83-5.81c0-3.37-2.62-5.81-5.83-5.81zm0 9.33c-1.76 0-3.28-1.45-3.28-3.52 0-2.09 1.52-3.52 3.28-3.52s3.28 1.43 3.28 3.52c0 2.07-1.52 3.52-3.28 3.52z" />
            <path fill="#FBBC05" d="M53.58 7.49h-.09c-.57-.68-1.67-1.3-3.06-1.3C47.53 6.19 45 8.72 45 12c0 3.26 2.53 5.81 5.43 5.81 1.39 0 2.49-.62 3.06-1.32h.09v.81c0 2.22-1.19 3.41-3.1 3.41-1.56 0-2.53-1.12-2.93-2.07l-2.22.92c.64 1.54 2.33 3.43 5.15 3.43 2.99 0 5.52-1.76 5.52-6.05V6.49h-2.42v1zm-2.93 8.03c-1.76 0-3.1-1.5-3.1-3.52 0-2.05 1.34-3.52 3.1-3.52 1.74 0 3.1 1.5 3.1 3.54.01 2.03-1.36 3.5-3.1 3.5z" />
            <path fill="#4285F4" d="M38 6.19c-3.21 0-5.83 2.44-5.83 5.81 0 3.34 2.62 5.81 5.83 5.81s5.83-2.46 5.83-5.81c0-3.37-2.62-5.81-5.83-5.81zm0 9.33c-1.76 0-3.28-1.45-3.28-3.52 0-2.09 1.52-3.52 3.28-3.52s3.28 1.43 3.28 3.52c0 2.07-1.52 3.52-3.28 3.52z" />
            <path fill="#34A853" d="M58 .24h2.51v17.57H58z" />
            <path fill="#EA4335" d="M68.26 15.52c-1.3 0-2.22-.59-2.82-1.76l7.77-3.21-.26-.66c-.48-1.3-1.96-3.7-4.97-3.7-2.99 0-5.48 2.35-5.48 5.81 0 3.26 2.46 5.81 5.76 5.81 2.66 0 4.2-1.63 4.84-2.57l-1.98-1.32c-.66.96-1.56 1.6-2.86 1.6zm-.18-7.15c1.03 0 1.91.53 2.2 1.28l-5.25 2.17c0-2.44 1.73-3.45 3.05-3.45z" />
          </svg>
          <div>
            <div style={{ fontSize: 22, color: '#202124', fontWeight: 400 }}>{adding ? 'Fazer login' : 'Escolha uma conta'}</div>
            <div style={{ fontSize: 14, color: '#5f6368', marginTop: 4 }}>para continuar em <span style={{ color: '#202124' }}>The Ledger</span></div>
          </div>
        </div>

        {!adding ?
        <div style={{ padding: '4px 0 12px' }}>
            {DEMO_GOOGLE_ACCOUNTS.map((acc) =>
          <button key={acc.email} onClick={() => onPick(acc)} style={{
            all: 'unset', boxSizing: 'border-box', cursor: 'pointer', width: '100%',
            display: 'flex', alignItems: 'center', gap: 14, padding: '12px 24px'
          }}
          onMouseEnter={(e) => e.currentTarget.style.background = '#f8f9fa'}
          onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                <div style={{ width: 36, height: 36, borderRadius: '50%', background: acc.color, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, fontWeight: 500 }}>
                  {acc.name.slice(0, 1).toUpperCase()}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, color: '#202124', fontWeight: 500 }}>{acc.name}</div>
                  <div style={{ fontSize: 13, color: '#5f6368', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{acc.email}</div>
                </div>
              </button>
          )}
            <button onClick={() => {setAdding(true);setErr('');}} style={{
            all: 'unset', boxSizing: 'border-box', cursor: 'pointer', width: '100%',
            display: 'flex', alignItems: 'center', gap: 14, padding: '12px 24px'
          }}
          onMouseEnter={(e) => e.currentTarget.style.background = '#f8f9fa'}
          onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
              <div style={{ width: 36, height: 36, borderRadius: '50%', border: '1px solid #dadce0', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <LedgerIcon name="user-plus" size={18} color="#5f6368" />
              </div>
              <div style={{ fontSize: 14, color: '#202124', fontWeight: 500 }}>Usar outra conta</div>
            </button>
          </div> :

        <form onSubmit={submitNew} style={{ padding: '8px 24px 16px', display: 'flex', flexDirection: 'column', gap: 14 }}>
            {err && <div style={{ fontSize: 13, color: '#d93025' }}>{err}</div>}
            <input value={name} onChange={(e) => setName(e.target.value)} onFocus={() => setFocus('n')} onBlur={() => setFocus(null)} placeholder="Nome" style={fld('n')} />
            <input value={email} onChange={(e) => setEmail(e.target.value)} onFocus={() => setFocus('e')} onBlur={() => setFocus(null)} placeholder="E-mail do Google" type="email" style={fld('e')} />
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 4 }}>
              <button type="button" onClick={() => setAdding(false)} style={{ all: 'unset', cursor: 'pointer', color: '#1a73e8', fontSize: 14, fontWeight: 600 }}>Voltar</button>
              <button type="submit" style={{ all: 'unset', cursor: 'pointer', background: '#1a73e8', color: '#fff', fontSize: 14, fontWeight: 600, padding: '10px 24px', borderRadius: 4 }}>Avançar</button>
            </div>
          </form>
        }

        <div style={{ padding: '14px 24px', borderTop: '1px solid #ebebeb', fontSize: 12, color: '#5f6368' }}>
          Para continuar, o Google compartilhará seu nome e e-mail com o app. <span style={{ color: '#1a73e8' }}>Protótipo — nada é enviado de verdade.</span>
        </div>
      </div>
    </div>);

}

window.LedgerAuthScreen = LedgerAuthScreen;
