// Órbita — Portal v2 mobile-first

// Mês atual do ciclo, a partir de `year_start` e da data de hoje — não é mais
// fixo (P0-7 do service blueprint: consulente lia/marcava o mês errado).
// Sem `year_start` (caminho mock puro, sem sessão real), cai no mês 0.
function monthIndexFromStart(yearStart) {
  if (!yearStart) return 0;
  const start = new Date(yearStart);
  if (Number.isNaN(start.getTime())) return 0;
  const now = new Date();
  // Mesmo cuidado de fuso que `cyclePeriodLabel` já usa mais abaixo: UTC evita
  // que o navegador puxe a data pra trás perto da virada do mês.
  let idx = (now.getUTCFullYear() - start.getUTCFullYear()) * 12 + (now.getUTCMonth() - start.getUTCMonth());
  if (now.getUTCDate() < start.getUTCDate()) idx -= 1;
  return Math.min(Math.max(idx, 0), 11);
}

// ── Check-in Modal ─────────────────────────────────────────
const CheckInModal = ({ onClose, accentColor, onSubmit }) => {
  const [mood, setMood] = React.useState(null);
  const [note, setNote] = React.useState('');
  const [sent, setSent] = React.useState(false);

  const moods = [
    { id: 'clarity',   emoji: '☀️', label: 'Clareza' },
    { id: 'confusion', emoji: '🌫️', label: 'Confusão' },
    { id: 'stuck',     emoji: '🪨', label: 'Travamento' },
  ];

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(16,13,10,0.85)',
      backdropFilter: 'blur(10px)', display: 'flex',
      alignItems: 'flex-end', justifyContent: 'center', zIndex: 3000,
      padding: '0',
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxWidth: 480,
        background: '#1A1612', border: '1px solid rgba(245,241,232,0.1)',
        borderRadius: '24px 24px 0 0',
        padding: '24px 24px 36px',
        boxShadow: '0 -16px 60px rgba(0,0,0,0.6)',
      }}>
        {/* drag handle */}
        <div style={{ width: 36, height: 4, borderRadius: 2, background: 'rgba(245,241,232,0.15)', margin: '0 auto 20px' }} />

        {sent ? (
          <div style={{ textAlign: 'center', padding: '16px 0 8px' }}>
            <div style={{ fontSize: 44, marginBottom: 12 }}>✓</div>
            <div style={{ fontFamily: '"Instrument Serif", serif', fontSize: 20, color: '#F5F1E8', marginBottom: 6 }}>Check-in registrado</div>
            <div style={{ fontSize: 13, color: 'rgba(245,241,232,0.5)' }}>Sua astróloga vai ver isso na próxima sessão.</div>
          </div>
        ) : (
          <>
            <div style={{ marginBottom: 24 }}>
              <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'rgba(245,241,232,0.4)', marginBottom: 4 }}>Check-in da semana</div>
              <div style={{ fontFamily: '"Instrument Serif", serif', fontSize: 22, color: '#F5F1E8', lineHeight: 1.3 }}>Como você está agora?</div>
            </div>
            <div style={{ display: 'flex', gap: 10, marginBottom: 20 }}>
              {moods.map(m => (
                <button key={m.id} onClick={() => setMood(m.id)} style={{
                  flex: 1, padding: '16px 8px 12px', borderRadius: 16,
                  background: mood === m.id ? `${accentColor}18` : 'rgba(245,241,232,0.04)',
                  border: `1.5px solid ${mood === m.id ? accentColor + '55' : 'rgba(245,241,232,0.08)'}`,
                  cursor: 'pointer', transition: 'all 0.18s', fontFamily: 'Inter, sans-serif',
                  transform: mood === m.id ? 'scale(1.04)' : 'scale(1)',
                }}>
                  <div style={{ fontSize: 30, marginBottom: 6 }}>{m.emoji}</div>
                  <div style={{ fontSize: 11, color: mood === m.id ? accentColor : 'rgba(245,241,232,0.45)', fontWeight: mood === m.id ? 500 : 400 }}>{m.label}</div>
                </button>
              ))}
            </div>
            <textarea
              value={note} onChange={e => setNote(e.target.value)}
              placeholder="Algo a anotar? (opcional)"
              rows={2}
              style={{
                width: '100%', background: 'rgba(245,241,232,0.04)',
                border: '1px solid rgba(245,241,232,0.08)', borderRadius: 12,
                padding: '10px 14px', color: '#F5F1E8', fontSize: 13,
                fontFamily: 'Inter, sans-serif', resize: 'none',
                outline: 'none', boxSizing: 'border-box', marginBottom: 16,
              }}
            />
            <button onClick={() => { if (mood) { onSubmit(mood, note); setSent(true); setTimeout(onClose, 2200); } }} style={{
              width: '100%', padding: '14px 0', borderRadius: 999, border: 'none',
              background: mood ? accentColor : 'rgba(245,241,232,0.08)',
              color: mood ? '#100D0A' : 'rgba(245,241,232,0.3)',
              fontSize: 14, fontWeight: 600, cursor: mood ? 'pointer' : 'not-allowed',
              fontFamily: 'Inter, sans-serif', transition: 'all 0.2s',
            }}>Enviar check-in</button>
          </>
        )}
      </div>
    </div>
  );
};

// P0-4 do blueprint: o gate de magic-link por e-mail que existia aqui não
// mandava e-mail nenhum — "Simular clique no link ↗" desbloqueava com
// qualquer string contendo "@", sem verificação real. Isso prometia uma
// segurança que não existia e ainda expunha "Simular" pro consulente real.
// Removido: por ora o slug longo (ver `publishLeitura` em lib/leituras.ts) é
// o portão real do piloto. Magic-link por e-mail de verdade é item futuro.

// Puramente decorativo — o motor real não devolve emoji por mês (ver
// lib/motor/schema.ts). Indexado pelo mês do calendário (`mes.i`, 1=jan).
const MONTH_EMOJI = ['🎯', '🌊', '🐟', '🌱', '🌿', '☀️', '🔥', '⚡', '🍂', '⚖️', '🌑', '🏹'];
const MESES_ABREV = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];
const emojiForMes = (mes) => mes.emoji || MONTH_EMOJI[(mes.i - 1 + 12) % 12];
const initialsOf = (name) => (name || '?').trim().split(/\s+/).map(w => w[0]).slice(0, 2).join('').toUpperCase();

// ── Portal Screen ──────────────────────────────────────────
// previewMode = astróloga vendo o portal a partir do editor/painel (com aviso + saída,
//   `session` é a LeituraRecord real vinda de cima — ver openSession/openPortalPreview em orbita-app.jsx).
// publicEntry = consulente entrando pelo link /portal/:slug (passa pelo gate de acesso;
//   busca tudo — leitura, consulente, astróloga, check-ins prévios — em GET /api/portal/:slug).
// Sem nenhum dos dois (atalho "◑ protótipo" pulando direto pra tela): cai no mock.
const PortalScreen = ({ onBack, publicEntry = false, previewMode = false, session = null, slug = null }) => {
  const usesRealData = publicEntry || previewMode;
  const [loadState, setLoadState] = React.useState(usesRealData ? 'loading' : 'data');
  const [leitura, setLeitura] = React.useState(() => (usesRealData ? null : window.ORBITA_DATA.sessionDetail));
  const [leituraId, setLeituraId] = React.useState(null);
  const [yearStart, setYearStart] = React.useState(null);
  const [consulente, setConsulente] = React.useState(() => (usesRealData ? null : window.ORBITA_DATA.consulentes[0]));
  const [astrologer, setAstrologer] = React.useState(() => (usesRealData ? null : window.ORBITA_DATA.astrologer));
  const [selectedMonth, setSelectedMonth] = React.useState(null);
  const [tooltipMonth, setTooltipMonth] = React.useState(null);
  const [showCheckin, setShowCheckin] = React.useState(false);
  const [ownCheckins, setOwnCheckins] = React.useState(() => (
    usesRealData
      ? []
      : window.ORBITA_DATA.checkins.filter(c => c.consulente_id === window.ORBITA_DATA.consulentes[0].id)
  ));

  const load = React.useCallback(() => {
    if (!usesRealData) return;
    setLoadState('loading');
    if (publicEntry) {
      if (!slug) { setLoadState('error'); return; }
      fetch(`/api/portal/${slug}`)
        .then(res => res.json().catch(() => ({})).then(data => { if (!res.ok) throw new Error(data.error || 'Portal não encontrado.'); return data; }))
        .then(data => {
          setLeitura(data.leitura);
          setLeituraId(data.leitura_id);
          setYearStart(data.year_start || null);
          setConsulente(data.consulente);
          setAstrologer(data.astrologer);
          setOwnCheckins(data.checkins || []);
          setLoadState('data');
        })
        .catch(() => setLoadState('error'));
      return;
    }
    // previewMode: `session` já é a LeituraRecord (astróloga está autenticada) —
    // só falta o perfil/marca, que não vem embutido na leitura.
    if (!session?.leitura) { setLoadState('error'); return; }
    fetch('/api/me')
      .then(res => res.json())
      .then(me => {
        setLeitura(session.leitura);
        setLeituraId(session.id ?? null);
        setYearStart(session.year_start || null);
        setConsulente(session.consulente || null);
        setAstrologer(me.astrologer || null);
        setLoadState('data');
      })
      .catch(() => setLoadState('error'));
  }, [publicEntry, previewMode, slug, session, usesRealData]);

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

  const accentColor = astrologer?.brand_color || '#F2EEE4';
  const meses = React.useMemo(() => (leitura?.meses || []).map(m => ({ ...m, emoji: emojiForMes(m) })), [leitura]);
  const currentMonthIdx = React.useMemo(() => monthIndexFromStart(yearStart), [yearStart]);
  const currentMes = meses[currentMonthIdx] || null;
  const upcomingAlertas = (leitura?.alertas || []).slice(0, 2);
  const cyclePeriodLabel = React.useMemo(() => {
    if (!yearStart) return null;
    // `yearStart` é uma data pura (sem hora) — usar métodos UTC evita que o
    // fuso horário do navegador puxe o dia pra trás (ex.: "2026-06-01" virando
    // 31/mai em quem está a oeste de UTC) e mostre o mês errado.
    const start = new Date(yearStart);
    if (Number.isNaN(start.getTime())) return null;
    const end = new Date(start); end.setUTCFullYear(end.getUTCFullYear() + 1); end.setUTCDate(end.getUTCDate() - 1);
    const fmt = (d) => `${MESES_ABREV[d.getUTCMonth()]} ${d.getUTCFullYear()}`;
    return `${fmt(start)} – ${fmt(end)}`;
  }, [yearStart]);

  const checkinsByMonth = React.useMemo(() => {
    const map = {};
    ownCheckins.forEach(c => { map[c.month_idx] = (map[c.month_idx] || []).concat(c); });
    return map;
  }, [ownCheckins]);

  const sortedCheckins = React.useMemo(
    () => ownCheckins.slice().sort((a, b) => new Date(b.created_at || b.date) - new Date(a.created_at || a.date)),
    [ownCheckins]
  );
  const lastCheckin = sortedCheckins[0] || null;
  const daysSinceLastCheckin = lastCheckin ? Math.floor((Date.now() - new Date(lastCheckin.created_at || lastCheckin.date)) / 86400000) : null;
  const checkedInThisWeek = daysSinceLastCheckin !== null && daysSinceLastCheckin < 7;

  // No modo prévia (astróloga) o check-in não é real — "Nada aqui é editável" —
  // então só entra no estado local, sem POST. No portal público, grava de verdade.
  const handleSubmitCheckin = (mood, note) => {
    if (publicEntry && slug) {
      fetch(`/api/portal/${slug}/checkin`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ month_idx: currentMonthIdx, mood, note }),
      })
        .then(res => res.json().catch(() => ({})).then(data => { if (!res.ok) throw new Error(data.error); return data; }))
        .then(data => setOwnCheckins(prev => [data.checkin, ...prev]))
        .catch(() => {
          // Falha de rede não trava o modal (já fechou com "enviado") — o check-in
          // só não aparece na lista local; a consulente pode tentar de novo depois.
        });
      return;
    }
    setOwnCheckins(prev => [{
      id: `chk-local-${Date.now()}`, consulente_id: consulente?.id ?? null, leitura_id: leituraId,
      created_at: new Date().toISOString(), month_idx: currentMonthIdx, mood, note,
    }, ...prev]);
  };

  const downloadTextFile = (filename, content) => {
    const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = filename;
    document.body.appendChild(a); a.click(); document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const handleExportText = () => {
    const consulenteName = consulente?.name || 'Consulente';
    const lines = [];
    lines.push(leitura.tema);
    lines.push(leitura.subtema);
    lines.push('');
    lines.push(`Consulente: ${consulenteName}`);
    lines.push(`Astróloga: ${astrologer?.name || ''}`);
    lines.push('');
    lines.push('RESUMO DO ANO');
    lines.push(`${leitura.subtema} Temas centrais: ${leitura.areas.map(a => a.label).join(', ')}.`);
    lines.push('');
    meses.forEach(mes => {
      lines.push(`--- Mês ${mes.i} · ${mes.nome} ---`);
      lines.push(`Foco: ${mes.foco}`);
      if (mes.foco_detail) lines.push(mes.foco_detail);
      lines.push(`Risco: ${mes.risco}`);
      if (mes.risco_detail) lines.push(mes.risco_detail);
      lines.push(`Oportunidade: ${mes.oportunidade}`);
      if (mes.oportunidade_detail) lines.push(mes.oportunidade_detail);
      if (mes.acoes?.length) lines.push(`Ações: ${mes.acoes.join('; ')}`);
      if (mes.rotina?.length) lines.push(`Rotina: ${mes.rotina.join('; ')}`);
      lines.push('');
    });
    if (leitura.alertas.length) {
      lines.push('JANELAS DE ATENÇÃO');
      leitura.alertas.forEach(a => lines.push(`${a.janela}: ${a.traducao}`));
      lines.push('');
    }
    lines.push(`Gerado pelo Órbitas · portal de ${astrologer?.brand_name || ''}`);
    downloadTextFile(`leitura-${consulenteName.toLowerCase().replace(/\s+/g, '-')}.txt`, lines.join('\n'));
  };

  if (loadState === 'loading') {
    return (
      <div style={{ minHeight: '100vh', background: '#100D0A', color: 'rgba(245,241,232,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'Inter, sans-serif', fontSize: 13 }}>
        Carregando portal…
      </div>
    );
  }
  if (loadState === 'error' || !leitura) {
    return (
      <div style={{ minHeight: '100vh', background: '#100D0A', color: '#F5F1E8', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'Inter, sans-serif' }}>
        <div style={{ textAlign: 'center', maxWidth: 320 }}>
          <div style={{ fontSize: 26, marginBottom: 12 }}>⚠</div>
          <p style={{ margin: '0 0 18px', fontSize: 13, color: 'rgba(245,241,232,0.6)', lineHeight: 1.6 }}>
            Não foi possível carregar este portal. O link pode ter expirado ou a sessão ainda não foi publicada.
          </p>
          <button onClick={load} style={{ padding: '10px 20px', borderRadius: 999, border: '1px solid rgba(245,241,232,0.2)', background: 'transparent', color: '#F5F1E8', fontSize: 13, cursor: 'pointer', fontFamily: 'Inter, sans-serif' }}>Tentar novamente</button>
        </div>
      </div>
    );
  }

  if (selectedMonth) {
    return (
      <PortalMonthScreen
        mes={selectedMonth}
        astrologer={astrologer}
        onBack={() => setSelectedMonth(null)}
        accentColor={accentColor}
        currentIdx={currentMonthIdx}
        meses={meses}
        hasCheckin={!!checkinsByMonth[selectedMonth.i - 1]}
      />
    );
  }

  return (
    <div style={{ minHeight: '100vh', background: '#100D0A', fontFamily: 'Inter, sans-serif', color: '#F5F1E8', position: 'relative' }}>
      <GrainOverlay />
      <div style={{
        position: 'absolute', top: -60, left: '50%', transform: 'translateX(-50%)',
        width: '100vw', maxWidth: 900, height: 400, pointerEvents: 'none',
        background: `radial-gradient(ellipse at 50% 0%, ${accentColor}1e, transparent 68%)`,
        zIndex: 0,
      }} />

      {/* Aviso de prévia — só quando a astróloga está pré-visualizando */}
      {previewMode && (
        <div style={{
          position: 'sticky', top: 0, zIndex: 210,
          background: 'rgba(244,162,97,0.14)', borderBottom: '1px solid rgba(244,162,97,0.3)',
          color: '#F4A261', fontSize: 12, fontFamily: 'Inter, sans-serif',
          padding: '9px 20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
        }}>
          <span>◑ Prévia do portal — é assim que a consulente vê. Nada aqui é editável.</span>
          {onBack && (
            <button onClick={onBack} style={{
              background: 'rgba(244,162,97,0.2)', border: 'none', borderRadius: 999,
              color: '#F4A261', fontSize: 12, cursor: 'pointer', padding: '5px 14px', fontFamily: 'Inter, sans-serif', whiteSpace: 'nowrap',
            }}>Sair da prévia</button>
          )}
        </div>
      )}

      {/* Botão de saída no modo consulente (aqui é protótipo — link real não teria) */}
      {onBack && !previewMode && (
        <button onClick={onBack} style={{
          position: 'fixed', top: 12, left: 12, zIndex: 200,
          background: 'rgba(16,13,10,0.8)', backdropFilter: 'blur(8px)',
          border: '1px solid rgba(245,241,232,0.08)', borderRadius: 999,
          color: 'rgba(245,241,232,0.5)', fontSize: 12, cursor: 'pointer',
          padding: '6px 12px', display: 'flex', alignItems: 'center', gap: 5,
          fontFamily: 'Inter, sans-serif',
        }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M15 18l-6-6 6-6"/></svg>
          Sair do protótipo
        </button>
      )}

      {/* Brand header */}
      <header style={{
        padding: '14px 20px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        borderBottom: '1px solid rgba(245,241,232,0.07)',
        position: 'relative', zIndex: 10,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{
            width: 34, height: 34, borderRadius: '50%',
            background: `${accentColor}22`, border: `1.5px solid ${accentColor}50`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: accentColor, fontSize: 11, fontWeight: 600, flexShrink: 0,
          }}>{astrologer?.initials || initialsOf(astrologer?.name)}</div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 500 }}>{astrologer?.brand_name || astrologer?.name || 'Portal'}</div>
            <div style={{ fontSize: 10, color: 'rgba(245,241,232,0.4)' }}>Portal da consulta</div>
          </div>
        </div>
        <div style={{ fontSize: 10, color: 'rgba(245,241,232,0.3)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>
          {consulente?.name || ''}
        </div>
      </header>

      <div style={{ maxWidth: 800, margin: '0 auto', padding: '36px 20px 120px', position: 'relative', zIndex: 1 }}>

        {/* Title block */}
        <div style={{ marginBottom: 40 }}>
          <p style={{ margin: '0 0 6px', fontSize: 10, color: 'rgba(245,241,232,0.4)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
            Revolução Solar{cyclePeriodLabel ? ` · ${cyclePeriodLabel}` : ''}
          </p>
          <h1 style={{
            margin: '0 0 14px',
            fontSize: 'clamp(26px, 6vw, 36px)',
            fontFamily: '"Instrument Serif", serif', fontWeight: 400,
            letterSpacing: '-0.02em', lineHeight: 1.2,
          }}>
            {leitura.tema}
          </h1>
          <p style={{ margin: '0 0 20px', fontSize: 14, color: 'rgba(245,241,232,0.55)', lineHeight: 1.65 }}>
            {leitura.subtema}
          </p>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {leitura.areas.map(a => {
              const color = areaMeta[a.name]?.color || 'rgba(245,241,232,0.4)';
              return (
                <span key={a.name} style={{
                  display: 'inline-flex', alignItems: 'center', gap: 5,
                  padding: '4px 11px', borderRadius: 999, fontSize: 11, fontWeight: 500,
                  color, background: `${color}14`, border: `1px solid ${color}30`,
                }}>
                  <span style={{ width: 5, height: 5, borderRadius: '50%', background: color }} />
                  {a.label}
                </span>
              );
            })}
          </div>
        </div>

        {/* Export actions */}
        <div style={{ display: 'flex', gap: 8, marginBottom: 36, flexWrap: 'wrap' }}>
          <button onClick={handleExportText} style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '9px 16px', borderRadius: 999,
            border: `1px solid ${accentColor}35`, background: `${accentColor}0c`, color: accentColor,
            fontSize: 12, fontWeight: 500, cursor: 'pointer', fontFamily: 'Inter, sans-serif',
          }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
            Baixar leitura completa (.txt)
          </button>
          <button disabled title="Em breve: requer integração de voz" style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '9px 16px', borderRadius: 999,
            border: '1px solid rgba(245,241,232,0.1)', background: 'rgba(245,241,232,0.03)', color: 'rgba(245,241,232,0.3)',
            fontSize: 12, fontWeight: 500, cursor: 'not-allowed', fontFamily: 'Inter, sans-serif',
          }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M11 5L6 9H2v6h4l5 4V5z"/><path d="M15.54 8.46a5 5 0 010 7.07"/></svg>
            Ouvir em áudio · em breve
          </button>
        </div>

        {/* Resumo do ano — condensado */}
        <div style={{ marginBottom: 36 }}>
          <h3 style={{ margin: '0 0 12px', fontSize: 10, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(245,241,232,0.4)' }}>
            Resumo do seu ano
          </h3>
          <div style={{
            padding: '18px 20px', borderRadius: 16, background: 'rgba(245,241,232,0.03)', border: '1px solid rgba(245,241,232,0.08)',
          }}>
            <p style={{ margin: 0, fontSize: 13, color: 'rgba(245,241,232,0.65)', lineHeight: 1.7 }}>
              {leitura.subtema} Os temas centrais do ciclo — {leitura.areas.map(a => a.label).join(', ').toLowerCase()} — se desdobram mês a mês abaixo, com os pontos de atenção específicos de cada período.
            </p>
          </div>
        </div>

        {/* Current month card */}
        <div style={{ marginBottom: 36 }}>
          <h3 style={{ margin: '0 0 12px', fontSize: 10, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(245,241,232,0.4)' }}>
            Mês atual
          </h3>
          <div style={{
            background: `linear-gradient(135deg, ${accentColor}0e, rgba(231,111,81,0.05))`,
            border: `1px solid ${accentColor}2a`, borderRadius: 20, padding: '20px 20px 18px',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
              <span style={{ fontSize: 26 }}>{currentMes.emoji}</span>
              <div>
                <div style={{ fontSize: 18, fontFamily: '"Instrument Serif", serif', fontWeight: 400 }}>{currentMes.nome}</div>
                <div style={{ fontSize: 10, color: 'rgba(245,241,232,0.4)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Mês {currentMonthIdx + 1} do seu ano solar</div>
              </div>
            </div>
            {/* 3 cards stacked on mobile, row on sm+ */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
              {[
                { label: 'Foco',        value: currentMes.foco,        color: '#7A9EC9', icon: '◎' },
                { label: 'Risco',       value: currentMes.risco,       color: '#E76F51', icon: '⚠' },
                { label: 'Oportunidade',value: currentMes.oportunidade, color: '#8CAF88', icon: '✦' },
              ].map(item => (
                <div key={item.label} style={{
                  padding: '12px 14px', borderRadius: 12,
                  background: `${item.color}0c`, border: `1px solid ${item.color}22`,
                  display: 'flex', gap: 10, alignItems: 'flex-start',
                }}>
                  <span style={{ fontSize: 12, color: item.color, flexShrink: 0, marginTop: 1 }}>{item.icon}</span>
                  <div>
                    <div style={{ fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.08em', color: item.color, fontWeight: 600, marginBottom: 3 }}>{item.label}</div>
                    <div style={{ fontSize: 12, color: '#F5F1E8', lineHeight: 1.5 }}>{item.value}</div>
                  </div>
                </div>
              ))}
            </div>
            <button onClick={() => setSelectedMonth(currentMes)} style={{
              width: '100%', padding: '11px 0', borderRadius: 999, border: 'none',
              background: `${accentColor}1a`, color: accentColor,
              fontSize: 13, fontWeight: 500, cursor: 'pointer',
              fontFamily: 'Inter, sans-serif', transition: 'all 0.15s',
            }}>
              Ver detalhes de {currentMes.nome} →
            </button>
          </div>
        </div>

        {/* Upcoming alerts */}
        <div style={{ marginBottom: 36 }}>
          <h3 style={{ margin: '0 0 12px', fontSize: 10, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(245,241,232,0.4)' }}>
            Próximos alertas
          </h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {upcomingAlertas.map((alerta, i) => {
              const color = alerta.severidade === 'forte' ? '#E76F51' : accentColor;
              return (
                <div key={i} style={{
                  display: 'flex', gap: 12, alignItems: 'flex-start',
                  padding: '13px 16px', borderRadius: 14,
                  background: `${color}07`, border: `1px solid ${color}22`,
                }}>
                  <span style={{ fontSize: 13, color, flexShrink: 0, marginTop: 1 }}>{alerta.severidade === 'forte' ? '⚠' : '◎'}</span>
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 600, color, marginBottom: 3 }}>{alerta.janela}</div>
                    <div style={{ fontSize: 13, color: '#F5F1E8', lineHeight: 1.5 }}>{alerta.traducao}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Seus check-ins */}
        <div style={{ marginBottom: 36 }}>
          <h3 style={{ margin: '0 0 12px', fontSize: 10, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(245,241,232,0.4)' }}>
            Seus check-ins
          </h3>
          <div style={{
            padding: '16px 18px', borderRadius: 16, background: 'rgba(245,241,232,0.03)', border: '1px solid rgba(245,241,232,0.08)',
          }}>
            {sortedCheckins.length === 0 ? (
              <p style={{ margin: 0, fontSize: 13, color: 'rgba(245,241,232,0.5)', lineHeight: 1.6 }}>
                Você ainda não fez nenhum check-in neste ciclo. Use o botão abaixo pra registrar como você está.
              </p>
            ) : (
              <>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
                  <span style={{ fontSize: 13, color: 'rgba(245,241,232,0.65)' }}>
                    <strong style={{ color: '#F5F1E8' }}>{sortedCheckins.length}</strong> check-in{sortedCheckins.length !== 1 ? 's' : ''} neste ciclo
                  </span>
                  {checkedInThisWeek && (
                    <span style={{ fontSize: 11, color: '#8CAF88', display: 'flex', alignItems: 'center', gap: 5 }}>
                      <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#8CAF88' }} />
                      Feito esta semana
                    </span>
                  )}
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {sortedCheckins.slice(0, 5).map(c => {
                    const mood = { clarity: { emoji: '☀️', label: 'Clareza' }, confusion: { emoji: '🌫️', label: 'Confusão' }, stuck: { emoji: '🪨', label: 'Travamento' } }[c.mood];
                    return (
                      <div key={c.id} style={{
                        display: 'flex', gap: 12, alignItems: 'flex-start', padding: '10px 12px', borderRadius: 12,
                        background: 'rgba(245,241,232,0.03)', border: '1px solid rgba(245,241,232,0.06)',
                      }}>
                        <span style={{ fontSize: 18, flexShrink: 0 }}>{mood.emoji}</span>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: c.note ? 3 : 0 }}>
                            <span style={{ fontSize: 12, fontWeight: 500, color: '#F5F1E8' }}>{mood.label}</span>
                            <span style={{ fontSize: 11, color: 'rgba(245,241,232,0.35)' }}>
                              {new Date(c.date).toLocaleDateString('pt-BR', { day: '2-digit', month: 'short' })}
                            </span>
                          </div>
                          {c.note && <div style={{ fontSize: 12, color: 'rgba(245,241,232,0.55)', lineHeight: 1.5 }}>{c.note}</div>}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </>
            )}
          </div>
        </div>

        {/* 12-month timeline */}
        <div style={{ marginBottom: 40 }}>
          <h3 style={{ margin: '0 0 12px', fontSize: 10, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(245,241,232,0.4)' }}>
            Seu ano — 12 meses
          </h3>

          {/* Mobile: vertical list */}
          <div className="months-mobile" style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {meses.map((mes, i) => {
              const isPast = i < currentMonthIdx;
              const isCurrent = i === currentMonthIdx;
              const hasCheckin = !!checkinsByMonth[i];
              return (
                <button key={mes.i} onClick={() => setSelectedMonth(mes)} style={{
                  display: 'flex', alignItems: 'center', gap: 14,
                  padding: '13px 16px', borderRadius: 14, cursor: 'pointer', textAlign: 'left',
                  background: isCurrent ? `${accentColor}12` : 'rgba(245,241,232,0.03)',
                  border: `1px solid ${isCurrent ? `${accentColor}30` : 'rgba(245,241,232,0.07)'}`,
                  fontFamily: 'Inter, sans-serif', width: '100%', transition: 'all 0.15s',
                }}>
                  <span style={{ fontSize: 20, flexShrink: 0 }}>{mes.emoji}</span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 2 }}>
                      <span style={{ fontSize: 13, fontWeight: isCurrent ? 600 : 400, color: isCurrent ? accentColor : '#F5F1E8' }}>{mes.nome}</span>
                      {isCurrent && <span style={{ fontSize: 9, padding: '1px 7px', borderRadius: 999, background: `${accentColor}18`, color: accentColor }}>Atual</span>}
                      {hasCheckin && <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#8CAF88', boxShadow: '0 0 6px rgba(140,175,136,0.6)' }} />}
                    </div>
                    <div style={{ fontSize: 12, color: 'rgba(245,241,232,0.45)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                      {mes.foco}
                    </div>
                  </div>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="rgba(245,241,232,0.28)" strokeWidth="2" style={{ flexShrink: 0 }}><path d="M9 18l6-6-6-6"/></svg>
                </button>
              );
            })}
          </div>

          {/* Desktop: 6-col grid (hidden on mobile via CSS) */}
          <div className="months-desktop" style={{ display: 'none', gridTemplateColumns: 'repeat(6,1fr)', gap: 8 }}>
            {meses.map((mes, i) => {
              const isPast = i < currentMonthIdx;
              const isCurrent = i === currentMonthIdx;
              const hasCheckin = !!checkinsByMonth[i];
              const hasAlerta = leitura.alertas.some(a => a.mes != null && a.mes - 1 === i);
              return (
                <div
                  key={mes.i}
                  onClick={() => setSelectedMonth(mes)}
                  onMouseEnter={() => setTooltipMonth(i)}
                  onMouseLeave={() => setTooltipMonth(null)}
                  style={{
                    padding: '12px 10px 10px', borderRadius: 14, cursor: 'pointer',
                    background: isCurrent ? `${accentColor}14` : isPast ? 'rgba(245,241,232,0.04)' : 'rgba(245,241,232,0.025)',
                    border: `1px solid ${isCurrent ? `${accentColor}35` : isPast ? 'rgba(245,241,232,0.08)' : 'rgba(245,241,232,0.05)'}`,
                    transition: 'all 0.15s', position: 'relative',
                    opacity: i > currentMonthIdx + 6 ? 0.6 : 1,
                  }}
                >
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
                    <span style={{ fontSize: 16 }}>{mes.emoji}</span>
                    <div style={{ display: 'flex', gap: 3 }}>
                      {hasCheckin && <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#8CAF88', boxShadow: '0 0 6px rgba(140,175,136,0.7)' }} />}
                      {isCurrent && <div style={{ width: 6, height: 6, borderRadius: '50%', background: accentColor, boxShadow: `0 0 8px ${accentColor}` }} />}
                      {hasAlerta && !isCurrent && <div style={{ width: 5, height: 5, borderRadius: '50%', background: '#E76F51' }} />}
                    </div>
                  </div>
                  <div style={{ fontSize: 11, fontWeight: isCurrent ? 600 : 400, color: isCurrent ? accentColor : isPast ? 'rgba(245,241,232,0.5)' : 'rgba(245,241,232,0.3)' }}>{mes.nome}</div>
                  <div style={{ fontSize: 10, color: 'rgba(245,241,232,0.25)', marginTop: 2, lineHeight: 1.3 }}>{mes.foco.slice(0,22)}{mes.foco.length>22?'…':''}</div>

                  {tooltipMonth === i && (
                    <div style={{
                      position: 'absolute', bottom: 'calc(100% + 8px)', left: '50%', transform: 'translateX(-50%)',
                      background: '#1A1612', border: '1px solid rgba(245,241,232,0.12)', borderRadius: 12,
                      padding: '10px 13px', width: 190, zIndex: 50, pointerEvents: 'none',
                      boxShadow: '0 8px 32px rgba(0,0,0,0.5)',
                    }}>
                      <div style={{ fontSize: 11, fontWeight: 600, color: '#F5F1E8', marginBottom: 5 }}>{mes.emoji} {mes.nome}</div>
                      <div style={{ fontSize: 10, color: '#7A9EC9', marginBottom: 3 }}>◎ {mes.foco}</div>
                      <div style={{ fontSize: 10, color: '#E76F51' }}>⚠ {mes.risco.slice(0,55)}{mes.risco.length>55?'…':''}</div>
                      {hasCheckin && (
                        <div style={{ fontSize: 9, color: '#8CAF88', display: 'flex', alignItems: 'center', gap: 4, marginTop: 6, paddingTop: 5, borderTop: '1px solid rgba(245,241,232,0.06)' }}>
                          <div style={{ width: 5, height: 5, borderRadius: '50%', background: '#8CAF88' }} />
                          Check-in registrado
                        </div>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* All alerts */}
        {leitura.alertas.length > 0 && (
          <div style={{ marginBottom: 40 }}>
            <h3 style={{ margin: '0 0 12px', fontSize: 10, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(245,241,232,0.4)' }}>
              Janelas de atenção
            </h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {leitura.alertas.map((alerta, i) => {
                const color = alerta.severidade === 'forte' ? '#E76F51' : accentColor;
                return (
                  <div key={i} style={{
                    display: 'flex', gap: 12, alignItems: 'flex-start',
                    padding: '13px 16px', borderRadius: 14,
                    background: `${color}07`, border: `1px solid ${color}22`,
                  }}>
                    <div style={{ width: 6, height: 6, borderRadius: '50%', background: color, boxShadow: `0 0 8px ${color}80`, marginTop: 5, flexShrink: 0 }} />
                    <div>
                      <div style={{ fontSize: 11, fontWeight: 600, color, marginBottom: 4 }}>{alerta.janela}</div>
                      <div style={{ fontSize: 13, color: '#F5F1E8', lineHeight: 1.55 }}>{alerta.traducao}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {/* Ciclos anteriores */}
        <div style={{ marginBottom: 36 }}>
          <h3 style={{ margin: '0 0 12px', fontSize: 10, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(245,241,232,0.4)' }}>
            Ciclos anteriores
          </h3>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 12, padding: '13px 16px', borderRadius: 14,
            background: 'rgba(245,241,232,0.025)', border: '1px solid rgba(245,241,232,0.06)', opacity: 0.6,
          }}>
            <span style={{ fontSize: 16 }}>🔒</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, color: '#F5F1E8' }}>Revolução Solar 2025 – 2026</div>
              <div style={{ fontSize: 11, color: 'rgba(245,241,232,0.4)' }}>Disponível a partir do seu segundo ano com {astrologer?.name}</div>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div style={{ paddingTop: 28, borderTop: '1px solid rgba(245,241,232,0.07)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ width: 24, height: 24, borderRadius: '50%', background: `${accentColor}20`, border: `1.5px solid ${accentColor}40`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: accentColor, fontSize: 8, fontWeight: 600 }}>{astrologer?.initials || initialsOf(astrologer?.name)}</div>
            <span style={{ fontSize: 12, color: 'rgba(245,241,232,0.45)' }}>Criado por <span style={{ color: '#F5F1E8' }}>{astrologer?.name}</span></span>
          </div>
          <div style={{ fontSize: 10, color: 'rgba(245,241,232,0.25)', display: 'flex', alignItems: 'center', gap: 4 }}>
            <OrbitasMark size={12} />
            Órbitas
          </div>
        </div>
      </div>

      {/* Floating check-in button — some no modo prévia: astróloga não é a consulente, "nada aqui é editável" */}
      {!previewMode && <button onClick={() => setShowCheckin(true)} style={{
        position: 'fixed', bottom: 24, right: 20, left: 20,
        maxWidth: 480, margin: '0 auto',
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
        padding: '14px 24px', borderRadius: 999,
        border: checkedInThisWeek ? '1px solid rgba(245,241,232,0.18)' : 'none',
        background: checkedInThisWeek ? 'rgba(26,22,18,0.94)' : accentColor,
        color: checkedInThisWeek ? '#F5F1E8' : '#100D0A', fontSize: 14, fontWeight: 600,
        cursor: 'pointer', fontFamily: 'Inter, sans-serif',
        backdropFilter: checkedInThisWeek ? 'blur(16px)' : 'none',
        boxShadow: checkedInThisWeek ? '0 4px 24px rgba(0,0,0,0.35)' : `0 4px 24px ${accentColor}50`,
        transition: 'all 0.15s',
        zIndex: 100,
      }}>
        <span style={{ fontSize: 15 }}>{checkedInThisWeek ? '✓' : '✦'}</span>
        {checkedInThisWeek ? 'Check-in feito esta semana' : 'Check-in da semana'}
      </button>}

      {showCheckin && <CheckInModal onClose={() => setShowCheckin(false)} accentColor={accentColor} onSubmit={handleSubmitCheckin} />}

      <style>{`
        @media (min-width: 640px) {
          .months-mobile { display: none !important; }
          .months-desktop { display: grid !important; }
          button[style*="left: 20px"] {
            left: auto !important;
            right: 28px !important;
            width: auto !important;
          }
        }
      `}</style>
    </div>
  );
};

// ── Monthly detail ─────────────────────────────────────────
const PortalMonthScreen = ({ mes, astrologer, onBack, accentColor, currentIdx, meses, hasCheckin = false }) => {
  const mesIdx = mes.i - 1;
  const isCurrent = mesIdx === currentIdx;

  const handleExportMonth = () => {
    const lines = [
      `${mes.nome} · Mês ${mes.i}`, '',
      `Foco: ${mes.foco}`, mes.foco_detail || '', '',
      `Risco: ${mes.risco}`, mes.risco_detail || '', '',
      `Oportunidade: ${mes.oportunidade}`, mes.oportunidade_detail || '', '',
      mes.acoes?.length ? `Ações: ${mes.acoes.join('; ')}` : '',
      mes.rotina?.length ? `Rotina: ${mes.rotina.join('; ')}` : '',
      '', `Gerado pelo Órbitas · portal de ${astrologer?.brand_name || ''}`,
    ].filter(Boolean);
    const blob = new Blob([lines.join('\n')], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = `resumo-${mes.nome.toLowerCase()}.txt`;
    document.body.appendChild(a); a.click(); document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ minHeight: '100vh', background: '#100D0A', fontFamily: 'Inter, sans-serif', color: '#F5F1E8' }}>
      <GrainOverlay />
      <div style={{
        position: 'absolute', top: -60, left: '50%', transform: 'translateX(-50%)',
        width: '100vw', height: 300, pointerEvents: 'none',
        background: `radial-gradient(ellipse at 50% 0%, ${accentColor}18, transparent 68%)`,
      }} />

      {/* Sticky header */}
      <header style={{
        padding: '12px 20px', display: 'flex', alignItems: 'center', gap: 14,
        borderBottom: '1px solid rgba(245,241,232,0.07)',
        position: 'sticky', top: 0, zIndex: 50,
        background: 'rgba(16,13,10,0.9)', backdropFilter: 'blur(16px)',
      }}>
        <button onClick={onBack} style={{
          background: 'none', border: 'none', color: 'rgba(245,241,232,0.5)',
          cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 5,
          fontSize: 13, padding: 0, fontFamily: 'Inter, sans-serif',
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M15 18l-6-6 6-6"/></svg>
          Painel
        </button>
        <span style={{ color: 'rgba(245,241,232,0.2)' }}>·</span>
        <span style={{ fontSize: 14, color: '#F5F1E8' }}>{mes.emoji} {mes.nome}</span>
        {isCurrent && (
          <span style={{ fontSize: 9, padding: '2px 8px', borderRadius: 999, background: `${accentColor}18`, color: accentColor, border: `1px solid ${accentColor}30` }}>
            Atual
          </span>
        )}
        {hasCheckin && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginLeft: 'auto' }}>
            <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#8CAF88' }} />
            <span style={{ fontSize: 10, color: '#8CAF88' }}>Check-in feito</span>
          </div>
        )}
      </header>

      <div style={{ maxWidth: 720, margin: '0 auto', padding: '32px 20px 80px', position: 'relative', zIndex: 1 }}>
        {/* Title */}
        <div style={{ marginBottom: 32 }}>
          <p style={{ margin: '0 0 5px', fontSize: 10, color: 'rgba(245,241,232,0.4)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>
            Mês {mes.i} · Seu ano solar
          </p>
          <h1 style={{ margin: 0, fontSize: 'clamp(26px,6vw,34px)', fontFamily: '"Instrument Serif", serif', fontWeight: 400, letterSpacing: '-0.02em' }}>
            {mes.emoji} {mes.nome}
          </h1>
        </div>

        {/* Foco / Risco / Oportunidade */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 36 }}>
          {[
            { label: 'Foco',         icon: '◎', color: '#7A9EC9', headline: mes.foco,        detail: mes.foco_detail },
            { label: 'Risco',        icon: '⚠', color: '#E76F51', headline: mes.risco,       detail: mes.risco_detail },
            { label: 'Oportunidade', icon: '✦', color: '#8CAF88', headline: mes.oportunidade, detail: mes.oportunidade_detail },
          ].map(item => (
            <div key={item.label} style={{ padding: '18px 20px', borderRadius: 16, background: `${item.color}0a`, border: `1px solid ${item.color}22` }}>
              <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                <span style={{ fontSize: 16, color: item.color, marginTop: 2, flexShrink: 0 }}>{item.icon}</span>
                <div>
                  <div style={{ fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.1em', color: item.color, fontWeight: 600, marginBottom: 5 }}>{item.label}</div>
                  <div style={{ fontSize: 15, fontFamily: '"Instrument Serif", serif', color: '#F5F1E8', marginBottom: 6, lineHeight: 1.35 }}>{item.headline}</div>
                  {item.detail && <div style={{ fontSize: 13, color: 'rgba(245,241,232,0.55)', lineHeight: 1.65 }}>{item.detail}</div>}
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Ações */}
        <div style={{ marginBottom: 28 }}>
          <h3 style={{ margin: '0 0 12px', fontSize: 10, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(245,241,232,0.4)' }}>Ações do mês</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {mes.acoes.map((acao, i) => (
              <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'center', padding: '11px 15px', borderRadius: 12, background: 'rgba(245,241,232,0.03)', border: '1px solid rgba(245,241,232,0.07)' }}>
                <div style={{ width: 20, height: 20, borderRadius: '50%', border: `1.5px solid ${accentColor}35`, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <span style={{ fontSize: 9, color: accentColor, fontWeight: 600 }}>{i + 1}</span>
                </div>
                <span style={{ fontSize: 13, color: '#F5F1E8' }}>{acao}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Rotina */}
        <div style={{ marginBottom: 40 }}>
          <h3 style={{ margin: '0 0 12px', fontSize: 10, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(245,241,232,0.4)' }}>Sugestões de rotina</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {mes.rotina.map((r, i) => (
              <div key={i} style={{ padding: '10px 15px', borderRadius: 12, background: 'rgba(196,155,201,0.08)', border: '1px solid rgba(196,155,201,0.18)', fontSize: 13, color: 'rgba(245,241,232,0.6)', display: 'flex', gap: 8, alignItems: 'center' }}>
                <span style={{ color: '#C49BC9', flexShrink: 0 }}>↻</span>
                {r}
              </div>
            ))}
          </div>
        </div>

        {/* Text download */}
        <button onClick={handleExportMonth} style={{
          width: '100%', marginBottom: 20, padding: '11px 0', borderRadius: 999,
          border: `1px solid ${accentColor}35`, background: `${accentColor}0c`, color: accentColor,
          fontSize: 13, fontWeight: 500, cursor: 'pointer', fontFamily: 'Inter, sans-serif',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
          Baixar resumo deste mês (.txt)
        </button>

        {/* Nav */}
        <div style={{ paddingTop: 24, borderTop: '1px solid rgba(245,241,232,0.07)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <button onClick={onBack} style={{ background: 'none', border: 'none', color: 'rgba(245,241,232,0.4)', cursor: 'pointer', fontSize: 13, padding: 0, display: 'flex', alignItems: 'center', gap: 5, fontFamily: 'Inter, sans-serif' }}>
            ← Painel anual
          </button>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <div style={{ width: 20, height: 20, borderRadius: '50%', background: `${accentColor}20`, border: `1.5px solid ${accentColor}40`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: accentColor, fontSize: 7, fontWeight: 600 }}>{astrologer?.initials || initialsOf(astrologer?.name)}</div>
            <span style={{ fontSize: 11, color: 'rgba(245,241,232,0.3)' }}>{astrologer?.name}</span>
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { PortalScreen, PortalMonthScreen });
