// Login + Signup + Forgot + Reset — backend real via /api/auth/*.

function AuthLayout({ children, mode, navigate }) {
  return (
    <div className="m-single-col" style={{ display:'grid', gridTemplateColumns:'1fr 1.1fr', minHeight:'100dvh', background:'var(--bg)' }}>
      <div className="mobile-safe-x" style={{
        display:'flex', flexDirection:'column', justifyContent:'space-between',
        padding: '32px 48px 40px', maxWidth: 560, width:'100%', margin:'0 auto',
        paddingTop: 'calc(20px + var(--safe-top))',
        paddingBottom: 'calc(24px + var(--safe-bottom))',
        minHeight: '100dvh',
      }}>
        <button onClick={() => navigate('#/landing')} style={{ display:'flex', alignItems:'center', gap: 10, padding: 0, alignSelf:'flex-start' }}>
          <AftershotMark />
          <span className="serif" style={{ fontSize: 24 }}>Aftershot</span>
        </button>
        <div style={{ padding: '24px 0' }}>{children}</div>
        <div style={{ fontSize: 12, color:'var(--ink-3)', display:'flex', justifyContent:'space-between', gap: 10, flexWrap:'wrap' }}>
          <span>© 2026 Aftershot</span>
          <span>Ajuda: <a href="mailto:contato@aftershot.com.br" style={{ color:'var(--ink-2)', textDecoration:'underline', textUnderlineOffset: 2 }}>contato@aftershot.com.br</a></span>
        </div>
      </div>

      <div className="m-hide" style={{
        background:'var(--ink)', color:'var(--bg-warm)', position:'relative', overflow:'hidden',
      }}>
        <img src={STOCK.livingRoomBright} alt="" style={{ position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'cover', opacity: .85 }}/>
        <div style={{ position:'absolute', inset:0, background:'linear-gradient(135deg, rgba(31,26,21,.55), rgba(31,26,21,.15))' }}/>
        <div style={{ position:'absolute', bottom: 48, left: 48, right: 48, color:'white' }}>
          <div className="serif" style={{ fontSize: 42, lineHeight: 1.05, maxWidth: 520, letterSpacing:'-0.01em' }}>
            {mode === 'login'
              ? '"Desde que uso Aftershot, minha taxa de ocupação subiu 32%."'
              : 'Suas fotos merecem o mesmo cuidado que sua hospedagem.'}
          </div>
          {mode === 'login' && (
            <div style={{ marginTop: 18, display:'flex', alignItems:'center', gap: 12 }}>
              <div style={{ width: 40, height: 40, borderRadius:'50%', background:'var(--accent)', display:'flex', alignItems:'center', justifyContent:'center', fontWeight: 600 }}>LC</div>
              <div>
                <div style={{ fontWeight: 600, fontSize: 14 }}>Lucas Carvalho</div>
                <div style={{ fontSize: 12, opacity: .75 }}>Anfitrião · 4 imóveis · Florianópolis</div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function useQueryFromHash() {
  const hash = window.location.hash || '';
  const q = hash.split('?')[1] || '';
  return new URLSearchParams(q);
}

function Login({ navigate }) {
  const [email, setEmail] = useState('');
  const [pass, setPass] = useState('');
  const [error, setError] = useState(() => useQueryFromHash().get('error') || '');
  const [loading, setLoading] = useState(false);
  return (
    <AuthLayout mode="login" navigate={navigate}>
      <div style={{ maxWidth: 420 }}>
        <h1 className="serif m-h1" style={{ fontSize: 52, lineHeight: 1, margin: '0 0 12px', letterSpacing:'-0.015em' }}>Entrar</h1>
        <p style={{ color:'var(--ink-3)', margin: '0 0 32px' }}>
          Bom te ver de novo. Suas fotos estão esperando.
        </p>
        <Button variant="secondary" size="lg" style={{ width:'100%', justifyContent:'center' }}
          onClick={() => window.DB.googleLogin()}>
          <GoogleG /> Continuar com Google
        </Button>
        <div style={{ display:'flex', alignItems:'center', gap: 14, margin:'20px 0', color:'var(--ink-4)', fontSize: 12 }}>
          <div style={{ flex:1, height: 1, background:'var(--line)' }}/><span>OU</span><div style={{ flex:1, height: 1, background:'var(--line)' }}/>
        </div>

        {error && <div style={{ padding:'10px 14px', background:'#FDECE7', color:'#7A2E18', borderRadius: 8, fontSize: 13, marginBottom: 14 }}>{error}</div>}

        <form onSubmit={async e => {
          e.preventDefault();
          setLoading(true); setError('');
          try {
            await window.DB.login(email, pass);
            navigate('#/dashboard');
          } catch (err) { setError(err.message); }
          finally { setLoading(false); }
        }} style={{ display:'flex', flexDirection:'column', gap: 14 }}>
          <Field label="E-mail">
            <input type="email" value={email} onChange={e=>setEmail(e.target.value)} placeholder="voce@exemplo.com" style={fieldInput} autoComplete="email"/>
          </Field>
          <Field label="Senha" right={<button type="button" onClick={() => navigate('#/forgot')} style={{ fontSize: 12, color:'var(--ink-3)' }}>Esqueci minha senha</button>}>
            <input type="password" value={pass} onChange={e=>setPass(e.target.value)} placeholder="••••••••" style={fieldInput} autoComplete="current-password"/>
          </Field>
          <Button variant="primary" size="lg" type="submit" disabled={loading} style={{ width:'100%', justifyContent:'center', marginTop: 6 }}>
            {loading ? 'Entrando…' : <>Entrar <Icons.Arrow size={16}/></>}
          </Button>
        </form>

        <div style={{ marginTop: 22, fontSize: 14, color:'var(--ink-3)' }}>
          Ainda não tem conta? <button onClick={() => navigate('#/signup')} style={{ color:'var(--accent)', fontWeight: 500 }}>Criar agora</button>
        </div>
      </div>
    </AuthLayout>
  );
}

function Signup({ navigate }) {
  const [step, setStep] = useState(0);
  const [form, setForm] = useState({ name:'', email:'', pass:'', listings: 1, plan: 'profissional' });
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  return (
    <AuthLayout mode="signup" navigate={navigate}>
      <div style={{ maxWidth: 440 }}>
        <div style={{ display:'flex', gap: 6, marginBottom: 22 }}>
          {[0,1,2].map(i => (
            <div key={i} style={{ flex: 1, height: 3, borderRadius: 2, background: i<=step ? 'var(--accent)' : 'var(--line)' }}/>
          ))}
        </div>
        {step === 0 && (
          <>
            <h1 className="serif m-h1" style={{ fontSize: 48, lineHeight: 1, margin: '0 0 10px', letterSpacing:'-0.015em' }}>
              Criar conta
            </h1>
            <p style={{ color:'var(--ink-3)', margin: '0 0 28px' }}>Escolha um plano e comece a editar em minutos.</p>
            <Button variant="secondary" size="lg" style={{ width:'100%', justifyContent:'center' }}
              onClick={() => window.DB.googleLogin()}>
              <GoogleG/> Continuar com Google
            </Button>
            <div style={{ display:'flex', alignItems:'center', gap: 14, margin:'20px 0', color:'var(--ink-4)', fontSize: 12 }}>
              <div style={{ flex:1, height: 1, background:'var(--line)' }}/><span>OU</span><div style={{ flex:1, height: 1, background:'var(--line)' }}/>
            </div>
            {error && <div style={{ padding:'10px 14px', background:'#FDECE7', color:'#7A2E18', borderRadius: 8, fontSize: 13, marginBottom: 14 }}>{error}</div>}
            <form onSubmit={async (e) => {
              e.preventDefault();
              setLoading(true); setError('');
              try {
                if (!form.name || !form.email || !form.pass) throw new Error('Preencha todos os campos.');
                await window.DB.signup(form);
                setStep(1);
              } catch(err) { setError(err.message); }
              finally { setLoading(false); }
            }} style={{ display:'flex', flexDirection:'column', gap: 14 }}>
              <Field label="Seu nome"><input required style={fieldInput} value={form.name} onChange={e=>setForm({...form,name:e.target.value})} placeholder="Marina Alves" autoComplete="name"/></Field>
              <Field label="E-mail"><input required style={fieldInput} type="email" value={form.email} onChange={e=>setForm({...form,email:e.target.value})} placeholder="voce@exemplo.com" autoComplete="email"/></Field>
              <Field label="Senha"><input required style={fieldInput} type="password" value={form.pass} onChange={e=>setForm({...form,pass:e.target.value})} placeholder="Mínimo 6 caracteres" autoComplete="new-password"/></Field>
              <Button type="submit" variant="primary" size="lg" disabled={loading} style={{ width:'100%', justifyContent:'center', marginTop: 6 }}>
                {loading ? 'Criando conta…' : <>Continuar <Icons.Arrow size={16}/></>}
              </Button>
            </form>
          </>
        )}
        {step === 1 && (
          <>
            <h1 className="serif m-h2" style={{ fontSize: 44, lineHeight: 1, margin: '0 0 10px' }}>Conte sobre seus imóveis</h1>
            <p style={{ color:'var(--ink-3)', margin:'0 0 28px' }}>Assim sugerimos o plano certo — você ajusta depois.</p>
            <Field label="Quantos imóveis você aluga?">
              <div style={{ display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap: 8 }}>
                {[1,2,3,'4+'].map(n => (
                  <button key={n} type="button" onClick={() => setForm({...form, listings: n})}
                    style={{
                      padding:'16px 0', borderRadius: 10, fontSize: 15, fontWeight: 500,
                      border: '1px solid ' + (form.listings===n ? 'var(--ink)' : 'var(--line)'),
                      background: form.listings===n ? 'var(--bg-deep)' : 'var(--paper)',
                      cursor: 'pointer',
                    }}>{n}</button>
                ))}
              </div>
            </Field>
            <div style={{ height: 18 }}/>
            <Field label="Plataforma principal">
              <div style={{ display:'flex', flexWrap:'wrap', gap: 8 }}>
                {['Airbnb','Booking','VRBO','Site próprio','Outro'].map(p => (
                  <button key={p} type="button" onClick={() => setForm({...form, platform: p})}
                    style={{
                      padding:'10px 14px', borderRadius: 999, fontSize: 13,
                      border: '1px solid ' + (form.platform===p ? 'var(--ink)' : 'var(--line-2)'),
                      background: form.platform===p ? 'var(--bg-deep)' : 'var(--paper)',
                      cursor: 'pointer',
                    }}>{p}</button>
                ))}
              </div>
            </Field>
            <Button variant="primary" size="lg" style={{ width:'100%', justifyContent:'center', marginTop: 24 }}
              onClick={async () => {
                const n = form.listings === '4+' ? 4 : Number(form.listings);
                try { await window.DB.updateUser({ listings: n }); } catch {}
                setStep(2);
              }}>
              Continuar <Icons.Arrow size={16}/>
            </Button>
          </>
        )}
        {step === 2 && (
          <>
            <h1 className="serif m-h2" style={{ fontSize: 44, lineHeight: 1, margin: '0 0 10px' }}>Escolha seu pacote de créditos</h1>
            <p style={{ color:'var(--ink-3)', margin:'0 0 24px' }}>Cada crédito edita uma foto. Créditos não expiram.</p>
            <div style={{ display:'flex', flexDirection:'column', gap: 10 }}>
              {PLANS.map(pl => (
                <button key={pl.id} onClick={() => setForm({...form, plan: pl.id})} style={{
                  display:'flex', alignItems:'center', gap: 14, padding: 16, borderRadius: 12, textAlign:'left',
                  border:'1.5px solid ' + (form.plan===pl.id ? 'var(--accent)' : 'var(--line)'),
                  background: form.plan===pl.id ? 'var(--accent-soft)' : 'var(--paper)',
                }}>
                  <div style={{
                    width: 18, height: 18, borderRadius:'50%',
                    border:'2px solid ' + (form.plan===pl.id ? 'var(--accent)' : 'var(--line-2)'),
                    display:'flex', alignItems:'center', justifyContent:'center', flexShrink: 0,
                  }}>
                    {form.plan===pl.id && <div style={{ width: 8, height: 8, borderRadius:'50%', background:'var(--accent)' }}/>}
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ display:'flex', gap: 8, alignItems:'center' }}>
                      <span style={{ fontWeight: 600 }}>{pl.name}</span>
                      {pl.featured && <Pill tone="accent">Popular</Pill>}
                      {pl.enterprise && <Pill tone="accent">Feito pra você</Pill>}
                    </div>
                    <div style={{ fontSize: 13, color:'var(--ink-3)' }}>
                      {pl.enterprise ? 'Você envia, a gente edita em até 24h' : `${pl.credits} créditos · ${pl.credits} fotos`}
                    </div>
                  </div>
                  <div style={{ textAlign:'right' }}>
                    {pl.enterprise ? (
                      <span className="serif" style={{ fontSize: 18 }}>Sob consulta</span>
                    ) : (
                      <>
                        <span className="serif" style={{ fontSize: 26 }}>R$ {pl.price}</span>
                        <div style={{ fontSize: 11, color:'var(--ink-3)' }}>único</div>
                      </>
                    )}
                  </div>
                </button>
              ))}
            </div>
            <Button variant="primary" size="lg" style={{ width:'100%', justifyContent:'center', marginTop: 20 }}
              onClick={async () => {
                try { await window.DB.updateUser({ planName: form.plan }); } catch {}
                navigate(form.plan === 'enterprise' ? '#/contact' : `#/checkout?plan=${form.plan}`);
              }}>
              {form.plan === 'enterprise' ? 'Falar com a gente' : 'Finalizar assinatura'} <Icons.Arrow size={16}/>
            </Button>
            <div style={{ fontSize: 12, color:'var(--ink-4)', textAlign:'center', marginTop: 10 }}>
              Pagamento único. Créditos sem prazo de validade.
            </div>
          </>
        )}
        {step === 0 && (
          <div style={{ marginTop: 22, fontSize: 14, color:'var(--ink-3)' }}>
            Já tem conta? <button onClick={() => navigate('#/login')} style={{ color:'var(--accent)', fontWeight: 500 }}>Entrar</button>
          </div>
        )}
      </div>
    </AuthLayout>
  );
}

function ForgotPassword({ navigate }) {
  const [email, setEmail] = useState('');
  const [sent, setSent] = useState(false);
  const [loading, setLoading] = useState(false);
  return (
    <AuthLayout mode="login" navigate={navigate}>
      <div style={{ maxWidth: 420 }}>
        <h1 className="serif m-h1" style={{ fontSize: 48, lineHeight: 1, margin: '0 0 12px', letterSpacing:'-0.015em' }}>Esqueci a senha</h1>
        <p style={{ color:'var(--ink-3)', margin: '0 0 28px' }}>
          Informe seu e-mail. Se existir uma conta, enviamos um link para redefinir a senha.
        </p>
        {sent ? (
          <div style={{ padding:'16px 18px', background:'#EAF2E4', border:'1px solid var(--olive)', color:'var(--olive)', borderRadius: 12, fontSize: 14 }}>
            Se houver uma conta com esse e-mail, o link foi enviado. Cheque também a caixa de spam.
          </div>
        ) : (
          <form onSubmit={async e => {
            e.preventDefault();
            setLoading(true);
            try { await window.DB.forgotPassword(email); setSent(true); }
            catch {}
            finally { setLoading(false); }
          }} style={{ display:'flex', flexDirection:'column', gap: 14 }}>
            <Field label="E-mail">
              <input type="email" required value={email} onChange={e=>setEmail(e.target.value)} placeholder="voce@exemplo.com" style={fieldInput}/>
            </Field>
            <Button variant="primary" size="lg" type="submit" disabled={loading} style={{ width:'100%', justifyContent:'center', marginTop: 6 }}>
              {loading ? 'Enviando…' : <>Enviar link <Icons.Arrow size={16}/></>}
            </Button>
          </form>
        )}
        <div style={{ marginTop: 22, fontSize: 14, color:'var(--ink-3)' }}>
          <button onClick={() => navigate('#/login')} style={{ color:'var(--accent)', fontWeight: 500 }}>Voltar para o login</button>
        </div>
      </div>
    </AuthLayout>
  );
}

function ResetPassword({ navigate }) {
  const token = useQueryFromHash().get('token') || '';
  const [pass, setPass] = useState('');
  const [pass2, setPass2] = useState('');
  const [error, setError] = useState(token ? '' : 'Token ausente na URL.');
  const [loading, setLoading] = useState(false);
  return (
    <AuthLayout mode="login" navigate={navigate}>
      <div style={{ maxWidth: 420 }}>
        <h1 className="serif m-h1" style={{ fontSize: 48, lineHeight: 1, margin: '0 0 12px', letterSpacing:'-0.015em' }}>Redefinir senha</h1>
        <p style={{ color:'var(--ink-3)', margin: '0 0 28px' }}>Escolha uma nova senha. Você ficará logado ao confirmar.</p>
        {error && <div style={{ padding:'10px 14px', background:'#FDECE7', color:'#7A2E18', borderRadius: 8, fontSize: 13, marginBottom: 14 }}>{error}</div>}
        <form onSubmit={async e => {
          e.preventDefault();
          setError('');
          if (!token) { setError('Token ausente.'); return; }
          if (pass.length < 6) { setError('Senha muito curta (mínimo 6 caracteres).'); return; }
          if (pass !== pass2) { setError('As senhas não conferem.'); return; }
          setLoading(true);
          try {
            await window.DB.resetPassword(token, pass);
            navigate('#/dashboard');
          } catch(err) { setError(err.message); }
          finally { setLoading(false); }
        }} style={{ display:'flex', flexDirection:'column', gap: 14 }}>
          <Field label="Nova senha">
            <input type="password" required value={pass} onChange={e=>setPass(e.target.value)} style={fieldInput} autoComplete="new-password"/>
          </Field>
          <Field label="Repita a senha">
            <input type="password" required value={pass2} onChange={e=>setPass2(e.target.value)} style={fieldInput} autoComplete="new-password"/>
          </Field>
          <Button variant="primary" size="lg" type="submit" disabled={loading} style={{ width:'100%', justifyContent:'center', marginTop: 6 }}>
            {loading ? 'Salvando…' : <>Salvar nova senha <Icons.Arrow size={16}/></>}
          </Button>
        </form>
      </div>
    </AuthLayout>
  );
}

function Field({ label, right, children }) {
  return (
    <label style={{ display:'flex', flexDirection:'column', gap: 6 }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
        <span style={{ fontSize: 13, fontWeight: 500, color:'var(--ink-2)' }}>{label}</span>
        {right}
      </div>
      {children}
    </label>
  );
}

const fieldInput = {
  width:'100%', padding:'13px 14px', borderRadius: 12,
  border:'1px solid var(--line-2)', background:'var(--paper)',
  fontSize: 16, color:'var(--ink)', outline:'none',
  minHeight: 46,
};

function GoogleG() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24">
      <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
      <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
      <path fill="#FBBC05" d="M5.84 14.1c-.22-.66-.35-1.36-.35-2.1s.13-1.44.35-2.1V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.83z"/>
      <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84C6.71 7.31 9.14 5.38 12 5.38z"/>
    </svg>
  );
}

Object.assign(window, { Login, Signup, ForgotPassword, ResetPassword });
