// Órbita — Additional flows (cadastro, verificação, consulente CRUD mocks, termos)

// ── Terms / Privacy Modal ──────────────────────────────────
const TermsModal = ({ onClose, initialTab = 'termos' }) => {
  const { theme } = useTheme();
  const [tab, setTab] = React.useState(initialTab);
  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(16,13,10,0.75)', backdropFilter:'blur(6px)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:5000, padding:20 }} onClick={onClose}>
      <div onClick={e=>e.stopPropagation()} style={{ width:'100%', maxWidth:560, maxHeight:'82vh', overflowY:'auto', background: theme.surface, border:`1px solid ${theme.border}`, borderRadius:20, padding:32, position:'relative' }}>
        <button onClick={onClose} style={{ position:'absolute', top:16, right:16, background:theme.inputBg, border:'none', borderRadius:'50%', width:26, height:26, color:theme.fgMuted, cursor:'pointer', fontSize:14 }}>×</button>
        <div style={{ display:'flex', gap:8, marginBottom:20 }}>
          {[{id:'termos',label:'Termos de Uso'},{id:'privacidade',label:'Privacidade & LGPD'}].map(t => (
            <button key={t.id} onClick={()=>setTab(t.id)} style={{ padding:'7px 14px', borderRadius:999, border:'none', fontSize:12, fontWeight:500, cursor:'pointer', fontFamily:'Inter, sans-serif', background: tab===t.id?`${theme.accent}18`:theme.inputBg, color: tab===t.id?theme.accent:theme.fgMuted }}>{t.label}</button>
          ))}
        </div>
        {tab === 'termos' ? (
          <div>
            <h3 style={{ margin:'0 0 14px', fontFamily:'"Instrument Serif", serif', fontSize:22, fontWeight:400, color:theme.fg }}>Termos de Uso</h3>
            <div style={{ fontSize:13, color:theme.fgMuted, lineHeight:1.7, display:'flex', flexDirection:'column', gap:12 }}>
              <p>Ao usar o Órbitas, você concorda em publicar conteúdo gerado a partir de sessões de consulentes que autorizaram o uso da ferramenta.</p>
              <p>A astróloga é responsável pela revisão e aprovação de todo conteúdo antes da publicação no portal. O Órbitas não se responsabiliza por interpretações astrológicas geradas automaticamente sem revisão humana.</p>
              <p>O plano contratado define o número de sessões processadas por mês. Sessões excedentes exigem upgrade de plano.</p>
              <p>Contas inativas por mais de 12 meses podem ter os dados arquivados, com aviso prévio por e-mail.</p>
            </div>
          </div>
        ) : (
          <div>
            <h3 style={{ margin:'0 0 14px', fontFamily:'"Instrument Serif", serif', fontSize:22, fontWeight:400, color:theme.fg }}>Privacidade & LGPD</h3>
            <div style={{ fontSize:13, color:theme.fgMuted, lineHeight:1.7, display:'flex', flexDirection:'column', gap:12 }}>
              <p>Coletamos dados de contato e nascimento das consulentes exclusivamente para gerar o conteúdo astrológico solicitado pela astróloga.</p>
              <p>Áudios enviados são processados e descartados após a transcrição — não armazenamos o arquivo original, apenas o texto gerado.</p>
              <p>Consulentes podem solicitar a exclusão de seus dados e sessões a qualquer momento, diretamente com a astróloga ou pelo suporte.</p>
              <p>Você pode exportar ou apagar todos os dados da sua conta em Configurações → Conta.</p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// ── Signup Screen ───────────────────────────────────────────
const SignupScreen = ({ onComplete, onBack }) => {
  const { theme } = useTheme();
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [accepted, setAccepted] = React.useState(false);
  const [showTerms, setShowTerms] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const valid = name.trim().length > 1 && email.includes('@') && password.length >= 8 && accepted;

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!valid) return;
    setLoading(true);
    setError(null);
    try {
      const res = await fetch('/api/auth/signup', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: name.trim(), email, password }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setError(data.error || `Erro ${res.status} ao criar conta.`);
        return;
      }
      // 202: a conta existe mas ainda não está confirmada, e não há sessão. Quem
      // entra é quem clica no link do e-mail (ver app/api/auth/signup/route.ts).
      onComplete(data.pendente ? { pendente: true, email: data.email || email } : data.user);
    } catch {
      setError('Falha de rede. Confira sua conexão e tente de novo.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ minHeight:'100vh', background: theme.bg, display:'flex', alignItems:'center', justifyContent:'center', fontFamily:'Inter, sans-serif', position:'relative', overflow:'hidden', padding: '32px 20px' }}>
      <GrainOverlay />
      <RadialGlow opacity={0.14} top="-100px" />
      <div style={{ width: '100%', maxWidth: 400, position:'relative', zIndex:1 }}>
        <div style={{ textAlign:'center', marginBottom:40 }}>
          <div style={{ display:'inline-flex', alignItems:'center', gap:10, marginBottom:8 }}>
            <OrbitasMark size={34} color={theme.gold} />
            <span style={{ fontFamily:'"Instrument Serif", serif', fontSize:28, color:theme.fg }}>Órbitas</span>
          </div>
          <p style={{ margin:0, fontSize:13, color:theme.fgMuted }}>Criar sua conta</p>
        </div>
        <Card hover={false} style={{ padding:32 }}>
          <form onSubmit={handleSubmit} style={{ display:'flex', flexDirection:'column', gap:16 }}>
            <Input label="Nome completo" value={name} onChange={e=>setName(e.target.value)} placeholder="Seu nome" />
            <Input label="E-mail" value={email} onChange={e=>setEmail(e.target.value)} type="email" placeholder="voce@email.com" />
            <Input label="Senha" value={password} onChange={e=>setPassword(e.target.value)} type="password" placeholder="Mínimo 8 caracteres" />
            {/* Duas linhas: "Li e aceito os Termos de Uso" em cima, a política
                embaixo. Numa linha só, cada pedaço do texto vira item de flex e
                o espaçamento quebra. */}
            <label style={{ display:'block', fontSize:12, color:theme.fgMuted, cursor:'pointer', lineHeight:1.5 }}>
              <span style={{ display:'flex', gap:8, alignItems:'center' }}>
                <input type="checkbox" checked={accepted} onChange={e=>setAccepted(e.target.checked)} />
                {/* Texto dentro de um span só: o gap do flex separa o check do texto,
                    e não cada palavra. */}
                <span>Li e aceito os <span onClick={e=>{e.preventDefault(); setShowTerms('termos');}} style={{ color:theme.accent, cursor:'pointer' }}>Termos de Uso</span></span>
              </span>
              <span style={{ display:'block', marginTop:3, paddingLeft:21 }}>
                e a <span onClick={e=>{e.preventDefault(); setShowTerms('privacidade');}} style={{ color:theme.accent, cursor:'pointer' }}>Política de Privacidade</span>.
              </span>
            </label>
            {error && (
              <div style={{
                fontSize: 12, color: theme.hot, background: `${theme.hot}14`,
                border: `1px solid ${theme.hot}40`, borderRadius: 10, padding: '9px 12px',
              }}>{error}</div>
            )}
            <BtnPrimary disabled={!valid || loading} style={{ width:'100%', marginTop:4 }}>{loading?'Criando conta…':'Criar conta'}</BtnPrimary>
          </form>
        </Card>
        <p style={{ textAlign:'center', marginTop:24, fontSize:12, color:theme.fgDim }}>
          Já tem conta? <span onClick={onBack} style={{ color:theme.accent, cursor:'pointer' }}>Entrar</span>
        </p>
      </div>
      {showTerms && <TermsModal initialTab={showTerms} onClose={()=>setShowTerms(null)} />}
    </div>
  );
};

// ── Email verification screen ───────────────────────────────
// Fim do cadastro: a conta existe, não confirmada, e o link já saiu por e-mail.
// Não há botão de "simular": quem confirma é o link, e depois a astróloga entra
// pela tela de login com a senha que acabou de criar.
const EmailVerifyScreen = ({ onVerified, email = 'voce@email.com' }) => {
  const { theme } = useTheme();
  const [resent, setResent] = React.useState(false);
  return (
    <div style={{ minHeight:'100vh', background: theme.bg, display:'flex', alignItems:'center', justifyContent:'center', fontFamily:'Inter, sans-serif', position:'relative', padding: '32px 20px' }}>
      <GrainOverlay />
      <RadialGlow opacity={0.12} top="-100px" />
      <Card hover={false} style={{ padding:36, width: '100%', maxWidth: 400, textAlign:'center', position:'relative', zIndex:1, boxSizing: 'border-box' }}>
        <div style={{ width:52, height:52, borderRadius:'50%', margin:'0 auto 18px', background:`${theme.info}18`, display:'flex', alignItems:'center', justifyContent:'center', fontSize:22, color:theme.info }}>✉</div>
        <h2 style={{ margin:'0 0 10px', fontFamily:'"Instrument Serif", serif', fontSize:22, fontWeight:400, color:theme.fg }}>Confirme seu e-mail</h2>
        <p style={{ margin:'0 0 24px', fontSize:13, color:theme.fgMuted, lineHeight:1.6 }}>
          Enviamos um link de confirmação para <strong style={{ color:theme.fg }}>{email}</strong>. Clique nele pra ativar sua conta e depois entre com a senha que você criou.
        </p>
        <p style={{ margin:'0 0 24px', fontSize:12, color:theme.fgDim, lineHeight:1.6 }}>
          O link vale por 24 horas. Se não chegar em alguns minutos, olhe o spam.
        </p>
        <BtnPrimary onClick={onVerified} style={{ width:'100%', marginBottom:12 }}>Ir para o login</BtnPrimary>
      </Card>
    </div>
  );
};

// ── Consulente form modal (add / edit) ─────────────────────
const ConsulenteFormModal = ({ onClose, onSaved, initial = null }) => {
  const { theme } = useTheme();
  const [name, setName] = React.useState(initial?.name || '');
  const [email, setEmail] = React.useState(initial?.email || '');
  const [phone, setPhone] = React.useState(initial?.phone || '');
  const [birthDate, setBirthDate] = React.useState(initial?.birth_date || '');
  const [birthTime, setBirthTime] = React.useState(initial?.birth_time || '');
  const [birthCity, setBirthCity] = React.useState(initial?.birth_city || '');
  const [saved, setSaved] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState(null);
  const valid = name.trim().length > 1 && email.includes('@');

  // Cadastro/edição de verdade — POST ou PATCH em /api/consulentes (ver
  // lib/consulentes.ts). Só mostra "salvo" depois da API confirmar; antes
  // disso o modal mostrava sucesso sem nunca ter chamado a API.
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!valid || saving) return;
    setSaving(true);
    setError(null);
    try {
      const payload = {
        name: name.trim(),
        email: email.trim(),
        phone: phone.trim() || undefined,
        birth_date: birthDate || undefined,
        birth_time: birthTime || undefined,
        birth_city: birthCity.trim() || undefined,
      };
      const url = initial ? `/api/consulentes/${initial.id}` : '/api/consulentes';
      const method = initial ? 'PATCH' : 'POST';
      const res = await fetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.consulente) throw new Error(data.error || 'Não foi possível salvar.');
      setSaved(true);
      onSaved && onSaved(data.consulente);
    } catch (err) {
      setError(err.message || 'Falha de rede ao salvar.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(16,13,10,0.7)', backdropFilter:'blur(6px)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:4000, padding:20 }} onClick={onClose}>
      <div onClick={e=>e.stopPropagation()} style={{ width:'100%', maxWidth:440, background:theme.surface, border:`1px solid ${theme.border}`, borderRadius:20, padding:32, position:'relative' }}>
        <button onClick={onClose} style={{ position:'absolute', top:16, right:16, background:theme.inputBg, border:'none', borderRadius:'50%', width:26, height:26, color:theme.fgMuted, cursor:'pointer', fontSize:14 }}>×</button>
        {!saved ? (
          <>
            <h3 style={{ margin:'0 0 20px', fontFamily:'"Instrument Serif", serif', fontSize:22, fontWeight:400, color:theme.fg }}>{initial ? 'Editar consulente' : 'Nova consulente'}</h3>
            <form onSubmit={handleSubmit} style={{ display:'flex', flexDirection:'column', gap:14 }}>
              <Input label="Nome completo" value={name} onChange={e=>setName(e.target.value)} placeholder="Nome da consulente" />
              <Input label="E-mail" value={email} onChange={e=>setEmail(e.target.value)} type="email" placeholder="consulente@email.com" />
              <Input label="Telefone" value={phone} onChange={e=>setPhone(e.target.value)} placeholder="(00) 00000-0000" />
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
                <Input label="Nascimento" value={birthDate} onChange={e=>setBirthDate(e.target.value)} type="date" />
                <Input label="Hora" value={birthTime} onChange={e=>setBirthTime(e.target.value)} type="time" />
              </div>
              <Input label="Cidade de nascimento" value={birthCity} onChange={e=>setBirthCity(e.target.value)} placeholder="Cidade, UF" />
              {error && <p style={{ margin: 0, fontSize: 12, color: theme.hot }}>{error}</p>}
              <BtnPrimary disabled={!valid || saving} style={{ width:'100%', marginTop:6 }}>
                {saving ? 'Salvando…' : initial ? 'Salvar alterações' : 'Cadastrar consulente'}
              </BtnPrimary>
            </form>
          </>
        ) : (
          <div style={{ textAlign:'center', padding:'8px 0' }}>
            <div style={{ width:52, height:52, borderRadius:'50%', margin:'0 auto 16px', background:`${theme.success}18`, display:'flex', alignItems:'center', justifyContent:'center', fontSize:22, color:theme.success }}>✓</div>
            <h3 style={{ margin:'0 0 8px', fontFamily:'"Instrument Serif", serif', fontSize:20, fontWeight:400, color:theme.fg }}>{initial ? 'Alterações salvas' : 'Consulente cadastrada'}</h3>
            <p style={{ margin:'0 0 20px', fontSize:13, color:theme.fgMuted }}><strong style={{ color:theme.fg }}>{name}</strong> {initial ? 'foi atualizada.' : 'já está na sua base.'}</p>
            <BtnGhost onClick={onClose} style={{ width:'100%' }}>Fechar</BtnGhost>
          </div>
        )}
      </div>
    </div>
  );
};

// ── CSV import modal ────────────────────────────────────────
const ImportCsvModal = ({ onClose }) => {
  const { theme } = useTheme();
  const [fileName, setFileName] = React.useState(null);
  const [imported, setImported] = React.useState(false);
  const mockRows = [
    { name: 'Beatriz Nogueira', email: 'bea.nogueira@gmail.com' },
    { name: 'Rafael Torres', email: 'rafael.torres@gmail.com' },
    { name: 'Carla Menezes', email: 'carla.menezes@gmail.com' },
  ];
  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(16,13,10,0.7)', backdropFilter:'blur(6px)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:4000, padding:20 }} onClick={onClose}>
      <div onClick={e=>e.stopPropagation()} style={{ width:'100%', maxWidth:460, background:theme.surface, border:`1px solid ${theme.border}`, borderRadius:20, padding:32, position:'relative' }}>
        <button onClick={onClose} style={{ position:'absolute', top:16, right:16, background:theme.inputBg, border:'none', borderRadius:'50%', width:26, height:26, color:theme.fgMuted, cursor:'pointer', fontSize:14 }}>×</button>
        {!imported ? (
          <>
            <h3 style={{ margin:'0 0 8px', fontFamily:'"Instrument Serif", serif', fontSize:22, fontWeight:400, color:theme.fg }}>Importar consulentes</h3>
            <p style={{ margin:'0 0 20px', fontSize:13, color:theme.fgMuted, lineHeight:1.6 }}>Envie um CSV com nome e e-mail (uma linha por consulente).</p>
            <div onClick={() => setFileName('consulentes-notion.csv')} style={{
              borderRadius:14, border:`2px dashed ${fileName ? theme.success : theme.border}`, padding:'28px 18px', textAlign:'center',
              cursor:'pointer', background: fileName ? `${theme.success}0a` : theme.inputBg, marginBottom:18,
            }}>
              {fileName ? (
                <><div style={{ fontSize:24, marginBottom:6 }}>✓</div><div style={{ fontSize:13, color:theme.success }}>{fileName}</div></>
              ) : (
                <><div style={{ fontSize:24, marginBottom:6, opacity:0.5 }}>📄</div><div style={{ fontSize:13, color:theme.fgMuted }}>Clique para selecionar um .csv</div></>
              )}
            </div>
            {fileName && (
              <div style={{ border:`1px solid ${theme.border}`, borderRadius:12, overflow:'hidden', marginBottom:20 }}>
                {mockRows.map((r,i) => (
                  <div key={r.email} style={{ display:'flex', justifyContent:'space-between', padding:'9px 14px', fontSize:12, color:theme.fgMuted, borderBottom: i<mockRows.length-1?`1px solid ${theme.border}`:'none' }}>
                    <span style={{ color:theme.fg }}>{r.name}</span><span>{r.email}</span>
                  </div>
                ))}
              </div>
            )}
            <BtnPrimary disabled={!fileName} onClick={() => setImported(true)} style={{ width:'100%' }}>Importar {fileName ? `${mockRows.length} consulentes` : ''}</BtnPrimary>
          </>
        ) : (
          <div style={{ textAlign:'center', padding:'8px 0' }}>
            <div style={{ width:52, height:52, borderRadius:'50%', margin:'0 auto 16px', background:`${theme.success}18`, display:'flex', alignItems:'center', justifyContent:'center', fontSize:22, color:theme.success }}>✓</div>
            <h3 style={{ margin:'0 0 8px', fontFamily:'"Instrument Serif", serif', fontSize:20, fontWeight:400, color:theme.fg }}>{mockRows.length} consulentes importadas</h3>
            <p style={{ margin:'0 0 20px', fontSize:13, color:theme.fgMuted }}>Elas já aparecem na sua lista de consulentes.</p>
            <BtnGhost onClick={onClose} style={{ width:'100%' }}>Fechar</BtnGhost>
          </div>
        )}
      </div>
    </div>
  );
};

// ── Delete consulente (LGPD) modal ─────────────────────────
const DeleteConsulenteModal = ({ consulente, onClose, onDeleted }) => {
  const { theme } = useTheme();
  const [confirmText, setConfirmText] = React.useState('');
  const [deleted, setDeleted] = React.useState(false);
  const [deleting, setDeleting] = React.useState(false);
  const [error, setError] = React.useState(null);
  const valid = confirmText.trim().toLowerCase() === consulente.name.trim().toLowerCase();

  // Exclusão de verdade — DELETE /api/consulentes/[id] (lib/consulentes.ts
  // remove a linha, não é soft-delete). Antes, "Excluir definitivamente" só
  // mudava um estado local; o cadastro continuava no banco.
  const handleDelete = async () => {
    if (!valid || deleting) return;
    setDeleting(true);
    setError(null);
    try {
      const res = await fetch(`/api/consulentes/${consulente.id}`, { method: 'DELETE' });
      if (!res.ok && res.status !== 204) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || 'Não foi possível excluir.');
      }
      setDeleted(true);
      onDeleted && onDeleted();
    } catch (err) {
      setError(err.message || 'Falha de rede ao excluir.');
    } finally {
      setDeleting(false);
    }
  };

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(16,13,10,0.75)', backdropFilter:'blur(6px)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:4500, padding:20 }} onClick={onClose}>
      <div onClick={e=>e.stopPropagation()} style={{ width:'100%', maxWidth:420, background:theme.surface, border:`1px solid ${theme.hot}40`, borderRadius:20, padding:32, position:'relative' }}>
        <button onClick={onClose} style={{ position:'absolute', top:16, right:16, background:theme.inputBg, border:'none', borderRadius:'50%', width:26, height:26, color:theme.fgMuted, cursor:'pointer', fontSize:14 }}>×</button>
        {!deleted ? (
          <>
            <h3 style={{ margin:'0 0 10px', fontFamily:'"Instrument Serif", serif', fontSize:20, fontWeight:400, color:theme.hot }}>Excluir consulente e dados</h3>
            <p style={{ margin:'0 0 16px', fontSize:13, color:theme.fgMuted, lineHeight:1.6 }}>
              Isso apaga para sempre o cadastro de <strong style={{ color:theme.fg }}>{consulente.name}</strong> e todas as leituras, check-ins e acessos ao portal dela. Os links já enviados param de abrir. Não pode ser desfeito.
            </p>
            <p style={{ margin:'0 0 8px', fontSize:12, color:theme.fgMuted }}>Digite o nome da consulente para confirmar:</p>
            <Input value={confirmText} onChange={e=>setConfirmText(e.target.value)} placeholder={consulente.name} style={{ marginBottom:12 }} />
            {error && <p style={{ margin: '0 0 12px', fontSize: 12, color: theme.hot }}>{error}</p>}
            <div style={{ display:'flex', gap:8 }}>
              <BtnGhost onClick={onClose} style={{ flex:1 }}>Cancelar</BtnGhost>
              <button disabled={!valid || deleting} onClick={handleDelete} style={{
                flex:1, padding:'11px 0', borderRadius:999, border:'none', cursor: valid && !deleting ?'pointer':'not-allowed',
                background: valid ? theme.hot : `${theme.hot}30`, color: valid ? '#100D0A' : theme.fgDim,
                fontFamily:'Inter, sans-serif', fontWeight:600, fontSize:13,
              }}>{deleting ? 'Excluindo…' : 'Excluir definitivamente'}</button>
            </div>
          </>
        ) : (
          <div style={{ textAlign:'center', padding:'8px 0' }}>
            <div style={{ width:52, height:52, borderRadius:'50%', margin:'0 auto 16px', background:`${theme.success}18`, display:'flex', alignItems:'center', justifyContent:'center', fontSize:22, color:theme.success }}>✓</div>
            <h3 style={{ margin:'0 0 8px', fontFamily:'"Instrument Serif", serif', fontSize:18, fontWeight:400, color:theme.fg }}>Dados excluídos</h3>
            <BtnGhost onClick={onClose} style={{ width:'100%' }}>Fechar</BtnGhost>
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { TermsModal, SignupScreen, EmailVerifyScreen, ConsulenteFormModal, ImportCsvModal, DeleteConsulenteModal });
