/* ═══════════════════════════════════════════════════════
   screens-auth · Login, Register, Recover, Clubs select
═══════════════════════════════════════════════════════ */

const LoginScreen = () => {
  const [mode, setMode] = useState('login'); // login | register | recover
  const [email, setEmail] = useState(() => { try { return localStorage.getItem('scp_saved_email') || ''; } catch (e) { return ''; } });
  const [pw, setPw] = useState('');
  const [pw2, setPw2] = useState('');
  const [name, setName] = useState('');
  const [remember, setRemember] = useState(true);
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState('');
  const [info, setInfo] = useState('');

  const submit = async (e) => {
    e?.preventDefault();
    setErr(''); setInfo('');
    if (!email || (mode !== 'recover' && !pw)) { setErr('Preencha os campos'); return; }
    if (mode === 'register') {
      if (pw !== pw2) { setErr('Senhas não coincidem'); return; }
      if (pw.length < 6) { setErr('Mínimo 6 caracteres'); return; }
    }
    setLoading(true);
    try {
      if (remember) { try { localStorage.setItem('scp_saved_email', email); } catch (e) {} }
      if (mode === 'login') await doLogin(email, pw);
      else if (mode === 'register') await doRegister(email, pw, name.trim());
      else if (mode === 'recover') { await fbRecoverPw(email); setInfo('Link enviado para seu e-mail.'); }
    } catch (e2) {
      setErr(e2.message || 'Erro inesperado');
    }
    setLoading(false);
  };

  return (
    <div className="page-enter" style={{
      minHeight: '100vh', display: 'flex', flexDirection: 'column',
      padding: '40px 24px', position: 'relative', overflow: 'hidden',
    }}>
      <SuitsCorner pos="tr" opacity={0.06}/>
      <SuitsCorner pos="bl" opacity={0.04}/>

      <div style={{ marginTop: 32, marginBottom: 28, textAlign: 'center' }}>
        <div className="anim-float" style={{ display: 'inline-block', marginBottom: 22 }}>
          <Logo variant="mark" size="lg"/>
        </div>
        <div className="font-display anim-glow" style={{
          fontSize: 26, letterSpacing: '0.22em', fontWeight: 800, color: 'var(--ink)', marginBottom: 8,
        }}>STACK CONTROL</div>
        <div className="font-display grad-gold" style={{
          fontSize: 12, letterSpacing: '0.7em', fontWeight: 600,
        }}>POKER&nbsp;&nbsp;CLUB</div>
        <div className="row" style={{ justifyContent: 'center', gap: 14, marginTop: 16, opacity: 0.5 }}>
          <Suit kind="spade" size={12}/>
          <Suit kind="heart" size={12} style={{ color: 'var(--red)' }}/>
          <Suit kind="diamond" size={12} style={{ color: 'var(--red)' }}/>
          <Suit kind="club" size={12}/>
        </div>
      </div>

      <form onSubmit={submit} className="card card-gold stagger" style={{ padding: 20 }}>
        <div className="eyebrow" style={{ textAlign: 'center', marginBottom: 16, color: 'var(--gold-1)' }}>
          {mode === 'login' ? 'Acessar conta' : mode === 'register' ? 'Criar conta' : 'Recuperar senha'}
        </div>
        <div style={{ marginBottom: 10 }}>
          <div className="row" style={{ marginBottom: 4 }}>
            <Icon name="mail" size={14} style={{ color: 'var(--ink-3)' }}/>
            <span className="eyebrow">E-mail</span>
          </div>
          <input className="input" type="email" autoComplete="email" value={email}
                 onChange={e => setEmail(e.target.value)} placeholder="voce@exemplo.com" autoFocus/>
        </div>
        {mode === 'register' && (
          <div style={{ marginBottom: 10 }}>
            <div className="row" style={{ marginBottom: 4 }}>
              <Icon name="user" size={14} style={{ color: 'var(--ink-3)' }}/>
              <span className="eyebrow">Nome (opcional)</span>
            </div>
            <input className="input" type="text" value={name} onChange={e => setName(e.target.value)} placeholder="Seu nome"/>
          </div>
        )}
        {mode !== 'recover' && (
          <div style={{ marginBottom: 10 }}>
            <div className="row" style={{ marginBottom: 4 }}>
              <Icon name="lock" size={14} style={{ color: 'var(--ink-3)' }}/>
              <span className="eyebrow">Senha</span>
            </div>
            <input className="input" type="password" autoComplete={mode === 'login' ? 'current-password' : 'new-password'}
                   value={pw} onChange={e => setPw(e.target.value)} placeholder="••••••"/>
          </div>
        )}
        {mode === 'register' && (
          <div style={{ marginBottom: 10 }}>
            <input className="input" type="password" autoComplete="new-password"
                   value={pw2} onChange={e => setPw2(e.target.value)} placeholder="Confirmar senha"/>
          </div>
        )}
        {mode === 'login' && (
          <div className="row" style={{ marginBottom: 14, fontSize: 12 }}>
            <input type="checkbox" checked={remember} onChange={e => setRemember(e.target.checked)} style={{ accentColor: 'var(--gold)' }}/>
            <span style={{ color: 'var(--ink-3)' }}>Lembrar e-mail</span>
            <span className="spacer"/>
            <button type="button" onClick={() => { setMode('recover'); setErr(''); setInfo(''); }}
                    style={{ color: 'var(--gold-1)', fontSize: 12 }}>Esqueci a senha</button>
          </div>
        )}

        {err && <div style={{ color: 'var(--red-1)', fontSize: 12, textAlign: 'center', marginBottom: 8 }}>⚠ {err}</div>}
        {info && <div style={{ color: 'var(--neon)', fontSize: 12, textAlign: 'center', marginBottom: 8 }}>✓ {info}</div>}

        <button type="submit" disabled={loading} className="btn btn-primary" style={{ width: '100%' }}>
          {loading ? '· · · · ·' : mode === 'login' ? 'ENTRAR' : mode === 'register' ? 'CRIAR CONTA' : 'ENVIAR LINK'}
          {!loading && <Icon name="arrow-right" size={16}/>}
        </button>

        <div className="divider"/>
        <div style={{ textAlign: 'center', fontSize: 12, color: 'var(--ink-3)' }}>
          {mode === 'login' ? (
            <>Ainda não tem conta?{' '}
              <button type="button" onClick={() => { setMode('register'); setErr(''); }} style={{ color: 'var(--gold-1)', fontWeight: 600 }}>
                Cadastre-se
              </button>
            </>
          ) : (
            <button type="button" onClick={() => { setMode('login'); setErr(''); setInfo(''); }} style={{ color: 'var(--gold-1)', fontWeight: 600 }}>
              ← Voltar ao login
            </button>
          )}
        </div>
      </form>

      <div className="spacer"/>
      <div style={{ textAlign: 'center', marginTop: 24 }}>
        <div style={{ fontSize: 10, color: 'var(--ink-faint)', fontFamily: 'var(--font-mono)', letterSpacing: '0.2em', marginBottom: 6 }}>
          v{APP_VERSION} · ROYAL FLUSH EDITION
        </div>
        <a href="https://www.brzware.com.br" target="_blank" rel="noopener noreferrer"
           style={{ fontSize: 11, color: 'var(--gold-1)', fontFamily: 'var(--font-mono)', letterSpacing: '0.1em', opacity: 0.7, textDecoration: 'none' }}>
          www.brzware.com.br
        </a>
      </div>
    </div>
  );
};

/* ── CLUBS SCREEN ────────────────────────── */
const ClubsScreen = () => {
  const s = useStore();
  const me = s.allUsers.find(u => u.uid === s.userUid) || {};
  return (
    <div className="page-enter" style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <div className="topbar">
        <Avatar name={me.displayName || me.email} src={me.avatar} size={40} ring/>
        <div style={{ flex: 1, marginLeft: 12, minWidth: 0 }}>
          <div className="eyebrow">Olá</div>
          <div style={{ fontFamily: 'var(--font-editorial)', fontStyle: 'italic', fontSize: 20, color: 'var(--ink)', lineHeight: 1.1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {me.displayName || (me.email || '').split('@')[0]}
          </div>
        </div>
        <button className="topbar-icon-btn" onClick={doLogout} title="Sair">
          <Icon name="logout" size={18}/>
        </button>
      </div>

      <div className="scroll-region" style={{ paddingTop: 4 }}>

        {/* Meus Clubes — acima quando já tem clubes */}
        {s.userClubs.length > 0 && (
          <>
            <div className="section-h">
              <h2>Meus clubes</h2>
              <span className="tag">{s.userClubs.length}</span>
            </div>
            <div className="col stagger" style={{ gap: 10, marginBottom: 16 }}>
              {s.userClubs.map(c => (
                <button key={c.clubId} onClick={() => loadClubData(c.clubId)} className="card" style={{
                  padding: 14, textAlign: 'left',
                  display: 'flex', alignItems: 'center', gap: 12,
                  cursor: 'pointer', transition: 'all 0.2s var(--ease)',
                }}>
                  <div style={{
                    width: 52, height: 52, borderRadius: 14, overflow: 'hidden',
                    background: 'linear-gradient(135deg, var(--gold) 0%, var(--felt-deep) 100%)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    flexShrink: 0,
                    boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.15)',
                  }}>
                    {c.info?.logo
                      ? <img src={c.info.logo} style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
                      : <Suit kind="spade" size={26} style={{ color: 'var(--gold-1)' }}/>}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ color: 'var(--ink)', fontWeight: 700, fontSize: 15 }}>{c.info?.name || c.clubId}</div>
                    <div style={{ color: 'var(--ink-3)', fontSize: 12, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {c.info?.description || ''}
                    </div>
                    <div className="row" style={{ gap: 6, marginTop: 6 }}>
                      {c.info?.clubCode && <span className="chip" style={{ padding: '3px 8px', fontFamily: 'var(--font-mono)' }}>{c.info.clubCode}</span>}
                      {c.role === 'admin' && <span className="chip chip-gold" style={{ padding: '3px 8px' }}>ADMIN</span>}
                    </div>
                  </div>
                  <Icon name="chevron" size={18} style={{ color: 'var(--ink-3)' }}/>
                </button>
              ))}
            </div>
          </>
        )}

        {/* Comece agora — sempre visível mas menos destaque se já tem clube */}
        <div className="card" style={{
          padding: 18, marginBottom: 16,
          background: s.userClubs.length > 0
            ? 'var(--surface)'
            : 'linear-gradient(135deg, var(--gold-soft) 0%, var(--surface) 100%)',
          position: 'relative', overflow: 'hidden',
          borderColor: s.userClubs.length > 0 ? 'var(--border)' : undefined,
        }}>
          {s.userClubs.length === 0 && (
            <div style={{ position: 'absolute', top: -20, right: -20, opacity: 0.12 }}>
              <Suit kind="spade" size={140} style={{ color: 'var(--gold)' }}/>
            </div>
          )}
          <div className="eyebrow" style={{ color: s.userClubs.length > 0 ? 'var(--ink-3)' : 'var(--gold-1)' }}>
            {s.userClubs.length > 0 ? 'Entrar em outro clube' : 'Comece agora'}
          </div>
          {s.userClubs.length === 0 && (
            <div className="font-editorial" style={{ fontStyle: 'italic', fontSize: 22, color: 'var(--ink)', margin: '6px 0 14px', maxWidth: '70%', lineHeight: 1.2 }}>
              Crie um clube ou entre em um existente.
            </div>
          )}
          <div className="row" style={{ gap: 8, marginTop: s.userClubs.length > 0 ? 8 : 0 }}>
            <button className="btn btn-primary" onClick={() => update({ sheet: 'create-club' })} style={{ flex: 1, fontSize: 12, padding: '11px 12px' }}>
              <Icon name="plus" size={14}/> Criar
            </button>
            <button className="btn btn-ghost" onClick={() => update({ sheet: 'join-club' })} style={{ flex: 1, fontSize: 12, padding: '11px 12px' }}>
              <Icon name="qr" size={14}/> Código
            </button>
          </div>
        </div>

        {/* Meus Clubes vazio state */}
        {s.userClubs.length === 0 && (
          <>
            <div className="section-h">
              <h2>Meus clubes</h2>
              <span className="tag">0</span>
            </div>
            <div className="card" style={{ padding: 28, textAlign: 'center' }}>
              <Suit kind="club" size={36} style={{ color: 'var(--ink-3)', opacity: 0.4 }}/>
              <div className="font-editorial" style={{ fontStyle: 'italic', fontSize: 16, color: 'var(--ink-3)', marginTop: 10, lineHeight: 1.4 }}>
                Você ainda não pertence a nenhum clube.<br/>Crie um novo ou peça um código.
              </div>
            </div>
          </>
        )}
      </div>

      {s.sheet === 'create-club' && <CreateClubSheet/>}
      {s.sheet === 'join-club' && <JoinClubSheet/>}
    </div>
  );
};

/* ── Create Club Sheet ───────────────────── */
const CreateClubSheet = () => {
  const [name, setName] = useState('');
  const [desc, setDesc] = useState('');
  const [logo, setLogo] = useState(null);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const fileRef = useRef(null);

  const pickFile = e => {
    const f = e.target.files?.[0]; if (!f) return;
    showCropModal(f, dataUrl => setLogo(dataUrl));
    e.target.value = '';
  };
  const save = async () => {
    if (!name.trim()) { setErr('Informe o nome do clube'); return; }
    setBusy(true);
    try { await createClub(name.trim(), desc.trim(), logo); }
    catch (e) { setErr(e.message || 'Erro'); setBusy(false); }
  };
  return (
    <Sheet onClose={() => update({ sheet: null })} eyebrow="Novo" title="Criar clube">
      <div className="col" style={{ gap: 14 }}>
        <div className="center" style={{ marginBottom: 4 }}>
          <button onClick={() => fileRef.current?.click()} style={{
            width: 84, height: 84, borderRadius: 20, overflow: 'hidden',
            background: 'var(--gold-soft)', border: '1px dashed var(--border-strong)',
            color: 'var(--gold-1)', display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexDirection: 'column', gap: 4,
          }}>
            {logo ? <img src={logo} style={{ width: '100%', height: '100%', objectFit: 'cover' }}/> : <><Icon name="camera" size={22}/><span style={{ fontSize: 9 }}>Logo</span></>}
          </button>
          <input ref={fileRef} type="file" accept="image/*" onChange={pickFile} style={{ display: 'none' }}/>
        </div>
        <div>
          <div className="eyebrow" style={{ marginBottom: 4 }}>Nome do clube</div>
          <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="Ex: Poker dos Amigos" maxLength={50}/>
        </div>
        <div>
          <div className="eyebrow" style={{ marginBottom: 4 }}>Descrição (opcional)</div>
          <input className="input" value={desc} onChange={e => setDesc(e.target.value)} placeholder="Encontros mensais, sábado..." maxLength={80}/>
        </div>
        <div className="card" style={{ padding: 12, background: 'var(--gold-soft)', borderColor: 'var(--border-strong)' }}>
          <div className="row">
            <Icon name="spark" size={16} style={{ color: 'var(--gold-1)' }}/>
            <div style={{ fontSize: 12, color: 'var(--ink-2)' }}>
              Você será o <b style={{ color: 'var(--gold-1)' }}>administrador</b> e poderá criar partidas, gerenciar membros e mensalidades.
            </div>
          </div>
        </div>
        {err && <div style={{ color: 'var(--red-1)', fontSize: 12 }}>⚠ {err}</div>}
        <button className="btn btn-primary" onClick={save} disabled={busy} style={{ width: '100%', marginTop: 6 }}>
          {busy ? 'Criando...' : <><Icon name="check" size={16}/> Criar e gerar código</>}
        </button>
      </div>
    </Sheet>
  );
};

/* ── Join Club Sheet ─────────────────────── */
const JoinClubSheet = () => {
  const [code, setCode] = useState('');
  const [found, setFound] = useState(null);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');

  const search = async () => {
    if (code.trim().length < 4) { setErr('Digite o código completo'); return; }
    setErr(''); setBusy(true);
    try {
      const r = await joinClubByCode(code.trim());
      setFound(r); setBusy(false);
    } catch (e) { setErr(e.message); setFound(null); setBusy(false); }
  };
  const join = async () => {
    if (!found) return;
    setBusy(true);
    try { await requestJoinClub(found.foundId, found.found); }
    catch (e) { setErr(e.message); setBusy(false); }
  };

  return (
    <Sheet onClose={() => update({ sheet: null })} eyebrow="Entrar" title="Código do clube">
      <div className="col" style={{ gap: 14 }}>
        <input className="input" value={code} onChange={e => { setCode(e.target.value.toUpperCase()); setFound(null); setErr(''); }}
               maxLength={6} placeholder="A B C 1 2 3"
               style={{ textAlign: 'center', fontSize: 24, letterSpacing: '0.5em', fontFamily: 'var(--font-mono)', fontWeight: 700, color: 'var(--gold-1)' }}/>
        <button className="btn btn-ghost" onClick={search} disabled={busy} style={{ width: '100%' }}>
          {busy && !found ? 'Buscando...' : <><Icon name="search" size={16}/> Buscar clube</>}
        </button>
        {err && <div style={{ color: 'var(--red-1)', fontSize: 12, textAlign: 'center' }}>⚠ {err}</div>}
        {found && (
          <div className="card card-gold anim-fade-up" style={{ padding: 14 }}>
            <div className="row">
              <div style={{
                width: 48, height: 48, borderRadius: 12, overflow: 'hidden',
                background: 'linear-gradient(135deg, var(--gold) 0%, var(--felt-deep) 100%)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                {found.found.logo
                  ? <img src={found.found.logo} style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
                  : <Suit kind="spade" size={22} style={{ color: 'var(--gold-1)' }}/>}
              </div>
              <div style={{ flex: 1, marginLeft: 10 }}>
                <div style={{ fontWeight: 700 }}>{found.found.name}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{found.found.description}</div>
              </div>
              <Icon name="check" size={20} style={{ color: 'var(--neon)' }}/>
            </div>
          </div>
        )}
        <button className="btn btn-primary" onClick={join} disabled={!found || busy} style={{ width: '100%', opacity: found ? 1 : 0.5 }}>
          {busy ? 'Enviando...' : <>Solicitar entrada <Icon name="arrow-right" size={16}/></>}
        </button>
      </div>
    </Sheet>
  );
};

Object.assign(window, { LoginScreen, ClubsScreen, CreateClubSheet, JoinClubSheet });
