/* global React, Logo, Button, Field, Icon, ICONS, sb */
const { useState } = React;

// ─── Modal de documentos legais (acessível no fluxo de cadastro) ──────────────
function LegalModal({ tab, onClose }) {
  const TABS = [
    { id: 'termos',      label: 'Termos de Uso' },
    { id: 'privacidade', label: 'Privacidade' },
    { id: 'reembolso',   label: 'Reembolso' },
    { id: 'cookies',     label: 'Cookies' },
  ];
  const [active, setActive] = useState(tab || 'termos');

  return (
    <div style={{ position:'fixed', inset:0, zIndex:9999, display:'flex', alignItems:'center', justifyContent:'center' }}>
      <div onClick={onClose} style={{ position:'absolute', inset:0, background:'rgba(0,0,0,0.7)', backdropFilter:'blur(4px)' }}/>
      <div style={{ position:'relative', zIndex:1, background:'var(--bg-surface)', borderRadius:20, boxShadow:'0 24px 80px rgba(0,0,0,0.6)', width:'min(720px, 95vw)', maxHeight:'88vh', display:'flex', flexDirection:'column' }}>
        {/* Header */}
        <div style={{ padding:'20px 24px 0', display:'flex', alignItems:'center', justifyContent:'space-between', flexShrink:0 }}>
          <div style={{ fontFamily:'var(--font-display)', fontSize:16, fontWeight:800, color:'var(--fg-primary)' }}>Documentos Legais</div>
          <button onClick={onClose} style={{ width:32, height:32, borderRadius:8, border:'1px solid var(--border-subtle)', background:'transparent', color:'var(--fg-muted)', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', fontSize:18 }}>×</button>
        </div>
        {/* Tabs */}
        <div style={{ display:'flex', gap:4, padding:'16px 24px 0', flexShrink:0 }}>
          {TABS.map(t => (
            <button key={t.id} onClick={() => setActive(t.id)} style={{ padding:'7px 14px', borderRadius:8, border:'none', cursor:'pointer', fontSize:12, fontWeight: active===t.id ? 700 : 500, fontFamily:'inherit', background: active===t.id ? 'var(--bg-elevated)' : 'transparent', color: active===t.id ? 'var(--fg-primary)' : 'var(--fg-muted)', transition:'all 150ms' }}>
              {t.label}
            </button>
          ))}
        </div>
        {/* Content — carrega Legal.jsx se disponível */}
        <div style={{ overflow:'auto', padding:'20px 24px 24px', flex:1 }}>
          {window.Legal
            ? React.createElement(window.Legal, { initialTab: active })
            : (
              <div style={{ padding:40, textAlign:'center', color:'var(--fg-muted)', fontSize:13 }}>
                Carregando documentos…
              </div>
            )
          }
        </div>
      </div>
    </div>
  );
}

const CAKTO_URL_MENSAL = 'https://pay.cakto.com.br/38vm695_679341';
const CAKTO_URL_ANUAL  = 'https://pay.cakto.com.br/us3762i';

function Login({ onLogin }) {
  // Se vier de /founders com ?cadastro=1, abre direto no signup
  const startInSignup = new URLSearchParams(window.location.search).get('cadastro') === '1';
  const [mode, setMode] = useState(startInSignup ? 'signup' : 'signin');
  if (mode === 'signup') return <SignUp onBack={()=>setMode('signin')} onLogin={onLogin}/>;
  return <SignIn onLogin={onLogin} onSwitch={()=>setMode('signup')} />;
}

// ─── Sign in ────────────────────────────────────────────────────────────────
function SignIn({ onLogin, onSwitch }) {
  const [email, setEmail] = useState('');
  const [pwd, setPwd] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  async function handleGoogleLogin() {
    const { error } = await sb.auth.signInWithOAuth({
      provider: 'google',
      options: {
        redirectTo: window.location.origin + window.location.pathname,
        scopes: 'openid email profile',
      },
    });
    if (error) console.error('Erro login Google:', error);
  }

  async function handleLogin() {
    setError('');
    setLoading(true);
    try {
      const { error: err } = await sb.auth.signInWithPassword({ email: email.trim(), password: pwd });
      if (err) { setError(err.message); return; }
      onLogin();
    } catch (e) {
      setError('Erro inesperado. Tente novamente.');
    } finally {
      setLoading(false);
    }
  }

  function handleKey(e) { if (e.key === 'Enter') handleLogin(); }

  return (
    <div className="login-grid" style={{ background: 'var(--bg-app)', color: 'var(--fg-primary)' }}>
      <div className="login-hero"><Hero/></div>
      <div className="login-form">
        <div style={{ width: '100%', maxWidth: 380, display: 'flex', flexDirection: 'column', gap: 20 }}>
          <div>
            <h2 style={{ margin: 0, fontSize: 28, fontWeight: 700, letterSpacing: '-0.01em' }}>Bem-vinda de volta</h2>
            <p style={{ marginTop: 6, color: 'var(--fg-muted)', fontSize: 14 }}>Entre na sua conta para continuar.</p>
          </div>
          <Field label="E-mail" icon="msg" value={email} onChange={e => setEmail(e.target.value)} onKeyDown={handleKey} />
          <div>
            <Field label="Senha" type="password" value={pwd} onChange={e => setPwd(e.target.value)} placeholder="••••••••" onKeyDown={handleKey} />
            <a href="#" onClick={e => e.preventDefault()} style={{
              fontSize: 12, color: 'var(--geek-blue-300)', textDecoration: 'none',
              display: 'inline-block', marginTop: 8,
            }}>Esqueceu sua senha?</a>
          </div>
          {error && (
            <div style={{ padding:'10px 14px', borderRadius:8, background:'rgba(255,77,79,0.12)', border:'1px solid rgba(255,77,79,0.3)', color:'#ff4d4f', fontSize:13 }}>
              {error}
            </div>
          )}
          <Button size="lg" disabled={loading || !email.trim() || !pwd} onClick={handleLogin} style={{ width: '100%', justifyContent: 'center' }}>
            {loading ? 'Entrando…' : 'Entrar'}
          </Button>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, color: 'var(--fg-muted)', fontSize: 12 }}>
            <span style={{ flex: 1, height: 1, background: 'var(--border-subtle)' }}/>
            ou continue com
            <span style={{ flex: 1, height: 1, background: 'var(--border-subtle)' }}/>
          </div>
          <Button variant="secondary" onClick={handleGoogleLogin} style={{ width: '100%', justifyContent: 'center' }}>Google</Button>
          <div style={{ fontSize: 13, color: 'var(--fg-muted)', textAlign: 'center', marginTop: 8 }}>
            Novo no inBrivvo?{' '}
            <a href="#" onClick={e => { e.preventDefault(); onSwitch(); }} style={{ color: 'var(--geek-blue-300)', fontWeight: 600 }}>Criar conta</a>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Hero ───────────────────────────────────────────────────────────────────
function Hero() {
  return (
    <div style={{
      position: 'relative', overflow: 'hidden',
      background: 'radial-gradient(1100px 500px at 20% 10%, rgba(54,207,201,0.18), transparent 60%), radial-gradient(900px 700px at 80% 80%, rgba(29,57,196,0.32), transparent 60%), var(--bg-surface)',
      padding: '56px 56px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
    }}>
      <Logo size={42} withText />
      <div>
        <div style={{
          fontFamily: 'var(--font-display)', fontSize: 11, fontWeight: 700,
          letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--geek-blue-300)', marginBottom: 14,
        }}>Acesso antecipado · Fundadores</div>
        <h1 style={{
          margin: 0, fontSize: 44, fontWeight: 700, letterSpacing: '-0.02em',
          lineHeight: 1.05, maxWidth: 520,
        }}>
          Tudo o que sua agência precisa,<br />
          <span style={{
            background: 'linear-gradient(120deg,#34E0A1,#00C2FF 60%,#85A5FF)',
            WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent',
          }}>em um só lugar.</span>
        </h1>
        <p style={{ marginTop: 18, color: 'var(--fg-secondary)', fontSize: 15, lineHeight: 1.55, maxWidth: 460 }}>
          Projetos, clientes, tarefas, financeiro e portfolios públicos — sem alternar entre 7 abas. Feito para profissionais de marketing brasileiros.
        </p>
        <div style={{ display:'flex', alignItems:'center', gap:8, marginTop:24, padding:'12px 16px', borderRadius:10, background:'rgba(250,173,20,0.1)', border:'1px solid rgba(250,173,20,0.25)', maxWidth:360 }}>
          <span style={{ fontSize:18 }}>⭐</span>
          <span style={{ fontSize:13, color:'#FAAD14', fontWeight:600 }}>Preço de Fundadores — R$47/mês ou R$397/ano para sempre</span>
        </div>
      </div>
      <div style={{ fontSize: 12, color: 'var(--fg-muted)' }}>© 2026 inBrivvo · São Paulo, BR</div>
    </div>
  );
}

// ─── Sign up ────────────────────────────────────────────────────────────────
const SEGMENTS = ['Branding', 'Web design', 'Social media', 'Audiovisual', 'Editorial', 'Outro'];
const SIZES    = ['Solo', '2–5 pessoas', '6–15 pessoas', '15+'];

function SignUp({ onBack, onLogin }) {
  const [step, setStep]       = useState(0);
  const [done, setDone]       = useState(false); // conta criada, mostrar checkout
  const [form, setForm]       = useState({
    name: '', email: '', pwd: '',
    studio: '', size: 'Solo', segments: [],
    terms: false,
  });
  const [loading, setLoading] = useState(false);
  const [error, setError]     = useState('');
  const [legalTab, setLegalTab] = useState(null); // null = fechado, 'termos' | 'privacidade' = aberto
  const set        = (k,v) => setForm(f => ({ ...f, [k]: v }));
  const toggleSeg  = (s) => set('segments', form.segments.includes(s) ? form.segments.filter(x=>x!==s) : [...form.segments, s]);

  const valid = [
    form.name.trim() && /^.+@.+\..+/.test(form.email) && form.pwd.length >= 6,
    form.studio.trim() && form.segments.length > 0,
    form.terms,
  ];
  const stepsLab = ['Conta', 'Workspace', 'Confirmar'];

  async function handleCreate() {
    setError('');
    setLoading(true);
    try {
      const { error: err } = await sb.auth.signUp({
        email: form.email.trim(),
        password: form.pwd,
        options: {
          emailRedirectTo: window.location.origin + '/entrar',
          data: {
            name:     form.name.trim(),
            studio:   form.studio.trim(),
            size:     form.size,
            segments: form.segments,
          }
        }
      });
      if (err) { setError(err.message); return; }
      setDone(true); // mostra tela de checkout, não entra no dashboard
    } catch (e) {
      setError('Erro inesperado. Tente novamente.');
    } finally {
      setLoading(false);
    }
  }

  // ── Tela pós-cadastro: escolher plano ─────────────────────────────────────
  if (done) {
    return (
      <div className="login-grid" style={{ background:'var(--bg-app)', color:'var(--fg-primary)' }}>
        <div className="login-hero"><Hero/></div>
        <div className="login-form" style={{ display:'flex', flexDirection:'column', justifyContent:'center', gap:24 }}>
          <div>
            <div style={{ display:'inline-flex', alignItems:'center', gap:8, padding:'6px 14px', borderRadius:999, background:'rgba(34,197,94,0.12)', border:'1px solid rgba(34,197,94,0.3)', marginBottom:16 }}>
              <svg width={14} height={14} viewBox="0 0 24 24" fill="none" stroke="#22C55E" strokeWidth={2.5} strokeLinecap="round" strokeLinejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
              <span style={{ fontSize:12, fontWeight:700, color:'#22C55E' }}>Conta criada com sucesso!</span>
            </div>
            <h2 style={{ margin:'0 0 8px', fontSize:28, fontWeight:700, letterSpacing:'-0.01em' }}>Agora escolha seu plano</h2>
            <p style={{ margin:0, color:'var(--fg-muted)', fontSize:14, lineHeight:1.6 }}>
              Você é um dos primeiros fundadores — garante esse preço para sempre, mesmo quando aumentar.
            </p>
          </div>

          {/* Mensal */}
          <a href={CAKTO_URL_MENSAL} target="_blank" rel="noopener noreferrer"
            style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'20px 22px', borderRadius:14, border:'1px solid var(--border-strong)', background:'var(--bg-surface)', textDecoration:'none', cursor:'pointer' }}>
            <div>
              <div style={{ fontSize:16, fontWeight:700, color:'var(--fg-primary)' }}>Mensal</div>
              <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:3 }}>Cancele quando quiser</div>
            </div>
            <div style={{ display:'flex', alignItems:'center', gap:16 }}>
              <div style={{ textAlign:'right' }}>
                <div style={{ fontSize:22, fontWeight:800, color:'var(--fg-primary)' }}>R$47</div>
                <div style={{ fontSize:11, color:'var(--fg-muted)' }}>/mês</div>
              </div>
              <div style={{ padding:'9px 18px', borderRadius:8, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', color:'var(--fg-secondary)', fontSize:13, fontWeight:600, whiteSpace:'nowrap' }}>Assinar →</div>
            </div>
          </a>

          {/* Anual */}
          <a href={CAKTO_URL_ANUAL} target="_blank" rel="noopener noreferrer"
            style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'20px 22px', borderRadius:14, border:'2px solid var(--primary)', background:'linear-gradient(135deg,rgba(29,57,196,0.1),transparent)', textDecoration:'none', cursor:'pointer', position:'relative' }}>
            <div style={{ position:'absolute', top:-1, right:18, background:'var(--primary)', color:'#fff', fontSize:9, fontWeight:800, padding:'3px 10px', borderRadius:'0 0 8px 8px', textTransform:'uppercase', letterSpacing:'0.06em' }}>MELHOR OFERTA</div>
            <div>
              <div style={{ fontSize:16, fontWeight:700, color:'var(--geek-blue-200)' }}>Anual</div>
              <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:3 }}>≈ R$33/mês · economize R$167</div>
            </div>
            <div style={{ display:'flex', alignItems:'center', gap:16 }}>
              <div style={{ textAlign:'right' }}>
                <div style={{ fontSize:22, fontWeight:800, color:'var(--geek-blue-200)' }}>R$397</div>
                <div style={{ fontSize:11, color:'var(--fg-muted)' }}>/ano</div>
              </div>
              <div style={{ padding:'9px 18px', borderRadius:8, background:'var(--primary)', color:'#fff', fontSize:13, fontWeight:600, whiteSpace:'nowrap' }}>Assinar →</div>
            </div>
          </a>

          <p style={{ margin:0, fontSize:12, color:'var(--fg-muted)', textAlign:'center' }}>
            Pagamento seguro via Cakto · PIX, cartão e boleto
          </p>

          <div style={{ textAlign:'center' }}>
            <button onClick={onLogin} style={{ background:'transparent', border:'none', color:'var(--geek-blue-300)', fontSize:13, fontWeight:600, cursor:'pointer', textDecoration:'underline' }}>
              Já assinei — entrar no inBrivvo →
            </button>
          </div>
        </div>
      </div>
    );
  }

  // ── Fluxo de cadastro ─────────────────────────────────────────────────────
  return (
    <div className="login-grid" style={{ background: 'var(--bg-app)', color: 'var(--fg-primary)' }}>
      <div className="login-hero"><Hero/></div>
      <div className="login-form" style={{ display: 'flex', flexDirection: 'column', overflow:'auto' }}>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom: 28 }}>
          <button onClick={onBack} style={{ background:'transparent', border:'none', cursor:'pointer', color:'var(--fg-muted)', fontSize:13, display:'inline-flex', alignItems:'center', gap:6, padding:0 }}>
            <Icon d={ICONS.arrowR} size={14} style={{ transform:'rotate(180deg)' }}/> Voltar para entrar
          </button>
          <div style={{ fontFamily:'var(--font-mono)', fontSize:11, color:'var(--fg-muted)' }}>Etapa {step+1} de {stepsLab.length}</div>
        </div>

        <div style={{ width:'100%', maxWidth: 480, alignSelf:'center', flex:1, display:'flex', flexDirection:'column', justifyContent:'center' }}>
          <h2 style={{ margin:0, fontSize:28, fontWeight:700, letterSpacing:'-0.01em' }}>
            {step===0 && 'Crie sua conta'}
            {step===1 && 'Sobre você'}
            {step===2 && 'Quase lá!'}
          </h2>
          <p style={{ margin:'6px 0 24px', color:'var(--fg-muted)', fontSize:14 }}>
            {step===0 && 'Em menos de 2 minutos você está dentro.'}
            {step===1 && 'Personalizamos sua experiência com base nessas respostas.'}
            {step===2 && 'Revise seus dados e aceite os termos para finalizar.'}
          </p>

          <div style={{ display:'flex', gap:6, marginBottom: 28 }}>
            {stepsLab.map((_,i) => (
              <div key={i} style={{ flex:1, height:4, borderRadius:2, background: i<=step ? 'var(--primary)' : 'var(--border-subtle)' }}/>
            ))}
          </div>

          {step===0 && (
            <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
              <Field label="Nome completo" value={form.name} onChange={e=>set('name', e.target.value)} placeholder="Ana Silva"/>
              <Field label="E-mail" icon="msg" value={form.email} onChange={e=>set('email', e.target.value)} placeholder="voce@estudio.com"/>
              <div>
                <Field label="Senha" type="password" value={form.pwd} onChange={e=>set('pwd', e.target.value)} placeholder="Mínimo 6 caracteres"/>
                <div style={{ display:'flex', gap:4, marginTop:8 }}>
                  {[0,1,2,3].map(i => (
                    <div key={i} style={{ flex:1, height:3, borderRadius:2, background: form.pwd.length > i*2 ? (form.pwd.length>=8?'#22C55E':'var(--primary)') : 'var(--border-subtle)' }}/>
                  ))}
                </div>
              </div>
            </div>
          )}

          {step===1 && (
            <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
              <Field label="Nome do estúdio ou empresa" value={form.studio} onChange={e=>set('studio', e.target.value)} placeholder="Estúdio Norte"/>
              <div>
                <div style={{ fontSize:12, fontWeight:600, color:'var(--fg-secondary)', marginBottom:8 }}>Tamanho do time</div>
                <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
                  {SIZES.map(s => (
                    <button key={s} onClick={()=>set('size', s)} style={{
                      padding:'8px 14px', borderRadius:999, fontSize:13, fontWeight:600, cursor:'pointer',
                      background: form.size===s ? 'var(--primary)' : 'var(--bg-surface)',
                      color: form.size===s ? '#fff' : 'var(--fg-secondary)',
                      border:`1px solid ${form.size===s ? 'var(--primary)' : 'var(--border-subtle)'}`,
                    }}>{s}</button>
                  ))}
                </div>
              </div>
              <div>
                <div style={{ fontSize:12, fontWeight:600, color:'var(--fg-secondary)', marginBottom:8 }}>O que você faz? <span style={{ color:'var(--fg-muted)', fontWeight:400 }}>(escolha 1+)</span></div>
                <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
                  {SEGMENTS.map(s => {
                    const on = form.segments.includes(s);
                    return (
                      <button key={s} onClick={()=>toggleSeg(s)} style={{
                        padding:'8px 14px', borderRadius:999, fontSize:13, fontWeight:600, cursor:'pointer',
                        background: on ? 'var(--primary-soft)' : 'var(--bg-surface)',
                        color: on ? 'var(--geek-blue-200)' : 'var(--fg-secondary)',
                        border:`1px solid ${on ? 'var(--geek-blue-a40)' : 'var(--border-subtle)'}`,
                      }}>{s}</button>
                    );
                  })}
                </div>
              </div>
            </div>
          )}

          {step===2 && (
            <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
              <div style={{ padding:18, borderRadius:12, background:'var(--bg-surface)', border:'1px solid var(--border-subtle)' }}>
                <div style={{ display:'grid', gridTemplateColumns:'auto 1fr', gap:'10px 18px', fontSize:13 }}>
                  <span style={{ color:'var(--fg-muted)' }}>Nome</span><strong>{form.name || '—'}</strong>
                  <span style={{ color:'var(--fg-muted)' }}>E-mail</span><strong>{form.email || '—'}</strong>
                  <span style={{ color:'var(--fg-muted)' }}>Estúdio</span><strong>{form.studio || '—'}</strong>
                  <span style={{ color:'var(--fg-muted)' }}>Time</span><strong>{form.size}</strong>
                  <span style={{ color:'var(--fg-muted)' }}>Áreas</span><strong>{form.segments.join(', ') || '—'}</strong>
                </div>
              </div>
              <label style={{ display:'flex', gap:10, alignItems:'flex-start', cursor:'pointer', fontSize:13, color:'var(--fg-secondary)', lineHeight:1.5 }}>
                <input type="checkbox" checked={form.terms} onChange={e=>set('terms', e.target.checked)} style={{ marginTop:3, accentColor:'var(--primary)' }}/>
                <span>Aceito os <button onClick={e=>{e.preventDefault();setLegalTab('termos');}} style={{ background:'none', border:'none', color:'var(--geek-blue-300)', cursor:'pointer', fontFamily:'inherit', fontSize:'inherit', padding:0, textDecoration:'underline' }}>Termos de uso</button> e a <button onClick={e=>{e.preventDefault();setLegalTab('privacidade');}} style={{ background:'none', border:'none', color:'var(--geek-blue-300)', cursor:'pointer', fontFamily:'inherit', fontSize:'inherit', padding:0, textDecoration:'underline' }}>Política de privacidade</button> do inBrivvo.</span>
              </label>
              {error && (
                <div style={{ padding:'10px 14px', borderRadius:8, background:'rgba(255,77,79,0.12)', border:'1px solid rgba(255,77,79,0.3)', color:'#ff4d4f', fontSize:13 }}>
                  {error}
                </div>
              )}
            </div>
          )}

          <div style={{ display:'flex', gap:10, marginTop:28 }}>
            {step>0 && <Button variant="secondary" onClick={()=>setStep(s=>s-1)} style={{ flex:'0 0 auto' }}>Voltar</Button>}
            {step < stepsLab.length-1
              ? <Button size="lg" disabled={!valid[step]} onClick={()=>setStep(s=>s+1)} style={{ flex:1, justifyContent:'center' }}>Avançar →</Button>
              : <Button size="lg" disabled={!valid[step] || loading} onClick={handleCreate} style={{ flex:1, justifyContent:'center' }}>
                  {loading ? 'Criando conta…' : 'Criar conta →'}
                </Button>
            }
          </div>
        </div>

        <div style={{ fontSize:12, color:'var(--fg-muted)', textAlign:'center', marginTop:24 }}>
          Já tem conta? <a href="#" onClick={e=>{ e.preventDefault(); onBack(); }} style={{ color:'var(--geek-blue-300)', fontWeight:600 }}>Entrar</a>
        </div>
      </div>
      {legalTab && <LegalModal tab={legalTab} onClose={() => setLegalTab(null)} />}
    </div>
  );
}

window.Login = Login;
