// ── InovaPED — Comprador: Configurações + Conferência XML ───────────────
const Topbar7 = window.BuyerParts1.Topbar;
const ICh = window.IC;
const rep7 = window.BuyerParts1.repById, cat7 = window.BuyerParts1.catById;

// controles reutilizáveis (cascas)
function Toggle({ on, onClick }) {
  return <button onClick={onClick} style={{ width: 44, height: 26, borderRadius: 99, border: 'none', cursor: 'pointer', padding: 3, background: on ? `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})` : 'rgba(255,255,255,0.12)', display: 'flex', justifyContent: on ? 'flex-end' : 'flex-start', transition: 'all .2s' }}><span style={{ width: 20, height: 20, borderRadius: 99, background: '#fff' }} /></button>;
}
function SRow({ title, desc, children, last }) {
  return <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '14px 0', borderBottom: last ? 'none' : `1px solid ${T.border}` }}>
    <div style={{ flex: 1 }}><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 SCard({ icon, title, children }) {
  return <Glass style={{ marginBottom: 16 }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
      <div style={{ width: 32, height: 32, borderRadius: 9, background: T.redBg, display:'flex',alignItems:'center',justifyContent:'center' }}><Icon name={icon} size={17} color={T.redBright} /></div>
      <div style={{ fontWeight: 700, fontSize: 15 }}>{title}</div>
    </div>
    {children}
  </Glass>;
}
const sInput = () => ({ width: 140, 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: 'right' });
function MiniSeg({ value, onChange, opts }) {
  return <div style={{ display: 'flex', gap: 2, padding: 3, borderRadius: 9, background: T.panel, border: `1px solid ${T.border}` }}>
    {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' }}>{o}</button>; })}
  </div>;
}

function Settings() {
  const [t, setT] = useState({ autoApprove: true, prioritize: true, hosSync: true, tg1: true, tg2: true, tg3: false, rebate: true, inovaprice: false });
  const tg = (k) => setT(s => ({ ...s, [k]: !s[k] }));
  const [shelf, setShelf] = useState(6);
  const [meta, setMeta] = useState(8);
  const [freq, setFreq] = useState('1h');
  return (
    <div>
      <Topbar7 title="Configurações" sub="Regras, integrações e automações do comprador"
        action={<button style={{ padding: '10px 18px', borderRadius: 11, border: 'none', cursor: 'pointer', fontWeight: 700, fontFamily: 'inherit', fontSize: 13.5, color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})` }}>Salvar alterações</button>} />
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, alignItems: 'start' }}>
        <div>
          <SCard icon="check" title="Aprovação automática">
            <SRow title="Aprovar pedidos sem revisão" desc="Abaixo do limite definido"><Toggle on={t.autoApprove} onClick={() => tg('autoApprove')} /></SRow>
            <SRow title="Limite de valor (R$)" desc="Acima disso exige revisão humana" last><input defaultValue="5.000,00" style={sInput()} /></SRow>
          </SCard>
          <SCard icon="shield" title="Política de validade (shelf-life)">
            <SRow title={`Validade mínima: ${shelf} meses`} desc="Recusa lotes com validade menor" last>
              <input type="range" min="1" max="24" value={shelf} onChange={e => setShelf(+e.target.value)} style={{ width: 160, accentColor: T.red }} />
            </SRow>
          </SCard>
          <SCard icon="trophy" title="Metas e fornecedores">
            <SRow title={`Meta de economia: ${meta}%`} desc="Redução de custo mensal"><input type="range" min="0" max="25" value={meta} onChange={e => setMeta(+e.target.value)} style={{ width: 130, accentColor: T.red }} /></SRow>
            <SRow title="Priorizar melhores entregadores" desc="Peso extra p/ histórico de prazo"><Toggle on={t.prioritize} onClick={() => tg('prioritize')} /></SRow>
            <SRow title="Considerar rebate/bonificação" desc="Inclui cashback na análise" last><Toggle on={t.rebate} onClick={() => tg('rebate')} /></SRow>
          </SCard>
          <SCard icon="box" title="Integração ERP HOS">
            <SRow title="Sincronização ativa" desc="25.000 produtos · último custo"><Toggle on={t.hosSync} onClick={() => tg('hosSync')} /></SRow>
            <SRow title="Endpoint" desc="API do HOS"><input defaultValue="api.hos.local/v2" style={{ ...sInput(), width: 170, textAlign: 'left' }} /></SRow>
            <SRow title="Frequência de sync" last><MiniSeg value={freq} onChange={setFreq} opts={['1h','6h','24h']} /></SRow>
          </SCard>
        </div>
        <div>
          <SCard icon="bell" title="Notificações no sistema">
            <SRow title="Oferta abaixo do custo"><Toggle on={t.tg1} onClick={() => tg('tg1')} /></SRow>
            <SRow title="Cotação encerrando"><Toggle on={t.tg2} onClick={() => tg('tg2')} /></SRow>
            <SRow title="Resumo diário" last><Toggle on={t.tg3} onClick={() => tg('tg3')} /></SRow>
          </SCard>
          <SCard icon="receipt" title="Fiscal & impostos">
            <SRow title="ICMS padrão (%)"><input defaultValue="18,00" style={sInput()} /></SRow>
            <SRow title="Considerar ST no custo real" last><Toggle on={true} onClick={() => {}} /></SRow>
          </SCard>
          <SCard icon="chart" title="InovaPrice (concorrência)">
            <SRow title="Comparar com sites concorrentes"><Toggle on={t.inovaprice} onClick={() => tg('inovaprice')} /></SRow>
            <SRow title="Alerta de cobertura de preço" desc="Avisa rep p/ cobrir menor preço" last><Toggle on={false} onClick={() => {}} /></SRow>
          </SCard>
          <SCard icon="user" title="Acessos da equipe (RBAC)">
            {[['Felipe Costa','Comprador · admin'],['Deivid Rocha','Aprovador'],['Carlos Nunes','Visualização']].map(([n, role], i, arr) => (
              <SRow key={n} title={n} desc={role} last={i === arr.length - 1}><Pill tone="mute">{role.split(' ')[0]}</Pill></SRow>
            ))}
          </SCard>
          <SCard icon="x" title="Blacklist de fornecedores">
            <SRow title="Bloquear reps que furam prazo" desc="Removidos das cotações" last><Toggle on={false} onClick={() => {}} /></SRow>
          </SCard>
        </div>
      </div>
    </div>
  );
}

// ═══ CONFERÊNCIA XML (divergências) ══════════════════════════════════════
function XMLConf() {
  const [open, setOpen] = useState('xml1');
  const tone = { ok: 'green', divergente: 'red', cnpj: 'yellow' };
  const label = { ok: 'Conferido', divergente: 'Preço divergente', cnpj: 'CNPJ não confere' };
  const divCount = ICh.XMLDOCS.filter(x => x.status !== 'ok').length;
  return (
    <div>
      <Topbar7 title="Conferência XML" sub="Notas subidas pelos reps validadas contra o preço negociado"
        action={<Pill tone="red"><Icon name="bell" size={12} color={T.redBright} /> {divCount} divergência(s)</Pill>} />
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 16px', borderRadius: 12, background: 'rgba(255,200,61,0.08)', border: '1px solid rgba(255,200,61,0.28)', marginBottom: 16 }}>
        <Icon name="shield" size={18} color="#FFC83D" /><span style={{ fontSize: 13, color: '#E8D9A8' }}>O InovaParser extrai <b style={{color:'#FFC83D'}}>lote e validade</b> do XML e bloqueia entrada se o preço for maior que o negociado ou a validade abaixo da política. <span style={{ color: T.mute2 }}>(parser real no Claude Code)</span></span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {ICh.XMLDOCS.map(x => {
          const r = rep7(x.rep), c = cat7(x.cat), isOpen = open === x.id;
          return (
            <Glass key={x.id} pad={0} style={{ overflow: 'hidden' }}>
              <div onClick={() => setOpen(isOpen ? null : x.id)} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 18, cursor: 'pointer' }}>
                <div style={{ width: 42, height: 42, borderRadius: 11, background: T.panelHi, display:'flex',alignItems:'center',justifyContent:'center' }}><Icon name="receipt" size={21} color={T.mute} /></div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 700, fontSize: 15 }}>{x.nf} <span style={{ color: T.mute2, fontWeight: 500, fontSize: 13 }}>· {x.items.length} itens</span></div>
                  <div style={{ fontSize: 12.5, color: T.mute, marginTop: 2, display:'flex',alignItems:'center',gap:8 }}><span style={{ display:'inline-flex',alignItems:'center',gap:5 }}><span style={{ width: 18, height: 18, borderRadius: 99, background: r.color, display:'flex',alignItems:'center',justifyContent:'center', fontSize: 9, fontWeight: 800, color:'#fff' }}>{r.name[0]}</span>{r.name}</span> · {c.name} · {x.uploaded}</div>
                </div>
                {!x.cnpjOk && <Pill tone="yellow"><Icon name="shield" size={11} color={T.yellow} /> CNPJ</Pill>}
                <Pill tone={tone[x.status]}>{label[x.status]}</Pill>
                <Icon name="chevron" size={16} color={T.mute2} style={{ transform: isOpen ? 'rotate(90deg)' : 'none', transition: 'transform .2s' }} />
              </div>
              {isOpen && (
                <div style={{ borderTop: `1px solid ${T.border}`, padding: '4px 0' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                    <thead><tr><th style={xth('left')}>Produto</th><th style={xth('right')}>Negociado</th><th style={xth('right')}>No XML</th><th style={xth('left')}>Lote</th><th style={xth('left')}>Validade</th><th style={xth('center')}>Situação</th></tr></thead>
                    <tbody>
                      {x.items.map((it, i) => { const div = it.xml > it.neg; const shortVal = /2026/.test(it.val); return (
                        <tr key={i} style={{ borderTop: `1px solid ${T.border}`, background: div ? 'rgba(255,19,48,0.05)' : 'transparent' }}>
                          <td style={xtd('left')}>{it.name}</td>
                          <td style={{ ...xtd('right'), color: T.mute, fontVariantNumeric: 'tabular-nums' }}>R$ {ICh.fmt(it.neg)}</td>
                          <td style={{ ...xtd('right'), fontWeight: 700, color: div ? T.redBright : T.green, fontVariantNumeric: 'tabular-nums' }}>R$ {ICh.fmt(it.xml)}</td>
                          <td style={{ ...xtd('left'), color: T.mute, fontVariantNumeric: 'tabular-nums' }}>{it.lote}</td>
                          <td style={xtd('left')}><span style={{ color: shortVal ? T.yellow : T.text }}>{it.val}{shortVal && ' ⚠'}</span></td>
                          <td style={xtd('center')}>{div ? <Pill tone="red">+R$ {ICh.fmt(it.xml - it.neg)}</Pill> : <Pill tone="green"><Icon name="check" size={11} color={T.green} strokeWidth={3} /> ok</Pill>}</td>
                        </tr>
                      ); })}
                    </tbody>
                  </table>
                  <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, padding: 16 }}>
                    <button style={{ padding: '10px 18px', borderRadius: 11, border: `1px solid ${T.border}`, background: 'transparent', color: T.redBright, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer', fontSize: 13.5 }}>Rejeitar entrada</button>
                    <button style={{ padding: '10px 18px', borderRadius: 11, border: 'none', background: x.status === 'ok' ? `linear-gradient(135deg, ${T.green}, #0AA968)` : T.panelHi, color: x.status === 'ok' ? '#04130C' : T.mute, fontWeight: 800, fontFamily: 'inherit', cursor: 'pointer', fontSize: 13.5, display:'flex',alignItems:'center',gap:7 }}><Icon name="box" size={16} color={x.status === 'ok' ? '#04130C' : T.mute} /> Importar p/ HOS</button>
                  </div>
                </div>
              )}
            </Glass>
          );
        })}
      </div>
    </div>
  );
}
const xth = (a) => ({ textAlign: a, padding: '12px 16px', fontSize: 11, fontWeight: 700, color: T.mute, textTransform: 'uppercase', letterSpacing: 0.4 });
const xtd = (a) => ({ textAlign: a, padding: '11px 16px' });

window.BuyerParts7 = { Settings, XMLConf };
