/* Zona C — Settings page (#screen=settings).
   Layout 2-col: sidebar 240px com lista de secções + main content.
   Identidade · Empresas&Permissões (read-only) · Aparência · Notificações ·
   Integrações · Modo Demo · Segurança · Sobre. */

const SETTINGS_SECTIONS = [
  { id: 'identity',     label: 'Identidade',           icon: 'user' },
  { id: 'permissions',  label: 'Empresas & Permissões', icon: 'building' },
  { id: 'appearance',   label: 'Aparência',            icon: 'sun' },
  { id: 'notifications', label: 'Notificações',        icon: 'bell' },
  { id: 'integrations', label: 'Integrações pessoais', icon: 'link' },
  { id: 'demo',         label: 'Modo Demo',            icon: 'eye',         requiresRole: ['admin','director','dev'] },
  { id: 'security',     label: 'Segurança',            icon: 'flag' },
  { id: 'about',        label: 'Sobre',                icon: 'info' },
];

const SettingsScreen = ({ user, theme, onToggleTheme }) => {
  const u = user || {};
  const [section, setSection] = React.useState(() => {
    try { return localStorage.getItem('digi-settings-section') || 'identity'; } catch { return 'identity'; }
  });
  React.useEffect(() => { try { localStorage.setItem('digi-settings-section', section); } catch {} }, [section]);

  const visibleSections = SETTINGS_SECTIONS.filter(s => {
    if (!s.requiresRole) return true;
    return s.requiresRole.includes(u.role);
  });

  return (
    <div style={{ display: 'flex', height: '100%', background: 'var(--bg)' }}>
      {/* Section sidebar */}
      <aside style={{
        width: 240, flexShrink: 0,
        borderRight: '1px solid var(--border)',
        background: 'var(--bg-elev)',
        padding: '20px 12px',
        overflowY: 'auto',
      }} className="scrollbar">
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-display)', fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', padding: '4px 10px 10px' }}>
          Settings
        </div>
        {visibleSections.map(s => (
          <button key={s.id} onClick={() => setSection(s.id)} style={{
            width: '100%', display: 'flex', alignItems: 'center', gap: 10,
            padding: '8px 10px', marginBottom: 2,
            borderRadius: 'var(--r-3)',
            background: section === s.id ? 'var(--brand-900)' : 'transparent',
            color: section === s.id ? '#fff' : 'var(--text)',
            fontSize: 13, fontWeight: section === s.id ? 500 : 400,
          }}
          onMouseEnter={e => { if (section !== s.id) e.currentTarget.style.background = 'var(--bg-hover)'; }}
          onMouseLeave={e => { if (section !== s.id) e.currentTarget.style.background = 'transparent'; }}>
            <Icon name={s.icon} size={14} style={{ flexShrink: 0 }} />
            <span style={{ textAlign: 'left' }}>{s.label}</span>
          </button>
        ))}
      </aside>

      {/* Main content */}
      <main className="scrollbar" style={{ flex: 1, minWidth: 0, overflowY: 'auto', padding: '32px 40px 60px', maxWidth: 880 }}>
        {section === 'identity' && <SettingsIdentity user={u} />}
        {section === 'permissions' && <SettingsPermissions user={u} />}
        {section === 'appearance' && <SettingsAppearance theme={theme} onToggleTheme={onToggleTheme} />}
        {section === 'notifications' && <SettingsNotifications user={u} />}
        {section === 'integrations' && <SettingsIntegrations user={u} />}
        {section === 'demo' && <SettingsDemo user={u} />}
        {section === 'security' && <SettingsSecurity user={u} />}
        {section === 'about' && <SettingsAbout />}
      </main>
    </div>
  );
};

const SHead = ({ title, subtitle }) => (
  <div style={{ marginBottom: 24 }}>
    <h2 className="font-display" style={{ margin: 0, fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em' }}>{title}</h2>
    {subtitle && <p style={{ margin: '4px 0 0', fontSize: 13, color: 'var(--text-muted)' }}>{subtitle}</p>}
  </div>
);
const SCard = ({ children, style }) => (
  <div className="card" style={{ padding: 18, marginBottom: 14, ...style }}>{children}</div>
);
const SRow = ({ label, value, mono }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', borderBottom: '1px solid var(--border)', fontSize: 13 }}>
    <span style={{ color: 'var(--text-muted)' }}>{label}</span>
    <span style={{ color: 'var(--text)', fontFamily: mono ? 'var(--font-mono)' : undefined, fontWeight: 500 }}>{value}</span>
  </div>
);
const SRadio = ({ name, value, options, onChange }) => (
  <div style={{ display: 'flex', gap: 6 }}>
    {options.map(o => (
      <button key={o.id} onClick={() => onChange(o.id)} style={{
        padding: '7px 14px', borderRadius: 'var(--r-3)',
        border: '1px solid ' + (value === o.id ? 'var(--ai-500)' : 'var(--border)'),
        background: value === o.id ? 'color-mix(in oklch, var(--ai-500) 10%, transparent)' : 'var(--bg-elev)',
        color: value === o.id ? 'var(--text)' : 'var(--text-muted)',
        fontSize: 12.5, fontWeight: value === o.id ? 600 : 400,
      }}>{o.label}</button>
    ))}
  </div>
);
const STitle = ({ children, sub }) => (
  <div style={{ marginBottom: 12 }}>
    <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>{children}</div>
    {sub && <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginTop: 2 }}>{sub}</div>}
  </div>
);

// === Identidade
const SettingsIdentity = ({ user }) => (
  <div>
    <SHead title="Identidade" subtitle="Sincronizado com HR + Microsoft Graph. Read-only." />
    <SCard>
      <div style={{ display: 'flex', gap: 16, alignItems: 'center', marginBottom: 12 }}>
        <div style={{
          width: 64, height: 64, borderRadius: '50%',
          background: 'var(--brand-700)', color: '#fff',
          display: 'grid', placeItems: 'center',
          fontSize: 22, fontWeight: 600, fontFamily: 'var(--font-display)',
        }}>{user.iniciais}</div>
        <div>
          <div style={{ fontSize: 18, fontWeight: 600, fontFamily: 'var(--font-display)' }}>{user.nome}</div>
          <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{user.cargo} · {user.departamento}</div>
        </div>
      </div>
      <SRow label="Email" value={user.email} mono />
      <SRow label="Cargo" value={user.cargo} />
      <SRow label="Departamento" value={user.departamento} />
      <SRow label="Manager" value={user.role === 'admin' ? '— (Admin)' : 'Rui Leitão'} />
      <SRow label="Empresa primária" value={(window.farbenCompany?.(user.empresaId)?.name) || user.empresa} />
    </SCard>
    <div style={{ fontSize: 11.5, color: 'var(--text-dim)', display: 'flex', alignItems: 'center', gap: 6 }}>
      <Icon name="info" size={12} /> Para alterar, contactar HR.
    </div>
  </div>
);

// === Empresas & Permissões
const SettingsPermissions = ({ user }) => {
  const companies = (window.FARBEN_COMPANIES || []).filter(c => (user.empresas || []).includes(c.id));
  return (
    <div>
      <SHead title="Empresas & Permissões" subtitle="Read-only. Para alterar, contactar Admin." />
      <SCard>
        <STitle>Empresa primária</STitle>
        <div style={{ fontSize: 13.5, marginBottom: 14 }}>{(window.farbenCompany?.(user.empresaId)?.name) || user.empresa}</div>
        <STitle>Empresas acessíveis</STitle>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {companies.map(c => (
            <div key={c.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0' }}>
              <div style={{ width: 26, height: 26, borderRadius: 4, background: 'var(--brand-900)', color: '#fff', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 10.5 }}>{c.code}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{c.name}</div>
                <div style={{ fontSize: 10.5, color: 'var(--text-dim)' }}>{c.country} · {c.tipo}</div>
              </div>
            </div>
          ))}
        </div>
      </SCard>
      <SCard>
        <STitle>Role</STitle>
        <div style={{ fontSize: 13, marginBottom: 14 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 9px', borderRadius: 4, fontSize: 10.5, fontFamily: 'var(--font-mono)', fontWeight: 700, letterSpacing: '0.06em', background: 'color-mix(in oklch, var(--ai-500) 14%, transparent)', color: 'var(--ai-500)', border: '1px solid color-mix(in oklch, var(--ai-500) 30%, transparent)' }}>
            {(user.role || 'user').toUpperCase()}
          </span>
          <span style={{ marginLeft: 10, color: 'var(--text-muted)', fontSize: 12 }}>
            {(window.FARBEN_ROLES || []).find(r => r.id === user.role)?.desc}
          </span>
        </div>
        <STitle>Modos permitidos</STitle>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 14 }}>
          {(user.modos || []).map(m => (
            <span key={m} className="badge badge-info" style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, fontWeight: 600, letterSpacing: '0.04em' }}>{m}</span>
          ))}
        </div>
        <STitle>Marcas</STitle>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 14 }}>
          {(user.marcas || []).map(m => (
            <span key={m} style={{ padding: '4px 9px', borderRadius: 999, background: 'var(--surface-muted)', border: '1px solid var(--border)', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 11, letterSpacing: '0.04em' }}>{m}</span>
          ))}
        </div>
        <STitle>Mercados</STitle>
        <div style={{ display: 'flex', gap: 6 }}>
          {(user.mercados || []).map(m => (
            <span key={m} style={{ padding: '4px 10px', borderRadius: 4, background: 'var(--brand-900)', color: '#fff', fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 600 }}>{m}</span>
          ))}
        </div>
      </SCard>
    </div>
  );
};

// === Aparência
const SettingsAppearance = ({ theme, onToggleTheme }) => {
  const [themeChoice, setThemeChoice] = React.useState(theme === 'dark' ? 'dark' : 'light');
  const [lang, setLang] = React.useState(() => { try { return localStorage.getItem('digi-lang') || 'PT'; } catch { return 'PT'; } });
  const [density, setDensity] = React.useState(() => { try { return localStorage.getItem('digi-density') || 'comfortable'; } catch { return 'comfortable'; } });
  React.useEffect(() => { try { localStorage.setItem('digi-lang', lang); } catch {} }, [lang]);
  React.useEffect(() => { try { localStorage.setItem('digi-density', density); } catch {} }, [density]);
  const onTheme = (t) => { setThemeChoice(t); if ((t === 'dark') !== (theme === 'dark')) onToggleTheme && onToggleTheme(); };
  return (
    <div>
      <SHead title="Aparência" subtitle="Tema, idioma e densidade da interface." />
      <SCard>
        <STitle>Tema</STitle>
        <SRadio value={themeChoice} onChange={onTheme} options={[{id:'light',label:'Light'},{id:'dark',label:'Dark'},{id:'system',label:'Sistema'}]} />
      </SCard>
      <SCard>
        <STitle>Idioma</STitle>
        <SRadio value={lang} onChange={setLang} options={[{id:'PT',label:'Português'},{id:'EN',label:'English'},{id:'ES',label:'Español'}]} />
      </SCard>
      <SCard>
        <STitle>Densidade</STitle>
        <SRadio value={density} onChange={setDensity} options={[{id:'comfortable',label:'Confortável'},{id:'compact',label:'Compacta'}]} />
      </SCard>
      <SCard>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <STitle sub="Lista de atalhos do portal">Atalhos de teclado</STitle>
          </div>
          <button className="btn btn-sm">
            <Icon name="keyboard" size={13} />
            Ver atalhos
            <kbd style={{ fontFamily: 'var(--font-mono)', fontSize: 10, marginLeft: 6, padding: '1px 5px', border: '1px solid var(--border)', borderRadius: 3, background: 'var(--bg-sunken)' }}>⌘/</kbd>
          </button>
        </div>
      </SCard>
    </div>
  );
};

// === Notificações
const SettingsNotifications = ({ user }) => {
  const [op, setOp] = React.useState({
    lead: ['wa','email','portal'],
    sat:  ['wa','email','portal'],
    urgent: ['wa','email','portal'],
    cost: ['email','portal'],
  });
  const [comm, setComm] = React.useState({
    novidades: ['email'],
    tips: [],
    surveys: [],
  });
  const [dnd, setDnd] = React.useState({ start: '19:00', end: '08:00', weekend: true });
  const showCost = user.role === 'admin' || user.role === 'director';
  const toggle = (state, setState, key, ch) => setState(s => ({ ...s, [key]: s[key].includes(ch) ? s[key].filter(c => c !== ch) : [...s[key], ch] }));

  return (
    <div>
      <SHead title="Notificações" subtitle="Operacionais (defeito ON) e Comunicações Digi (defeito OFF)." />

      <SCard>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 12 }}>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Operacionais</div>
          <span style={{ fontSize: 9.5, fontFamily: 'var(--font-mono)', fontWeight: 700, letterSpacing: '0.08em', color: 'var(--success)', padding: '2px 7px', borderRadius: 3, background: 'color-mix(in oklch, var(--success) 14%, transparent)' }}>RECOMENDADO</span>
        </div>
        <NotifRow label="Novo lead atribuído" channels={op.lead} onToggle={ch => toggle(op, setOp, 'lead', ch)} />
        <NotifRow label="Escalação SAT" channels={op.sat} onToggle={ch => toggle(op, setOp, 'sat', ch)} />
        <NotifRow label="Ticket urgente" channels={op.urgent} onToggle={ch => toggle(op, setOp, 'urgent', ch)} />
        {showCost && <NotifRow label="Alerta custos AI" channels={op.cost} onToggle={ch => toggle(op, setOp, 'cost', ch)} adminOnly />}
      </SCard>

      <SCard>
        <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 12 }}>Comunicações Digi</div>
        <NotifRow label="Novidades portal" channels={comm.novidades} onToggle={ch => toggle(comm, setComm, 'novidades', ch)} channelsAvailable={['email']} />
        <NotifRow label="Tips de uso Digi" channels={comm.tips} onToggle={ch => toggle(comm, setComm, 'tips', ch)} channelsAvailable={['portal']} />
        <NotifRow label="Surveys feedback" channels={comm.surveys} onToggle={ch => toggle(comm, setComm, 'surveys', ch)} channelsAvailable={['email']} />
      </SCard>

      <SCard>
        <STitle>Horário não-perturbar</STitle>
        <div style={{ display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
          <div>
            <div style={{ fontSize: 11, color: 'var(--text-dim)', marginBottom: 4 }}>Início</div>
            <input type="time" value={dnd.start} onChange={e => setDnd(d => ({...d, start: e.target.value}))} style={{ padding: '6px 10px', borderRadius: 'var(--r-2)', border: '1px solid var(--border)', background: 'var(--bg-elev)', fontFamily: 'var(--font-mono)', fontSize: 12 }} />
          </div>
          <div>
            <div style={{ fontSize: 11, color: 'var(--text-dim)', marginBottom: 4 }}>Fim</div>
            <input type="time" value={dnd.end} onChange={e => setDnd(d => ({...d, end: e.target.value}))} style={{ padding: '6px 10px', borderRadius: 'var(--r-2)', border: '1px solid var(--border)', background: 'var(--bg-elev)', fontFamily: 'var(--font-mono)', fontSize: 12 }} />
          </div>
          <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, cursor: 'pointer', marginTop: 16 }}>
            <input type="checkbox" checked={dnd.weekend} onChange={() => setDnd(d => ({...d, weekend: !d.weekend}))} />
            Fim-de-semana
          </label>
        </div>
        <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 14, display: 'flex', alignItems: 'center', gap: 6 }}>
          <Icon name="info" size={11} /> Canais disponíveis: WhatsApp · Email · Portal
        </div>
      </SCard>
    </div>
  );
};

const NotifRow = ({ label, channels, onToggle, channelsAvailable, adminOnly }) => {
  const all = channelsAvailable || ['wa','email','portal'];
  const labels = { wa: 'WA', email: 'Email', portal: 'Portal' };
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px solid var(--border)' }}>
      <div style={{ fontSize: 12.5, display: 'flex', alignItems: 'center', gap: 8 }}>
        {label}
        {adminOnly && <span style={{ fontSize: 9, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', padding: '1px 5px', border: '1px solid var(--border)', borderRadius: 2 }}>ADMIN</span>}
      </div>
      <div style={{ display: 'flex', gap: 4 }}>
        {all.map(ch => {
          const on = channels.includes(ch);
          return (
            <button key={ch} onClick={() => onToggle(ch)} style={{
              padding: '3px 9px', fontSize: 10.5, fontFamily: 'var(--font-mono)', fontWeight: 600, letterSpacing: '0.04em',
              borderRadius: 4,
              background: on ? 'var(--ai-500)' : 'transparent',
              color: on ? '#fff' : 'var(--text-muted)',
              border: '1px solid ' + (on ? 'var(--ai-500)' : 'var(--border)'),
            }}>{labels[ch]}</button>
          );
        })}
      </div>
    </div>
  );
};

// === Integrações pessoais
const SettingsIntegrations = ({ user }) => {
  const integ = [
    { id: 'ms365', name: 'Microsoft 365 (SSO)', status: 'connected', meta: 'fabio.costa@digidelta.pt' },
    { id: 'clickup', name: 'ClickUp', status: 'connected', meta: '7 tarefas abertas' },
    { id: 'apollo', name: 'Apollo seat', status: user.role === 'user' ? 'n/a' : 'connected', meta: user.role === 'user' ? 'Sem perfil' : 'seat 12 / 50' },
    { id: 'vnnox', name: 'VNNOX user', status: user.empresas?.includes('NSC') ? 'connected' : 'n/a', meta: user.empresas?.includes('NSC') ? 'NSC tenant' : 'Sem perfil' },
    { id: 'primavera', name: 'Primavera', status: 'connected', meta: `User code: ${user.iniciais?.toUpperCase()}001` },
  ];
  return (
    <div>
      <SHead title="Integrações pessoais" subtitle="Sistemas externos ligados a este utilizador." />
      <SCard>
        {integ.map((i, idx) => (
          <div key={i.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: idx < integ.length - 1 ? '1px solid var(--border)' : 'none' }}>
            <div style={{ width: 32, height: 32, borderRadius: 6, background: 'var(--surface-muted)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
              <Icon name="link" size={14} style={{ color: 'var(--text-muted)' }} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 500 }}>{i.name}</div>
              <div style={{ fontSize: 11, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{i.meta}</div>
            </div>
            {i.status === 'connected' ? (
              <span style={{ fontSize: 10.5, fontFamily: 'var(--font-mono)', fontWeight: 600, color: 'var(--success)', padding: '3px 8px', borderRadius: 3, background: 'color-mix(in oklch, var(--success) 14%, transparent)', letterSpacing: '0.06em' }}>● CONNECTED</span>
            ) : i.status === 'n/a' ? (
              <span style={{ fontSize: 10.5, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', padding: '3px 8px', borderRadius: 3, background: 'var(--bg-sunken)', letterSpacing: '0.06em' }}>n/a</span>
            ) : (
              <button className="btn btn-xs">Ligar</button>
            )}
          </div>
        ))}
      </SCard>
    </div>
  );
};

// === Modo Demo
const SettingsDemo = ({ user }) => {
  const [on, setOn] = React.useState(false);
  return (
    <div>
      <SHead title="Modo Demo" subtitle="Visível só a Admin, Director e DEV." />
      <SCard>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <STitle sub="Mantém dados reais mas marca a sessão como demo para auditoria. Útil para apresentações e demos a clientes.">Activar modo demo</STitle>
          <button onClick={() => setOn(v => !v)} style={{
            width: 44, height: 24, borderRadius: 12,
            background: on ? 'var(--ai-500)' : 'var(--surface-muted)',
            border: '1px solid var(--border)',
            position: 'relative',
            transition: 'all 0.2s',
          }}>
            <span style={{
              position: 'absolute', top: 2, left: on ? 22 : 2,
              width: 18, height: 18, borderRadius: '50%',
              background: '#fff',
              transition: 'left 0.2s',
              boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
            }} />
          </button>
        </div>
      </SCard>
    </div>
  );
};

// === Segurança
const SettingsSecurity = ({ user }) => {
  const sessions = [
    { device: 'MacBook Pro · Safari 17', ip: '94.62.143.21 · Lisboa', lastSeen: 'há 2 min', current: true },
    { device: 'iPhone 15 · Safari', ip: '188.250.49.7 · Porto', lastSeen: 'há 14h' },
    { device: 'Windows · Edge', ip: '85.244.218.4 · Lisboa', lastSeen: 'há 3 dias' },
  ];
  const showApiKeys = user.role === 'admin' || user.role === 'dev';
  return (
    <div>
      <SHead title="Segurança" subtitle="2FA, sessões activas, histórico." />
      <SCard>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <STitle sub={user.tfa ? 'Microsoft Authenticator · activo' : 'Não configurado'}>2FA</STitle>
          </div>
          <span style={{ fontSize: 10.5, fontFamily: 'var(--font-mono)', fontWeight: 600, color: user.tfa ? 'var(--success)' : 'var(--warning)', padding: '3px 8px', borderRadius: 3, background: `color-mix(in oklch, ${user.tfa ? 'var(--success)' : 'var(--warning)'} 14%, transparent)` }}>
            {user.tfa ? '● ACTIVO' : '○ INACTIVO'}
          </span>
        </div>
        <div style={{ marginTop: 12 }}>
          <button className="btn btn-sm">Reset 2FA</button>
        </div>
      </SCard>

      <SCard>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <STitle>Sessões activas</STitle>
          <button className="btn btn-sm" style={{ color: 'var(--danger)', borderColor: 'color-mix(in oklch, var(--danger) 30%, transparent)' }}>Revogar todas</button>
        </div>
        {sessions.map((s, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '8px 0', borderBottom: i < sessions.length - 1 ? '1px solid var(--border)' : 'none' }}>
            <Icon name="layers" size={14} style={{ color: 'var(--text-muted)' }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12.5, fontWeight: 500 }}>{s.device} {s.current && <span style={{ fontSize: 9.5, fontFamily: 'var(--font-mono)', fontWeight: 600, color: 'var(--success)', marginLeft: 6 }}>● ESTA SESSÃO</span>}</div>
              <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{s.ip} · {s.lastSeen}</div>
            </div>
            {!s.current && <button className="btn btn-xs">Revogar</button>}
          </div>
        ))}
      </SCard>

      <SCard>
        <STitle sub="Últimos 30 dias">Histórico de login</STitle>
        <button className="btn btn-sm">Ver histórico completo</button>
      </SCard>

      {showApiKeys && (
        <SCard>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <STitle sub="Visível só a DEV / Admin">API keys</STitle>
            <button className="btn btn-sm">+ Nova chave</button>
          </div>
        </SCard>
      )}
    </div>
  );
};

// === Sobre
const SettingsAbout = () => (
  <div>
    <SHead title="Sobre" subtitle="Documentação, T&C, contactos." />
    <SCard>
      <SettingsLink icon="doc" label="Documentação" />
      <SettingsLink icon="flag" label="Reportar bug" />
      <SettingsLink icon="zap" label="Novidades" meta="v1.0 · 27 abr 2026" />
      <SettingsLink icon="doc" label="Termos & Condições" />
      <SettingsLink icon="info" label="Política RGPD" last />
    </SCard>
  </div>
);
const SettingsLink = ({ icon, label, meta, last }) => (
  <button style={{
    display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0',
    width: '100%', borderBottom: last ? 'none' : '1px solid var(--border)',
    fontSize: 13, color: 'var(--text)',
  }}>
    <Icon name={icon} size={14} style={{ color: 'var(--text-muted)' }} />
    <span style={{ flex: 1, textAlign: 'left' }}>{label}</span>
    {meta && <span style={{ fontSize: 11, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{meta}</span>}
    <Icon name="chevronRight" size={13} style={{ color: 'var(--text-dim)' }} />
  </button>
);

window.SettingsScreen = SettingsScreen;
