// Profile / Gamification / Plans / Settings — all "more" content

const MoreScreen = ({ state, setState, navigate, showToast, user, onLogout, syncStatus, profile, themePref, onChangeTheme }) => {
  const [openSheet, setOpenSheet] = React.useState(null); // 'lgpd' | 'help' | 'theme' | 'settings' | 'profile' | 'security'

  const confirmLogout = () => {
    if (window.confirm && window.confirm('Sair da conta? Seus dados locais permanecem salvos neste dispositivo.')) {
      onLogout && onLogout();
    }
  };

  const syncReal = user && !user.isMock && window.CloudSync && window.CloudSync.isConfigured();
  const isAdmin = profile && profile.role === 'admin';

  return (
    <div style={{ paddingBottom: 110 }}>
      <Header title="Mais" subtitle="EXPLORE TODAS AS ÁREAS" />

      <div style={{ padding: '0 22px 18px' }}>
        <ProfileCard state={state} onClick={() => navigate('profile')} />
      </div>

      <div style={{ padding: '0 22px 18px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <ModuleTile icon="target" label="Metas" desc="3 em andamento" color={CDV.mint} onClick={() => navigate('goals')} />
          <ModuleTile icon="calendar" label="Agenda" desc="5 eventos hoje" color={CDV.sky} onClick={() => navigate('calendar')} />
          <ModuleTile icon="trophy" label="Conquistas" desc="4 novas" color={CDV.amber} onClick={() => navigate('achievements')} />
          <ModuleTile icon="diamond" label="Premium" desc="Upgrade" color={CDV.brand} onClick={() => navigate('plans')} />
          <ModuleTile icon="lock" label="Cofre" desc="Senhas e dados" color={CDV.flame} onClick={() => navigate('vault')} />
        </div>
      </div>

      {isAdmin && (
        <div style={{ padding: '0 22px 18px' }}>
          <div onClick={() => navigate('admin')} style={{
            padding: 16, borderRadius: 18, position: 'relative', overflow: 'hidden',
            background: 'linear-gradient(135deg, rgba(177,151,252,0.18), rgba(255,143,177,0.10))',
            border: `1px solid ${CDV.brand}40`, cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{
              width: 44, height: 44, borderRadius: 12, background: CDV.brandGrad,
              display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', flexShrink: 0,
              boxShadow: '0 6px 18px -4px rgba(177,151,252,0.5)',
            }}><Icon name="shield" size={22} /></div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <div style={{ fontSize: 15, fontWeight: 700, color: CDV.text }}>Painel Admin</div>
                <Pill color={CDV.brand} size="sm">interno</Pill>
              </div>
              <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 2 }}>Usuários, planos, métricas e receita</div>
            </div>
            <Icon name="chevronRight" size={16} color={CDV.textMuted} />
          </div>
        </div>
      )}

      <SectionHeader title="Atalhos rápidos" />
      <div style={{ padding: '0 22px 18px', background: 'transparent' }}>
        <div style={{ background: CDV.surface, border: `1px solid ${CDV.stroke}`, borderRadius: 18, overflow: 'hidden' }}>
          <ListRow icon="bell" iconColor={CDV.coral} title="Notificações" detail="12 hoje" onClick={() => navigate('notifications')} />
          <ListRow icon="pomodoro" iconColor={CDV.brand} title="Modo foco · Pomodoro" detail="Iniciar" onClick={() => navigate('dashboard')} />
          <ListRow icon="pdf" iconColor={CDV.sky} title="Exportar relatório PDF" detail="Premium" onClick={() => showToast('Disponível no plano Premium')} />
          <ListRow icon="palette" iconColor={CDV.amber} title="Personalizar tema" detail={themePref === 'auto' ? 'Automático' : themePref === 'light' ? 'Claro' : 'Escuro'} onClick={() => setOpenSheet('theme')} />
          <ListRow icon="shield" iconColor={CDV.mint} title="Privacidade & LGPD" onClick={() => setOpenSheet('lgpd')} last />
        </div>
      </div>

      <SectionHeader title="Conta" />
      <div style={{ padding: '0 22px 18px' }}>
        <div style={{ background: CDV.surface, border: `1px solid ${CDV.stroke}`, borderRadius: 18, overflow: 'hidden' }}>
          <ListRow icon="user" iconColor={CDV.brand} title="Editar perfil" onClick={() => setOpenSheet('profile')} />
          <ListRow icon="lock" iconColor={CDV.coral} title="Senha e segurança" onClick={() => setOpenSheet('security')} />
          <ListRow icon="settings" iconColor={CDV.textDim} title="Configurações" onClick={() => setOpenSheet('settings')} />
          <ListRow icon="info" iconColor={CDV.sky} title="Ajuda e suporte" onClick={() => setOpenSheet('help')} last />
        </div>
      </div>

      {onLogout && (
        <div style={{ padding: '0 22px 18px' }}>
          {syncReal && <SyncBadge status={syncStatus} />}
          <button onClick={confirmLogout} style={{
            width: '100%', height: 50, borderRadius: 14,
            background: CDV.surface, border: `1px solid ${CDV.coral}30`,
            color: CDV.coral, fontWeight: 600, fontSize: 14, fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, cursor: 'pointer',
          }}>
            <Icon name="lock" size={16} /> Sair da conta
          </button>
          {user && user.email && (
            <div style={{ textAlign: 'center', fontSize: 11, color: CDV.textMuted, marginTop: 8 }}>
              Logado como <b style={{ color: CDV.textDim }}>{user.email}</b>{user.isMock ? ' · modo demo' : ''}
            </div>
          )}
        </div>
      )}

      <div style={{ textAlign: 'center', fontSize: 11, color: CDV.textMuted, padding: '12px 0 8px' }}>
        Central da Vida · versão 1.0 · feito com 💜 pela JuFlow Digital
      </div>

      <Sheet open={openSheet === 'lgpd'} onClose={() => setOpenSheet(null)} title="Privacidade & LGPD">
        <LGPDPanel onReset={() => { if (window.CDV_RESET) window.CDV_RESET(); window.location.reload(); }} />
      </Sheet>
      <Sheet open={openSheet === 'theme'} onClose={() => setOpenSheet(null)} title="Personalizar tema">
        <ThemePanel pref={themePref} onChange={(p) => { onChangeTheme && onChangeTheme(p); showToast && showToast('Tema atualizado'); }} />
      </Sheet>
      <Sheet open={openSheet === 'profile'} onClose={() => setOpenSheet(null)} title="Editar perfil">
        <EditProfileForm state={state} setState={setState} onDone={() => { setOpenSheet(null); showToast('Perfil atualizado'); }} />
      </Sheet>
      <Sheet open={openSheet === 'security'} onClose={() => setOpenSheet(null)} title="Senha e segurança">
        <ComingSoon icon="lock" title="Troca de senha por e-mail" desc="A integração com servidor de autenticação está sendo finalizada. Em breve você poderá redefinir sua senha por aqui." />
      </Sheet>
      <Sheet open={openSheet === 'settings'} onClose={() => setOpenSheet(null)} title="Configurações">
        <SettingsPanel showToast={showToast} />
      </Sheet>
      <Sheet open={openSheet === 'help'} onClose={() => setOpenSheet(null)} title="Ajuda e suporte">
        <HelpPanel />
      </Sheet>
    </div>
  );
};

const SyncBadge = ({ status }) => {
  const s = status || { status: 'idle' };
  const map = {
    idle:    { dot: CDV.textMuted, label: 'Aguardando sincronização' },
    loading: { dot: CDV.amber,     label: 'Carregando da nuvem...' },
    pending: { dot: CDV.amber,     label: 'Alterações pendentes...' },
    saving:  { dot: CDV.brand,     label: 'Salvando na nuvem...' },
    saved:   { dot: CDV.mint,      label: s.lastSyncedAt ? `Sincronizado · ${formatSyncTime(s.lastSyncedAt)}` : 'Sincronizado' },
    error:   { dot: CDV.coral,     label: 'Erro ao sincronizar — tente novamente' },
  };
  const info = map[s.status] || map.idle;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      padding: '8px 12px', borderRadius: 99, marginBottom: 10,
      background: CDV.surface, border: `1px solid ${CDV.stroke}`,
      fontSize: 11, color: CDV.textDim, fontWeight: 500,
    }}>
      <div style={{
        width: 8, height: 8, borderRadius: 99, background: info.dot,
        animation: s.status === 'saving' || s.status === 'loading' ? 'pulseGlow 1.4s ease-in-out infinite' : 'none',
      }} />
      <Icon name="shield" size={11} color={info.dot} />
      {info.label}
    </div>
  );
};

function formatSyncTime(iso) {
  try {
    const d = new Date(iso);
    const today = new Date();
    const isSameDay = d.toDateString() === today.toDateString();
    const hh = String(d.getHours()).padStart(2, '0');
    const mm = String(d.getMinutes()).padStart(2, '0');
    if (isSameDay) return `hoje ${hh}:${mm}`;
    return d.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' }) + ` ${hh}:${mm}`;
  } catch (e) {
    return '';
  }
}

const ThemePanel = ({ pref, onChange }) => {
  const currentMode = window.CDV && window.CDV._mode;
  const options = [
    { id: 'auto',  label: 'Automático', desc: 'Claro durante o dia (7h-19h) · escuro à noite', icon: 'sparkle' },
    { id: 'light', label: 'Claro',      desc: 'Sempre o modo claro',                            icon: 'sun' },
    { id: 'dark',  label: 'Escuro',     desc: 'Sempre o modo escuro',                           icon: 'moon' },
  ];
  return (
    <div style={{ padding: '8px 22px 28px' }}>
      <div style={{ display: 'flex', gap: 10, marginBottom: 16 }}>
        {/* Preview escuro */}
        <ThemePreview mode="dark" active={currentMode === 'dark'} />
        {/* Preview claro */}
        <ThemePreview mode="light" active={currentMode === 'light'} />
      </div>
      <div style={{ fontSize: 11, color: CDV.brand, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 8 }}>
        Modo · atualmente {currentMode === 'light' ? 'claro' : 'escuro'}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {options.map(o => {
          const active = pref === o.id;
          return (
            <button key={o.id} onClick={() => onChange(o.id)} style={{
              padding: 14, borderRadius: 14, textAlign: 'left',
              background: active ? CDV.brandSoft : CDV.surface,
              border: `1.5px solid ${active ? CDV.brand : CDV.stroke}`,
              color: CDV.text, fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 12,
              cursor: 'pointer',
            }}>
              <div style={{
                width: 38, height: 38, borderRadius: 11,
                background: active ? CDV.brand : CDV.surfaceHi,
                color: active ? '#fff' : CDV.textDim,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}><Icon name={o.icon} size={16} /></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>{o.label}</div>
                <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 2 }}>{o.desc}</div>
              </div>
              {active && (
                <div style={{
                  width: 22, height: 22, borderRadius: 99, background: CDV.brand,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}><Icon name="check" size={12} color="#fff" /></div>
              )}
            </button>
          );
        })}
      </div>
    </div>
  );
};

const ThemePreview = ({ mode, active }) => {
  const palette = mode === 'light' ? (window.LIGHT_PALETTE || {}) : (window.DARK_PALETTE || {});
  return (
    <div style={{
      flex: 1, padding: 12, borderRadius: 14,
      background: palette.bg || (mode === 'light' ? '#F4F3F8' : '#08070C'),
      border: `2px solid ${active ? CDV.brand : 'transparent'}`,
      boxShadow: active ? `0 0 20px -5px ${CDV.brand}55` : 'none',
      display: 'flex', flexDirection: 'column', gap: 6, minHeight: 96,
    }}>
      <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
        <div style={{ width: 16, height: 16, borderRadius: 6, background: CDV.brand }} />
        <div style={{ flex: 1, height: 4, borderRadius: 99, background: palette.surfaceHi || palette.surface || '#fff' }} />
      </div>
      <div style={{ flex: 1, borderRadius: 8, background: palette.surface || (mode === 'light' ? '#fff' : '#14131C'), padding: 6, display: 'flex', flexDirection: 'column', gap: 3 }}>
        <div style={{ height: 5, borderRadius: 99, background: palette.text || (mode === 'light' ? '#0A0911' : '#F5F4F8'), width: '60%', opacity: 0.85 }} />
        <div style={{ height: 4, borderRadius: 99, background: palette.textDim || '#999', width: '80%' }} />
        <div style={{ height: 4, borderRadius: 99, background: palette.textDim || '#999', width: '40%' }} />
      </div>
      <div style={{ fontSize: 10, color: palette.textDim || '#888', fontWeight: 600, textAlign: 'center', textTransform: 'uppercase', letterSpacing: 0.4 }}>{mode === 'light' ? 'Claro' : 'Escuro'}</div>
    </div>
  );
};

const ComingSoon = ({ icon, title, desc }) => (
  <div style={{ padding: '20px 22px 32px', textAlign: 'center' }}>
    <div style={{
      width: 70, height: 70, borderRadius: 20, background: CDV.brandSoft, margin: '0 auto 14px',
      display: 'flex', alignItems: 'center', justifyContent: 'center', color: CDV.brand,
    }}><Icon name={icon} size={32} /></div>
    <div style={{ fontSize: 18, fontWeight: 700, color: CDV.text, letterSpacing: -0.2 }}>{title}</div>
    <div style={{ fontSize: 13, color: CDV.textDim, marginTop: 8, lineHeight: 1.5, maxWidth: 320, marginInline: 'auto' }}>{desc}</div>
  </div>
);

const LGPDPanel = ({ onReset }) => (
  <div style={{ padding: '12px 22px 32px', color: CDV.text, fontSize: 13, lineHeight: 1.55 }}>
    <div style={{ fontSize: 11, color: CDV.brand, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6 }}>Lei Geral de Proteção de Dados</div>
    <p style={{ color: CDV.textDim, margin: '0 0 14px' }}>
      Este aplicativo respeita a LGPD (Lei nº 13.709/2018). Resumo dos seus direitos:
    </p>
    <ul style={{ paddingLeft: 18, margin: '0 0 14px', color: CDV.textDim }}>
      <li style={{ marginBottom: 6 }}>Você pode <b style={{ color: CDV.text }}>solicitar exclusão</b> de todos os seus dados a qualquer momento.</li>
      <li style={{ marginBottom: 6 }}>Seus dados são armazenados <b style={{ color: CDV.text }}>localmente</b> neste dispositivo (localStorage). Nenhuma informação é enviada para servidores externos sem seu consentimento.</li>
      <li style={{ marginBottom: 6 }}>O assistente Sofia (IA) usa apenas os dados que você fornece, sem compartilhar com terceiros.</li>
      <li style={{ marginBottom: 6 }}>Você pode revogar o consentimento a qualquer momento na tela de Configurações.</li>
    </ul>
    <div style={{ background: CDV.surfaceHi, borderRadius: 14, padding: 14, marginBottom: 12 }}>
      <div style={{ fontSize: 12, fontWeight: 700, color: CDV.text }}>Termos de uso e política completa</div>
      <div style={{ fontSize: 12, color: CDV.textDim, marginTop: 4 }}>
        Documento legal completo disponível em juflow.com.br/lgpd
      </div>
    </div>
    <button onClick={() => {
      if (typeof window !== 'undefined' && window.confirm && window.confirm('Apagar TODOS os dados do app neste dispositivo? Esta ação não pode ser desfeita.')) {
        onReset && onReset();
      }
    }} style={{
      width: '100%', height: 50, borderRadius: 14,
      background: CDV.coral + '18', border: `1px solid ${CDV.coral}40`, color: CDV.coral,
      fontWeight: 600, fontSize: 14, fontFamily: 'inherit',
    }}>Excluir minha conta e dados</button>
  </div>
);

const EditProfileForm = ({ state, setState, onDone }) => {
  const [name, setName] = React.useState((state && state.profile && state.profile.name) || 'Lucas Mendes');
  const [email, setEmail] = React.useState((state && state.profile && state.profile.email) || 'lucas@email.com');
  const save = () => {
    setState && setState(s => ({ ...s, profile: { ...(s.profile || {}), name, email } }));
    onDone && onDone();
  };
  return (
    <div style={{ padding: '12px 22px 28px' }}>
      <div style={{ fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 6 }}>Nome</div>
      <input value={name} onChange={e => setName(e.target.value)} placeholder="Seu nome"
        style={{ width: '100%', height: 50, borderRadius: 14, border: `1px solid ${CDV.stroke}`, background: CDV.surfaceHi, color: CDV.text, padding: '0 16px', fontSize: 15, outline: 'none', fontFamily: 'inherit', marginBottom: 14 }} />
      <div style={{ fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 6 }}>E-mail</div>
      <input value={email} onChange={e => setEmail(e.target.value)} placeholder="email@exemplo.com"
        style={{ width: '100%', height: 50, borderRadius: 14, border: `1px solid ${CDV.stroke}`, background: CDV.surfaceHi, color: CDV.text, padding: '0 16px', fontSize: 15, outline: 'none', fontFamily: 'inherit', marginBottom: 20 }} />
      <button onClick={save} style={{
        width: '100%', height: 54, borderRadius: 16, background: CDV.brandGrad,
        border: 'none', color: '#fff', fontWeight: 600, fontSize: 15,
      }}>Salvar alterações</button>
    </div>
  );
};

const SettingsPanel = ({ showToast }) => {
  const initialPrefs = window.Push ? window.Push.loadPrefs() : { enabled: false, leadMinutes: 10, quiet: { enabled: true, start: 22, end: 7 } };
  const [prefs, setPrefs] = React.useState(initialPrefs);
  const [permission, setPermission] = React.useState(window.Push ? window.Push.permission() : 'unsupported');
  const [haptic, setHaptic] = React.useState(true);

  const persist = (next) => {
    setPrefs(next);
    window.Push && window.Push.savePrefs(next);
  };

  const togglePush = async (next) => {
    if (next) {
      const result = window.Push ? await window.Push.requestPermission() : 'denied';
      setPermission(result);
      if (result === 'granted') {
        persist({ ...prefs, enabled: true });
        showToast && showToast('Notificações ativadas');
      } else if (result === 'denied') {
        showToast && showToast('Permissão negada — habilite no navegador');
        persist({ ...prefs, enabled: false });
      } else if (result === 'unsupported') {
        showToast && showToast('Notificações não suportadas neste navegador');
      }
    } else {
      persist({ ...prefs, enabled: false });
      window.Push && window.Push.cancelAll();
      showToast && showToast('Notificações desativadas');
    }
  };

  const test = () => {
    if (!window.Push) { showToast && showToast('Push não disponível'); return; }
    if (permission !== 'granted') { showToast && showToast('Habilite as notificações primeiro'); return; }
    const ok = window.Push.showNow('Central da Vida', 'Notificação de teste — tudo funcionando!', { bypassQuiet: true });
    if (!ok) showToast && showToast('Suprimida pelo modo silencioso');
  };

  return (
    <div style={{ padding: '12px 22px 28px' }}>
      {/* Status do navegador */}
      <div style={{
        padding: 12, borderRadius: 12, marginBottom: 14,
        background: permission === 'granted' ? CDV.mintSoft : permission === 'denied' ? CDV.coral + '14' : CDV.surfaceHi,
        border: `1px solid ${permission === 'granted' ? CDV.mint + '40' : permission === 'denied' ? CDV.coral + '40' : CDV.stroke}`,
        display: 'flex', alignItems: 'center', gap: 10,
        fontSize: 12,
        color: permission === 'granted' ? CDV.mint : permission === 'denied' ? CDV.coral : CDV.textDim,
      }}>
        <Icon name={permission === 'granted' ? 'check' : 'bell'} size={14} />
        {permission === 'granted' && 'Permissão concedida pelo navegador'}
        {permission === 'default' && 'Permissão ainda não solicitada'}
        {permission === 'denied' && 'Bloqueado no navegador — desbloqueie nas configurações do site'}
        {permission === 'unsupported' && 'Navegador não suporta notificações'}
      </div>

      <SettingToggle
        label="Notificações push"
        desc="Receber alertas de tarefas com horário"
        checked={prefs.enabled && permission === 'granted'}
        onChange={togglePush}
      />

      <SettingToggle
        label={`Modo silencioso (${String(prefs.quiet.start).padStart(2, '0')}h–${String(prefs.quiet.end).padStart(2, '0')}h)`}
        desc="Pausa notificações no período noturno"
        checked={prefs.quiet.enabled}
        onChange={(v) => persist({ ...prefs, quiet: { ...prefs.quiet, enabled: v } })}
      />

      <SettingToggle
        label="Feedback tátil"
        desc="Vibração leve em ações importantes"
        checked={haptic}
        onChange={setHaptic}
      />

      <div style={{ marginTop: 14, fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 6 }}>
        Avisar antes da tarefa
      </div>
      <div style={{ display: 'flex', gap: 6, marginBottom: 16 }}>
        {[5, 10, 15, 30, 60].map(m => {
          const active = prefs.leadMinutes === m;
          return (
            <button key={m} onClick={() => persist({ ...prefs, leadMinutes: m })} style={{
              flex: 1, height: 38, borderRadius: 10,
              background: active ? CDV.brandSoft : CDV.surfaceHi,
              border: `1.5px solid ${active ? CDV.brand : CDV.stroke}`,
              color: active ? CDV.brand : CDV.textDim,
              fontSize: 12, fontWeight: 600, fontFamily: 'inherit',
            }}>{m}m</button>
          );
        })}
      </div>

      <button onClick={test} disabled={permission !== 'granted'} style={{
        width: '100%', height: 50, borderRadius: 14, background: CDV.surfaceHi,
        border: `1px solid ${CDV.stroke}`, color: permission === 'granted' ? CDV.text : CDV.textDim,
        fontWeight: 600, fontSize: 14, fontFamily: 'inherit',
        opacity: permission === 'granted' ? 1 : 0.5, cursor: permission === 'granted' ? 'pointer' : 'not-allowed',
      }}>
        Disparar notificação de teste
      </button>
    </div>
  );
};

const SettingToggle = ({ label, desc, checked, onChange }) => (
  <div style={{
    display: 'flex', alignItems: 'center', gap: 12, padding: '14px 0',
    borderBottom: `1px solid ${CDV.divider}`,
  }}>
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 14, fontWeight: 600, color: CDV.text }}>{label}</div>
      <div style={{ fontSize: 12, color: CDV.textDim, marginTop: 2 }}>{desc}</div>
    </div>
    <button onClick={() => onChange(!checked)} style={{
      width: 44, height: 26, borderRadius: 99,
      background: checked ? CDV.brand : CDV.surfaceHi, border: 'none',
      position: 'relative', transition: 'background .2s', cursor: 'pointer',
    }}>
      <div style={{
        position: 'absolute', top: 3, left: checked ? 22 : 3,
        width: 20, height: 20, borderRadius: 99, background: '#fff',
        transition: 'left .2s', boxShadow: '0 2px 6px rgba(0,0,0,0.3)',
      }} />
    </button>
  </div>
);

const HelpPanel = () => (
  <div style={{ padding: '12px 22px 32px' }}>
    <div style={{ background: CDV.surfaceHi, borderRadius: 14, padding: 16, marginBottom: 12 }}>
      <div style={{ fontSize: 12, color: CDV.textMuted, fontWeight: 600 }}>SUPORTE</div>
      <div style={{ fontSize: 14, color: CDV.text, marginTop: 4, fontWeight: 600 }}>JuFlow Digital</div>
      <div style={{ fontSize: 12, color: CDV.textDim, marginTop: 6 }}>Segunda a sexta · 9h às 18h</div>
      <div style={{ fontSize: 12, color: CDV.textDim }}>Sábado · 9h às 12h</div>
    </div>
    <ListLink label="contato@juflow.com.br" icon="bell" />
    <ListLink label="Central de ajuda" icon="info" />
    <ListLink label="Reportar um bug" icon="shield" />
    <div style={{ fontSize: 11, color: CDV.textMuted, marginTop: 18, textAlign: 'center', lineHeight: 1.5 }}>
      Central da Vida · versão 1.0<br />
      Correção de bugs sem limite, conforme o briefing.
    </div>
  </div>
);

const ListLink = ({ label, icon }) => (
  <div style={{
    padding: 14, borderRadius: 12, background: CDV.surface, border: `1px solid ${CDV.stroke}`,
    display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8,
  }}>
    <Icon name={icon} size={16} color={CDV.brand} />
    <div style={{ flex: 1, fontSize: 13, color: CDV.text }}>{label}</div>
    <Icon name="chevronRight" size={14} color={CDV.textMuted} />
  </div>
);

const ProfileCard = ({ state, onClick }) => {
  const { xp, level } = state;
  const nextLevel = 2400;
  const pct = (xp / nextLevel) * 100;
  const profileName = (state && state.profile && state.profile.name) || 'Lucas Mendes';
  const profileEmail = (state && state.profile && state.profile.email) || 'lucas@email.com';
  const initial = (profileName || 'L').charAt(0).toUpperCase();
  return (
    <div onClick={onClick} style={{
      padding: 18, borderRadius: 22, position: 'relative', overflow: 'hidden', cursor: 'pointer',
      background: 'linear-gradient(135deg, rgba(177,151,252,0.15) 0%, rgba(255,143,177,0.08) 100%)',
      border: `1px solid ${CDV.strokeHi}`,
    }}>
      <div style={{
        position: 'absolute', top: -40, right: -40, width: 200, height: 200, borderRadius: 99,
        background: 'radial-gradient(circle, rgba(177,151,252,0.3), transparent 70%)', filter: 'blur(30px)',
      }} />
      <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{
          width: 64, height: 64, borderRadius: 18,
          background: 'linear-gradient(135deg, #FFB547, #FF7A6B)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
          fontSize: 26, fontWeight: 700,
          boxShadow: '0 8px 24px -8px rgba(255,181,71,0.5)',
        }}>{initial}</div>
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ fontSize: 18, fontWeight: 700, color: CDV.text }}>{profileName}</div>
            <Pill color={CDV.amber} size="sm">
              <Icon name="diamond" size={10} /> Premium
            </Pill>
          </div>
          <div style={{ fontSize: 12, color: CDV.textDim, marginTop: 2 }}>{profileEmail}</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 6 }}>
            <Icon name="flame" size={13} color={CDV.flame} />
            <div style={{ fontSize: 12, color: CDV.text, fontWeight: 600 }}>47 dias de constância</div>
          </div>
        </div>
      </div>
      <div style={{ marginTop: 16, padding: 12, background: 'rgba(0,0,0,0.18)', borderRadius: 14 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <div style={{
              width: 22, height: 22, borderRadius: 7, background: CDV.brandGrad,
              display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 11, fontWeight: 700,
            }}>{level}</div>
            <div style={{ fontSize: 13, fontWeight: 600, color: CDV.text }}>Nível {level} · Mestre da Rotina</div>
          </div>
          <div style={{ fontSize: 11, color: CDV.textDim }}>{xp} / {nextLevel} XP</div>
        </div>
        <ProgressBar percent={pct} gradient="linear-gradient(90deg, #B197FC, #FF8FB1)" height={6} />
      </div>
    </div>
  );
};

const ModuleTile = ({ icon, label, desc, color, onClick }) => (
  <button onClick={onClick} style={{
    background: CDV.surface, border: `1px solid ${CDV.stroke}`, borderRadius: 18,
    padding: 16, textAlign: 'left', color: CDV.text, fontFamily: 'inherit',
    display: 'flex', flexDirection: 'column', gap: 10,
  }}>
    <div style={{
      width: 40, height: 40, borderRadius: 12, background: color + '22',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <Icon name={icon} size={20} color={color} />
    </div>
    <div>
      <div style={{ fontSize: 15, fontWeight: 600 }}>{label}</div>
      <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 2 }}>{desc}</div>
    </div>
  </button>
);

const ListRow = ({ icon, iconColor = CDV.brand, title, detail, onClick, last }) => (
  <div onClick={onClick} style={{
    padding: '14px 14px 14px 14px', display: 'flex', alignItems: 'center', gap: 12,
    borderBottom: last ? 'none' : `1px solid ${CDV.divider}`, cursor: 'pointer',
  }}>
    <div style={{
      width: 32, height: 32, borderRadius: 9, background: iconColor + '22',
      display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
    }}>
      <Icon name={icon} size={16} color={iconColor} />
    </div>
    <div style={{ flex: 1, fontSize: 14, color: CDV.text, fontWeight: 500 }}>{title}</div>
    {detail && <div style={{ fontSize: 12, color: CDV.textDim, marginRight: 6 }}>{detail}</div>}
    <Icon name="chevronRight" size={14} color={CDV.textMuted} />
  </div>
);

// ── Achievements screen ────────────────────────────────────
const AchievementsScreen = ({ state, navigate }) => {
  const unlocked = conquistasData.filter(c => c.unlocked).length;
  return (
    <div style={{ paddingBottom: 110 }}>
      <Header title="Conquistas" subtitle={`${unlocked} DE ${conquistasData.length}`} onBack={() => navigate('more')} />

      <div style={{ padding: '0 22px 18px' }}>
        <div style={{
          padding: 18, borderRadius: 22,
          background: 'linear-gradient(135deg, rgba(255,181,71,0.18), rgba(255,122,107,0.08))',
          border: `1px solid ${CDV.amber}40`, position: 'relative', overflow: 'hidden',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{
              width: 64, height: 64, borderRadius: 18,
              background: 'linear-gradient(135deg, #FFB547, #FF7A3D)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
              boxShadow: '0 10px 30px -10px rgba(255,181,71,0.6)',
            }}><Icon name="trophy" size={32} /></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11, color: CDV.amber, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase' }}>Próxima recompensa</div>
              <div style={{ fontSize: 17, fontWeight: 600, color: CDV.text, marginTop: 2 }}>Mestre dos Hábitos</div>
              <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 2 }}>53 dias para desbloquear</div>
            </div>
          </div>
          <div style={{ marginTop: 14 }}>
            <ProgressBar percent={47} gradient="linear-gradient(90deg, #FFB547, #FF7A3D)" height={5} />
          </div>
        </div>
      </div>

      <SectionHeader title="Desbloqueadas" action={`${unlocked}/${conquistasData.length}`} />
      <div style={{ padding: '0 22px 16px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {conquistasData.filter(c => c.unlocked).map(c => <AchievementBadge key={c.id} a={c} />)}
      </div>

      <SectionHeader title="Por desbloquear" />
      <div style={{ padding: '0 22px 18px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {conquistasData.filter(c => !c.unlocked).map(c => <AchievementBadge key={c.id} a={c} locked />)}
      </div>
    </div>
  );
};

const AchievementBadge = ({ a, locked }) => (
  <div style={{
    padding: 14, borderRadius: 18,
    background: locked ? CDV.surface : `linear-gradient(135deg, ${a.color}22, ${a.color}06)`,
    border: `1px solid ${locked ? CDV.stroke : a.color + '40'}`,
    position: 'relative', overflow: 'hidden',
  }}>
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
      <div style={{
        width: 44, height: 44, borderRadius: 14,
        background: locked ? CDV.surfaceHi : a.color + '22',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        filter: locked ? 'grayscale(1)' : 'none', opacity: locked ? 0.5 : 1,
      }}>
        <Icon name={locked ? 'lock' : a.icon} size={22} color={locked ? CDV.textMuted : a.color} />
      </div>
      <Pill color={a.color} size="sm" bg={locked ? CDV.surfaceHi : a.color + '18'}>{a.rarity}</Pill>
    </div>
    <div style={{ fontSize: 13, fontWeight: 600, color: locked ? CDV.textMuted : CDV.text, lineHeight: 1.2 }}>{a.name}</div>
    <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 4, lineHeight: 1.3 }}>{a.desc}</div>
  </div>
);

// ── Plans screen ────────────────────────────────────────────
const PLANS = [
  {
    id: 'mensal',
    name: 'Mensal',
    subtitle: 'Mais flexível',
    total: 29.90,
    months: 1,
    color: '#6FB8FF',
    icon: 'star',
  },
  {
    id: 'semestral',
    name: 'Semestral',
    subtitle: 'Equilibrado',
    total: 149.40,
    months: 6,
    color: '#FFB547',
    icon: 'crown',
    save: '17%',
  },
  {
    id: 'anual',
    name: 'Anual',
    subtitle: 'Melhor custo',
    total: 238.80,
    months: 12,
    color: '#B197FC',
    icon: 'diamond',
    recommended: true,
    save: '33%',
  },
];

const fmtBRL = (v) => `R$ ${v.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;

const PlansScreen = ({ navigate, showToast, user, profile }) => {
  const trialEnds = profile && profile.trial_ends_at ? new Date(profile.trial_ends_at) : null;
  const trialActive = trialEnds && trialEnds > new Date() && (!profile || profile.plan === 'trial');
  const daysLeft = trialEnds ? Math.max(0, Math.ceil((trialEnds - new Date()) / (1000 * 60 * 60 * 24))) : null;
  const currentPlan = profile && profile.plan;

  const selectPlan = async (planId) => {
    const plan = PLANS.find(p => p.id === planId);
    // Redireciona pro checkout Nexano (abre em nova aba)
    if (window.Checkout && window.Checkout.openCheckout(planId, user)) {
      showToast(`Abrindo checkout · ${plan.name}`);
      return;
    }
    showToast(`Plano ${plan.name} selecionado`);
  };

  return (
    <div style={{ paddingBottom: 110 }}>
      <Header title="Seu plano" subtitle="ESCOLHA SEU CICLO" onBack={() => navigate('more')} />

      <div style={{ padding: '0 22px 18px' }}>
        <div style={{
          padding: 20, borderRadius: 24,
          background: 'linear-gradient(135deg, #2A1B4A 0%, #4A1B33 100%)',
          border: `1px solid ${CDV.strokeHi}`,
          position: 'relative', overflow: 'hidden', textAlign: 'center',
        }}>
          <div style={{
            position: 'absolute', inset: 0,
            background: 'radial-gradient(circle at 50% 0, rgba(177,151,252,0.3), transparent 70%)',
          }} />
          <div style={{ position: 'relative' }}>
            <div style={{
              display: 'inline-flex', padding: 14, borderRadius: 18, background: CDV.brandGrad,
              boxShadow: '0 10px 30px -10px rgba(177,151,252,0.6)',
            }}>
              <Icon name="diamond" size={28} color="#fff" />
            </div>
            <div style={{ fontFamily: fontDisplay, fontSize: 32, color: CDV.text, marginTop: 14, letterSpacing: -0.6 }}>
              Central <i style={{ color: CDV.brand }}>completa</i>
            </div>
            <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.7)', marginTop: 6, maxWidth: 280, marginInline: 'auto', lineHeight: 1.4 }}>
              Sofia 24/7, tarefas, hábitos, metas, finanças e backup em nuvem.
            </div>
          </div>
        </div>
      </div>

      {/* Trial banner */}
      {trialActive && (
        <div style={{ padding: '0 22px 14px' }}>
          <div style={{
            padding: 14, borderRadius: 16,
            background: 'linear-gradient(135deg, rgba(94,227,168,0.14), rgba(94,227,168,0.04))',
            border: `1px solid ${CDV.mint}40`,
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{ width: 34, height: 34, borderRadius: 10, background: CDV.mintSoft, color: CDV.mint, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="sparkle" size={18} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: CDV.text }}>Período grátis ativo</div>
              <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 2 }}>
                {daysLeft === 0 ? 'Expira hoje' : `${daysLeft} dia${daysLeft === 1 ? '' : 's'} restante${daysLeft === 1 ? '' : 's'}`} · sem cobrança até você confirmar
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Tudo incluído em qualquer plano */}
      <div style={{ padding: '0 22px 14px' }}>
        <div style={{
          padding: 16, borderRadius: 18, position: 'relative', overflow: 'hidden',
          background: `linear-gradient(135deg, ${CDV.brand}14 0%, ${CDV.brand}06 35%, ${CDV.surface} 100%)`,
          border: `1px solid ${CDV.brand}30`,
        }}>
          <div style={{
            position: 'absolute', top: -30, right: -30, width: 130, height: 130, borderRadius: 99,
            background: `radial-gradient(circle, ${CDV.brand}44, transparent 60%)`,
            filter: 'blur(24px)', opacity: 0.55, pointerEvents: 'none',
          }} />
          <div style={{
            position: 'absolute', left: 0, top: 14, bottom: 14, width: 3, borderRadius: 99,
            background: `linear-gradient(180deg, ${CDV.brand}, ${CDV.brand}40)`,
            boxShadow: `0 0 12px ${CDV.brand}80`,
          }} />
          <div style={{ position: 'relative' }}>
            <div style={{ fontSize: 10, color: CDV.brand, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 8 }}>
              Todos os planos incluem
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                'Sofia 24/7 com IA ilimitada',
                'Tarefas, hábitos, finanças e agenda',
                'Cofrinhos e metas ilimitados',
                'Backup automático na nuvem',
                'Sincronização entre dispositivos',
                'Relatórios em PDF e suporte prioritário',
              ].map((f, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: CDV.text }}>
                  <div style={{
                    width: 18, height: 18, borderRadius: 99, flexShrink: 0,
                    background: CDV.brandSoft, border: `1px solid ${CDV.brand}40`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}><Icon name="check" size={10} color={CDV.brand} /></div>
                  {f}
                </div>
              ))}
            </div>
            <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 12, lineHeight: 1.5 }}>
              A diferença entre os planos é só o ciclo de cobrança. Quanto mais longo, mais você economiza.
            </div>
          </div>
        </div>
      </div>

      {/* Plan cards */}
      <div style={{ padding: '0 22px 18px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {PLANS.map(plan => (
          <PlanCard
            key={plan.id}
            plan={plan}
            current={currentPlan === plan.id}
            onSelect={() => selectPlan(plan.id)}
          />
        ))}
      </div>

      <div style={{ padding: '0 22px 12px', textAlign: 'center' }}>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '8px 14px', borderRadius: 99,
          background: CDV.surface, border: `1px solid ${CDV.stroke}`,
          fontSize: 12, color: CDV.textDim, fontWeight: 500,
        }}>
          <Icon name="shield" size={12} color={CDV.mint} />
          3 dias grátis · sem cobrança até confirmação
        </div>
      </div>

      <div style={{ padding: '4px 22px 18px', textAlign: 'center', fontSize: 11, color: CDV.textMuted, lineHeight: 1.5 }}>
        Cancele quando quiser.<br />
        Pagamento via App Store, Google Play ou PIX.
      </div>
    </div>
  );
};

const PlanCard = ({ plan, current, onSelect }) => {
  const perMonth = plan.total / plan.months;
  return (
    <div style={{
      padding: 18, borderRadius: 22, position: 'relative',
      background: plan.recommended ? `linear-gradient(135deg, ${plan.color}24, ${plan.color}06)` : CDV.surface,
      border: `1.5px solid ${current ? plan.color : (plan.recommended ? plan.color : CDV.stroke)}`,
    }}>
      {plan.recommended && (
        <div style={{
          position: 'absolute', top: -12, left: 18, padding: '4px 10px',
          background: CDV.brandGrad, color: '#fff', borderRadius: 99,
          fontSize: 10, fontWeight: 700, letterSpacing: 0.4,
          boxShadow: '0 4px 12px -4px rgba(177,151,252,0.5)',
        }}>MAIS POPULAR</div>
      )}
      {current && (
        <div style={{
          position: 'absolute', top: -12, right: 18, padding: '4px 10px',
          background: CDV.mint, color: '#062014', borderRadius: 99,
          fontSize: 10, fontWeight: 700, letterSpacing: 0.4,
        }}>SEU PLANO</div>
      )}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <Icon name={plan.icon} size={18} color={plan.color} />
            <div style={{ fontSize: 17, fontWeight: 700, color: CDV.text, letterSpacing: -0.2 }}>{plan.name}</div>
            {plan.save && <Pill color={CDV.mint} size="sm">economize {plan.save}</Pill>}
          </div>
          <div style={{ fontSize: 12, color: CDV.textDim, marginTop: 2 }}>{plan.subtitle}</div>
        </div>
      </div>

      <div style={{ marginTop: 14, display: 'flex', alignItems: 'baseline', gap: 6 }}>
        <div style={{ fontSize: 32, fontWeight: 700, color: CDV.text, letterSpacing: -0.5 }}>{fmtBRL(plan.total)}</div>
        <div style={{ fontSize: 12, color: CDV.textDim }}>
          {plan.months === 1 ? '/mês' : plan.months === 6 ? 'a cada 6 meses' : '/ano'}
        </div>
      </div>
      {plan.months > 1 && (
        <div style={{ fontSize: 12, color: plan.color, fontWeight: 600, marginTop: 4 }}>
          equivale a {fmtBRL(perMonth)}/mês
        </div>
      )}

      <button onClick={onSelect} disabled={current} style={{
        marginTop: 16, width: '100%', height: 50, borderRadius: 14,
        background: current ? CDV.surfaceHi2 : (plan.recommended ? CDV.brandGrad : CDV.surfaceHi2),
        border: current ? `1px solid ${CDV.strokeHi}` : (plan.recommended ? 'none' : `1px solid ${plan.color}40`),
        color: current ? CDV.textDim : '#fff',
        fontWeight: 600, fontSize: 14, fontFamily: 'inherit',
        cursor: current ? 'default' : 'pointer',
        boxShadow: plan.recommended && !current ? '0 8px 24px -8px rgba(177,151,252,0.6)' : 'none',
      }}>
        {current ? 'Plano atual' : `Escolher ${plan.name}`}
      </button>
    </div>
  );
};

// ── Notifications screen ────────────────────────────────────
const NotificationsScreen = ({ navigate, showToast }) => {
  const defaultItems = [
    { id: 'n1', time: 'agora', icon: 'sparkle', color: CDV.brand, title: 'Sofia tem uma sugestão', desc: 'Você ainda não bateu sua meta de água hoje.', smart: true, route: 'habits' },
    { id: 'n2', time: '8min', icon: 'flame', color: CDV.flame, title: 'Hábito de meditar à vista', desc: 'Falta 1 hora para seu horário ideal.', route: 'habits' },
    { id: 'n3', time: '1h', icon: 'wallet', color: CDV.amber, title: 'Alerta financeiro', desc: 'Você gastou R$ 78 em delivery hoje (acima da média).', route: 'finance' },
    { id: 'n4', time: '3h', icon: 'check', color: CDV.mint, title: 'Tarefa concluída', desc: 'Você ganhou +85 XP por concluir 7 tarefas.', route: 'tasks' },
    { id: 'n5', time: '5h', icon: 'trophy', color: CDV.amber, title: 'Nova conquista 🎉', desc: 'Madrugador desbloqueado — 10 dias acordando cedo.', route: 'achievements' },
    { id: 'n6', time: '12h', icon: 'bell', color: CDV.sky, title: 'Lembrete inteligente', desc: 'Reunião com diretoria em 30 minutos.', route: 'calendar' },
    { id: 'n7', time: 'ontem', icon: 'target', color: CDV.coral, title: 'Meta avançada', desc: 'Você está 2 semanas adiantado em "Apartamento".', route: 'goals' },
  ];
  const [items, setItems] = React.useState(defaultItems);

  const markAll = () => {
    setItems([]);
    showToast && showToast('Todas marcadas como lidas');
  };
  const openDetails = (n) => {
    if (n.route) navigate(n.route);
  };
  const dismiss = (id, e) => {
    e && e.stopPropagation();
    setItems(arr => arr.filter(x => x.id !== id));
  };

  return (
    <div style={{ paddingBottom: 110 }}>
      <Header title="Notificações" subtitle={items.length ? `HOJE · ${items.length} ATIVAS` : 'TUDO EM DIA'} onBack={() => navigate('more')} right={
        items.length > 0 && (
          <button onClick={markAll} style={{
            background: CDV.surfaceHi, border: `1px solid ${CDV.stroke}`, padding: '7px 12px', borderRadius: 99,
            color: CDV.textDim, fontSize: 12, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer',
          }}>Marcar tudo</button>
        )
      } />
      <div style={{ padding: '0 22px 18px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {items.length === 0 && (
          <div style={{ padding: 32, borderRadius: 16, background: CDV.surface, border: `1px dashed ${CDV.stroke}`, color: CDV.textDim, fontSize: 13, textAlign: 'center' }}>
            <Icon name="check" size={28} color={CDV.mint} />
            <div style={{ marginTop: 10 }}>Nenhuma notificação pendente.</div>
          </div>
        )}
        {items.map((n) => (
          <div key={n.id} onClick={() => openDetails(n)} style={{
            padding: 14, paddingLeft: 16, borderRadius: 16,
            background: n.smart
              ? `linear-gradient(135deg, ${n.color}18 0%, ${n.color}06 40%, ${CDV.surface} 100%)`
              : `linear-gradient(135deg, ${n.color}0d 0%, ${CDV.surface} 50%)`,
            border: `1px solid ${n.smart ? n.color + '44' : n.color + '22'}`,
            display: 'flex', alignItems: 'flex-start', gap: 12, cursor: 'pointer',
            position: 'relative', overflow: 'hidden',
            boxShadow: n.smart ? `0 6px 18px -10px ${n.color}55` : `0 4px 14px -10px ${n.color}30`,
          }}>
            {/* Glow blob — só nas smart pra não poluir */}
            {n.smart && (
              <div style={{
                position: 'absolute', top: -30, right: -30, width: 130, height: 130, borderRadius: 99,
                background: `radial-gradient(circle, ${n.color}55, transparent 60%)`,
                filter: 'blur(24px)', opacity: 0.5, pointerEvents: 'none',
              }} />
            )}
            <div style={{
              position: 'absolute', left: 0, top: 14, bottom: 14, width: 3, borderRadius: 99,
              background: `linear-gradient(180deg, ${n.color}, ${n.color}40)`,
              boxShadow: `0 0 12px ${n.color}80`,
            }} />
            <div style={{
              width: 38, height: 38, borderRadius: 11,
              background: `linear-gradient(135deg, ${n.color}38, ${n.color}14)`,
              border: `1px solid ${n.color}30`,
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              boxShadow: `0 6px 16px -6px ${n.color}80, inset 0 0 0 1px rgba(255,255,255,0.06)`,
              position: 'relative',
            }}><Icon name={n.icon} size={18} color={n.color} /></div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: CDV.text }}>{n.title}</div>
                <div style={{ fontSize: 11, color: CDV.textMuted, marginLeft: 8, flexShrink: 0 }}>{n.time}</div>
              </div>
              <div style={{ fontSize: 12, color: CDV.textDim, marginTop: 3, lineHeight: 1.4 }}>{n.desc}</div>
              {n.smart && (
                <div style={{ marginTop: 8, display: 'flex', gap: 6 }}>
                  <button onClick={(e) => { e.stopPropagation(); openDetails(n); }} style={{
                    background: CDV.brandGrad, color: '#fff', border: 'none', padding: '5px 10px',
                    borderRadius: 99, fontSize: 11, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer',
                  }}>Ver detalhes</button>
                  <button onClick={(e) => dismiss(n.id, e)} style={{
                    background: CDV.surfaceHi, color: CDV.textDim, border: `1px solid ${CDV.stroke}`, padding: '5px 10px',
                    borderRadius: 99, fontSize: 11, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer',
                  }}>Dispensar</button>
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// ── Profile detail screen ─────────────────────────────────
const ProfileScreen = ({ state, navigate }) => {
  return (
    <div style={{ paddingBottom: 110 }}>
      <Header title="Perfil" subtitle="SUA CONTA" onBack={() => navigate('more')} />
      <div style={{ padding: '0 22px 18px' }}>
        <ProfileCard state={state} onClick={() => {}} />
      </div>

      <SectionHeader title="Seu progresso esta semana" />
      <div style={{ padding: '0 22px 18px' }}>
        <Card padding={18}>
          <div style={{ display: 'flex', justifyContent: 'space-around', alignItems: 'flex-end', height: 140, gap: 8 }}>
            {[40, 65, 80, 50, 90, 75, 95].map((v, i) => (
              <div key={i} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, flex: 1 }}>
                <div style={{
                  width: '100%', height: `${v}%`, borderRadius: '8px 8px 4px 4px',
                  background: `linear-gradient(180deg, ${CDV.brand}, ${CDV.brand}80)`,
                  boxShadow: i === 6 ? `0 0 16px ${CDV.brand}88` : 'none',
                }} />
                <div style={{ fontSize: 10, color: CDV.textDim, fontWeight: 600 }}>{['S','T','Q','Q','S','S','D'][i]}</div>
              </div>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 14, marginTop: 16, paddingTop: 14, borderTop: `1px solid ${CDV.stroke}` }}>
            <MiniStat val="847" label="XP da semana" color={CDV.brand} />
            <MiniStat val="42" label="Tarefas" color={CDV.mint} />
            <MiniStat val="86%" label="Eficiência" color={CDV.amber} />
          </div>
        </Card>
      </div>
    </div>
  );
};

Object.assign(window, { MoreScreen, AchievementsScreen, PlansScreen, NotificationsScreen, ProfileScreen });
