/* Área do Aluno — telas */

// ============ LOGIN ============
function LoginScreen({ onLogin }) {
  const [email, setEmail] = React.useState('ana.mendes@email.com');
  const [senha, setSenha] = React.useState('••••••••');
  const [showPass, setShowPass] = React.useState(false);

  return (
    <div style={{
      minHeight: '100vh',
      display: 'grid',
      gridTemplateColumns: '1fr 1fr',
      background: 'var(--fc-azul-profundo)',
    }}>
      {/* Left: hero image */}
      <div style={{
        position: 'relative',
        background: `linear-gradient(135deg, rgba(15,27,51,0.85), rgba(27,42,74,0.4)), url(${FC_ASSETS.hero}) center/cover`,
        display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
        padding: 48,
        color: 'var(--fc-white)',
      }}>
        <BrandLockup dark size="lg" />
        <div>
          <div style={{ fontSize: 13, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--fc-dourado)', marginBottom: 18, fontWeight: 600 }}>
            Prof. Vinícius Ferraz
          </div>
          <div style={{ fontSize: 36, fontWeight: 700, lineHeight: 1.15, letterSpacing: '-0.02em', marginBottom: 16, maxWidth: 480 }}>
            Contabilidade é um idioma. Aqui você aprende a falar.
          </div>
          <div style={{ fontSize: 15, color: 'rgba(255,255,255,0.7)', maxWidth: 440, lineHeight: 1.55 }}>
            Auditor Fiscal do Município do Rio de Janeiro. 36 aulas, 3 bônus, mentoria semanal no plano anual.
          </div>
        </div>
        <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.45)', letterSpacing: '0.08em' }}>
          fluenciacontabil.com.br · @prof.viniciusferraz
        </div>
      </div>

      {/* Right: form */}
      <div style={{ background: 'var(--fc-cream)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 48 }}>
        <div style={{ width: '100%', maxWidth: 380 }}>
          <div className="fc-h2" style={{ marginBottom: 6 }}>Entrar na plataforma</div>
          <div className="fc-body" style={{ marginBottom: 28, color: 'var(--fc-gray-600)' }}>
            Use o e-mail que você cadastrou no momento da compra.
          </div>

          <label className="fc-label">E-mail</label>
          <input className="fc-input" type="email" value={email} onChange={e => setEmail(e.target.value)} />

          <div style={{ height: 14 }} />

          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <label className="fc-label">Senha</label>
            <a className="fc-small" style={{ color: 'var(--fc-azul-medio)', cursor: 'pointer' }}>Esqueci minha senha</a>
          </div>
          <div style={{ position: 'relative' }}>
            <input className="fc-input" type={showPass ? 'text' : 'password'} value={senha} onChange={e => setSenha(e.target.value)} style={{ paddingRight: 40 }} />
            <button onClick={() => setShowPass(!showPass)} style={{ position: 'absolute', right: 10, top: 9, color: 'var(--fc-gray-500)' }}>
              {showPass ? <I.eyeOff size={18} /> : <I.eye size={18} />}
            </button>
          </div>

          <button className="fc-btn fc-btn-primary fc-btn-block fc-btn-lg" style={{ marginTop: 24 }} onClick={onLogin}>
            Entrar
          </button>

          <div style={{ margin: '28px 0 20px', textAlign: 'center', fontSize: 12, color: 'var(--fc-gray-500)', position: 'relative' }}>
            <div style={{ position: 'absolute', left: 0, right: 0, top: '50%', borderTop: '1px solid var(--fc-gray-200)', zIndex: 0 }} />
            <span style={{ background: 'var(--fc-cream)', padding: '0 12px', position: 'relative', zIndex: 1 }}>ou</span>
          </div>

          <div className="fc-small" style={{ textAlign: 'center' }}>
            Ainda não é aluno?{' '}
            <a style={{ color: 'var(--fc-azul-profundo)', fontWeight: 600, borderBottom: '1px solid var(--fc-dourado)', cursor: 'pointer' }}>
              Conheça a Fluência →
            </a>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============ DASHBOARD DO ALUNO ============
function AlunoDashboard({ user, state, onNavigate, onOpenAula }) {
  const greeting = (() => {
    const h = new Date().getHours();
    if (h < 12) return 'Bom dia';
    if (h < 18) return 'Boa tarde';
    return 'Boa noite';
  })();

  const concluidas = FC_AULAS_CONCLUIDAS[user.id] || [];
  const totalAulas = FC_AULAS.length;
  const pctProgresso = state.progressoOverride != null ? state.progressoOverride : Math.round((concluidas.length / totalAulas) * 100);

  // "Continue de onde parou" — última aula não concluída que é acessível
  const proxAula = FC_AULAS.find(a => !concluidas.includes(a.id)) || FC_AULAS[0];

  const showRenewBanner = state.proximoVencimento || (user.acessoAtivo && user.diasAteExpiracao <= 15 && user.diasAteExpiracao > 0);
  const expirado = !user.acessoAtivo;

  // Módulos com progresso
  const modulosStats = FC_MODULOS.map(m => {
    const aulasMod = FC_AULAS.filter(a => a.modulo === m.id);
    const concMod = aulasMod.filter(a => concluidas.includes(a.id)).length;
    const bloqueado = m.bloqueadoDiasApos > 0 && user.diasDesdeCadastro < m.bloqueadoDiasApos;
    const diasFaltando = bloqueado ? m.bloqueadoDiasApos - user.diasDesdeCadastro : 0;
    return { ...m, total: aulasMod.length, concluidas: concMod, pct: Math.round((concMod / aulasMod.length) * 100), bloqueado, diasFaltando };
  });

  if (expirado) {
    return <AcessoExpirado user={user} />;
  }

  return (
    <div className="fc-stack fc-gap-6">
      {/* Renewal banner */}
      {showRenewBanner && (
        <div style={{
          background: 'var(--fc-warning-bg)',
          border: '1px solid rgba(184,134,11,0.3)',
          borderRadius: 'var(--fc-r-lg)',
          padding: '14px 20px',
          display: 'flex', alignItems: 'center', gap: 14,
        }}>
          <div style={{ color: 'var(--fc-warning)' }}><I.alert size={22} /></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fc-gray-800)' }}>
              Seu acesso vence em {user.diasAteExpiracao} dias
            </div>
            <div className="fc-small">
              Renove com antecedência para não perder seu progresso nem interromper os estudos.
            </div>
          </div>
          <button className="fc-btn fc-btn-primary fc-btn-sm">Renovar acesso</button>
        </div>
      )}

      {/* Greeting */}
      <div>
        <div className="fc-h1">
          {greeting}, {user.primeiroNome}. Bora estudar?
        </div>
        <div className="fc-body" style={{ color: 'var(--fc-gray-600)', marginTop: 6 }}>
          Você está focando em <strong style={{ color: 'var(--fc-azul-profundo)' }}>{user.concursoFocado}</strong>.
          Mais {totalAulas - concluidas.length} aulas até o certificado.
        </div>
      </div>

      {/* Continue de onde parou + stats lateral */}
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 20 }}>
        <Card style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '280px 1fr', minHeight: 200 }}>
            <div className="fc-video-placeholder" style={{ borderRadius: 0, aspectRatio: 'auto', height: '100%' }}>
              <div className="fc-video-meta">Aula {proxAula.num}</div>
              <div className="fc-video-play" style={{ width: 56, height: 56 }}><I.play size={22} fill="#1B2A4A" /></div>
            </div>
            <div style={{ padding: '24px 28px', display: 'flex', flexDirection: 'column' }}>
              <div className="fc-overline" style={{ color: 'var(--fc-dourado-escuro)' }}>Continue de onde parou</div>
              <div className="fc-h3" style={{ marginTop: 8, marginBottom: 6 }}>{proxAula.titulo}</div>
              <div className="fc-small" style={{ marginBottom: 14 }}>
                Módulo {FC_MODULOS.find(m => m.id === proxAula.modulo)?.numero} · {proxAula.duracao}
              </div>
              <div style={{ marginTop: 'auto', display: 'flex', gap: 10 }}>
                <button className="fc-btn fc-btn-primary" onClick={() => onOpenAula(proxAula.id)}>
                  <I.play size={16} fill="#1B2A4A" /> Continuar assistindo
                </button>
                <button className="fc-btn fc-btn-secondary fc-btn-sm" onClick={() => onNavigate('aulas')}>
                  Ver todas as aulas
                </button>
              </div>
            </div>
          </div>
        </Card>

        {/* Streak / XP card */}
        <Card>
          <div className="fc-overline" style={{ color: 'var(--fc-dourado-escuro)' }}>Disciplina</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 10 }}>
            <div style={{ fontSize: 40, fontWeight: 700, color: 'var(--fc-azul-profundo)', lineHeight: 1 }}>{user.streakDias}</div>
            <div className="fc-body" style={{ color: 'var(--fc-gray-600)' }}>dias seguidos</div>
          </div>
          <div className="fc-small" style={{ marginTop: 4 }}>
            {user.streakDias > 7 ? 'Ritmo de concurseiro aprovado. Continue.' : 'Comece uma sequência hoje.'}
          </div>
          <hr className="fc-divider" />
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
            <div>
              <div className="fc-caption">Nível</div>
              <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--fc-azul-profundo)', marginTop: 2, display: 'flex', alignItems: 'center', gap: 6 }}>
                <I.trophy size={16} /> {user.nivel}
              </div>
            </div>
            <div>
              <div className="fc-caption">XP total</div>
              <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--fc-azul-profundo)', marginTop: 2 }}>{user.xp.toLocaleString('pt-BR')}</div>
            </div>
          </div>
          <Progress value={(user.xp % 500) / 5} size="xs" />
          <div className="fc-caption" style={{ marginTop: 6 }}>Faltam {500 - (user.xp % 500)} XP pro nível {user.nivel + 1}</div>
        </Card>
      </div>

      {/* Acesso + Concurso focado + Progresso geral — 3 cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
        <Card>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <div className="fc-overline">Seu acesso</div>
            {user.badgePremium && <Badge tone="gold" icon={I.sparkle}>Premium</Badge>}
          </div>
          <div className="fc-h3" style={{ marginBottom: 2 }}>{user.planoLabel}</div>
          <div className="fc-small" style={{ marginBottom: 14 }}>{user.diasAteExpiracao} dias restantes · vence {new Date(user.dataExpiracao).toLocaleDateString('pt-BR')}</div>
          <Progress value={100 - (user.diasAteExpiracao / (user.plano === 'mensal' ? 30 : user.plano === 'semestral' ? 180 : 365) * 100)} size="sm" />
        </Card>

        <Card>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <div className="fc-overline">Concurso focado</div>
            <button className="fc-btn-ghost fc-tip" data-tip="Editar foco" style={{ color: 'var(--fc-gray-500)' }}>
              <I.edit size={14} />
            </button>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
            <div style={{
              width: 38, height: 38, borderRadius: 8,
              background: 'linear-gradient(135deg, var(--fc-azul-profundo), var(--fc-azul-medio))',
              color: 'var(--fc-dourado)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <I.target size={20} />
            </div>
            <div>
              <div className="fc-h3" style={{ margin: 0 }}>{user.concursoFocado}</div>
              <div className="fc-caption">Prova prevista: 2º sem/2026</div>
            </div>
          </div>
          <div className="fc-small">Dica do professor: foque nos CPCs 00, 26, 27 e 47 para essa banca.</div>
        </Card>

        <Card>
          <div className="fc-overline">Progresso geral</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 10, marginBottom: 10 }}>
            <div style={{ fontSize: 32, fontWeight: 700, color: 'var(--fc-azul-profundo)', lineHeight: 1 }}>{pctProgresso}%</div>
            <div className="fc-small">concluído</div>
          </div>
          <Progress value={pctProgresso} size="sm" />
          <div className="fc-caption" style={{ marginTop: 8 }}>
            {concluidas.length} de {totalAulas} aulas · certificado liberado aos 100%
          </div>
        </Card>
      </div>

      {/* Grid de módulos */}
      <div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 16 }}>
          <div>
            <div className="fc-h2">Módulos do curso</div>
            <div className="fc-small" style={{ marginTop: 4 }}>4 módulos · {totalAulas} aulas · atualização contínua</div>
          </div>
          <button className="fc-btn fc-btn-secondary fc-btn-sm" onClick={() => onNavigate('aulas')}>Ver lista completa <I.chevronRight size={14} /></button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16 }}>
          {modulosStats.map(m => (
            <Card key={m.id} style={{ padding: 20, position: 'relative', opacity: m.bloqueado ? 0.6 : 1 }}>
              <div style={{ display: 'flex', gap: 14 }}>
                <div style={{
                  width: 48, height: 48, borderRadius: 10,
                  background: m.bloqueado ? 'var(--fc-gray-200)' : 'linear-gradient(135deg, var(--fc-azul-profundo), var(--fc-azul-medio))',
                  color: m.bloqueado ? 'var(--fc-gray-500)' : 'var(--fc-dourado)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  flexShrink: 0, fontWeight: 700, fontSize: 18,
                }}>
                  {m.bloqueado ? <I.lock size={20} /> : m.numero}
                </div>
                <div style={{ flex: 1 }}>
                  <div className="fc-caption" style={{ marginBottom: 2 }}>Módulo {m.numero}</div>
                  <div className="fc-h4" style={{ marginBottom: 6 }}>{m.nome}</div>
                  <div className="fc-small" style={{ marginBottom: 12, minHeight: 40 }}>{m.descricao}</div>
                  {m.bloqueado ? (
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--fc-warning)', fontSize: 12, fontWeight: 600 }}>
                      <I.clock size={13} /> Libera em {m.diasFaltando} dia{m.diasFaltando > 1 ? 's' : ''}
                    </div>
                  ) : (
                    <Progress value={m.pct} size="sm" rightLabel={`${m.concluidas}/${m.total}`} label="Progresso" />
                  )}
                </div>
              </div>
            </Card>
          ))}
        </div>
      </div>

      {/* Mentoria premium (só anual) */}
      {user.plano === 'anual' && user.proxLive && (
        <Card style={{ padding: 0, overflow: 'hidden', background: 'var(--fc-azul-profundo)', color: 'var(--fc-white)', border: 'none' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '240px 1fr', alignItems: 'stretch' }}>
            <div style={{
              background: `linear-gradient(135deg, rgba(15,27,51,0.2), rgba(27,42,74,0.6)), url(${FC_ASSETS.hero}) center/cover`,
              minHeight: 180,
            }} />
            <div style={{ padding: '26px 28px' }}>
              <div style={{ display: 'flex', gap: 10, marginBottom: 10 }}>
                <Badge tone="gold" icon={I.sparkle}>Fluência Premium</Badge>
                <Badge tone="gold">Em 6 dias</Badge>
              </div>
              <div className="fc-h2" style={{ color: 'var(--fc-white)', marginBottom: 8 }}>Próxima Mentoria ao vivo</div>
              <div style={{ fontSize: 15, color: 'rgba(255,255,255,0.8)', marginBottom: 14 }}>
                <strong style={{ color: 'var(--fc-dourado)' }}>{user.proxLive.tema}</strong><br/>
                {new Date(user.proxLive.data).toLocaleDateString('pt-BR', { weekday: 'long', day: 'numeric', month: 'long' })} · {user.proxLive.hora} · 2h · grupo de até 35 alunos
              </div>
              <button className="fc-btn fc-btn-primary fc-btn-sm" onClick={() => onNavigate('mentoria')}>Ver detalhes da mentoria</button>
            </div>
          </div>
        </Card>
      )}
    </div>
  );
}

// ============ ACESSO EXPIRADO ============
function AcessoExpirado({ user }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 'calc(100vh - var(--fc-header-h) - 64px)' }}>
      <Card style={{ maxWidth: 520, textAlign: 'center', padding: 40 }}>
        <div style={{
          width: 72, height: 72, borderRadius: '50%',
          background: 'var(--fc-warning-bg)', color: 'var(--fc-warning)',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          marginBottom: 20,
        }}>
          <I.clock size={32} />
        </div>
        <div className="fc-h2" style={{ marginBottom: 10 }}>Seu acesso expirou</div>
        <div className="fc-body" style={{ color: 'var(--fc-gray-600)', marginBottom: 8 }}>
          {user.primeiroNome}, seu plano venceu em <strong>{new Date(user.dataExpiracao).toLocaleDateString('pt-BR')}</strong>. 
          Renove para retomar de onde parou — seu progresso de <strong>{user.progresso}%</strong> e seus certificados já emitidos continuam aqui.
        </div>
        <div className="fc-small" style={{ marginBottom: 24 }}>
          Continua com acesso ao perfil e a certificados já emitidos. Novo conteúdo fica bloqueado até a renovação.
        </div>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
          <button className="fc-btn fc-btn-primary fc-btn-lg">Renovar meu acesso</button>
          <button className="fc-btn fc-btn-secondary">Falar com suporte</button>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { LoginScreen, AlunoDashboard, AcessoExpirado });
