// ═══════════════════════════════════════════════════════════════════
// Screens: Histórico de alterações + Trimestres anteriores + Fechar
// ═══════════════════════════════════════════════════════════════════

const origemLabel = { ativa:'Ativa', parceiros:'Parceiros', hunter:'Hunter', fidelizacao:'Fidelização', eventos:'Eventos', marketing:'Mkt de conteúdo', site:'Site' };
const origemCor   = { ativa:'brand', hunter:'warn', fidelizacao:'success', eventos:'neutral', marketing:'neutral', site:'neutral' };

function HistoricoScreen({ state }) {
  const { historico, historicoPeriodos = [], vendedores, leads, regras, trimestre } = state;
  const [aba, setAba] = React.useState('trimestres');
  const [mostrarLeads, setMostrarLeads] = React.useState({});

  const porVendedorAtual = useMemo(() => calcularComissoes(leads, regras, vendedores), [leads, regras, vendedores]);
  const periodoAtual = {
    id: 'atual',
    label: trimestre,
    periodo: trimestre,
    fechado: false,
    totalFaturado: leads.filter(l => l.vendido && l.comissiona).reduce((s,l) => s + l.valor, 0),
    totalVariavel: Object.values(porVendedorAtual).reduce((s,v) => s + v.variavel + v.evento, 0),
    totalFixa:     Object.values(porVendedorAtual).reduce((s,v) => s + v.fixaSetor, 0),
    totalGeral:    Object.values(porVendedorAtual).reduce((s,v) => s + v.total, 0),
    porVendedor:   vendedores.filter(v => v.ativo && (porVendedorAtual[v.id]?.total || 0) > 0).map(v => ({
      id: v.id, nome: v.nome,
      fixa:     porVendedorAtual[v.id]?.fixaSetor || 0,
      variavel: (porVendedorAtual[v.id]?.variavel || 0) + (porVendedorAtual[v.id]?.evento || 0),
      total:    porVendedorAtual[v.id]?.total || 0,
    })),
    leads,
  };
  const todosPeriodos = [periodoAtual, ...historicoPeriodos];

  const [periodoAberto, setPeriodoAberto] = React.useState('atual');

  const toggleLeads = (pid) => setMostrarLeads(s => ({ ...s, [pid]: !s[pid] }));

  const totalHistorico = todosPeriodos.reduce((s, p) => ({
    geral: s.geral + p.totalGeral,
    fixa: s.fixa + p.totalFixa,
    variavel: s.variavel + p.totalVariavel,
  }), { geral: 0, fixa: 0, variavel: 0 });

  const maioresComissoes = (() => {
    const mapa = {};
    todosPeriodos.forEach(p => {
      (p.porVendedor || []).forEach(v => {
        if (!mapa[v.nome]) mapa[v.nome] = { nome: v.nome, id: v.id, total: 0, melhorPeriodo: null, melhorValor: 0 };
        mapa[v.nome].total += v.total;
        if (v.total > mapa[v.nome].melhorValor) {
          mapa[v.nome].melhorValor = v.total;
          mapa[v.nome].melhorPeriodo = p.label;
        }
      });
    });
    return Object.values(mapa).sort((a, b) => b.total - a.total);
  })();

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
      <div>
        <Eyebrow idx="04">Histórico</Eyebrow>
        <h1 style={{ fontSize: 44, margin: 0, letterSpacing: '-.02em', lineHeight: 1.05 }}>
          Memória do <em style={{ fontStyle: 'normal', color: 'var(--escalab-brand)' }}>time</em>.
        </h1>
        <p style={{ marginTop: 14, color: 'var(--escalab-slate)', fontSize: 16, maxWidth: 640 }}>
          Registros de todas as regras alteradas e o histórico completo de períodos fechados.
        </p>
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 4, background: 'var(--escalab-paper)', border: '1px solid var(--escalab-line)', borderRadius: 10, padding: 4, width: 'fit-content' }}>
        {[
          { id: 'trimestres', label: 'Todos os períodos' },
          { id: 'regras',     label: 'Alterações de regras' },
        ].map(t => (
          <button key={t.id} onClick={() => setAba(t.id)}
            style={{ padding: '8px 18px', border: 0, borderRadius: 7, fontFamily: 'inherit', fontSize: 13.5, fontWeight: 500, cursor: 'pointer', transition: 'all .15s',
              background: aba === t.id ? '#fff' : 'transparent',
              color: aba === t.id ? 'var(--escalab-ink)' : 'var(--escalab-slate)',
              boxShadow: aba === t.id ? '0 1px 4px rgba(0,0,0,.10)' : 'none' }}>
            {t.label}
          </button>
        ))}
      </div>

      {/* ── ABA: TRIMESTRES ANTERIORES ─────────────────────── */}
      {aba === 'trimestres' && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>

          {/* Cards resumo global */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
            <Stat label="Total distribuído (todos os períodos)" value={brl(totalHistorico.geral)} tone="dark" sublabel={`${historicoPeriodos.length} período(s) fechado(s) + atual`} />
            <Stat label="Total comissão variável" value={brl(totalHistorico.variavel)} tone="light" sublabel="Soma de todos os períodos" />
            <Stat label="Total comissão fixa" value={brl(totalHistorico.fixa)} tone="light" sublabel="Soma de todos os períodos" />
          </div>

          {/* Ranking histórico */}
          {maioresComissoes.length > 0 && (
            <Card pad={0}>
              <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--escalab-line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <h3 style={{ margin: 0, fontSize: 16 }}>Ranking acumulado — todos os períodos</h3>
                <span style={{ fontSize: 12, color: 'var(--escalab-mute)' }}>{maioresComissoes.length} pessoas</span>
              </div>
              <div style={{ padding: '6px 0' }}>
                {maioresComissoes.map((v, i) => {
                  const vend = vendedores.find(x => x.id === v.id);
                  return (
                    <div key={v.nome} style={{ display: 'grid', gridTemplateColumns: '32px 36px 1fr 160px 160px', gap: 12, padding: '10px 24px', borderBottom: i < maioresComissoes.length - 1 ? '1px solid var(--escalab-line)' : 'none', alignItems: 'center' }}>
                      <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--escalab-mute)' }}>{String(i + 1).padStart(2, '0')}</span>
                      {vend ? <Avatar v={vend} size={32} /> : <div style={{ width: 32, height: 32, borderRadius: '50%', background: 'var(--escalab-line)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700 }}>{v.nome.slice(0,2)}</div>}
                      <div>
                        <div style={{ fontSize: 13.5, fontWeight: 600 }}>{v.nome}</div>
                        <div style={{ fontSize: 11.5, color: 'var(--escalab-mute)' }}>Melhor período: {v.melhorPeriodo} · {brl(v.melhorValor)}</div>
                      </div>
                      <div style={{ textAlign: 'right' }}>
                        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--escalab-brand-deep)' }}>{brl(v.total)}</div>
                        <div style={{ fontSize: 11, color: 'var(--escalab-mute)' }}>total acumulado</div>
                      </div>
                      <div style={{ height: 6, background: 'var(--escalab-line)', borderRadius: 3, overflow: 'hidden' }}>
                        <div style={{ height: '100%', borderRadius: 3, background: 'var(--escalab-brand)', width: pct(v.total / (maioresComissoes[0]?.total || 1)) }} />
                      </div>
                    </div>
                  );
                })}
              </div>
            </Card>
          )}

          {/* Períodos fechados */}
          {todosPeriodos.map(periodo => {
            const aberto = periodoAberto === periodo.id;
            return (
              <Card key={periodo.id} pad={0}>
                {/* Header do período */}
                <button onClick={() => setPeriodoAberto(aberto ? null : periodo.id)}
                  style={{ width: '100%', display: 'grid', gridTemplateColumns: '1fr auto auto auto auto', gap: 24, padding: '20px 24px', border: 0, background: 'transparent', cursor: 'pointer', alignItems: 'center', borderBottom: aberto ? '1px solid var(--escalab-line)' : 'none', textAlign: 'left' }}>
                  <div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <Tag tone="brand">{periodo.label}</Tag>
                      {periodo.fechado
                        ? <Tag tone="neutral"><Icon name="lock" size={11} /> Fechado</Tag>
                        : <Tag tone="success">Em curso</Tag>}
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--escalab-mute)', marginTop: 4 }}>
                      {(periodo.leads || []).length} leads · {(periodo.porVendedor || []).length} comissionados
                    </div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: 13, color: 'var(--escalab-mute)' }}>Faturado</div>
                    <div style={{ fontSize: 16, fontWeight: 700 }}>{brl(periodo.totalFaturado)}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: 13, color: 'var(--escalab-mute)' }}>Variável</div>
                    <div style={{ fontSize: 16, fontWeight: 700 }}>{brl(periodo.totalVariavel)}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: 13, color: 'var(--escalab-mute)' }}>Fixa</div>
                    <div style={{ fontSize: 16, fontWeight: 700 }}>{brl(periodo.totalFixa)}</div>
                  </div>
                  <div style={{ textAlign: 'right', minWidth: 120 }}>
                    <div style={{ fontSize: 13, color: 'var(--escalab-mute)' }}>Total distribuído</div>
                    <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--escalab-brand-deep)' }}>{brl(periodo.totalGeral)}</div>
                  </div>
                </button>

                {aberto && (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
                    {/* Por vendedor */}
                    <div style={{ padding: '16px 24px', borderBottom: '1px solid var(--escalab-line)' }}>
                      <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--escalab-slate)', marginBottom: 12 }}>Comissão por pessoa</div>
                      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 10 }}>
                        {(periodo.porVendedor || []).sort((a, b) => b.total - a.total).map(v => {
                          const vend = vendedores.find(x => x.id === v.id);
                          return (
                            <div key={v.nome} style={{ display: 'flex', gap: 10, alignItems: 'center', padding: '10px 14px', background: 'var(--escalab-paper)', borderRadius: 8, border: '1px solid var(--escalab-line)' }}>
                              {vend ? <Avatar v={vend} size={28} /> : <div style={{ width: 28, height: 28, borderRadius: '50%', background: '#ddd', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700, flexShrink: 0 }}>{v.nome.slice(0,2)}</div>}
                              <div style={{ flex: 1, minWidth: 0 }}>
                                <div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{v.nome}</div>
                                <div style={{ fontSize: 11, color: 'var(--escalab-mute)' }}>Fix. {brl(v.fixa)} · Var. {brl(v.variavel)}</div>
                              </div>
                              <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--escalab-brand-deep)', flexShrink: 0 }}>{brl(v.total)}</div>
                            </div>
                          );
                        })}
                      </div>
                    </div>

                    {/* Leads do período */}
                    <div style={{ padding: '12px 24px' }}>
                      <button onClick={() => toggleLeads(periodo.id)}
                        style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'transparent', border: 0, cursor: 'pointer', fontSize: 13, fontWeight: 600, color: 'var(--escalab-slate)', padding: '4px 0', marginBottom: mostrarLeads[periodo.id] ? 12 : 0 }}>
                        <Chev open={!!mostrarLeads[periodo.id]} />
                        {mostrarLeads[periodo.id] ? 'Ocultar' : 'Ver'} {(periodo.leads || []).length} leads
                      </button>
                      {mostrarLeads[periodo.id] && (
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
                          <div style={{ display: 'grid', gridTemplateColumns: '1fr 120px 90px 90px 1fr', gap: 10, padding: '8px 0', borderBottom: '1px solid var(--escalab-line)', fontSize: 11, fontWeight: 600, color: 'var(--escalab-mute)', textTransform: 'uppercase', letterSpacing: '.06em' }}>
                            <span>Lead</span><span>Origem</span><span>Qualif.</span><span>Proposta</span><span>Comissionados</span>
                          </div>
                          {(periodo.leads || []).map(l => (
                            <div key={l.id} style={{ display: 'grid', gridTemplateColumns: '1fr 120px 90px 90px 1fr', gap: 10, padding: '8px 0', borderBottom: '1px solid var(--escalab-line)', alignItems: 'center', fontSize: 12.5 }}>
                              <span style={{ fontWeight: 500 }}>{l.lead}</span>
                              <Tag tone={origemCor[l.origem] || 'neutral'} style={{ fontSize: 11 }}>{origemLabel[l.origem] || l.origem}</Tag>
                              <span style={{ color: l.qualificado === 'sim' ? 'var(--escalab-brand)' : 'var(--escalab-mute)' }}>
                                {l.qualificado === 'sim' ? 'Sim' : l.qualificado === 'na' ? 'N/A' : 'Não'}
                              </span>
                              <span style={{ color: l.proposta === 'aprovada' ? 'var(--escalab-brand)' : 'var(--escalab-mute)' }}>
                                {l.proposta === 'aprovada' ? 'Sim' : l.proposta === 'nao' ? 'Não' : 'Pend.'}
                              </span>
                              <span style={{ color: l.comissiona ? 'var(--escalab-ink)' : 'var(--escalab-mute)', fontStyle: l.comissiona ? 'normal' : 'italic' }}>
                                {l.comissionados
                                  || (l.comissiona && l.participacoes?.length
                                    ? l.participacoes.map(p => vendedores.find(v => v.id === p.v)?.nome?.split(' ')[0]).filter(Boolean).join(', ')
                                    : null)
                                  || (l.comissiona ? '—' : 'Não comissionado')}
                              </span>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </Card>
            );
          })}
        </div>
      )}

      {/* ── ABA: ALTERAÇÕES DE REGRAS ──────────────────────── */}
      {aba === 'regras' && (
        <Card pad={0}>
          <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--escalab-line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <h3 style={{ margin: 0, fontSize: 16 }}>Últimas alterações de regras</h3>
            <Button variant="outline" size="sm" icon="download">Exportar</Button>
          </div>
          <div>
            {historico.map((h, i) => (
              <div key={h.id} style={{ display: 'grid', gridTemplateColumns: '160px 180px 1fr 260px', gap: 16, padding: '16px 24px', borderTop: i > 0 ? '1px solid var(--escalab-line)' : 'none', alignItems: 'center' }}>
                <div style={{ fontSize: 12.5, color: 'var(--escalab-slate)', fontVariantNumeric: 'tabular-nums' }}>{h.data}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <Avatar v={vendedores.find(v => v.nome === h.usuario) || { iniciais: 'M', cor: '#00967B' }} size={26} />
                  <span style={{ fontSize: 13, fontWeight: 500 }}>{h.usuario}</span>
                </div>
                <div>
                  <div style={{ fontSize: 13.5, fontWeight: 600 }}>{h.regra}</div>
                  <div style={{ fontSize: 12, color: 'var(--escalab-mute)', marginTop: 2 }}>{h.nota}</div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, justifyContent: 'flex-end' }}>
                  <Tag tone="neutral">{h.de}</Tag>
                  <span style={{ fontSize: 13, color: 'var(--escalab-mute)' }}>→</span>
                  <Tag tone="brand">{h.para}</Tag>
                </div>
              </div>
            ))}
          </div>
        </Card>
      )}
    </div>
  );
}

function FecharTrimestreModal({ state, open, onClose, onConfirm }) {
  const { trimestre, leads, regras, vendedores } = state;
  const porVendedor = useMemo(() => calcularComissoes(leads, regras, vendedores), [leads, regras, vendedores]);
  const totalPagar   = Object.values(porVendedor).reduce((s, v) => s + v.total, 0);
  const totalFaturado = leads.filter(l => l.vendido && l.comissiona).reduce((s, l) => s + l.valor, 0);
  const indefinidos  = leads.filter(l => l.proposta === 'pendente' || l.status === 'qualificado').length;
  const pendentes    = leads.filter(l => !l.vendido && l.status !== 'perdido');

  const parseQ = (t) => { const m = String(t).match(/(\d)T\/(\d{4})/); return m ? {q:+m[1],year:+m[2]} : null; };
  const nextQ  = (t) => { const p = parseQ(t); if(!p) return t; return p.q===4 ? `1T/${p.year+1}` : `${p.q+1}T/${p.year}`; };

  return (
    <Modal open={open} onClose={onClose} title={`Fechar ${trimestre} e avançar`} width={600}
      footer={<>
        <Button variant="outline" onClick={onClose}>Cancelar</Button>
        <Button variant="dark" icon="lock" onClick={onConfirm}>Fechar e abrir {nextQ(trimestre)}</Button>
      </>}
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <Banner tone="warn" icon="warn">
          Esta ação <strong>arquiva</strong> as comissões do {trimestre} e <strong>abre automaticamente</strong> o {nextQ(trimestre)}.
        </Banner>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
          <Stat label="Total a pagar" value={brl(totalPagar)} tone="light" />
          <Stat label="Total faturado" value={brl(totalFaturado)} tone="light" />
          <Stat label="Leads indefinidos" value={indefinidos} sublabel="Precisam de status" tone="light" />
        </div>
        {indefinidos > 0 && (
          <Banner tone="warn" icon="warn">
            <strong>{indefinidos} lead(s) ainda em "pendente".</strong> Defina o status antes de fechar ou marque como não-comissionados.
          </Banner>
        )}
        <div style={{ padding: 16, background: 'var(--escalab-paper)', borderRadius: 10, border: '1px solid var(--escalab-line)' }}>
          <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 8 }}>Ao confirmar, o sistema vai:</div>
          <ul style={{ margin: 0, paddingLeft: 18, fontSize: 13, color: 'var(--escalab-slate)', lineHeight: 1.8 }}>
            <li>Arquivar todos os {leads.length} leads em "Histórico → Trimestres Anteriores".</li>
            <li>Registrar comissões por pessoa neste período.</li>
            <li>Abrir automaticamente o <strong>{nextQ(trimestre)}</strong>.</li>
            {pendentes.length > 0 && (
              <li><strong>{pendentes.length} lead(s) ainda em aberto</strong> serão carregados no {nextQ(trimestre)} para continuidade.</li>
            )}
            <li>Bloquear edições retroativas neste período.</li>
          </ul>
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { HistoricoScreen, FecharTrimestreModal });
