/* Secondary views: Histórico, Progresso, Plano */

function PageHead({ title, sub }) {
  return (
    <div className="page-head">
      <h1>{title}</h1>
      {sub && <p className="greet-sub">{sub}</p>}
    </div>
  );
}

const HISTORY = [
  { score: '8.4', good: true, title: 'Treino guiado · Trabalho', meta: 'Ontem, 19:32 · 14 min · 9 falas', tag: 'B1' },
  { score: '7.6', good: false, title: 'Conversa livre · Viagem', meta: '5 jun, 08:10 · 11 min · 7 falas', tag: 'B1' },
  { score: '8.9', good: true, title: 'Pronúncia · Reuniões', meta: '4 jun, 20:05 · 9 min · 12 frases', tag: 'B2' },
  { score: '7.2', good: false, title: 'Treino guiado · Small talk', meta: '3 jun, 12:40 · 13 min · 8 falas', tag: 'A2' },
  { score: '8.1', good: true, title: 'Conversa livre · Vida diária', meta: '2 jun, 21:18 · 16 min · 10 falas', tag: 'B1' },
];

function HistoryView() {
  return (
    <div className="page">
      <PageHead title="Histórico" sub="Revise suas sessões anteriores e acompanhe a evolução." />
      <div className="empty-hint"><Icon name="bookmark" size={18} /> Toque em uma sessão para ver o resumo completo, com correções e versões mais naturais.</div>
      <div className="card list-card">
        {HISTORY.map((h, i) => (
          <div className="session-row" key={i}>
            <div className={'sr-score ' + (h.good ? 'good' : 'mid')}>{h.score}</div>
            <div className="sr-main">
              <strong>{h.title}</strong>
              <span>{h.meta}</span>
            </div>
            <span className="sr-tag">{h.tag}</span>
            <Icon name="chevronRight" size={20} className="sr-arrow" />
          </div>
        ))}
      </div>
    </div>
  );
}

const STATS = [
  { icon: 'flame', tone: 'amber-soft', color: 'var(--amber)', num: '5', label: 'Dias seguidos', delta: '+2 esta semana' },
  { icon: 'clock', tone: 'blue-soft', color: 'var(--blue)', num: '6h 12m', label: 'Tempo falando', delta: '+48 min' },
  { icon: 'message', tone: 'green-soft', color: 'var(--green)', num: '143', label: 'Falas avaliadas', delta: '+31' },
  { icon: 'trophy', tone: 'violet-soft', color: 'var(--violet)', num: '8.2', label: 'Nota média', delta: '+0.4' },
];

const SKILLS = [
  { k: 'Pronúncia', v: 81 },
  { k: 'Fluência', v: 76 },
  { k: 'Gramática', v: 68 },
  { k: 'Vocabulário', v: 88 },
  { k: 'Compreensão', v: 73 },
];

function ProgressView() {
  return (
    <div className="page">
      <PageHead title="Progresso" sub="Seu desempenho ao longo do plano de 6 meses." />
      <div className="stat-grid">
        {STATS.map((s, i) => (
          <article className="card stat-card" key={i}>
            <div className="icon-chip" style={{ background: `var(--${s.tone})`, color: s.color }}><Icon name={s.icon} size={20} /></div>
            <h3>{s.num}</h3>
            <p>{s.label}</p>
            <p style={{ marginTop: '6px' }}><small>{s.delta}</small></p>
          </article>
        ))}
      </div>

      <div className="section-title"><h2>Habilidades</h2><span className="faint" style={{ fontSize: '13.5px' }}>vs. mês passado</span></div>
      <div className="card" style={{ padding: '24px' }}>
        <div className="skill-bars">
          {SKILLS.map((s) => (
            <div className="skill-bar-row" key={s.k}>
              <div className="skill-bar-head"><strong>{s.k}</strong><span>{s.v}%</span></div>
              <div className="skill-track"><div className="skill-fill" style={{ width: s.v + '%' }} /></div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

const PRO_FEATURES = [
  'Sessões ilimitadas por mês',
  'Feedback detalhado por IA',
  'Avaliação de pronúncia com Azure',
  'Histórico completo de sessões',
  'Coach de vocabulário ilimitado',
];

function PlanView({ user }) {
  const { useState: useStateV } = React;
  const [loading, setLoading] = useStateV(null); // 'monthly' | 'yearly' | 'portal'
  const [error, setError] = useStateV(null);

  const isPro = user?.plan === 'pro';
  const usageCount = user?.usageCount ?? 0;
  const usageLimit = user?.usageLimit ?? 30;
  const usedPct = usageLimit > 0 ? Math.min(100, Math.round((usageCount / usageLimit) * 100)) : 0;
  const status = user?.subscriptionStatus;
  const endsAt = user?.subscriptionEndsAt ? new Date(user.subscriptionEndsAt) : null;
  const endsStr = endsAt ? endsAt.toLocaleDateString('pt-BR', { day: '2-digit', month: 'long', year: 'numeric' }) : null;

  async function checkout(interval) {
    setError(null);
    setLoading(interval);
    try {
      const res = await fetch('/api/billing/checkout', {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ interval }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Erro ao iniciar pagamento.');
      window.location.href = data.url;
    } catch (e) {
      setError(e.message);
      setLoading(null);
    }
  }

  async function openPortal() {
    setError(null);
    setLoading('portal');
    try {
      const res = await fetch('/api/billing/portal', {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'Content-Type': 'application/json' },
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Erro ao abrir portal.');
      window.location.href = data.url;
    } catch (e) {
      setError(e.message);
      setLoading(null);
    }
  }

  if (isPro) {
    return (
      <div className="page">
        <PageHead title="Seu plano" sub="Gerencie sua assinatura Oravio Pro." />

        <article className="card" style={{ padding: '28px', marginBottom: '16px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '14px', marginBottom: '20px' }}>
            <div className="icon-chip" style={{ background: 'var(--blue-soft)', color: 'var(--blue)' }}>
              <Icon name="trophy" size={22} />
            </div>
            <div>
              <strong style={{ fontSize: '17px' }}>Oravio Pro</strong>
              {status === 'past_due' && (
                <p style={{ color: 'var(--coral)', fontSize: '13px', margin: '2px 0 0' }}>
                  Pagamento pendente — atualize seu método de pagamento.
                </p>
              )}
              {status === 'canceled' && endsStr && (
                <p style={{ color: 'var(--amber)', fontSize: '13px', margin: '2px 0 0' }}>
                  Acesso até {endsStr}.
                </p>
              )}
              {status === 'active' && endsStr && (
                <p style={{ color: 'var(--ink-faint)', fontSize: '13px', margin: '2px 0 0' }}>
                  Renova em {endsStr}.
                </p>
              )}
            </div>
          </div>

          <ul style={{ listStyle: 'none', padding: 0, margin: '0 0 24px', display: 'flex', flexDirection: 'column', gap: '10px' }}>
            {PRO_FEATURES.map((f) => (
              <li key={f} style={{ display: 'flex', alignItems: 'center', gap: '10px', fontSize: '14px' }}>
                <Icon name="check" size={16} style={{ color: 'var(--green)', flexShrink: 0 }} />
                {f}
              </li>
            ))}
          </ul>

          <button
            className="btn btn-soft"
            onClick={openPortal}
            disabled={!!loading}
            style={{ alignSelf: 'flex-start' }}
          >
            {loading === 'portal' ? 'Abrindo portal…' : 'Gerenciar assinatura'}
          </button>
        </article>

        {error && <p style={{ color: 'var(--coral)', fontSize: '13px' }}>{error}</p>}
      </div>
    );
  }

  return (
    <div className="page">
      <PageHead title="Seu plano" sub="Assine para ter acesso ilimitado ao Oravio." />

      <article className="card" style={{ padding: '20px 24px', marginBottom: '20px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' }}>
          <strong style={{ fontSize: '14px' }}>Plano gratuito — uso este mês</strong>
          <span style={{ fontSize: '13px', color: 'var(--ink-faint)' }}>{usageCount} / {usageLimit} sessões</span>
        </div>
        <div style={{ background: 'var(--border)', borderRadius: '99px', height: '6px', overflow: 'hidden' }}>
          <div style={{ width: usedPct + '%', height: '100%', background: usedPct >= 90 ? 'var(--coral)' : 'var(--blue)', borderRadius: '99px', transition: 'width .4s' }} />
        </div>
        {usedPct >= 90 && (
          <p style={{ color: 'var(--coral)', fontSize: '12px', marginTop: '8px' }}>
            Você está quase no limite. Assine para continuar praticando.
          </p>
        )}
      </article>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: '16px' }}>
        <article className="card" style={{ padding: '28px' }}>
          <p style={{ fontSize: '12px', fontWeight: 600, color: 'var(--ink-faint)', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: '6px' }}>Mensal</p>
          <div style={{ fontSize: '28px', fontWeight: 700, marginBottom: '4px' }}>—</div>
          <p style={{ fontSize: '13px', color: 'var(--ink-faint)', marginBottom: '20px' }}>Preço a definir · cobrado mensalmente</p>
          <ul style={{ listStyle: 'none', padding: 0, margin: '0 0 24px', display: 'flex', flexDirection: 'column', gap: '9px' }}>
            {PRO_FEATURES.map((f) => (
              <li key={f} style={{ display: 'flex', alignItems: 'center', gap: '9px', fontSize: '13.5px' }}>
                <Icon name="check" size={15} style={{ color: 'var(--green)', flexShrink: 0 }} />
                {f}
              </li>
            ))}
          </ul>
          <button
            className="btn btn-primary"
            style={{ width: '100%' }}
            onClick={() => checkout('month')}
            disabled={!!loading}
          >
            {loading === 'month' ? 'Aguarde…' : 'Assinar mensalmente'}
          </button>
        </article>

        <article className="card" style={{ padding: '28px', position: 'relative', outline: '2px solid var(--blue)', outlineOffset: '-2px' }}>
          <div style={{ position: 'absolute', top: '-11px', left: '24px', background: 'var(--blue)', color: '#fff', fontSize: '11px', fontWeight: 700, padding: '2px 10px', borderRadius: '99px', letterSpacing: '.04em' }}>
            MELHOR VALOR
          </div>
          <p style={{ fontSize: '12px', fontWeight: 600, color: 'var(--ink-faint)', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: '6px' }}>Anual</p>
          <div style={{ fontSize: '28px', fontWeight: 700, marginBottom: '4px' }}>—</div>
          <p style={{ fontSize: '13px', color: 'var(--ink-faint)', marginBottom: '20px' }}>Preço a definir · equivalente por mês</p>
          <ul style={{ listStyle: 'none', padding: 0, margin: '0 0 24px', display: 'flex', flexDirection: 'column', gap: '9px' }}>
            {PRO_FEATURES.map((f) => (
              <li key={f} style={{ display: 'flex', alignItems: 'center', gap: '9px', fontSize: '13.5px' }}>
                <Icon name="check" size={15} style={{ color: 'var(--green)', flexShrink: 0 }} />
                {f}
              </li>
            ))}
          </ul>
          <button
            className="btn btn-primary"
            style={{ width: '100%' }}
            onClick={() => checkout('year')}
            disabled={!!loading}
          >
            {loading === 'year' ? 'Aguarde…' : 'Assinar anualmente'}
          </button>
        </article>
      </div>

      {error && <p style={{ color: 'var(--coral)', fontSize: '13px', marginTop: '16px' }}>{error}</p>}
    </div>
  );
}

Object.assign(window, { HistoryView, ProgressView, PlanView });
