// Órbita — Auth + Dashboard screens

// ── Recover access modal (magic-link style: e-mail → confirmação) ──
const RecoverAccessModal = ({ onClose }) => {
  const { theme } = useTheme();
  const [email, setEmail] = React.useState('');
  const [sent, setSent] = React.useState(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: 400, 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, display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>×</button>

        {!sent ? (
          <>
            <h3 style={{ margin: '0 0 8px', fontFamily: '"Instrument Serif", serif', fontSize: 22, fontWeight: 400, color: theme.fg }}>
              Recuperar acesso
            </h3>
            <p style={{ margin: '0 0 24px', fontSize: 13, color: theme.fgMuted, lineHeight: 1.6 }}>
              Informe seu e-mail. Enviamos um link para você entrar sem senha.
            </p>
            <form onSubmit={e => { e.preventDefault(); if (email.includes('@')) setSent(true); }} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <Input label="E-mail" value={email} onChange={e => setEmail(e.target.value)} type="email" placeholder="voce@email.com" />
              <BtnPrimary disabled={!email.includes('@')} style={{ width: '100%' }}>Enviar link de acesso</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 }}>
              Link enviado
            </h3>
            <p style={{ margin: '0 0 20px', fontSize: 13, color: theme.fgMuted, lineHeight: 1.6 }}>
              Enviamos um link de acesso para <strong style={{ color: theme.fg }}>{email}</strong>. Ele expira em 15 minutos.
            </p>
            <BtnGhost onClick={onClose} style={{ width: '100%' }}>Voltar ao login</BtnGhost>
          </div>
        )}
      </div>
    </div>
  );
};

const LoginScreen = ({ onLogin, onGoSignup, aviso = null }) => {
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [showRecover, setShowRecover] = React.useState(false);
  const { theme } = useTheme();

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setError(data.error || `Erro ${res.status} ao entrar.`);
        return;
      }
      onLogin(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',
      transition: 'background 0.25s', padding: '32px 20px',
    }}>
      <GrainOverlay />
      <RadialGlow opacity={0.14} top="-100px" />

      {/* Stars / dots BG */}
      <div style={{ position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none' }}>
        {[...Array(40)].map((_, i) => (
          <div key={i} style={{
            position: 'absolute',
            left: `${Math.sin(i * 137.5) * 50 + 50}%`,
            top: `${Math.cos(i * 97.3) * 50 + 50}%`,
            width: i % 5 === 0 ? 2 : 1, height: i % 5 === 0 ? 2 : 1,
            borderRadius: '50%', background: theme.fg,
            opacity: theme.id === 'light' ? 0.06 + (i % 4) * 0.02 : 0.08 + (i % 4) * 0.04,
          }} />
        ))}
      </div>

      <div style={{ width: '100%', maxWidth: 400, position: 'relative', zIndex: 1 }}>
        <div style={{ textAlign: 'center', marginBottom: 48 }}>
          <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, letterSpacing: '-0.01em' }}>
              Órbitas
            </span>
          </div>
          <p style={{ margin: 0, fontSize: 13, color: theme.fgMuted }}>Plataforma para astrólogas profissionais</p>
        </div>

        <Card hover={false} style={{ padding: 32 }}>
          <h2 style={{ margin: '0 0 24px', fontSize: 20, fontFamily: '"Instrument Serif", serif', color: theme.fg, fontWeight: 400 }}>
            Entrar na sua conta
          </h2>
          <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <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="Sua senha" />
            {aviso && !error && (
              <div style={{
                fontSize: 12, color: theme.success, background: `${theme.success}14`,
                border: `1px solid ${theme.success}40`, borderRadius: 10, padding: '9px 12px',
              }}>{aviso}</div>
            )}
            {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>
            )}
            <div style={{ height: 4 }} />
            <BtnPrimary disabled={loading || !email || !password} style={{ width: '100%' }}>
              {loading ? 'Entrando…' : 'Entrar'}
            </BtnPrimary>
          </form>
          <p style={{ margin: '20px 0 0', fontSize: 12, color: theme.fgDim, textAlign: 'center' }}>
            Esqueceu a senha? <span onClick={() => setShowRecover(true)} style={{ color: theme.accent, cursor: 'pointer' }}>Recuperar acesso</span>
          </p>
        </Card>

        <p style={{ textAlign: 'center', marginTop: 24, fontSize: 12, color: theme.fgDim }}>
          Novo por aqui? <span onClick={onGoSignup} style={{ color: theme.accent, cursor: 'pointer' }}>Criar conta</span>
        </p>
      </div>

      {showRecover && <RecoverAccessModal onClose={() => setShowRecover(false)} />}
    </div>
  );
};

// ── Analytics teaser card ──────────────────────────────────
const AnalyticsCard = ({ onClick, A }) => {
  const { theme } = useTheme();
  const [hovered, setHovered] = React.useState(false);
  const bars = A.weekly_visits.slice(-8);
  const max = Math.max(...bars, 1);

  return (
    <Card onClick={onClick} style={{ padding: '20px 22px', marginBottom: 40 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 20, flexWrap: 'wrap' }}>
        <div style={{ flex: '1 1 220px', minWidth: 200 }}>
          <div style={{ fontSize: 11, color: theme.fgMuted, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 8 }}>
            Analytics · engajamento médio
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
            <span style={{ fontSize: 34, fontFamily: '"Instrument Serif", serif', color: theme.fg }}>
              {Math.round(A.totals.avg_engagement * 100)}%
            </span>
            <span style={{ fontSize: 12, color: theme.success, fontWeight: 500 }}>
              {A.totals.check_ins_30d} check-ins · 30d
            </span>
          </div>
        </div>

        {/* Mini sparkline */}
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, height: 40, flex: '0 0 auto' }}>
          {bars.map((v, i) => (
            <div key={i} style={{
              width: 6, borderRadius: 2, background: i === bars.length - 1 ? theme.accent : theme.border,
              height: `${Math.max(10, (v / max) * 100)}%`,
            }} />
          ))}
        </div>

        <div style={{ flex: 1 }} />
        <span style={{
          fontSize: 13, fontWeight: 500, color: theme.accent,
          display: 'flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap',
        }}>
          Ver Analytics
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ transform: hovered ? 'translateX(2px)' : 'none', transition: 'transform 0.15s' }}
            onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)}>
            <path d="M9 18l6-6-6-6"/>
          </svg>
        </span>
      </div>
    </Card>
  );
};

// ── Dashboard ──────────────────────────────────────────────
const DashboardScreen = ({ onNewSession, onOpenSession, onOpenPortal, onOpenSettings, onOpenAnalytics, onOpenConsulentes }) => {
  const { theme } = useTheme();
  const [loadState, setLoadState] = React.useState('loading'); // loading | error | data
  const [astrologer, setAstrologer] = React.useState(null);
  const [sessions, setSessions] = React.useState([]);
  const [consulentes, setConsulentes] = React.useState([]);
  const [analytics, setAnalytics] = React.useState(null);

  const load = React.useCallback(() => {
    setLoadState('loading');
    Promise.all([
      fetch('/api/me').then(r => r.json()),
      fetch('/api/leituras').then(r => r.json()),
      fetch('/api/consulentes').then(r => r.json()),
      fetch('/api/analytics?range=4w').then(r => r.json()).catch(() => null),
    ])
      .then(([me, l, c, a]) => {
        if (me.error || l.error || c.error) throw new Error(me.error || l.error || c.error);
        setAstrologer(me.astrologer);
        setSessions(l.leituras || []);
        setConsulentes(c.consulentes || []);
        setAnalytics(a && !a.error ? a.analytics : null);
        setLoadState('data');
      })
      .catch(() => setLoadState('error'));
  }, []);

  React.useEffect(() => { load(); }, [load]);

  if (loadState === 'loading') {
    return (
      <div style={{ minHeight: '100vh', background: theme.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', color: theme.fgMuted, fontFamily: 'Inter, sans-serif', fontSize: 13 }}>
        Carregando painel…
      </div>
    );
  }
  if (loadState === 'error') {
    return (
      <div style={{ minHeight: '100vh', background: theme.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'Inter, sans-serif' }}>
        <div style={{ textAlign: 'center', maxWidth: 340 }}>
          <div style={{ fontSize: 28, color: theme.hot, marginBottom: 14, fontFamily: '"Instrument Serif", serif' }}>⚠</div>
          <h3 style={{ margin: '0 0 8px', fontSize: 17, color: theme.fg }}>Não foi possível carregar o painel</h3>
          <p style={{ margin: '0 0 18px', fontSize: 13, color: theme.fgMuted }}>Verifique sua conexão e tente novamente.</p>
          <BtnGhost onClick={load}>Tentar novamente</BtnGhost>
        </div>
      </div>
    );
  }

  // Conta genuinamente vazia — nem sessão nem consulente cadastrados ainda.
  if (sessions.length === 0 && consulentes.length === 0) {
    return (
      <EmptyDashboardScreen
        variant="guided"
        astrologer={astrologer}
        onNewSession={onNewSession}
        onAddConsulente={onOpenConsulentes}
        onOpenSettings={onOpenSettings}
      />
    );
  }

  const getConsulente = (id) => consulentes.find(c => c.id === id);
  const statusOrder = { published: 0, ready: 1, draft: 2 };
  const sorted = [...sessions].sort((a, b) => (statusOrder[a.status] ?? 9) - (statusOrder[b.status] ?? 9));

  return (
    <div style={{ minHeight: '100vh', background: theme.bg, fontFamily: 'Inter, sans-serif', color: theme.fg, transition: 'background 0.25s, color 0.25s' }}>
      <GrainOverlay />

      {/* Topo contextual — sem logo (a barra lateral já tem). Só título + conta. */}
      <header className="orbita-shell-header" style={{
        position: 'sticky', top: 0, zIndex: 100,
        background: theme.headerBg,
        backdropFilter: 'blur(16px)',
        borderBottom: `1px solid rgba(255,255,255,0.09)`,
        boxShadow: theme.id === 'light' ? '0 1px 0 rgba(24,20,15,0.12), 0 2px 12px rgba(24,20,15,0.08)' : 'none',
        padding: '0 32px', height: 60,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <style>{`@media (max-width: 899px){ .orbita-shell-header{ padding-left: 64px !important; } }`}</style>
        <span style={{ fontFamily: '"Instrument Serif", serif', fontSize: 19, letterSpacing: '-0.01em', color: '#F5F1E8' }}>Painel</span>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <span style={{ fontSize: 13, color: 'rgba(245,241,232,0.55)' }}>
            Plano <span style={{ color: '#F5F1E8', textTransform: 'capitalize' }}>{astrologer.plan}</span>
          </span>
          <ThemeSwitcher name={astrologer.name} onOpenSettings={onOpenSettings} />
        </div>
      </header>

      <div className="orbita-page" style={{ maxWidth: 1100, margin: '0 auto', padding: '40px 32px 100px' }}>
        <RadialGlow opacity={0.1} top="-80px" />

        {/* Welcome */}
        <div style={{ marginBottom: 40, position: 'relative', zIndex: 1 }}>
          <p style={{ margin: '0 0 4px', fontSize: 12, color: theme.fgMuted, textTransform: 'uppercase', letterSpacing: '0.08em' }}>
            Bem-vinda de volta
          </p>
          <h1 style={{ margin: '0 0 6px', fontSize: 32, fontFamily: '"Instrument Serif", serif', fontWeight: 400, letterSpacing: '-0.01em', color: theme.fg }}>
            {astrologer.name}
          </h1>
          <p style={{ margin: 0, fontSize: 14, color: theme.fgMuted }}>
            {sessions.filter(s => s.status === 'published').length} sessões publicadas ·{' '}
            {sessions.filter(s => s.status === 'ready').length} prontas para revisar
          </p>
        </div>

        {analytics && <AnalyticsCard onClick={onOpenAnalytics} A={analytics} />}

        {/* Stats row */}
        <div className="orbita-stats-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12, marginBottom: 40, position: 'relative', zIndex: 1 }}>
          <style>{`@media (min-width: 640px){ .orbita-stats-grid{ grid-template-columns: repeat(4, 1fr) !important; } }`}</style>
          {[
            { label: 'Consulentes',   value: consulentes.length,                                          colorKey: 'info'    },
            { label: 'Sessões ativas',value: sessions.length,                                             colorKey: 'accent'  },
            { label: 'Publicadas',    value: sessions.filter(s => s.status === 'published').length,       colorKey: 'success' },
            { label: 'Para revisar',  value: sessions.filter(s => s.status === 'ready').length,           colorKey: 'hot'     },
          ].map(stat => (
            <Card key={stat.label} hover={false} style={{ padding: '16px 20px' }}>
              <div style={{ fontSize: 28, fontFamily: '"Instrument Serif", serif', color: theme[stat.colorKey], marginBottom: 4 }}>{stat.value}</div>
              <div style={{ fontSize: 11, color: theme.fgMuted, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{stat.label}</div>
            </Card>
          ))}
        </div>

        {/* Sessions list */}
        <div style={{ position: 'relative', zIndex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
            <h2 style={{ margin: 0, fontSize: 16, fontWeight: 500, color: theme.fg }}>Sessões</h2>
            <BtnPrimary small onClick={onNewSession}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
                <line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>
              </svg>
              Nova sessão
            </BtnPrimary>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {sorted.map(session => {
              const consulente = getConsulente(session.consulente_id) || session.consulente;
              const isPublished = session.status === 'published';
              const isReady = session.status === 'ready';
              const title = session.title || consulente?.name || 'Sessão sem título';
              return (
                <Card key={session.id} onClick={() => onOpenSession(session)} style={{ padding: '18px 22px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                    <Avatar name={consulente?.name || '?'} size={38} color={isPublished ? theme.accent : theme.info} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
                        <span style={{ fontSize: 15, fontWeight: 500, color: theme.fg }}>{title}</span>
                        <Badge status={session.status} />
                      </div>
                      <div style={{ fontSize: 12, color: theme.fgMuted }}>
                        {consulente?.name} · {session.source_type === 'audio' ? '🎙 Áudio' : '📄 Transcrição'} · {
                          new Date(session.created_at).toLocaleDateString('pt-BR', { day: 'numeric', month: 'short' })
                        }
                      </div>
                    </div>
                    <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                      {isPublished && (
                        <BtnGhost small onClick={(e) => { e.stopPropagation(); onOpenPortal(session); }}>
                          Ver portal
                        </BtnGhost>
                      )}
                      {isReady && (
                        <BtnPrimary small onClick={(e) => { e.stopPropagation(); onOpenSession(session); }}>
                          Revisar
                        </BtnPrimary>
                      )}
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={theme.fgDim} strokeWidth="2">
                        <path d="M9 18l6-6-6-6"/>
                      </svg>
                    </div>
                  </div>
                </Card>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { LoginScreen, DashboardScreen });
