// Órbita — Empty states (primeiro acesso) com 2 variações

const { useState: useStateE } = React;

// Empty dashboard for first-time users (no sessions, no consulentes).
// `astrologer` vem de cima (perfil real, /api/me) quando a tela é alcançada
// pela navegação de verdade; sem ele (atalho de protótipo), cai no mock.
const EmptyDashboardScreen = ({ onNewSession, onOpenSettings, onAddConsulente, onOpenDemo, variant = 'guided', astrologer }) => {
  const { theme } = useTheme();
  astrologer = astrologer || window.ORBITA_DATA.astrologer;

  return (
    <div style={{ minHeight: '100vh', background: theme.bg, color: theme.fg, fontFamily: 'Inter, sans-serif' }}>
      <GrainOverlay />
      <ScreenHeader title="Painel" onOpenSettings={onOpenSettings} />

      <div className="orbita-page" style={{ maxWidth: 1100, margin: '0 auto', padding: '40px 32px 100px', position: 'relative' }}>
        <RadialGlow opacity={0.1} top="-100px" />
        {variant === 'minimal'
          ? <EmptyMinimal astrologer={astrologer} onNewSession={onNewSession} onOpenDemo={onOpenDemo} />
          : <EmptyGuided astrologer={astrologer} onNewSession={onNewSession} onOpenSettings={onOpenSettings} onAddConsulente={onAddConsulente} />}
      </div>
    </div>
  );
};

// Variant 1: Guided onboarding checklist
const EmptyGuided = ({ astrologer, onNewSession, onOpenSettings, onAddConsulente }) => {
  const { theme } = useTheme();
  const firstName = astrologer.name.split(' ')[0];

  const [completed, setCompleted] = useStateE({
    profile: true, brand: false, session: false, share: false,
  });

  const steps = [
    { id: 'profile', title: 'Configurar seu perfil',           desc: 'Nome, foto, biografia que aparece no portal.', cta: 'Já feito',           done: completed.profile },
    { id: 'brand',   title: 'Personalizar a estética',         desc: 'Paleta de cores e tipografia que combina com sua prática.', cta: 'Personalizar', done: completed.brand },
    { id: 'session', title: 'Criar sua primeira sessão',       desc: 'Faça upload de uma gravação. O Órbitas organiza pra você.',     cta: 'Começar',      primary: true, done: completed.session },
    { id: 'share',   title: 'Compartilhar com sua consulente', desc: 'Envie o portal por e-mail ou WhatsApp.',                     cta: 'Mais tarde',   done: completed.share },
  ];

  const doneCount = steps.filter(s => s.done).length;
  const progress = (doneCount / steps.length) * 100;

  return (
    <>
      {/* Hero greeting */}
      <div style={{ marginBottom: 36, position: 'relative', zIndex: 1 }}>
        <p style={{ margin: '0 0 8px', fontSize: 12, color: theme.fgMuted, textTransform: 'uppercase', letterSpacing: '0.12em' }}>
          Bem-vinda ao Órbitas
        </p>
        <h1 style={{ margin: '0 0 14px', fontSize: 44, fontFamily: '"Instrument Serif", serif', fontWeight: 400, letterSpacing: '-0.015em', lineHeight: 1.1 }}>
          Olá, {firstName}.<br/>
          <span style={{ color: theme.fgMuted, fontStyle: 'italic' }}>Vamos começar?</span>
        </h1>
        <p style={{ margin: 0, fontSize: 15, color: theme.fgMuted, maxWidth: 540, lineHeight: 1.6 }}>
          Quatro passos curtos pra colocar sua prática em órbita. Você pode pular qualquer um — o Órbitas continua funcionando enquanto você entende o ritmo.
        </p>
      </div>

      {/* Progress + checklist */}
      <div style={{
        background: theme.card, border: `1px solid ${theme.border}`, borderRadius: 20,
        padding: '28px 32px', marginBottom: 24, position: 'relative', zIndex: 1,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 22 }}>
          <span style={{ fontSize: 12, color: theme.fgMuted, textTransform: 'uppercase', letterSpacing: '0.1em' }}>
            Primeiros passos
          </span>
          <span style={{ fontSize: 12, color: theme.fgMuted, fontFamily: 'DM Mono, monospace' }}>
            {doneCount} de {steps.length}
          </span>
        </div>

        <div style={{ height: 3, background: theme.inputBg, borderRadius: 2, marginBottom: 24, overflow: 'hidden' }}>
          <div style={{
            width: `${progress}%`, height: '100%',
            background: `linear-gradient(90deg, ${theme.accent}, ${theme.hot})`,
            borderRadius: 2, transition: 'width 0.4s ease',
          }} />
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {steps.map((s, i) => (
            <div key={s.id} style={{
              display: 'flex', alignItems: 'center', gap: 18,
              padding: '18px 4px',
              borderTop: i === 0 ? 'none' : `1px solid ${theme.border}`,
              opacity: s.done ? 0.55 : 1,
            }}>
              {/* Step indicator */}
              <div style={{
                width: 32, height: 32, borderRadius: '50%',
                background: s.done ? theme.success : (s.primary ? theme.accent : 'transparent'),
                border: s.done || s.primary ? 'none' : `1.5px solid ${theme.border}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                color: s.done ? '#100D0A' : (s.primary ? '#100D0A' : theme.fgMuted),
                fontFamily: 'DM Mono, monospace', fontSize: 12, fontWeight: 600,
              }}>
                {s.done ? (
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><polyline points="20 6 9 17 4 12"/></svg>
                ) : (i + 1).toString().padStart(2, '0')}
              </div>

              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 15, fontWeight: 500, color: theme.fg, marginBottom: 3, textDecoration: s.done ? 'line-through' : 'none', textDecorationColor: theme.fgDim }}>
                  {s.title}
                </div>
                <div style={{ fontSize: 13, color: theme.fgMuted }}>{s.desc}</div>
              </div>

              {!s.done && (
                s.primary ? (
                  <BtnPrimary small onClick={s.id === 'session' ? onNewSession : () => setCompleted({ ...completed, [s.id]: true })}>
                    {s.cta}
                  </BtnPrimary>
                ) : (
                  <BtnGhost small onClick={s.id === 'brand' ? onOpenSettings : () => setCompleted({ ...completed, [s.id]: true })}>{s.cta}</BtnGhost>
                )
              )}
              {s.done && <span style={{ fontSize: 11, color: theme.success, fontFamily: 'DM Mono, monospace' }}>✓ feito</span>}
            </div>
          ))}
        </div>
      </div>

      {/* Two empty cards */}
      <div className="orbita-empty-cards" style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 14, position: 'relative', zIndex: 1 }}>
        <style>{`@media (min-width: 640px){ .orbita-empty-cards{ grid-template-columns: 1fr 1fr !important; } }`}</style>
        <EmptyCard
          eyebrow="Suas sessões"
          title="Nenhuma sessão ainda"
          desc="Quando você criar uma, ela aparece aqui com status, data e atalhos pro editor."
          ctaPrimary="Criar primeira sessão"
          onCta={onNewSession}
          glyph={
            <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
              <circle cx="20" cy="20" r="2" fill={theme.accent} />
              <circle cx="20" cy="20" r="8" stroke={theme.accent} strokeWidth="0.8" opacity="0.4" fill="none" />
              <circle cx="20" cy="20" r="14" stroke={theme.accent} strokeWidth="0.6" opacity="0.2" fill="none" />
            </svg>
          }
        />
        <EmptyCard
          eyebrow="Suas consulentes"
          title="Sua base está vazia"
          desc="Cadastre uma consulente agora ou ela é criada automaticamente quando você publica a primeira sessão."
          ctaSecondary="Cadastrar consulente"
          onCtaSecondary={onAddConsulente}
          glyph={
            <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
              <circle cx="14" cy="16" r="4" stroke={theme.accent} strokeWidth="1" opacity="0.6" fill="none" />
              <circle cx="26" cy="16" r="4" stroke={theme.accent} strokeWidth="1" opacity="0.4" fill="none" />
              <path d="M6 30 Q20 24 34 30" stroke={theme.accent} strokeWidth="1" opacity="0.4" fill="none" />
            </svg>
          }
        />
      </div>
    </>
  );
};

// Variant 2: Minimal — single hero CTA
// Conta recém-criada: sempre em trial (3 dias ou 3 sessões, o que vier primeiro),
// independente do plano configurado na conta principal do mock.
const DEMO_NEW_ACCOUNT_TRIAL = { active: true, started_at: new Date(Date.now() - 1 * 86400000).toISOString(), sessions_used: 1 };

const EmptyMinimal = ({ astrologer, onNewSession, onOpenDemo }) => {
  const { theme } = useTheme();
  const firstName = astrologer.name.split(' ')[0];
  const trial = getTrialStatus(DEMO_NEW_ACCOUNT_TRIAL);
  return (
    <div style={{ minHeight: '70vh', display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', textAlign: 'center', position: 'relative', zIndex: 1 }}>
      {/* Animated orbit glyph */}
      <div style={{ position: 'relative', width: 180, height: 180, marginBottom: 32 }}>
        <svg viewBox="0 0 180 180" width="180" height="180">
          <style>{`
            @keyframes spin { to { transform: rotate(360deg); } }
            .orb-r1 { transform-origin: 90px 90px; animation: spin 22s linear infinite; }
            .orb-r2 { transform-origin: 90px 90px; animation: spin 38s linear infinite reverse; }
            .orb-r3 { transform-origin: 90px 90px; animation: spin 60s linear infinite; }
          `}</style>
          <circle cx="90" cy="90" r="80" stroke={theme.accent} strokeWidth="0.4" opacity="0.12" fill="none" />
          <circle cx="90" cy="90" r="55" stroke={theme.accent} strokeWidth="0.5" opacity="0.2" fill="none" />
          <circle cx="90" cy="90" r="32" stroke={theme.accent} strokeWidth="0.6" opacity="0.35" fill="none" />
          <g className="orb-r3"><circle cx="170" cy="90" r="2" fill={theme.fgMuted} /></g>
          <g className="orb-r2"><circle cx="145" cy="90" r="2.5" fill={theme.info} /></g>
          <g className="orb-r1"><circle cx="122" cy="90" r="3" fill={theme.hot} /></g>
          <circle cx="90" cy="90" r="8" fill={theme.accent} />
          <circle cx="90" cy="90" r="14" stroke={theme.accent} strokeWidth="0.6" opacity="0.5" fill="none" />
        </svg>
      </div>

      <p style={{ margin: '0 0 12px', fontSize: 12, color: theme.fgMuted, textTransform: 'uppercase', letterSpacing: '0.14em' }}>
        Conta nova
      </p>
      <h1 style={{ margin: '0 0 18px', fontSize: 56, fontFamily: '"Instrument Serif", serif', fontWeight: 400, letterSpacing: '-0.02em', lineHeight: 1.05, maxWidth: 620 }}>
        {firstName}, sua órbita<br/>
        <span style={{ fontStyle: 'italic', color: theme.fgMuted }}>está pronta para começar.</span>
      </h1>
      <p style={{ margin: '0 0 32px', fontSize: 16, color: theme.fgMuted, maxWidth: 460, lineHeight: 1.65 }}>
        Faça upload da sua primeira sessão. Em até 10 minutos, você recebe a transcrição e os cards organizados — prontos pra revisar.
      </p>
      <div style={{ display: 'flex', gap: 12 }}>
        <BtnPrimary onClick={onNewSession}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M12 5v14M5 12h14"/></svg>
          Criar primeira sessão
        </BtnPrimary>
        <BtnGhost onClick={onOpenDemo}>Explorar com sessão demo</BtnGhost>
      </div>

      <p style={{ margin: '48px 0 0', fontSize: 12, color: theme.fgDim, fontFamily: 'DM Mono, monospace' }}>
        Plano <span style={{ color: theme.fgMuted }}>TRIAL</span> · {trial.daysLeft} {trial.daysLeft === 1 ? 'dia restante' : 'dias restantes'} · {trial.sessionsLeft} {trial.sessionsLeft === 1 ? 'sessão restante' : 'sessões restantes'}
      </p>
    </div>
  );
};

const EmptyCard = ({ eyebrow, title, desc, ctaPrimary, ctaSecondary, onCta, onCtaSecondary, glyph }) => {
  const { theme } = useTheme();
  return (
    <div style={{
      background: theme.card, border: `1px dashed ${theme.border}`, borderRadius: 18,
      padding: '28px 28px 26px',
      display: 'flex', flexDirection: 'column', gap: 14,
    }}>
      <div style={{ marginBottom: 4 }}>{glyph}</div>
      <div>
        <p style={{ margin: '0 0 6px', fontSize: 11, color: theme.fgMuted, textTransform: 'uppercase', letterSpacing: '0.1em' }}>{eyebrow}</p>
        <h3 style={{ margin: '0 0 8px', fontSize: 20, fontFamily: '"Instrument Serif", serif', fontWeight: 400 }}>{title}</h3>
        <p style={{ margin: 0, fontSize: 13, color: theme.fgMuted, lineHeight: 1.55 }}>{desc}</p>
      </div>
      <div style={{ marginTop: 'auto', paddingTop: 4 }}>
        {ctaPrimary && <BtnPrimary small onClick={onCta}>{ctaPrimary}</BtnPrimary>}
        {ctaSecondary && <BtnGhost small onClick={onCtaSecondary}>{ctaSecondary}</BtnGhost>}
      </div>
    </div>
  );
};

Object.assign(window, { EmptyDashboardScreen });
