// ═══════════════════════════════════════════════════════════════════
// Screen: Painel de Regras (a tela-chave) — 5 abas editáveis
// ═══════════════════════════════════════════════════════════════════

function PainelRegras({ state, setState }) {
  const { regras, vendedores, historico } = state;
  const [aba, setAba] = useState('variavel');
  const [editado, setEditado] = useState({});
  const [saveModal, setSaveModal] = useState(false);
  const [novaRegraModal, setNovaRegraModal] = useState(false);
  const [novaRegraForm, setNovaRegraForm] = useState({ label: '', valor: '', gatilho: '', recebe: '' });

  const abas = [
    { id: 'variavel',   label: 'Comissão variável', hint: 'Valores por gatilho' },
    { id: 'fixa',       label: 'Comissão fixa',     hint: '% sobre projeto' },
    { id: 'setor',      label: 'Taxas por setor',   hint: 'Pesos PMO/P&D/NNE/Mkt' },
    { id: 'rateio',     label: 'Rateio por salário', hint: 'Fórmula Sal / S' },
    { id: 'vendedores', label: 'Vendedores',        hint: 'Cadastro + salários' },
  ];

  const registrarEdicao = (key, valor) => setEditado({ ...editado, [key]: valor });
  const temEdicao = Object.keys(editado).length > 0;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
      <div>
        <Eyebrow idx="02">Painel de Regras</Eyebrow>
        <h1 style={{ fontSize: 44, margin: 0, letterSpacing: '-.02em', lineHeight: 1.05, maxWidth: 740 }}>
          Edite as regras <em style={{ fontStyle: 'normal', color: 'var(--escalab-brand)' }}>sem escrever código</em>.
        </h1>
        <p style={{ marginTop: 14, color: 'var(--escalab-slate)', fontSize: 16, maxWidth: 640 }}>
          Cada valor abaixo é um dado no banco, não uma linha de código. Ao salvar, você decide se a mudança vale a partir do próximo trimestre ou retroage — trimestres fechados ficam protegidos por padrão.
        </p>
      </div>

      {/* Aba strip */}
      <div style={{ display: 'flex', borderBottom: '1px solid var(--escalab-line)', gap: 4, overflowX: 'auto' }}>
        {abas.map(a => (
          <button key={a.id} onClick={() => setAba(a.id)}
            style={{ border: 0, background: 'transparent', padding: '14px 18px 16px', cursor: 'pointer', position: 'relative', fontFamily: 'inherit', textAlign: 'left', whiteSpace: 'nowrap',
              borderBottom: aba === a.id ? '2px solid var(--escalab-brand)' : '2px solid transparent',
              color: aba === a.id ? 'var(--escalab-ink)' : 'var(--escalab-slate)' }}>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 2 }}>{a.label}</div>
            <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)', fontWeight: 400 }}>{a.hint}</div>
          </button>
        ))}
      </div>

      {/* Content */}
      {aba === 'variavel' && (
        <div>
          <Card pad={0}>
            <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--escalab-line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <h3 style={{ margin: 0, fontSize: 16 }}>Comissão variável por origem</h3>
                <p style={{ margin: '4px 0 0', fontSize: 13, color: 'var(--escalab-slate)' }}>Valores pagos por gatilho — reunião, proposta, NPS. Agrupados por origem do lead.</p>
              </div>
              <Button variant="outline" size="sm" icon="plus" onClick={() => setNovaRegraModal(true)}>Nova regra</Button>
            </div>
            <div>
              {Object.entries(regras.variavel).map(([k, r], i) => (
                <div key={k} style={{ display: 'grid', gridTemplateColumns: '1.8fr 1.1fr 140px 120px', gap: 16, padding: '16px 24px', alignItems: 'center', borderBottom: i < Object.keys(regras.variavel).length - 1 ? '1px solid var(--escalab-line)' : 'none' }}>
                  <div>
                    <div style={{ fontSize: 14, fontWeight: 600 }}>{r.label}</div>
                    <div style={{ fontSize: 12, color: 'var(--escalab-mute)', marginTop: 2 }}>{r.gatilho}</div>
                  </div>
                  <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                    <Tag tone="brand">{r.recebe}</Tag>
                  </div>
                  <Input value={editado[k] ?? r.valor} onChange={v => registrarEdicao(k, v)} prefix="R$" />
                  <div style={{ display: 'flex', gap: 6 }}>
                    <Button variant="ghost" size="sm" icon="history">Hist.</Button>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </div>
      )}

      {aba === 'fixa' && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          <Card>
            <h3 style={{ margin: '0 0 4px', fontSize: 16 }}>Percentual sobre projeto vendido</h3>
            <p style={{ fontSize: 13, color: 'var(--escalab-slate)', margin: '0 0 18px' }}>Escala conforme markup apurado na venda.</p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {['markup_baixo', 'markup_medio', 'markup_alto'].map(k => {
                const r = regras.fixa[k];
                return (
                  <div key={k} style={{ display: 'grid', gridTemplateColumns: '1fr 130px', gap: 12, alignItems: 'center' }}>
                    <div style={{ fontSize: 14, fontWeight: 500 }}>{r.label}</div>
                    <Input value={r.valor} suffix="%" />
                  </div>
                );
              })}
            </div>
          </Card>
          <Card>
            <h3 style={{ margin: '0 0 4px', fontSize: 16 }}>Percentual sobre editais</h3>
            <p style={{ fontSize: 13, color: 'var(--escalab-slate)', margin: '0 0 18px' }}>Faixas de markup para projetos de editais.</p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {['edital_baixo', 'edital_medio', 'edital_alto'].filter(k => regras.fixa[k]).map(k => {
                const r = regras.fixa[k];
                return (
                  <div key={k} style={{ display: 'grid', gridTemplateColumns: '1fr 130px', gap: 12, alignItems: 'center' }}>
                    <div style={{ fontSize: 14, fontWeight: 500 }}>{r.label}</div>
                    <Input value={editado[k] ?? r.valor} onChange={v => registrarEdicao(k, v)} suffix="%" />
                  </div>
                );
              })}
            </div>
          </Card>
        </div>
      )}

      {aba === 'setor' && (
        <Card pad={0}>
          <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--escalab-line)' }}>
            <h3 style={{ margin: 0, fontSize: 16 }}>Pesos de distribuição entre setores</h3>
            <p style={{ margin: '4px 0 0', fontSize: 13, color: 'var(--escalab-slate)' }}>Fração do total da comissão fixa que vai para cada setor. Soma dos pesos = 8,5.</p>
          </div>
          <div style={{ padding: 24, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
            {Object.entries(regras.taxasSetor).map(([k, s]) => {
              const pct = (s.numerador / s.denominador) * 100;
              return (
                <div key={k} style={{ background: 'var(--escalab-paper)', border: '1px solid var(--escalab-line)', borderRadius: 10, padding: 18 }}>
                  <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--escalab-mute)' }}>{s.label}</div>
                  <div style={{ fontSize: 30, fontWeight: 700, letterSpacing: '-.02em', margin: '8px 0', color: 'var(--escalab-brand-deep)' }}>
                    {s.numerador.toString().replace('.', ',')}<span style={{ fontSize: 16, color: 'var(--escalab-mute)', fontWeight: 500 }}> / {s.denominador.toString().replace('.', ',')}</span>
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--escalab-slate)', marginBottom: 10 }}>≈ {pct.toFixed(1).replace('.', ',')}% do total</div>
                  <Progress value={pct} max={100} />
                </div>
              );
            })}
          </div>
          <div style={{ padding: '14px 24px', background: 'var(--escalab-brand-tint)', borderTop: '1px solid var(--escalab-brand-soft)', fontSize: 13, color: 'var(--escalab-brand-deep)' }}>
            <strong>Fórmula:</strong> Comissão<sub>setor</sub> = V × T · onde V é o valor da venda e T é o peso do setor. O total do setor é então rateado entre as pessoas por salário.
          </div>
        </Card>
      )}

      {aba === 'rateio' && (
        <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 16 }}>
          <Card>
            <h3 style={{ margin: '0 0 4px', fontSize: 16 }}>Fórmula de rateio por salário</h3>
            <p style={{ fontSize: 13, color: 'var(--escalab-slate)', margin: '0 0 18px' }}>Quando mais de um vendedor atua no mesmo papel, o valor é dividido proporcionalmente.</p>
            <div style={{ background: 'var(--escalab-ink)', color: '#fff', padding: '24px 26px', borderRadius: 10, fontFamily: 'var(--font-serif)', fontSize: 24, letterSpacing: '-.01em', lineHeight: 1.3 }}>
              Comissão<sub style={{ fontSize: 14 }}>vendedor</sub> = Valor<sub style={{ fontSize: 14 }}>base</sub> × <span style={{ color: 'var(--escalab-brand-accent)' }}>(Sal<sub style={{ fontSize: 14 }}>X</sub> / S)</span>
            </div>
            <p style={{ fontSize: 13, color: 'var(--escalab-slate)', marginTop: 16, marginBottom: 0 }}>
              <strong>Sal<sub>X</sub></strong> = salário do vendedor · <strong>S</strong> = soma dos salários no mesmo papel no mesmo lead.
            </p>
          </Card>
          <Card>
            <h3 style={{ margin: '0 0 12px', fontSize: 16 }}>Exemplo vivo</h3>
            <p style={{ fontSize: 13, color: 'var(--escalab-slate)', marginBottom: 16 }}>Dois qualificadores em uma reunião (R$ 250):</p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 14px', background: 'var(--escalab-paper)', borderRadius: 8 }}>
                <span style={{ fontSize: 13.5 }}>Ingrid · sal. R$ 5.000</span>
                <span style={{ fontWeight: 700, color: 'var(--escalab-brand-deep)' }}>{brlCents(156.25)}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 14px', background: 'var(--escalab-paper)', borderRadius: 8 }}>
                <span style={{ fontSize: 13.5 }}>Rafa · sal. R$ 3.000</span>
                <span style={{ fontWeight: 700, color: 'var(--escalab-brand-deep)' }}>{brlCents(93.75)}</span>
              </div>
            </div>
            <Banner tone="info" icon="info" >
              250 × (5/8) = 156,25 e 250 × (3/8) = 93,75. A soma sempre fecha no valor base.
            </Banner>
          </Card>
        </div>
      )}

      {aba === 'vendedores' && (
        <Card pad={0}>
          <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--escalab-line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div>
              <h3 style={{ margin: 0, fontSize: 16 }}>Cadastro de vendedores</h3>
              <p style={{ margin: '4px 0 0', fontSize: 13, color: 'var(--escalab-slate)' }}>Base para o rateio por salário. Papéis são atribuídos por lead, não fixos aqui.</p>
            </div>
            <Button variant="primary" size="sm" icon="plus" onClick={() => setState.abrirNovoVendedor?.()}>Adicionar vendedor</Button>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ fontSize: 11, fontWeight: 600, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--escalab-mute)' }}>
                <th style={{ textAlign: 'left', padding: '12px 24px' }}>Pessoa</th>
                <th style={{ textAlign: 'left', padding: '12px 16px' }}>Setor primário</th>
                <th style={{ textAlign: 'right', padding: '12px 16px' }}>Salário</th>
                <th style={{ textAlign: 'center', padding: '12px 16px' }}>Status</th>
                <th style={{ width: 60 }}></th>
              </tr>
            </thead>
            <tbody>
              {vendedores.filter(v => v.papel !== 'Diretora').map(v => (
                <tr key={v.id} style={{ borderTop: '1px solid var(--escalab-line)' }}>
                  <td style={{ padding: '12px 24px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                      <Avatar v={v} size={32} />
                      <div>
                        <div style={{ fontSize: 14, fontWeight: 600 }}>{v.nome}</div>
                        <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)' }}>{v.papel}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{ padding: '12px 16px' }}><Tag tone="outline">{v.setor}</Tag></td>
                  <td style={{ padding: '12px 16px', textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontWeight: 600 }}>{brl(v.salario)}</td>
                  <td style={{ padding: '12px 16px', textAlign: 'center' }}>{v.ativo ? <Tag tone="success">Ativo</Tag> : <Tag tone="neutral">Inativo</Tag>}</td>
                  <td style={{ padding: '12px 16px' }}><Button variant="ghost" size="sm" icon="edit" onClick={() => setState.abrirVendedor?.(v)}></Button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}

      {/* Save bar (sticky) */}
      {temEdicao && (
        <div style={{ position: 'sticky', bottom: 20, zIndex: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'var(--escalab-ink)', color: '#fff', padding: '14px 20px', borderRadius: 12, boxShadow: 'var(--shadow-lg)' }}>
          <div style={{ fontSize: 13.5 }}>
            <strong>{Object.keys(editado).length} alteração(ões) pendente(s).</strong> &nbsp;Ao salvar, você escolhe se vale a partir do próximo trimestre.
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <Button variant="ghost" onClick={() => setEditado({})} style={{ color: 'rgba(255,255,255,.8)', border: '1px solid rgba(255,255,255,.2)' }}>Descartar</Button>
            <Button variant="primary" icon="check" onClick={() => setSaveModal(true)}>Salvar alterações</Button>
          </div>
        </div>
      )}

      <Modal open={novaRegraModal} onClose={() => setNovaRegraModal(false)} title="Nova regra variável" width={520}
        footer={<>
          <Button variant="outline" onClick={() => setNovaRegraModal(false)}>Cancelar</Button>
          <Button variant="primary" icon="check" onClick={() => {
            if (!novaRegraForm.label || !novaRegraForm.valor) { alert('Preencha pelo menos o nome e o valor.'); return; }
            const key = 'regra_' + Date.now();
            setState.setRegras({
              ...regras,
              variavel: { ...regras.variavel, [key]: { label: novaRegraForm.label, valor: +novaRegraForm.valor || 0, unidade: 'R$', origem: 'todos', gatilho: novaRegraForm.gatilho, recebe: novaRegraForm.recebe } }
            });
            setNovaRegraModal(false);
            setNovaRegraForm({ label: '', valor: '', gatilho: '', recebe: '' });
          }}>Adicionar regra</Button>
        </>}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Field label="Nome da regra"><Input value={novaRegraForm.label} onChange={v => setNovaRegraForm(f => ({...f, label: v}))} placeholder="Ex: Publicação de case" /></Field>
          <Field label="Valor (R$)"><Input value={novaRegraForm.valor} onChange={v => setNovaRegraForm(f => ({...f, valor: v}))} type="number" prefix="R$" placeholder="0" /></Field>
          <Field label="Gatilho / condição"><Input value={novaRegraForm.gatilho} onChange={v => setNovaRegraForm(f => ({...f, gatilho: v}))} placeholder="Ex: Quando o cliente autoriza publicação" /></Field>
          <Field label="Quem recebe"><Input value={novaRegraForm.recebe} onChange={v => setNovaRegraForm(f => ({...f, recebe: v}))} placeholder="Ex: Responsável pelo pós-venda" /></Field>
        </div>
      </Modal>

      <Modal open={saveModal} onClose={() => setSaveModal(false)} title="Como esta mudança se aplica?"
        footer={<>
          <Button variant="outline" onClick={() => setSaveModal(false)}>Cancelar</Button>
          <Button variant="primary" onClick={() => { setEditado({}); setSaveModal(false); }}>Confirmar e salvar</Button>
        </>}
      >
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <Banner tone="info" icon="info">Trimestres já fechados <strong>não</strong> são recalculados por padrão.</Banner>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {[
              { id: 'proximo', label: 'A partir do próximo trimestre (2T/2026)', desc: 'Recomendado. Preserva o histórico do trimestre atual.' },
              { id: 'atual', label: 'A partir de hoje no trimestre atual', desc: 'Cálculos futuros do 1T usam o novo valor; passados ficam como estão.' },
              { id: 'retro', label: 'Retroagir no trimestre atual', desc: 'Refaz todos os cálculos do 1T desde o início.' },
            ].map((opt, i) => (
              <label key={opt.id} style={{ display: 'flex', gap: 12, padding: 14, border: '1px solid var(--escalab-line)', borderRadius: 10, cursor: 'pointer' }}>
                <input type="radio" name="vigencia" defaultChecked={i === 0} style={{ marginTop: 3 }} />
                <div>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>{opt.label}</div>
                  <div style={{ fontSize: 12.5, color: 'var(--escalab-slate)', marginTop: 2 }}>{opt.desc}</div>
                </div>
              </label>
            ))}
          </div>
          <Field label="Observação para o histórico">
            <Input placeholder="Ex: reajuste anual aprovado em diretoria" />
          </Field>
        </div>
      </Modal>
    </div>
  );
}

Object.assign(window, { PainelRegras });
