// Órbita — Settings screen
//
// Estrutura portada da referência (dashboard "Untitled UI"): cabeçalho de
// perfil (nome/subtítulo/busca/convidar/upgrade), abas horizontais, banner
// de status contextual por aba, linhas com rótulo+descrição à esquerda e
// controle à direita separadas por borda fina, e a seção "Navegadores e
// dispositivos" com localização, último acesso e remoção com toast de desfazer.
//
// Vermelho de erro/perigo fica fixo (não amarrado ao tema), igual ao resto
// do protótipo (orbita-components.jsx, orbita-onboarding.jsx, orbita-portal.jsx
// já usam essa mesma cor fixa pra estados de erro).
const DANGER_COLOR = '#E76F51';

const PLAN_DATA = {
  current: 'atelier',
  plans: [
    {
      id: 'inicio',
      name: 'Início',
      price: 'R$89',
      period: '/mês',
      desc: 'Para astrólogas que estão começando',
      sessions: 10,
      features: ['10 sessões/mês', 'Portal da consulente', 'Transcrição automática', 'Suporte por e-mail'],
      missing: ['Cards com IA', 'Múltiplas astrólogas', 'Domínio próprio'],
    },
    {
      id: 'atelier',
      name: 'Atelier',
      price: 'R$189',
      period: '/mês',
      desc: 'Para a prática profissional consolidada',
      sessions: 25,
      features: ['25 sessões/mês', 'Portal da consulente', 'Cards com IA + reescrita', 'Check-in de consulentes', 'Suporte prioritário', 'Analytics básico'],
      missing: ['Múltiplas astrólogas', 'Domínio próprio'],
      current: true,
    },
    {
      id: 'studio',
      name: 'Studio',
      price: 'R$389',
      period: '/mês',
      desc: 'Para escolas e práticas em equipe',
      sessions: 100,
      features: ['Sessões ilimitadas', 'Múltiplas astrólogas (até 5)', 'Domínio próprio', 'Analytics avançado', 'API access', 'Onboarding dedicado'],
      missing: [],
    },
  ],
  invoices: [
    { id: 'inv-001', date: '01/05/2026', amount: 'R$189,00', status: 'Pago', plan: 'Atelier' },
    { id: 'inv-002', date: '01/04/2026', amount: 'R$189,00', status: 'Pago', plan: 'Atelier' },
    { id: 'inv-003', date: '01/03/2026', amount: 'R$189,00', status: 'Pago', plan: 'Atelier' },
  ],
};

const SETTINGS_SECTIONS = [
  { id: 'geral',      label: 'Geral' },
  { id: 'seguranca',  label: 'Segurança' },
  { id: 'plano',      label: 'Plano' },
  { id: 'notif',      label: 'Notificações' },
  { id: 'marca',      label: 'Marca' },
];
const SETTINGS_TAB_LABEL = Object.fromEntries(SETTINGS_SECTIONS.map(s => [s.id, s.label]));

// Índice plano só pra busca — mapeia rótulo de cada campo/ação pra aba onde ele mora.
const SETTINGS_SEARCH_INDEX = [
  { tab: 'geral', label: 'Foto de perfil' },
  { tab: 'geral', label: 'Nome completo' },
  { tab: 'geral', label: 'E-mail' },
  { tab: 'geral', label: 'Exportar todos os meus dados' },
  { tab: 'geral', label: 'Apagar dados da conta' },
  { tab: 'geral', label: 'Deletar conta permanentemente' },
  { tab: 'seguranca', label: 'Senha' },
  { tab: 'seguranca', label: 'Verificação em duas etapas' },
  { tab: 'seguranca', label: 'Navegadores e dispositivos' },
  { tab: 'plano', label: 'Plano atual e uso de sessões' },
  { tab: 'plano', label: 'Comparar planos' },
  { tab: 'plano', label: 'Histórico de faturas' },
  { tab: 'plano', label: 'Cancelar assinatura' },
  { tab: 'notif', label: 'Sessão pronta para revisão' },
  { tab: 'notif', label: 'Check-in de consulente' },
  { tab: 'notif', label: 'Cobrança e fatura' },
  { tab: 'notif', label: 'Dicas e novidades' },
  { tab: 'marca', label: 'Nome da marca' },
  { tab: 'marca', label: 'Logo' },
  { tab: 'marca', label: 'Cor principal' },
  { tab: 'marca', label: 'Endereço do portal' },
  { tab: 'marca', label: 'Domínio próprio' },
];

// ── CSS mobile-first compartilhado da tela de Settings ─────
const SETTINGS_CSS = `
  @media (max-width: 640px) {
    .orbita-settings-profile { flex-direction: column; align-items: stretch !important; }
    .orbita-settings-profile > div:last-child { width: 100%; }
    .orbita-settings-search { max-width: none !important; flex-basis: 100% !important; }
    .orbita-settings-row { flex-direction: column; gap: 10px !important; }
    .orbita-settings-row > div:first-child { flex-basis: auto !important; max-width: none !important; }
    .orbita-plan-grid { grid-template-columns: 1fr !important; }
  }
  .orbita-settings-tabs::-webkit-scrollbar { display: none; }
`;

// ── Shared row / section / banner / tabs ───────────────────
const SettingsRow = ({ label, description, id, children }) => {
  const { theme } = useTheme();
  return (
    <div id={id} className="orbita-settings-row" style={{
      display: 'flex', gap: 24, padding: '18px 0',
      borderBottom: `1px solid ${theme.border}`,
    }}>
      <div style={{ flex: '0 0 240px', maxWidth: 240 }}>
        <div style={{ fontSize: 13.5, fontWeight: 500, color: theme.fg, marginBottom: 4 }}>{label}</div>
        {description && <div style={{ fontSize: 12, color: theme.fgMuted, lineHeight: 1.5 }}>{description}</div>}
      </div>
      <div style={{ flex: 1, minWidth: 0, display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: 10 }}>
        {children}
      </div>
    </div>
  );
};

const SettingsSectionBlock = ({ title, description, children, style = {} }) => {
  const { theme } = useTheme();
  return (
    <div style={{ marginBottom: 40, ...style }}>
      {title && <h3 style={{ margin: '0 0 4px', fontSize: 14, fontWeight: 600, color: theme.fg }}>{title}</h3>}
      {description && <p style={{ margin: '0 0 14px', fontSize: 12.5, color: theme.fgMuted }}>{description}</p>}
      <div>{children}</div>
    </div>
  );
};

const SettingsBanner = ({ pct, title, desc, tone = 'accent', onDismiss, primaryLabel, onPrimary }) => {
  const { theme } = useTheme();
  const color = tone === 'danger' ? DANGER_COLOR : theme.accent;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 18, padding: '16px 20px', borderRadius: 16,
      background: `${color}12`, border: `1px solid ${color}35`, marginBottom: 28, flexWrap: 'wrap',
    }}>
      {typeof pct === 'number' ? (
        <div style={{ position: 'relative', width: 42, height: 42, flexShrink: 0 }}>
          <svg viewBox="0 0 44 44" width="42" height="42">
            <circle cx="22" cy="22" r="18" fill="none" stroke={`${color}25`} strokeWidth="4" />
            <circle cx="22" cy="22" r="18" fill="none" stroke={color} strokeWidth="4"
              strokeDasharray={`${(pct / 100) * 113} 113`} strokeLinecap="round" transform="rotate(-90 22 22)" />
          </svg>
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10.5, fontWeight: 700, color }}>{pct}%</div>
        </div>
      ) : (
        <div style={{ fontSize: 22, color, flexShrink: 0 }}>⚠</div>
      )}
      <div style={{ flex: 1, minWidth: 180 }}>
        <div style={{ fontSize: 13.5, fontWeight: 600, color: theme.fg, marginBottom: 3 }}>{title}</div>
        <div style={{ fontSize: 12, color: theme.fgMuted }}>{desc}</div>
      </div>
      <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
        {onDismiss && <BtnGhost small onClick={onDismiss}>Dispensar</BtnGhost>}
        {primaryLabel && (
          <BtnPrimary small onClick={onPrimary} style={tone === 'danger' ? { background: DANGER_COLOR, color: '#100D0A' } : {}}>
            {primaryLabel}
          </BtnPrimary>
        )}
      </div>
    </div>
  );
};

const SettingsTabs = ({ sections, active, onChange }) => {
  const { theme } = useTheme();
  return (
    <div className="orbita-settings-tabs" style={{ display: 'flex', gap: 4, borderBottom: `1px solid ${theme.border}`, marginBottom: 32, overflowX: 'auto' }}>
      {sections.map(s => {
        const isActive = active === s.id;
        return (
          <button key={s.id} onClick={() => onChange(s.id)} style={{
            padding: '10px 16px', background: 'none', border: 'none',
            borderBottom: `2px solid ${isActive ? theme.accent : 'transparent'}`,
            color: isActive ? theme.fg : theme.fgMuted, fontSize: 13, fontWeight: isActive ? 600 : 500,
            cursor: 'pointer', fontFamily: 'Inter, sans-serif', whiteSpace: 'nowrap', marginBottom: -1,
            transition: 'color .15s, border-color .15s',
          }}>{s.label}</button>
        );
      })}
    </div>
  );
};

const ToggleSwitch = ({ on, onToggle }) => {
  const { theme } = useTheme();
  return (
    <button onClick={onToggle} style={{
      width: 42, height: 24, borderRadius: 999, border: 'none', flexShrink: 0,
      background: on ? theme.accent : theme.inputBg, cursor: 'pointer', position: 'relative', transition: 'background 0.2s',
    }}>
      <div style={{
        width: 16, height: 16, borderRadius: '50%', background: on ? theme.bg : theme.fgDim,
        position: 'absolute', top: 4, left: on ? 22 : 4, transition: 'left 0.2s, background 0.2s',
      }} />
    </button>
  );
};

// ── Busca global de configurações (dropdown de resultados) ─
const SettingsSearch = ({ onNavigate }) => {
  const { theme } = useTheme();
  const [query, setQuery] = React.useState('');
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);

  React.useEffect(() => {
    const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const q = query.trim().toLowerCase();
  const results = q ? SETTINGS_SEARCH_INDEX.filter(r => r.label.toLowerCase().includes(q)).slice(0, 6) : [];

  const goTo = (r) => { onNavigate(r.tab); setQuery(''); setOpen(false); };

  return (
    <div ref={ref} className="orbita-settings-search" style={{ position: 'relative', flex: '1 1 200px', maxWidth: 260 }}>
      <div style={{ position: 'relative' }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={theme.fgDim} strokeWidth="2"
          style={{ position: 'absolute', left: 11, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }}>
          <circle cx="11" cy="11" r="7" /><path d="M21 21l-4.35-4.35" />
        </svg>
        <input
          value={query}
          onChange={e => { setQuery(e.target.value); setOpen(true); }}
          onFocus={() => setOpen(true)}
          placeholder="Buscar em configurações"
          style={{
            width: '100%', boxSizing: 'border-box', background: theme.inputBg, border: `1px solid ${theme.border}`,
            borderRadius: 10, padding: '8px 12px 8px 32px', color: theme.fg, fontSize: 13,
            fontFamily: 'Inter, sans-serif', outline: 'none',
          }}
        />
      </div>
      {open && q && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 6px)', left: 0, right: 0,
          background: theme.id === 'light' ? '#FDFAF5' : '#1F1A14',
          border: `1px solid ${theme.border}`, borderRadius: 12, overflow: 'hidden', zIndex: 200,
          boxShadow: theme.id === 'dark' ? '0 16px 48px rgba(0,0,0,0.5)' : '0 8px 30px rgba(0,0,0,0.12)',
        }}>
          {results.length === 0 ? (
            <div style={{ padding: '12px 14px', fontSize: 12.5, color: theme.fgMuted }}>Nada encontrado para "{query}"</div>
          ) : results.map((r, i) => (
            <button key={r.tab + r.label} onClick={() => goTo(r)} style={{
              display: 'flex', width: '100%', alignItems: 'center', justifyContent: 'space-between', gap: 10,
              padding: '10px 14px', background: 'none', border: 'none',
              borderBottom: i < results.length - 1 ? `1px solid ${theme.border}` : 'none',
              cursor: 'pointer', fontFamily: 'Inter, sans-serif', textAlign: 'left',
            }}
            onMouseEnter={e => e.currentTarget.style.background = theme.inputBg}
            onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
            >
              <span style={{ fontSize: 13, color: theme.fg }}>{r.label}</span>
              <span style={{ fontSize: 10, color: theme.fgDim, textTransform: 'uppercase', letterSpacing: '0.05em', flexShrink: 0 }}>{SETTINGS_TAB_LABEL[r.tab]}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

// ── Convidar colega (gated pelo plano Studio) ──────────────
const InviteModal = ({ onClose, isStudio, onUpgrade }) => {
  const { theme } = useTheme();
  const [email, setEmail] = React.useState('');
  const [sent, setSent] = React.useState(false);
  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(16,13,10,0.7)', backdropFilter: 'blur(6px)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 4000, padding: 20 }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{ background: theme.surface, border: `1px solid ${theme.border}`, borderRadius: 18, padding: 28, width: '100%', maxWidth: 400, boxSizing: 'border-box' }}>
        <h3 style={{ margin: '0 0 8px', fontFamily: '"Instrument Serif", serif', fontSize: 22, color: theme.fg, fontWeight: 400 }}>Convidar colega</h3>
        {isStudio ? (
          sent ? (
            <div style={{ fontSize: 13, color: theme.success, margin: '16px 0 4px' }}>✓ Convite enviado para {email}</div>
          ) : (
            <>
              <p style={{ margin: '0 0 18px', fontSize: 13, color: theme.fgMuted, lineHeight: 1.6 }}>Convide outra astróloga para colaborar na sua conta Studio.</p>
              <input value={email} onChange={e => setEmail(e.target.value)} type="email" placeholder="email@exemplo.com" style={{
                width: '100%', boxSizing: 'border-box', background: theme.inputBg, border: `1px solid ${theme.border}`,
                borderRadius: 10, padding: '10px 14px', color: theme.fg, fontSize: 14,
                fontFamily: 'Inter, sans-serif', outline: 'none', marginBottom: 16,
              }} />
              <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
                <BtnGhost small onClick={onClose}>Cancelar</BtnGhost>
                <BtnPrimary small disabled={!email.includes('@')} onClick={() => setSent(true)}>Enviar convite</BtnPrimary>
              </div>
            </>
          )
        ) : (
          <>
            <p style={{ margin: '0 0 20px', fontSize: 13, color: theme.fgMuted, lineHeight: 1.6 }}>
              Convide outras astrólogas pra colaborar na sua conta. Esse recurso está disponível a partir do plano <strong style={{ color: theme.fg }}>Studio</strong>.
            </p>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
              <BtnGhost small onClick={onClose}>Fechar</BtnGhost>
              <BtnPrimary small onClick={() => { onClose(); onUpgrade(); }}>Fazer upgrade</BtnPrimary>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

// ── Cabeçalho de perfil ─────────────────────────────────────
const SettingsProfileHeader = ({ astrologer, onNavigateSearch, onInvite, onUpgrade }) => {
  const { theme } = useTheme();
  return (
    <div className="orbita-settings-profile" style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 20, flexWrap: 'wrap', marginBottom: 28 }}>
      <div>
        <h1 style={{ margin: '0 0 4px', fontFamily: '"Instrument Serif", serif', fontSize: 30, fontWeight: 400, color: theme.fg }}>{astrologer.name}</h1>
        <p style={{ margin: 0, fontSize: 13.5, color: theme.fgMuted }}>Gerencie sua conta e suas preferências aqui.</p>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
        <SettingsSearch onNavigate={onNavigateSearch} />
        <BtnGhost small onClick={onInvite}>+ Convidar</BtnGhost>
        <BtnPrimary small onClick={onUpgrade}>Fazer upgrade</BtnPrimary>
      </div>
    </div>
  );
};

// ── Section: Geral ──────────────────────────────────────────
const SectionGeral = () => {
  const { theme } = useTheme();
  const { astrologer } = window.ORBITA_DATA;
  const [name, setName] = React.useState(astrologer.name);
  const [email, setEmail] = React.useState(astrologer.email);
  const [dirty, setDirty] = React.useState(false);
  const [saved, setSaved] = React.useState(false);

  const change = (setter) => (e) => { setter(e.target.value); setDirty(true); setSaved(false); };
  const save = () => { setSaved(true); setDirty(false); setTimeout(() => setSaved(false), 2400); };

  return (
    <div>
      <SettingsSectionBlock title="Perfil" description="Como você aparece dentro do Órbitas e no portal das suas consulentes.">
        <SettingsRow id="row-foto" label="Foto de perfil" description="Aparece no seu perfil e no rodapé dos portais publicados.">
          <Avatar name={name} size={40} />
          <MockButton label="Alterar foto" done="Foto atualizada" />
        </SettingsRow>
        <SettingsRow id="row-nome" label="Nome completo" description="Usado nos seus portais e nas comunicações da conta.">
          <input value={name} onChange={change(setName)} style={{ ...inputStyle(theme), maxWidth: 320 }} />
        </SettingsRow>
        <SettingsRow id="row-email" label="E-mail" description="Usado pra login e notificações da conta.">
          <input value={email} onChange={change(setEmail)} type="email" style={{ ...inputStyle(theme), maxWidth: 320 }} />
        </SettingsRow>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center', paddingTop: 6 }}>
          <button onClick={save} disabled={!dirty && !saved} style={primaryBtnStyle(theme, !dirty && !saved)}>
            {saved ? '✓ Salvo' : 'Salvar alterações'}
          </button>
          {saved && <span style={{ fontSize: 12, color: theme.success }}>Dados atualizados</span>}
        </div>
      </SettingsSectionBlock>

      <SettingsSectionBlock title="Seus dados" description="Baixe ou remova as informações associadas à sua conta.">
        <SettingsRow id="row-exportar" label="Exportar dados" description="Recebe um .zip com tudo que o Órbitas guarda sobre sua conta.">
          <MockButton label="Exportar todos os meus dados" done="Preparando o .zip — enviaremos o link por e-mail" />
        </SettingsRow>
        <SettingsRow id="row-apagar-dados" label="Apagar dados da conta" description="Remove sessões, portais e consulentes — mantém login ativo.">
          <MockButton label="Apagar todos os dados" done="Solicitação registrada — processada em até 48h" danger />
        </SettingsRow>
      </SettingsSectionBlock>

      <SettingsSectionBlock title="Zona de perigo">
        <div style={{ border: `1px solid ${DANGER_COLOR}30`, borderRadius: 14, padding: '4px 20px', background: `${DANGER_COLOR}08` }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, padding: '16px 0', flexWrap: 'wrap' }}>
            <div>
              <div style={{ fontSize: 13.5, fontWeight: 500, color: theme.fg, marginBottom: 4 }}>Deletar conta permanentemente</div>
              <div style={{ fontSize: 12, color: theme.fgMuted }}>Apaga sua conta, portais publicados e todo o histórico. Não pode ser desfeito depois de 7 dias.</div>
            </div>
            <MockButton label="Deletar conta" done="Conta agendada para exclusão — você tem 7 dias pra desfazer" danger />
          </div>
        </div>
      </SettingsSectionBlock>
    </div>
  );
};

// ── Section: Segurança ──────────────────────────────────────
const BROWSER_META = {
  brave:   { letter: 'B', color: '#FB542B' },
  safari:  { letter: 'S', color: '#3D9CE8' },
  chrome:  { letter: 'C', color: '#8CAF88' },
  firefox: { letter: 'F', color: '#F4A261' },
};

const INITIAL_DEVICES = [
  { id: 'dev-1', icon: 'brave',   label: 'Brave · macOS',       location: 'São Paulo, Brasil',         current: true },
  { id: 'dev-2', icon: 'safari',  label: "iPhone de Luciana",    location: 'São Paulo, Brasil',         current: true },
  { id: 'dev-3', icon: 'chrome',  label: 'Chrome · Windows',    location: 'Belo Horizonte, Brasil',    lastActive: '3 dias atrás' },
  { id: 'dev-4', icon: 'firefox', label: 'Firefox · macOS',     location: 'Curitiba, Brasil',          lastActive: '1 mês atrás' },
];

const DeviceRow = ({ device, onRemove }) => {
  const { theme } = useTheme();
  const meta = BROWSER_META[device.icon] || { letter: '?', color: theme.fgMuted };
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 0', borderBottom: `1px solid ${theme.border}` }}>
      <div style={{
        width: 32, height: 32, borderRadius: 9, flexShrink: 0,
        background: `${meta.color}22`, border: `1.5px solid ${meta.color}55`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: meta.color, fontSize: 13, fontWeight: 700,
      }}>{meta.letter}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 500, color: theme.fg }}>{device.label}</div>
        <div style={{ fontSize: 12, color: theme.fgMuted, marginTop: 2 }}>
          {device.location} · {device.current ? 'Sessão atual' : device.lastActive}
        </div>
      </div>
      <button onClick={() => onRemove(device.id)} title="Remover" style={{
        background: 'none', border: 'none', cursor: 'pointer', color: theme.fgDim, padding: 6,
        display: 'flex', flexShrink: 0, transition: 'color 0.15s',
      }}
      onMouseEnter={e => e.currentTarget.style.color = DANGER_COLOR}
      onMouseLeave={e => e.currentTarget.style.color = theme.fgDim}
      >
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <polyline points="3 6 5 6 21 6" /><path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2" />
        </svg>
      </button>
    </div>
  );
};

const UndoToast = ({ removed, onUndo, onDismiss }) => {
  if (!removed) return null;
  return (
    <div style={{
      position: 'fixed', bottom: 20, right: 20, left: 20, maxWidth: 380, margin: '0 0 0 auto',
      background: '#18140F', color: '#F5F1E8', borderRadius: 14, padding: '14px 16px',
      display: 'flex', alignItems: 'center', gap: 12, boxShadow: '0 12px 40px rgba(0,0,0,0.35)',
      zIndex: 2000, fontFamily: 'Inter, sans-serif',
    }}>
      <span style={{ color: '#8CAF88', fontSize: 16, flexShrink: 0 }}>✓</span>
      <div style={{ flex: 1, fontSize: 13, minWidth: 0 }}>
        <strong>{removed.device.label}</strong> removido
      </div>
      <button onClick={onUndo} style={{ background: 'none', border: 'none', color: '#F4A261', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'Inter, sans-serif', flexShrink: 0 }}>Desfazer</button>
      <button onClick={onDismiss} style={{ background: 'none', border: 'none', color: 'rgba(245,241,232,0.4)', fontSize: 16, cursor: 'pointer', lineHeight: 1, flexShrink: 0 }}>×</button>
    </div>
  );
};

const SectionSeguranca = () => {
  const { theme } = useTheme();
  const [twoFA, setTwoFA] = React.useState(true);
  const [bannerDismissed, setBannerDismissed] = React.useState(false);
  const [devices, setDevices] = React.useState(INITIAL_DEVICES);
  const [removed, setRemoved] = React.useState(null);
  const removeTimeoutRef = React.useRef(null);

  const pct = 60 + (twoFA ? 40 : 0);

  const handleRemove = (id) => {
    setDevices(prev => {
      const idx = prev.findIndex(d => d.id === id);
      if (idx === -1) return prev;
      clearTimeout(removeTimeoutRef.current);
      setRemoved({ device: prev[idx], index: idx });
      removeTimeoutRef.current = setTimeout(() => setRemoved(null), 5000);
      return prev.filter(d => d.id !== id);
    });
  };
  const handleUndo = () => {
    if (!removed) return;
    clearTimeout(removeTimeoutRef.current);
    setDevices(prev => {
      const copy = [...prev];
      copy.splice(Math.min(removed.index, copy.length), 0, removed.device);
      return copy;
    });
    setRemoved(null);
  };
  const handleDismissToast = () => { clearTimeout(removeTimeoutRef.current); setRemoved(null); };

  const scrollToRow = (id) => document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'center' });

  return (
    <div>
      {!bannerDismissed && (
        <SettingsBanner
          pct={pct}
          title={pct === 100 ? 'Sua conta está totalmente protegida' : `Segurança da sua conta está em ${pct}%`}
          desc="Revise sua senha e a verificação em duas etapas regularmente."
          onDismiss={() => setBannerDismissed(true)}
          primaryLabel="Revisar segurança"
          onPrimary={() => scrollToRow('row-senha')}
        />
      )}

      <SettingsSectionBlock title="Básico">
        <SettingsRow id="row-senha" label="Senha" description="Defina uma senha para proteger sua conta.">
          <span style={{ fontFamily: 'monospace', letterSpacing: 2, color: theme.fgMuted, fontSize: 13 }}>••••••••••••</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 12, color: theme.success }}>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M20 6L9 17l-5-5" /></svg>
            Muito segura
          </span>
          <MockButton label="Editar" done="Link de redefinição enviado pro seu e-mail" style={{ marginLeft: 'auto' }} />
        </SettingsRow>
        <SettingsRow id="row-2fa" label="Verificação em duas etapas" description="Exige um código junto com a senha ao entrar.">
          <ToggleSwitch on={twoFA} onToggle={() => setTwoFA(v => !v)} />
          <span style={{ fontSize: 13, color: theme.fgMuted }}>{twoFA ? 'Ativada' : 'Desativada'}</span>
        </SettingsRow>
      </SettingsSectionBlock>

      <SettingsSectionBlock title="Navegadores e dispositivos" description="Estes navegadores e dispositivos estão conectados à sua conta. Remova qualquer um que você não reconheça.">
        <div>
          {devices.map(d => <DeviceRow key={d.id} device={d} onRemove={handleRemove} />)}
          {devices.length === 0 && <p style={{ fontSize: 13, color: theme.fgMuted, padding: '14px 0' }}>Nenhum dispositivo conectado.</p>}
        </div>
      </SettingsSectionBlock>

      <UndoToast removed={removed} onUndo={handleUndo} onDismiss={handleDismissToast} />
    </div>
  );
};

// ── Section: Marca ─────────────────────────────────────────
const SectionMarca = ({ onUpgrade }) => {
  const { theme } = useTheme();
  const [brandName, setBrandName] = React.useState('Luciana Vega Astrologia');
  const [brandColor, setBrandColor] = React.useState(theme.accent);
  const [subdomain, setSubdomain] = React.useState('lucianavega');
  const [saved, setSaved] = React.useState(false);

  return (
    <div>
      <SettingsSectionBlock title="Identidade visual" description="Como sua marca aparece no portal da consulente.">
        <SettingsRow id="row-brand-nome" label="Nome da marca" description="Aparece no topo do portal e nos e-mails enviados.">
          <input value={brandName} onChange={e => setBrandName(e.target.value)} style={{ ...inputStyle(theme), maxWidth: 320 }} />
        </SettingsRow>

        <SettingsRow id="row-brand-logo" label="Logo" description="PNG ou SVG, fundo transparente recomendado.">
          <div style={{
            height: 72, width: 140, borderRadius: 12, border: `2px dashed ${theme.border}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer', color: theme.fgDim, fontSize: 12, background: theme.inputBg,
          }}>
            ⊕ Trocar logo
          </div>
        </SettingsRow>

        <SettingsRow id="row-brand-cor" label="Cor principal" description="Usada em botões e destaques do portal.">
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
            {['#F4A261', '#E76F51', '#7A9EC9', '#8CAF88', '#C49BC9', '#F4C261'].map(c => (
              <button key={c} onClick={() => setBrandColor(c)} style={{
                width: 26, height: 26, borderRadius: '50%', background: c, border: 'none', cursor: 'pointer',
                boxShadow: brandColor === c ? `0 0 0 2px ${theme.bg}, 0 0 0 4px ${c}` : 'none', transition: 'box-shadow 0.15s',
              }} />
            ))}
            <input type="color" value={brandColor} onChange={e => setBrandColor(e.target.value)} style={{ width: 26, height: 26, borderRadius: 8, border: 'none', cursor: 'pointer', background: 'none', padding: 0 }} />
            <input value={brandColor} onChange={e => setBrandColor(e.target.value)} style={{
              width: 90, background: theme.inputBg, border: `1px solid ${theme.border}`, borderRadius: 8,
              padding: '6px 8px', color: theme.fg, fontSize: 12, fontFamily: 'monospace', outline: 'none',
            }} />
          </div>
        </SettingsRow>

        <SettingsRow id="row-brand-subdominio" label="Endereço do portal" description="Link que suas consulentes recebem para acessar.">
          <div style={{ display: 'flex', alignItems: 'center', background: theme.inputBg, border: `1px solid ${theme.border}`, borderRadius: 10, overflow: 'hidden' }}>
            <span style={{ padding: '9px 0 9px 12px', fontSize: 12, color: theme.fgDim, whiteSpace: 'nowrap' }}>orbita.app/c/</span>
            <input value={subdomain} onChange={e => setSubdomain(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))} style={{
              flex: 1, minWidth: 100, background: 'none', border: 'none', padding: '9px 12px 9px 2px',
              color: theme.fg, fontSize: 13, fontFamily: 'Inter, sans-serif', outline: 'none',
            }} />
          </div>
        </SettingsRow>

        <SettingsRow id="row-brand-dominio" label="Domínio próprio" description="Disponível no plano Studio.">
          <input placeholder="consultas.seudominio.com.br" disabled style={{
            flex: '1 1 200px', minWidth: 160, background: theme.card, border: `1px solid ${theme.border}`,
            borderRadius: 10, padding: '9px 12px', color: theme.fgDim, fontSize: 13,
            fontFamily: 'Inter, sans-serif', outline: 'none', boxSizing: 'border-box', cursor: 'not-allowed',
          }} />
          <BtnGhost small onClick={onUpgrade}>Fazer upgrade</BtnGhost>
        </SettingsRow>

        <div style={{ display: 'flex', gap: 10, alignItems: 'center', paddingTop: 18 }}>
          <button onClick={() => { setSaved(true); setTimeout(() => setSaved(false), 2000); }} style={primaryBtnStyle(theme, false)}>
            {saved ? '✓ Salvo' : 'Salvar alterações'}
          </button>
          {saved && <span style={{ fontSize: 12, color: theme.success }}>Marca atualizada</span>}
        </div>
      </SettingsSectionBlock>
    </div>
  );
};

// ── Section: Plano ─────────────────────────────────────────
const SectionPlano = ({ billingError = false }) => {
  const { theme } = useTheme();
  const [selectedPlan, setSelectedPlan] = React.useState(PLAN_DATA.current);
  const [showCancel, setShowCancel] = React.useState(false);
  const [canceled, setCanceled] = React.useState(false);
  const usedSessions = 8;
  const totalSessions = 25;

  return (
    <div>
      {billingError && (
        <div style={{
          display: 'flex', gap: 14, alignItems: 'flex-start', padding: '16px 18px', borderRadius: 14,
          background: `${DANGER_COLOR}14`, border: `1px solid ${DANGER_COLOR}4d`, marginBottom: 28, flexWrap: 'wrap',
        }}>
          <div style={{ fontSize: 20, lineHeight: 1, color: DANGER_COLOR }}>⚠</div>
          <div style={{ flex: 1, minWidth: 180 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: DANGER_COLOR, marginBottom: 4 }}>Pagamento recusado</div>
            <div style={{ fontSize: 13, color: theme.fgMuted }}>Não conseguimos cobrar o cartão final 4242 em 01/06/2026. Atualize a forma de pagamento para manter o acesso ao Atelier.</div>
          </div>
          <MockButton label="Atualizar cartão →" done="Cartão atualizado — vamos tentar a cobrança de novo" style={{ flexShrink: 0, borderRadius: 999, border: 'none', background: DANGER_COLOR, color: '#100D0A', fontWeight: 600 }} />
        </div>
      )}

      {/* Plano atual */}
      <div style={{ padding: '22px 24px', borderRadius: 18, background: theme.card, border: `1px solid ${theme.borderHover}`, marginBottom: 32 }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 16, flexWrap: 'wrap', gap: 12 }}>
          <div>
            <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.1em', color: theme.fgMuted, marginBottom: 4 }}>Plano atual</div>
            <div style={{ fontFamily: '"Instrument Serif", serif', fontSize: 26, marginBottom: 2, color: theme.fg }}>Atelier</div>
            <div style={{ fontSize: 13, color: theme.fgMuted }}>Renovação em 01/06/2026</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 28, fontFamily: '"Instrument Serif", serif', color: theme.fg }}>R$189</div>
            <div style={{ fontSize: 12, color: theme.fgDim }}>/mês</div>
          </div>
        </div>
        <div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: theme.fgMuted, marginBottom: 8 }}>
            <span>Sessões neste mês</span>
            <span><span style={{ color: theme.fg, fontWeight: 500 }}>{usedSessions}</span> de {totalSessions}</span>
          </div>
          <div style={{ height: 6, background: theme.inputBg, borderRadius: 999, overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${(usedSessions / totalSessions) * 100}%`, background: theme.accent, borderRadius: 999, transition: 'width 0.3s' }} />
          </div>
          <div style={{ fontSize: 11, color: theme.fgDim, marginTop: 6 }}>{totalSessions - usedSessions} sessões restantes</div>
        </div>
      </div>

      {/* Comparação de planos */}
      <h3 style={{ margin: '0 0 16px', fontSize: 13, fontWeight: 500, color: theme.fg }}>Comparar planos</h3>
      <div className="orbita-plan-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 12, marginBottom: 32 }}>
        {PLAN_DATA.plans.map(plan => {
          const isCurrentPlan = plan.id === PLAN_DATA.current;
          const isSelected = plan.id === selectedPlan;
          return (
            <div key={plan.id} onClick={() => setSelectedPlan(plan.id)} style={{
              padding: '20px 18px', borderRadius: 16, cursor: 'pointer',
              background: isCurrentPlan ? theme.card : isSelected ? theme.inputBg : 'transparent',
              border: `1.5px solid ${isCurrentPlan ? theme.borderHover : isSelected ? theme.border : theme.border}`,
              transition: 'all 0.15s', position: 'relative',
            }}>
              {isCurrentPlan && (
                <div style={{ position: 'absolute', top: -1, right: 12, transform: 'translateY(-50%)', background: theme.fg, color: theme.bg, fontSize: 9, fontWeight: 700, padding: '2px 8px', borderRadius: 999, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Atual</div>
              )}
              <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 4, color: theme.fg }}>{plan.name}</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 2, marginBottom: 8 }}>
                <span style={{ fontSize: 22, fontFamily: '"Instrument Serif", serif', color: theme.fg }}>{plan.price}</span>
                <span style={{ fontSize: 11, color: theme.fgDim }}>{plan.period}</span>
              </div>
              <div style={{ fontSize: 11, color: theme.fgDim, marginBottom: 14 }}>{plan.desc}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
                {plan.features.map(f => (
                  <div key={f} style={{ display: 'flex', gap: 6, alignItems: 'flex-start', fontSize: 11, color: theme.fgMuted }}>
                    <span style={{ color: theme.success, flexShrink: 0, marginTop: 1 }}>✓</span> {f}
                  </div>
                ))}
                {plan.missing.map(f => (
                  <div key={f} style={{ display: 'flex', gap: 6, alignItems: 'flex-start', fontSize: 11, color: theme.fgDim }}>
                    <span style={{ flexShrink: 0, marginTop: 1 }}>–</span> {f}
                  </div>
                ))}
              </div>
            </div>
          );
        })}
      </div>

      <div style={{ display: 'flex', gap: 10, marginBottom: 44, flexWrap: 'wrap', alignItems: 'center' }}>
        <MockButton label="Mudar para Studio (upgrade) →" done="Plano alterado pra Studio — vale a partir da próxima fatura" style={{ borderRadius: 999, border: 'none', background: theme.fg, color: theme.bg, fontWeight: 600 }} />
        <MockButton label="Mudar para Início (downgrade)" done="Downgrade agendado pro fim do ciclo atual" style={{ borderRadius: 999 }} />
      </div>

      {/* Faturas */}
      <div>
        <h3 style={{ margin: '0 0 14px', fontSize: 13, fontWeight: 500, color: theme.fg }}>Histórico de faturas</h3>
        <div style={{ border: `1px solid ${theme.border}`, borderRadius: 12, overflow: 'hidden' }}>
          {PLAN_DATA.invoices.map((inv, i) => (
            <div key={inv.id} style={{
              display: 'flex', alignItems: 'center', padding: '14px 18px', flexWrap: 'wrap',
              borderBottom: i < PLAN_DATA.invoices.length - 1 ? `1px solid ${theme.border}` : 'none',
              gap: 16,
            }}>
              <div style={{ flex: 1, minWidth: 100 }}>
                <div style={{ fontSize: 13, color: theme.fg, marginBottom: 2 }}>{inv.plan}</div>
                <div style={{ fontSize: 11, color: theme.fgDim }}>{inv.date}</div>
              </div>
              <div style={{ fontSize: 13, fontWeight: 500, color: theme.fg }}>{inv.amount}</div>
              <span style={{ fontSize: 10, padding: '2px 8px', borderRadius: 999, background: `${theme.success}20`, color: theme.success }}>{inv.status}</span>
              <InvoicePdfButton />
            </div>
          ))}
        </div>
      </div>

      {/* Cancelar */}
      <div style={{ marginTop: 36, paddingTop: 24, borderTop: `1px solid ${theme.border}` }}>
        <button onClick={() => setShowCancel(true)} style={{
          background: 'none', border: 'none', color: theme.fgDim,
          fontSize: 12, cursor: 'pointer', padding: 0, fontFamily: 'Inter, sans-serif',
          textDecoration: 'underline', textUnderlineOffset: '3px',
        }}>
          Cancelar assinatura
        </button>
        {showCancel && (
          <div style={{ marginTop: 14, padding: '16px 18px', borderRadius: 12, background: `${DANGER_COLOR}10`, border: `1px solid ${DANGER_COLOR}30`, maxWidth: 400 }}>
            {canceled ? (
              <div style={{ fontSize: 13, color: theme.success }}>
                ✓ Assinatura cancelada. Seu acesso vai até <strong>01/06/2026</strong>. Dá pra reativar antes disso.
              </div>
            ) : (
              <>
                <div style={{ fontSize: 13, marginBottom: 10, color: theme.fg }}>Tem certeza? Você perderá acesso a todos os portais publicados.</div>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  <button onClick={() => setCanceled(true)} style={{ padding: '7px 16px', borderRadius: 999, border: `1px solid ${DANGER_COLOR}4d`, background: `${DANGER_COLOR}1a`, color: DANGER_COLOR, fontSize: 12, cursor: 'pointer', fontFamily: 'Inter, sans-serif' }}>Sim, cancelar</button>
                  <button onClick={() => setShowCancel(false)} style={{ padding: '7px 16px', borderRadius: 999, border: `1px solid ${theme.border}`, background: 'transparent', color: theme.fgMuted, fontSize: 12, cursor: 'pointer', fontFamily: 'Inter, sans-serif' }}>Manter plano</button>
                </div>
              </>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

// ── Section: Notificações ──────────────────────────────────
const SectionNotif = () => {
  const { theme } = useTheme();
  const [prefs, setPrefs] = React.useState({
    session_ready: true, checkin: true, billing: true, tips: false,
  });
  const toggle = k => setPrefs(p => ({ ...p, [k]: !p[k] }));
  const items = [
    { id: 'session_ready', label: 'Sessão pronta para revisão', desc: 'Quando a IA termina de processar uma sessão' },
    { id: 'checkin', label: 'Check-in de consulente', desc: 'Quando uma consulente registra humor ou nota' },
    { id: 'billing', label: 'Cobrança e fatura', desc: 'Confirmação de pagamento e renovação' },
    { id: 'tips', label: 'Dicas e novidades', desc: 'Funcionalidades novas e boas práticas' },
  ];
  return (
    <div>
      <SettingsSectionBlock title="E-mail" description="Escolha o que você quer receber por e-mail.">
        {items.map(item => (
          <SettingsRow key={item.id} id={`row-notif-${item.id}`} label={item.label} description={item.desc}>
            <ToggleSwitch on={prefs[item.id]} onToggle={() => toggle(item.id)} />
          </SettingsRow>
        ))}
      </SettingsSectionBlock>
    </div>
  );
};

// ── Shared style helpers ───────────────────────────────────
const inputStyle = (theme) => ({
  width: '100%', background: theme.inputBg, border: `1px solid ${theme.border}`,
  borderRadius: 10, padding: '9px 14px', color: theme.fg, fontSize: 14,
  fontFamily: 'Inter, sans-serif', outline: 'none', boxSizing: 'border-box', transition: 'border-color 0.15s',
});
const primaryBtnStyle = (theme, disabled) => ({
  padding: '10px 24px', borderRadius: 999, border: 'none',
  background: disabled ? theme.inputBg : theme.accent,
  color: disabled ? theme.fgDim : theme.bg, fontSize: 13, fontWeight: 600,
  cursor: disabled ? 'default' : 'pointer', fontFamily: 'Inter, sans-serif',
});

// Botão de mock: ao clicar, mostra a confirmação em verde por alguns segundos.
// Evita botão que não faz nada num protótipo.
const MockButton = ({ label, done, danger, style = {} }) => {
  const { theme } = useTheme();
  const [state, setState] = React.useState('idle'); // idle | confirm | done
  const base = danger
    ? { border: `1px solid ${DANGER_COLOR}40`, background: `${DANGER_COLOR}10`, color: DANGER_COLOR }
    : { border: `1px solid ${theme.border}`, background: theme.inputBg, color: theme.fgMuted };
  const commit = () => { setState('done'); setTimeout(() => setState('idle'), 2600); };
  if (state === 'done') {
    return <span style={{ fontSize: 12, color: theme.success, display: 'inline-flex', alignItems: 'center', gap: 6 }}>✓ {done}</span>;
  }
  if (danger && state === 'confirm') {
    return (
      <span style={{ display: 'inline-flex', gap: 8, alignItems: 'center', fontSize: 12, color: theme.fgMuted, flexWrap: 'wrap' }}>
        Tem certeza?
        <button onClick={commit} style={{ ...base, padding: '6px 14px', borderRadius: 999, fontSize: 12, cursor: 'pointer', fontFamily: 'Inter, sans-serif' }}>Confirmar</button>
        <button onClick={() => setState('idle')} style={{ background: 'none', border: 'none', color: theme.fgDim, fontSize: 12, cursor: 'pointer', fontFamily: 'Inter, sans-serif' }}>cancelar</button>
      </span>
    );
  }
  return (
    <button onClick={() => (danger ? setState('confirm') : commit())} style={{
      padding: '9px 18px', borderRadius: 10, fontSize: 13, cursor: 'pointer', fontFamily: 'Inter, sans-serif', ...base, ...style,
    }}>{label}</button>
  );
};

const InvoicePdfButton = () => {
  const { theme } = useTheme();
  const [done, setDone] = React.useState(false);
  return (
    <button onClick={() => { setDone(true); setTimeout(() => setDone(false), 2000); }} style={{
      background: 'none', border: 'none', color: done ? theme.success : theme.fgDim,
      fontSize: 11, cursor: 'pointer', padding: '4px 8px', fontFamily: 'Inter, sans-serif',
    }}>{done ? '✓ baixado' : 'PDF'}</button>
  );
};

// ── Settings Screen ────────────────────────────────────────
const SettingsScreen = ({ billingError = false }) => {
  const { theme } = useTheme();
  const { astrologer } = window.ORBITA_DATA;
  const [activeSection, setActiveSection] = React.useState(billingError ? 'plano' : 'geral');
  const [showInvite, setShowInvite] = React.useState(false);
  const goToPlano = () => setActiveSection('plano');
  const isStudio = PLAN_DATA.current === 'studio';

  const renderSection = () => {
    switch (activeSection) {
      case 'geral': return <SectionGeral />;
      case 'seguranca': return <SectionSeguranca />;
      case 'plano': return <SectionPlano billingError={billingError} />;
      case 'notif': return <SectionNotif />;
      case 'marca': return <SectionMarca onUpgrade={goToPlano} />;
      default: return null;
    }
  };

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

      <div className="orbita-page" style={{ maxWidth: 1100, margin: '0 auto', padding: '40px 32px 100px', position: 'relative' }}>
        <SettingsProfileHeader
          astrologer={astrologer}
          onNavigateSearch={setActiveSection}
          onInvite={() => setShowInvite(true)}
          onUpgrade={goToPlano}
        />
        <SettingsTabs sections={SETTINGS_SECTIONS} active={activeSection} onChange={setActiveSection} />
        {renderSection()}
      </div>

      {showInvite && <InviteModal onClose={() => setShowInvite(false)} isStudio={isStudio} onUpgrade={goToPlano} />}
    </div>
  );
};

Object.assign(window, { SettingsScreen });
