// ── InovaPED — Configurações COMPLETAS (tema, IA, regras, equipe…) ───────
// Substitui o Settings simples. Navegação por seções. Persiste em
// localStorage (chave inovaped.cfg). Aplica de verdade: modo claro/escuro,
// fontes do sistema e densidade — para TODO o sistema (comprador + rep).
const TopbarCfg = window.BuyerParts1.Topbar;
const ICcfg = window.IC;

const CFG_KEY = 'inovaped.cfg';
const CFG_DEFAULT = {
  // aparência
  mode: 'escuro', accent: 'vermelho', density: 'confortável', uiFont: 'Manrope', displayFont: 'Space Grotesk', radius: 'médio', motion: true, applyToReps: true,
  // IA
  aiOn: true, aiAggr: 3, aiAutosuggest: true, aiAntiTypo: true, aiForecast: true, aiCrossSell: true, aiSentiment: true, aiAudio: true,
  aiSources: { custo: true, giro: true, validade: true, score: true, concorrencia: false, sazonal: true },
  aiTypoPct: 50, aiDivPct: 30, aiInstr: 'Priorize sempre o menor custo com validade acima de 6 meses. Avise quando um similar genérico for 30% mais barato que a marca. Nunca compare preços com e sem imposto sem destacar.',
  // cotações
  autoApprove: true, autoLimit: '5.000,00', loteMin: '12', recorrente: true, ruptura: true,
  // fiscal
  icms: '18,00', st: true, impostoPadrao: 'sem',
  // erp
  hosSync: true, hosEndpoint: 'api.hos.local/v2', hosFreq: '1h',
  // notificações (sistema)
  nOferta: true, nPrazo: true, nResumo: false, nCorte: true, nXml: true,
  // reps
  shelf: 6, blacklist: false, autoMural: true, exclusivo: false,
};

function cfgLoad() { try { return { ...CFG_DEFAULT, ...JSON.parse(localStorage.getItem(CFG_KEY) || '{}'), aiSources: { ...CFG_DEFAULT.aiSources, ...(JSON.parse(localStorage.getItem(CFG_KEY) || '{}').aiSources || {}) } }; } catch { return { ...CFG_DEFAULT }; } }
function cfgA(hex, a) { const h=(hex||'#888').replace('#',''); const n=parseInt(h.length===3?h.split('').map(c=>c+c).join(''):h,16); return `rgba(${(n>>16)&255},${(n>>8)&255},${n&255},${a})`; }

const ACCENTS = { vermelho: '#FF1330', âmbar: '#FF8A1F', esmeralda: '#00C277', violeta: '#9B5DE5', azul: '#2A8FEB' };
const UI_FONTS = ['Manrope', 'IBM Plex Sans', 'Spectral'];
const DISPLAY_FONTS = ['Space Grotesk', 'Manrope', 'Spectral'];

// aplica tema de verdade (fonte + densidade + accent var) ao :root
function applyTheme(c) {
  const r = document.documentElement.style;
  r.setProperty('--display', `'${c.displayFont}', sans-serif`);
  r.setProperty('--accent', ACCENTS[c.accent] || ACCENTS.vermelho);
  document.body.style.fontFamily = `'${c.uiFont}', -apple-system, system-ui, sans-serif`;
  r.setProperty('--cfg-density', c.density === 'compacto' ? '0.86' : c.density === 'espaçoso' ? '1.12' : '1');
}

// ── controles ────────────────────────────────────────────────────────────
function CfgToggle({ on, onClick }) {
  return <button onClick={onClick} style={{ width: 46, height: 27, borderRadius: 99, border: 'none', cursor: 'pointer', padding: 3, flexShrink: 0, background: on ? `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})` : 'rgba(255,255,255,0.13)', display: 'flex', justifyContent: on ? 'flex-end' : 'flex-start', transition: 'all .2s' }}><span style={{ width: 21, height: 21, borderRadius: 99, background: '#fff' }} /></button>;
}
function CfgRow({ title, desc, children, last }) {
  return <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '13px 0', borderBottom: last ? 'none' : `1px solid ${T.border}` }}>
    <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontWeight: 600, fontSize: 14 }}>{title}</div>{desc && <div style={{ fontSize: 12, color: T.mute, marginTop: 2 }}>{desc}</div>}</div>
    <div style={{ flexShrink: 0 }}>{children}</div>
  </div>;
}
function CfgInput({ value, onChange, w = 150, left }) {
  return <input value={value} onChange={e => onChange(e.target.value)} style={{ width: w, boxSizing: 'border-box', padding: '9px 12px', borderRadius: 9, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 13.5, outline: 'none', textAlign: left ? 'left' : 'right' }} />;
}
function CfgSeg({ value, onChange, opts }) {
  return <div style={{ display: 'flex', gap: 2, padding: 3, borderRadius: 9, background: T.panel, border: `1px solid ${T.border}`, flexWrap: 'wrap' }}>
    {opts.map(o => { const on = value === o; return <button key={o} onClick={() => onChange(o)} style={{ padding: '6px 12px', borderRadius: 6, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: on ? 700 : 500, color: on ? '#fff' : T.mute, background: on ? `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})` : 'transparent', whiteSpace: 'nowrap' }}>{o}</button>; })}
  </div>;
}
function CfgSlider({ value, onChange, min, max, step }) {
  return <input type="range" min={min} max={max} step={step || 1} value={value} onChange={e => onChange(+e.target.value)} style={{ width: 170, accentColor: T.red }} />;
}

window.CfgBits = { CFG_KEY, CFG_DEFAULT, cfgLoad, cfgA, ACCENTS, UI_FONTS, DISPLAY_FONTS, applyTheme, CfgToggle, CfgRow, CfgInput, CfgSeg, CfgSlider };

// card de grupo
function CfgCard({ icon, title, desc, children, accent }) {
  const c = accent || T.redBright;
  return <Glass style={{ marginBottom: 16 }}>
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 11, marginBottom: 6 }}>
      <div style={{ width: 34, height: 34, borderRadius: 9, background: cfgA(c, 0.14), display:'flex',alignItems:'center',justifyContent:'center', flexShrink: 0 }}><Icon name={icon} size={18} color={c} /></div>
      <div><div style={{ fontWeight: 700, fontSize: 15.5 }}>{title}</div>{desc && <div style={{ fontSize: 12, color: T.mute, marginTop: 1 }}>{desc}</div>}</div>
    </div>
    {children}
  </Glass>;
}

// swatch de cor de destaque
function CfgSwatches({ value, onChange }) {
  return <div style={{ display: 'flex', gap: 9, flexWrap: 'wrap' }}>
    {Object.entries(ACCENTS).map(([name, hex]) => { const on = value === name; return (
      <button key={name} onClick={() => onChange(name)} title={name} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '7px 12px 7px 8px', borderRadius: 99, cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: on ? 700 : 600, textTransform: 'capitalize',
        background: on ? cfgA(hex, 0.15) : T.panel, color: on ? hex : T.mute, border: `1.5px solid ${on ? hex : T.border}` }}>
        <span style={{ width: 18, height: 18, borderRadius: 99, background: hex, boxShadow: on ? `0 0 0 3px ${cfgA(hex,0.3)}` : 'none' }} />{name}
      </button>
    ); })}
  </div>;
}

// ── SEÇÃO: Aparência & Tema ──────────────────────────────────────────────
function SecAparencia({ c, set }) {
  return <div>
    <CfgCard icon="bolt" title="Tema do sistema" desc="Aplica a todas as telas — comprador e representantes" accent="#9B5DE5">
      <CfgRow title="Modo de exibição" desc="Claro, escuro ou conforme o dispositivo"><CfgSeg value={c.mode} onChange={v => set('mode', v)} opts={['claro','escuro','auto']} /></CfgRow>
      <CfgRow title="Cor de destaque" desc="Usada em botões, alertas e gráficos" last>
        <div /></CfgRow>
      <div style={{ marginTop: -4, marginBottom: 4 }}><CfgSwatches value={c.accent} onChange={v => set('accent', v)} /></div>
    </CfgCard>
    <CfgCard icon="list" title="Tipografia" desc="Fontes do sistema — alteração aplicada na hora">
      <CfgRow title="Fonte da interface" desc="Textos, menus e tabelas"><CfgSeg value={c.uiFont} onChange={v => set('uiFont', v)} opts={UI_FONTS} /></CfgRow>
      <CfgRow title="Fonte dos títulos" desc="Cabeçalhos e números grandes" last><CfgSeg value={c.displayFont} onChange={v => set('displayFont', v)} opts={DISPLAY_FONTS} /></CfgRow>
    </CfgCard>
    <CfgCard icon="table" title="Layout & densidade">
      <CfgRow title="Densidade da interface" desc="Espaçamento das listas e tabelas"><CfgSeg value={c.density} onChange={v => set('density', v)} opts={['compacto','confortável','espaçoso']} /></CfgRow>
      <CfgRow title="Cantos arredondados"><CfgSeg value={c.radius} onChange={v => set('radius', v)} opts={['reto','médio','suave']} /></CfgRow>
      <CfgRow title="Animações e transições" desc="Desligue para máxima performance"><CfgToggle on={c.motion} onClick={() => set('motion', !c.motion)} /></CfgRow>
      <CfgRow title="Aplicar tema aos representantes" desc="Padroniza o app dos reps com o mesmo tema" last><CfgToggle on={c.applyToReps} onClick={() => set('applyToReps', !c.applyToReps)} /></CfgRow>
    </CfgCard>
  </div>;
}

// ── SEÇÃO: Inteligência (IA) ─────────────────────────────────────────────
function SecIA({ c, set, setSrc }) {
  const aggrLabel = ['Conservadora','Cautelosa','Equilibrada','Proativa','Agressiva'][c.aiAggr - 1] || 'Equilibrada';
  const SRC = [['custo','Histórico de custo (entradas)'],['giro','Giro e curva ABC do ERP'],['validade','Validade / shelf-life'],['score','Score e prazo dos reps'],['concorrencia','Preço de concorrentes (InovaPrice)'],['sazonal','Sazonalidade e demanda']];
  return <div>
    <CfgCard icon="bolt" title="Motor de Inteligência" desc="Ligue e ajuste como a IA analisa cotações e produtos" accent="#00C277">
      <CfgRow title="IA ativa" desc="Desliga todas as sugestões automáticas"><CfgToggle on={c.aiOn} onClick={() => set('aiOn', !c.aiOn)} /></CfgRow>
      <CfgRow title={`Agressividade: ${aggrLabel}`} desc="Quão proativa a IA é ao sugerir trocas e counter-offers" last><CfgSlider value={c.aiAggr} onChange={v => set('aiAggr', v)} min={1} max={5} /></CfgRow>
    </CfgCard>
    <CfgCard icon="box" title="Fontes de dados que a IA lê" desc="Marque o que entra na análise da IA">
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 10, marginTop: 4 }}>
        {SRC.map(([k, label]) => { const on = c.aiSources[k]; return (
          <button key={k} onClick={() => setSrc(k, !on)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 13px', borderRadius: 11, cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit',
            background: on ? cfgA(T.green, 0.08) : T.panel, border: `1px solid ${on ? cfgA(T.green,0.32) : T.border}` }}>
            <span style={{ width: 20, height: 20, borderRadius: 6, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: on ? T.green : 'transparent', border: `1.5px solid ${on ? T.green : T.mute2}` }}>{on && <Icon name="check" size={13} color="#04130C" strokeWidth={3} />}</span>
            <span style={{ fontSize: 13, fontWeight: 600, color: on ? T.text : T.mute }}>{label}</span>
          </button>
        ); })}
      </div>
    </CfgCard>
    <CfgCard icon="shield" title="Recursos de IA">
      <CfgRow title="Sugestão de aceite na grade" desc='"Aceitar e atualizar preço"'><CfgToggle on={c.aiAutosuggest} onClick={() => set('aiAutosuggest', !c.aiAutosuggest)} /></CfgRow>
      <CfgRow title="Anti-erro de digitação" desc="Bloqueia oferta numericamente impossível"><CfgToggle on={c.aiAntiTypo} onClick={() => set('aiAntiTypo', !c.aiAntiTypo)} /></CfgRow>
      <CfgRow title="Previsão de ruptura" desc="Avisa quando o estoque vai acabar pelo giro"><CfgToggle on={c.aiForecast} onClick={() => set('aiForecast', !c.aiForecast)} /></CfgRow>
      <CfgRow title="Cross-sell inteligente" desc='"Comprando Whey? Creatina está verde"'><CfgToggle on={c.aiCrossSell} onClick={() => set('aiCrossSell', !c.aiCrossSell)} /></CfgRow>
      <CfgRow title="Análise de sentimento no chat" desc="Detecta urgência / tom agressivo"><CfgToggle on={c.aiSentiment} onClick={() => set('aiSentiment', !c.aiSentiment)} /></CfgRow>
      <CfgRow title="Transcrição de áudio → grade" desc="Extrai valores de áudios do rep" last><CfgToggle on={c.aiAudio} onClick={() => set('aiAudio', !c.aiAudio)} /></CfgRow>
    </CfgCard>
    <CfgCard icon="bell" title="Limiares de alerta">
      <CfgRow title={`Preço suspeito abaixo de ${c.aiTypoPct}%`} desc="Marca como possível erro de digitação"><CfgSlider value={c.aiTypoPct} onChange={v => set('aiTypoPct', v)} min={10} max={90} step={5} /></CfgRow>
      <CfgRow title={`Divergência de XML acima de ${c.aiDivPct}%`} desc="Bloqueia importação da nota" last><CfgSlider value={c.aiDivPct} onChange={v => set('aiDivPct', v)} min={5} max={100} step={5} /></CfgRow>
    </CfgCard>
    <CfgCard icon="send" title="Instruções personalizadas da IA" desc="Texto livre que orienta como a IA decide e avisa">
      <textarea value={c.aiInstr} onChange={e => set('aiInstr', e.target.value)} rows={5} style={{ width: '100%', boxSizing: 'border-box', padding: '13px 15px', borderRadius: 12, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 13.5, lineHeight: 1.5, outline: 'none', resize: 'vertical' }} />
      <div style={{ fontSize: 11.5, color: T.mute2, marginTop: 8 }}>Essas instruções são enviadas ao modelo junto de cada análise. Ex.: regras de validade, prioridade de marca, política fiscal.</div>
    </CfgCard>
  </div>;
}

// ── SEÇÃO: Cotações & Aprovação ──────────────────────────────────────────
function SecCotacoes({ c, set }) {
  return <div>
    <CfgCard icon="check" title="Aprovação automática" accent="#2A8FEB">
      <CfgRow title="Aprovar pedidos sem revisão" desc="Abaixo do limite definido"><CfgToggle on={c.autoApprove} onClick={() => set('autoApprove', !c.autoApprove)} /></CfgRow>
      <CfgRow title="Limite de valor (R$)" desc="Acima disso exige aprovador" last><CfgInput value={c.autoLimit} onChange={v => set('autoLimit', v)} /></CfgRow>
    </CfgCard>
    <CfgCard icon="refresh" title="Automação de cotações">
      <CfgRow title="Reposição automática pelo giro" desc="Cria cotação quando o estoque baixa"><CfgToggle on={c.recorrente} onClick={() => set('recorrente', !c.recorrente)} /></CfgRow>
      <CfgRow title="Mover cotação parada p/ Mural" desc="Sem resposta, publica como demanda"><CfgToggle on={c.autoMural} onClick={() => set('autoMural', !c.autoMural)} /></CfgRow>
      <CfgRow title="Filtro de ruptura total" desc="Estoque zero + giro alto em destaque"><CfgToggle on={c.ruptura} onClick={() => set('ruptura', !c.ruptura)} /></CfgRow>
      <CfgRow title="Lote mínimo padrão (un.)" last><CfgInput value={c.loteMin} onChange={v => set('loteMin', v)} w={100} /></CfgRow>
    </CfgCard>
  </div>;
}

// ── SEÇÃO: Fiscal ────────────────────────────────────────────────────────
function SecFiscal({ c, set }) {
  return <CfgCard icon="receipt" title="Fiscal & impostos" desc="Base de comparação de custo" accent="#FF8A1F">
    <CfgRow title="Imposto padrão da oferta" desc="Como o rep declara por padrão"><CfgSeg value={c.impostoPadrao} onChange={v => set('impostoPadrao', v)} opts={['com','sem']} /></CfgRow>
    <CfgRow title="ICMS padrão (%)"><CfgInput value={c.icms} onChange={v => set('icms', v)} w={100} /></CfgRow>
    <CfgRow title="Considerar ST no custo real" desc="Substituição tributária embutida" last><CfgToggle on={c.st} onClick={() => set('st', !c.st)} /></CfgRow>
  </CfgCard>;
}

// ── SEÇÃO: ERP ───────────────────────────────────────────────────────────
function SecERP({ c, set }) {
  return <CfgCard icon="box" title="Integração ERP HOS" desc="24.830 produtos · sincronização de custo">
    <CfgRow title="Sincronização ativa"><CfgToggle on={c.hosSync} onClick={() => set('hosSync', !c.hosSync)} /></CfgRow>
    <CfgRow title="Endpoint da API"><CfgInput value={c.hosEndpoint} onChange={v => set('hosEndpoint', v)} w={190} left /></CfgRow>
    <CfgRow title="Frequência de sync"><CfgSeg value={c.hosFreq} onChange={v => set('hosFreq', v)} opts={['1h','6h','24h']} /></CfgRow>
    <CfgRow title="Testar conexão" desc="Verifica acesso ao HOS agora" last><button style={{ padding: '9px 16px', borderRadius: 10, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer', fontSize: 13 }}>Testar</button></CfgRow>
  </CfgCard>;
}

// ── SEÇÃO: Equipe (RBAC) — VIVA (/api/users) ─────────────────────────────
const ROLE_LABEL = { admin: 'Admin · acesso a tudo', aprovador: 'Aprovador', view: 'Visualização', rep: 'Representante' };
const ROLE_TONE = { admin: 'red', aprovador: 'yellow', view: 'mute', rep: 'green' };
function SecEquipe() {
  const [users, setUsers] = useState([]);
  const [open, setOpen] = useState(false);
  const [f, setF] = useState({ nome: '', email: '', senha: '', role: 'view' });
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);
  const load = () => { if (window.api) window.api.get('/users').then(r => setUsers(r.items || [])).catch(() => {}); };
  useEffect(load, []);
  const cadastrar = async () => {
    if (busy) return; setErr('');
    if (!f.nome || !f.email || !f.senha) { setErr('Preencha nome, e-mail e senha'); return; }
    setBusy(true);
    try {
      await window.api.post('/users', f);
      setF({ nome: '', email: '', senha: '', role: 'view' }); setOpen(false); load();
    } catch (e) { setErr(e.data && e.data.error ? e.data.error : 'Falha ao cadastrar'); }
    setBusy(false);
  };
  const toggle = async (id) => { try { await window.api.post('/users/' + id + '/toggle', {}); load(); } catch (e) {} };
  const approve = async (id) => { try { await window.api.post('/users/' + id + '/approve', {}); load(); } catch (e) {} };
  const reject = async (id) => { try { await window.api.post('/users/' + id + '/reject', {}); load(); } catch (e) {} };
  const inp = { width: '100%', boxSizing: 'border-box', padding: '10px 12px', borderRadius: 10, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 13.5, outline: 'none' };
  const pendentes = users.filter(u => !u.aprovado);
  const ativos = users.filter(u => u.aprovado);

  return <div>
    {pendentes.length > 0 && (
      <CfgCard icon="bell" title={`Aprovações pendentes (${pendentes.length})`} desc="Representantes que se cadastraram — liberar acesso" accent="#FFC83D">
        {pendentes.map((u, i) => (
          <CfgRow key={u.id} title={u.nome} desc={u.email + ' · representante'} last={i === pendentes.length - 1}>
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => approve(u.id)} style={{ padding: '7px 14px', borderRadius: 9, border: 'none', background: `linear-gradient(135deg, ${T.green}, #0AA968)`, color: '#fff', fontWeight: 800, fontFamily: 'inherit', cursor: 'pointer', fontSize: 12.5 }}>Aprovar</button>
              <button onClick={() => reject(u.id)} style={{ padding: '7px 12px', borderRadius: 9, border: `1px solid ${T.border}`, background: 'transparent', color: T.mute, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer', fontSize: 12.5 }}>Recusar</button>
            </div>
          </CfgRow>
        ))}
      </CfgCard>
    )}
    <CfgCard icon="user" title="Equipe & permissões (RBAC)" desc="Quem acessa o quê · cadastre novas pessoas" accent="#9B5DE5">
    {ativos.map((u, i) => (
      <CfgRow key={u.id} title={u.nome + (u.ativo ? '' : ' (inativo)')} desc={u.email} last={i === ativos.length - 1 && !open}>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <Pill tone={ROLE_TONE[u.role] || 'mute'}>{(ROLE_LABEL[u.role] || u.role).split(' ')[0]}</Pill>
          <button onClick={() => toggle(u.id)} title={u.ativo ? 'Desativar' : 'Ativar'} style={{ padding: '6px 11px', borderRadius: 9, border: `1px solid ${T.border}`, background: 'transparent', color: u.ativo ? T.mute : T.green, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer', fontSize: 12 }}>{u.ativo ? 'Desativar' : 'Ativar'}</button>
        </div>
      </CfgRow>
    ))}
    {open ? (
      <div style={{ marginTop: 14, padding: 16, borderRadius: 14, background: T.panel, border: `1px solid ${T.borderHi}` }}>
        <div style={{ fontWeight: 800, fontSize: 14, marginBottom: 12 }}>Cadastrar pessoa</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <input value={f.nome} onChange={e => setF({ ...f, nome: e.target.value })} placeholder="Nome" style={inp} />
          <input value={f.email} onChange={e => setF({ ...f, email: e.target.value })} placeholder="E-mail" style={inp} />
          <input type="password" value={f.senha} onChange={e => setF({ ...f, senha: e.target.value })} placeholder="Senha" style={inp} />
          <select value={f.role} onChange={e => setF({ ...f, role: e.target.value })} style={inp}>
            <option value="admin">Admin · acesso a tudo</option>
            <option value="aprovador">Aprovador</option>
            <option value="view">Visualização</option>
          </select>
        </div>
        {err && <div style={{ marginTop: 10, color: T.redBright, fontSize: 12.5, fontWeight: 600 }}>{err}</div>}
        <div style={{ display: 'flex', gap: 9, marginTop: 12 }}>
          <button onClick={() => { setOpen(false); setErr(''); }} style={{ padding: '10px 16px', borderRadius: 10, border: `1px solid ${T.border}`, background: 'transparent', color: T.mute, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer', fontSize: 13 }}>Cancelar</button>
          <button onClick={cadastrar} disabled={busy} style={{ padding: '10px 18px', borderRadius: 10, border: 'none', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, color: '#fff', fontWeight: 800, fontFamily: 'inherit', cursor: 'pointer', fontSize: 13, opacity: busy ? 0.6 : 1 }}>{busy ? 'Cadastrando…' : 'Cadastrar'}</button>
        </div>
      </div>
    ) : (
      <div style={{ marginTop: 12 }}><button onClick={() => setOpen(true)} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '9px 15px', borderRadius: 10, border: `1px dashed ${T.border}`, background: 'transparent', color: T.mute, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer', fontSize: 13 }}><Icon name="plus" size={15} color={T.mute} /> Cadastrar pessoa</button></div>
    )}
    </CfgCard>
  </div>;
}

// ── SEÇÃO: Notificações ──────────────────────────────────────────────────
function SecNotif({ c, set }) {
  return <CfgCard icon="bell" title="Notificações no sistema" desc="Avisos entregues na central interna — comprador e reps" accent="#00C277">
    <CfgRow title="Oferta abaixo do custo"><CfgToggle on={c.nOferta} onClick={() => set('nOferta', !c.nOferta)} /></CfgRow>
    <CfgRow title="Cotação encerrando"><CfgToggle on={c.nPrazo} onClick={() => set('nPrazo', !c.nPrazo)} /></CfgRow>
    <CfgRow title="Item cortado / não faturado"><CfgToggle on={c.nCorte} onClick={() => set('nCorte', !c.nCorte)} /></CfgRow>
    <CfgRow title="Divergência em XML"><CfgToggle on={c.nXml} onClick={() => set('nXml', !c.nXml)} /></CfgRow>
    <CfgRow title="Resumo diário" last><CfgToggle on={c.nResumo} onClick={() => set('nResumo', !c.nResumo)} /></CfgRow>
  </CfgCard>;
}

// ── SEÇÃO: Representantes ─────────────────────────────────────────────────
function SecReps({ c, set }) {
  return <CfgCard icon="user" title="Representantes & validade" accent="#FF8A1F">
    <CfgRow title={`Validade mínima: ${c.shelf} meses`} desc="Recusa lotes com validade menor"><CfgSlider value={c.shelf} onChange={v => set('shelf', v)} min={1} max={24} /></CfgRow>
    <CfgRow title="Fila prioritária p/ exclusivos" desc="Reps de contrato cotam primeiro"><CfgToggle on={c.exclusivo} onClick={() => set('exclusivo', !c.exclusivo)} /></CfgRow>
    <CfgRow title="Blacklist por pendência" desc="Bloqueia rep que fura prazo ou doc" last><CfgToggle on={c.blacklist} onClick={() => set('blacklist', !c.blacklist)} /></CfgRow>
  </CfgCard>;
}

// ── SEÇÃO: Dados & Backup ────────────────────────────────────────────────
function SecDados() {
  return <CfgCard icon="box" title="Dados & backup">
    <CfgRow title="Exportar base (Excel)" desc="Catálogo completo com custo"><button style={cfgBtnGhost()}>Exportar</button></CfgRow>
    <CfgRow title="Log de auditoria" desc="Toda alteração manual de preço"><button style={cfgBtnGhost()}>Ver log</button></CfgRow>
    <CfgRow title="Backup automático" desc="Diário · 30 dias de retenção" last><button style={cfgBtnGhost()}>Configurar</button></CfgRow>
  </CfgCard>;
}
const cfgBtnGhost = () => ({ padding: '9px 16px', borderRadius: 10, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer', fontSize: 13 });

window.CfgSections = { SecAparencia, SecIA, SecCotacoes, SecFiscal, SecERP, SecEquipe, SecNotif, SecReps, SecDados, CfgCard };

// ── SHELL com navegação por seções ───────────────────────────────────────
const CFG_NAV = [
  { id: 'aparencia', label: 'Aparência & Tema', icon: 'bolt' },
  { id: 'ia',        label: 'Inteligência (IA)', icon: 'shield' },
  { id: 'cotacoes',  label: 'Cotações & Aprovação', icon: 'check' },
  { id: 'fiscal',    label: 'Fiscal & Impostos', icon: 'receipt' },
  { id: 'erp',       label: 'Integração ERP HOS', icon: 'box' },
  { id: 'equipe',    label: 'Equipe & Permissões', icon: 'user' },
  { id: 'notif',     label: 'Notificações', icon: 'bell' },
  { id: 'reps',      label: 'Representantes', icon: 'user' },
  { id: 'dados',     label: 'Dados & Backup', icon: 'table' },
];

function ConfigCompleta() {
  const [c, setC] = useState(cfgLoad);
  const [sec, setSec] = useState('aparencia');
  const [saved, setSaved] = useState(false);
  const set = (k, v) => setC(s => ({ ...s, [k]: v }));
  const setSrc = (k, v) => setC(s => ({ ...s, aiSources: { ...s.aiSources, [k]: v } }));

  // aplica tema (fonte/accent) ao vivo conforme muda
  useEffect(() => { applyTheme(c); }, [c.uiFont, c.displayFont, c.accent, c.density]);

  const save = () => { try { localStorage.setItem(CFG_KEY, JSON.stringify(c)); } catch {} applyTheme(c); setSaved(true); setTimeout(() => setSaved(false), 2200); };

  return (
    <div>
      <TopbarCfg title="Configurações" sub="Personalize o sistema inteiro — tema, IA, regras, equipe e integrações"
        action={<button onClick={save} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '10px 20px', borderRadius: 11, border: 'none', cursor: 'pointer', fontWeight: 700, fontFamily: 'inherit', fontSize: 13.5, color: '#fff', background: saved ? `linear-gradient(135deg, ${T.green}, #0AA968)` : `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, boxShadow: '0 4px 14px rgba(255,19,48,0.3)' }}>
          {saved ? <><Icon name="check" size={16} color="#fff" strokeWidth={3} /> Salvo!</> : 'Salvar alterações'}</button>} />

      <div style={{ display: 'grid', gridTemplateColumns: '230px 1fr', gap: 20, alignItems: 'start' }} className="cfg-grid">
        {/* nav lateral de seções */}
        <Glass pad={8} style={{ position: 'sticky', top: 0 }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            {CFG_NAV.map(n => { const on = sec === n.id; return (
              <button key={n.id} onClick={() => setSec(n.id)} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '11px 13px', borderRadius: 10, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13.5, fontWeight: on ? 700 : 600, textAlign: 'left', width: '100%',
                background: on ? cfgA(T.red, 0.13) : 'transparent', color: on ? T.redBright : T.mute }}>
                <Icon name={n.icon} size={17} color={on ? T.redBright : T.mute} /> {n.label}
              </button>
            ); })}
          </div>
        </Glass>

        {/* conteúdo da seção */}
        <div style={{ minWidth: 0 }}>
          {sec === 'aparencia' && <SecAparencia c={c} set={set} />}
          {sec === 'ia'        && <SecIA c={c} set={set} setSrc={setSrc} />}
          {sec === 'cotacoes'  && <SecCotacoes c={c} set={set} />}
          {sec === 'fiscal'    && <SecFiscal c={c} set={set} />}
          {sec === 'erp'       && <SecERP c={c} set={set} />}
          {sec === 'equipe'    && <SecEquipe />}
          {sec === 'notif'     && <SecNotif c={c} set={set} />}
          {sec === 'reps'      && <SecReps c={c} set={set} />}
          {sec === 'dados'     && <SecDados />}
        </div>
      </div>
    </div>
  );
}

// aplica o tema salvo logo no load
try { applyTheme(cfgLoad()); } catch {}

// sobrescreve o Settings simples do buyer-7
if (window.BuyerParts7) window.BuyerParts7.Settings = ConfigCompleta;
window.BuyerConfig = { ConfigCompleta };

