/* COBRANÇAS · Vista 3 — CLIENTES
   Lista 16 clientes (filtros + sort) + drawer ficha completa em painel direito.
   Drawer = 8 blocos: header, parâmetros, conta corrente, aging, ageing chart, docs, pagamentos, histórico. */

const FinClientesView = ({ ctx, onGoTo, onOpenChat }) => {
  const H = window.FinHelpers;
  const CLIENTES = window.FIN_CLIENTES;
  const ESTADOS = window.FIN_ESTADOS;

  // filters / sort
  const [empresaF, setEmpresaF] = React.useState(ctx.empresa || 'todas');
  const [estadoF,  setEstadoF]  = React.useState(ctx.estado  || 'todos');   // todos | PEN | PDT | …
  const [idadeF,   setIdadeF]   = React.useState(ctx.idade   || 'todos');   // todos|30|60|90
  const [segmentoF, setSegmentoF] = React.useState('todos');                 // todos|A|B|C
  const [search, setSearch] = React.useState('');
  const [sort, setSort] = React.useState('exposicao_desc');
  const [selectedId, setSelectedId] = React.useState(ctx.focus || 'olimpo');

  const filtered = CLIENTES.filter(c => {
    if (empresaF !== 'todas' && !(c.empresas || []).includes(empresaF)) return false;
    if (segmentoF !== 'todos' && c.segmento !== segmentoF) return false;
    if (estadoF !== 'todos') {
      const v = c.estados?.[estadoF]?.v || 0;
      if (v <= 0) return false;
    }
    if (idadeF !== 'todos') {
      const limit = parseInt(idadeF, 10);
      const oldest = Math.max(...Object.values(c.estados || {}).map(s => s.oldest || 0));
      if (oldest < limit) return false;
    }
    if (search) {
      const s = search.toLowerCase();
      if (!c.nome.toLowerCase().includes(s) && !c.codigo.toLowerCase().includes(s)) return false;
    }
    return true;
  });

  const exposicao = (c) => Object.values(c.estados || {}).reduce((s, x) => s + (x.v || 0), 0);
  const oldestOf  = (c) => Math.max(0, ...Object.values(c.estados || {}).map(s => s.oldest || 0));

  filtered.sort((a, b) => {
    if (sort === 'exposicao_desc') return exposicao(b) - exposicao(a);
    if (sort === 'idade_desc')     return oldestOf(b) - oldestOf(a);
    if (sort === 'score_asc')      return a.score - b.score;
    if (sort === 'nome')           return a.nome.localeCompare(b.nome);
    return 0;
  });

  const selected = CLIENTES.find(c => c.id === selectedId) || filtered[0];

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '380px minmax(0, 1fr)', gap: 12, height: '100%', minHeight: 0 }}>

      {/* ─── lista ─── */}
      <div className="card" style={{ display: 'flex', flexDirection: 'column', minHeight: 0, padding: 0, overflow: 'hidden' }}>
        {/* search + filtros */}
        <div style={{ padding: 12, borderBottom: '1px solid var(--border)' }}>
          <input className="input" placeholder="Pesquisar cliente · NIF · código…"
            value={search} onChange={e => setSearch(e.target.value)}
            style={{ width: '100%', marginBottom: 8 }} />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
            <select className="input input-sm" value={empresaF} onChange={e => setEmpresaF(e.target.value)}>
              {window.FIN_EMPRESAS.map(e => <option key={e.id} value={e.id}>{e.label}</option>)}
            </select>
            <select className="input input-sm" value={segmentoF} onChange={e => setSegmentoF(e.target.value)}>
              <option value="todos">Todos segmentos</option>
              <option value="A">Segmento A</option>
              <option value="B">Segmento B</option>
              <option value="C">Segmento C</option>
            </select>
            <select className="input input-sm" value={estadoF} onChange={e => setEstadoF(e.target.value)}>
              <option value="todos">Todos estados</option>
              {Object.keys(ESTADOS).map(k => <option key={k} value={k}>{k} · {ESTADOS[k].label}</option>)}
            </select>
            <select className="input input-sm" value={idadeF} onChange={e => setIdadeF(e.target.value)}>
              <option value="todos">Toda a idade</option>
              <option value="30">≥ 30 dias</option>
              <option value="60">≥ 60 dias</option>
              <option value="90">≥ 90 dias</option>
            </select>
          </div>
        </div>

        {/* sort + count */}
        <div style={{ padding: '8px 12px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 11 }}>
          <span style={{ color: 'var(--text-muted)' }}>{filtered.length} clientes</span>
          <select className="input input-xs" value={sort} onChange={e => setSort(e.target.value)} style={{ width: 160 }}>
            <option value="exposicao_desc">Exposição ↓</option>
            <option value="idade_desc">Idade saldo ↓</option>
            <option value="score_asc">Score ↑ (pior)</option>
            <option value="nome">Nome A→Z</option>
          </select>
        </div>

        {/* lista scroll */}
        <div className="scrollbar" style={{ flex: 1, overflowY: 'auto', minHeight: 0 }}>
          {filtered.map(c => {
            const expo = exposicao(c);
            const oldest = oldestOf(c);
            const limTotal = c.limiteInterno || 1;
            const usadoPct = Math.min(100, Math.round((expo / limTotal) * 100));
            return (
              <button key={c.id} onClick={() => setSelectedId(c.id)} style={{
                width: '100%', textAlign: 'left',
                padding: '10px 12px',
                background: selectedId === c.id ? 'color-mix(in oklch, var(--ai-500) 8%, transparent)' : 'transparent',
                borderLeft: selectedId === c.id ? '2px solid var(--ai-500)' : '2px solid transparent',
                borderBottom: '1px solid var(--border)',
                cursor: 'pointer',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                  <span style={{ width: 8, height: 8, borderRadius: '50%', background: H.scoreColor(c.score) }} />
                  <span style={{ fontSize: 12.5, fontWeight: 600, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.nome}</span>
                  <span className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)' }}>{c.codigo}</span>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4, fontSize: 10.5, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>
                  <span>{c.pais}</span>
                  <span>·</span>
                  <span>SEG {c.segmento}</span>
                  <span>·</span>
                  <span>{c.paymode}</span>
                  {c.suspenso && <span style={{ color: 'var(--danger)', fontWeight: 700, marginLeft: 4 }}>SUSP</span>}
                </div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginBottom: 4 }}>
                  <span className="font-mono" style={{ fontSize: 11, fontWeight: 600 }}>{H.fmtEURcompact(expo)}</span>
                  <span className="font-mono" style={{ fontSize: 10, color: H.idadeColor(oldest) }}>{oldest}d</span>
                </div>
                <div style={{ height: 3, background: 'var(--bg-sunken)', borderRadius: 2, overflow: 'hidden' }}>
                  <div style={{ height: '100%', width: usadoPct + '%', background: usadoPct > 90 ? 'var(--danger)' : usadoPct > 70 ? '#F59E0B' : 'var(--success)' }} />
                </div>
              </button>
            );
          })}
          {filtered.length === 0 && (
            <div style={{ padding: 24, textAlign: 'center', fontSize: 12, color: 'var(--text-muted)' }}>Sem clientes para os filtros activos.</div>
          )}
        </div>
      </div>

      {/* ─── ficha cliente ─── */}
      {selected && (
        <FichaCliente cliente={selected} onOpenChat={onOpenChat} onGoToQueue={() => onGoTo('queue')} />
      )}
    </div>
  );
};

// ─── ficha cliente (drawer 8 blocos) ──────────────────────────────

const FichaCliente = ({ cliente: c, onOpenChat, onGoToQueue }) => {
  const H = window.FinHelpers;
  const ESTADOS = window.FIN_ESTADOS;

  const expo = Object.values(c.estados || {}).reduce((s, x) => s + (x.v || 0), 0);
  const usoLim = Math.round((expo / (c.limiteInterno || 1)) * 100);
  const oldestOverall = Math.max(0, ...Object.values(c.estados || {}).map(s => s.oldest || 0));

  return (
    <div className="scrollbar" style={{ overflowY: 'auto', minHeight: 0, paddingRight: 4 }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12, paddingBottom: 60 }}>

        {/* 1. Header */}
        <div className="card" style={{ padding: 16 }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                <span style={{ width: 12, height: 12, borderRadius: '50%', background: H.scoreColor(c.score) }} />
                <h3 className="font-display" style={{ margin: 0, fontSize: 22, fontWeight: 600 }}>{c.nome}</h3>
                {c.suspenso && (
                  <span className="font-mono" style={{ fontSize: 10, padding: '2px 6px', borderRadius: 3, background: 'color-mix(in oklch, var(--danger) 14%, transparent)', color: 'var(--danger)', border: '1px solid color-mix(in oklch, var(--danger) 30%, transparent)', fontWeight: 700 }}>SUSPENSO · FAL</span>
                )}
              </div>
              <div style={{ fontSize: 12, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>
                {c.codigo} · NIF {c.nif} · {c.pais === 'PT' ? 'Portugal' : 'España'}
              </div>
              <div style={{ display: 'flex', gap: 6, marginTop: 8, flexWrap: 'wrap' }}>
                {(c.empresas || []).map(e => <span key={e}>{H.empresaChip(e, { large: true })}</span>)}
              </div>
            </div>

            <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
              <button className="btn btn-sm">Editar</button>
              <button className="btn btn-sm btn-ai" onClick={onOpenChat}>Falar c/ Digi</button>
            </div>
          </div>

          {/* KPI strip */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, marginTop: 14 }}>
            <KpiTile label="Exposição" v={H.fmtEURcompact(expo)} />
            <KpiTile label="Limite usado" v={usoLim + '%'} sub={H.fmtEURcompact(c.limiteInterno) + ' lim'} color={usoLim > 90 ? 'var(--danger)' : usoLim > 70 ? '#F59E0B' : 'var(--text)'} />
            <KpiTile label="Saldo + antigo" v={oldestOverall + 'd'} color={H.idadeColor(oldestOverall)} />
            <KpiTile label="Score · Digi" v={c.score} sub="0–100" color={H.scoreColor(c.score)} />
          </div>
        </div>

        {/* 2. Parâmetros */}
        <Block title="Parâmetros · ficha Primavera" sub={'Account manager: ' + c.accountManager}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10, fontSize: 12 }}>
            <Param label="Segmento" v={c.segmento} />
            <Param label="Modo pagamento" v={window.FIN_PAYMODE[c.paymode]?.label || c.paymode} />
            <Param label="Limite interno" v={H.fmtEUR(c.limiteInterno)} />
            <Param label="Limite Coface" v={c.limiteCoface ? H.fmtEUR(c.limiteCoface) : '—'} muted={!c.limiteCoface} />
            <Param label="Condições" v={c.condicoes} wide />
          </div>
        </Block>

        {/* 3. Conta corrente */}
        <Block title="Conta corrente · estados Primavera" sub="Click num estado para ver os documentos">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
            {Object.keys(ESTADOS).map(k => {
              const s = c.estados?.[k] || { v: 0, n: 0 };
              const dim = s.v === 0;
              const conf = ESTADOS[k];
              return (
                <div key={k} style={{
                  padding: '8px 10px', borderRadius: 4,
                  background: dim ? 'var(--bg-sunken)' : 'color-mix(in oklch, ' + conf.color + ' 8%, transparent)',
                  border: '1px solid ' + (dim ? 'var(--border)' : 'color-mix(in oklch, ' + conf.color + ' 24%, transparent)'),
                  opacity: dim ? 0.55 : 1,
                }}>
                  <div className="font-mono" style={{ fontSize: 9, fontWeight: 700, color: conf.color, letterSpacing: '0.06em' }}>{k}</div>
                  <div className="font-mono" style={{ fontSize: 11, fontWeight: 600, marginTop: 2 }}>{H.fmtEURcompact(s.v)}</div>
                  <div style={{ fontSize: 9.5, color: 'var(--text-dim)' }}>{s.n} doc · {s.oldest || 0}d</div>
                </div>
              );
            })}
          </div>
        </Block>

        {/* 4. Aging chart */}
        <Block title="Aging · saldo em curso">
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 90 }}>
            {[
              { label: '0-30',  v: c.aging.d030,  color: 'var(--success)' },
              { label: '31-60', v: c.aging.d3160, color: '#F59E0B' },
              { label: '61-90', v: c.aging.d6190, color: '#F97316' },
              { label: '> 90',  v: c.aging.d90,   color: 'var(--danger)' },
            ].map(b => {
              const max = Math.max(c.aging.d030, c.aging.d3160, c.aging.d6190, c.aging.d90, 1);
              const h = Math.round((b.v / max) * 70) + 2;
              return (
                <div key={b.label} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-end' }}>
                  <span className="font-mono" style={{ fontSize: 10, fontWeight: 600, color: b.color, marginBottom: 4 }}>
                    {b.v ? H.fmtEURcompact(b.v) : '—'}
                  </span>
                  <div style={{ width: '100%', height: h, background: b.color, borderRadius: '3px 3px 0 0', opacity: b.v ? 1 : 0.2 }} />
                  <span style={{ fontSize: 10, color: 'var(--text-dim)', marginTop: 4 }}>{b.label}</span>
                </div>
              );
            })}
          </div>
        </Block>

        {/* 5. Documentos abertos */}
        {c.docs && (
          <Block title="Documentos abertos · top recentes">
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11.5 }}>
              <thead>
                <tr style={{ borderBottom: '1px solid var(--border)' }}>
                  {['Doc', 'Emissão', 'Venc.', 'Valor', 'Estado', 'Idade'].map(h => (
                    <th key={h} className="font-mono" style={{ padding: '6px 8px', textAlign: 'left', fontSize: 9, color: 'var(--text-dim)', letterSpacing: '0.06em', fontWeight: 600 }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {c.docs.map(d => (
                  <tr key={d.id} style={{ borderBottom: '1px solid var(--border)' }}>
                    <td className="font-mono" style={{ padding: '7px 8px' }}>{d.id}</td>
                    <td className="font-mono" style={{ padding: '7px 8px', color: 'var(--text-muted)' }}>{d.emissao}</td>
                    <td className="font-mono" style={{ padding: '7px 8px', color: 'var(--text-muted)' }}>{d.vencimento}</td>
                    <td className="font-mono" style={{ padding: '7px 8px', textAlign: 'right', fontWeight: 600 }}>{H.fmtEUR(d.valor)}</td>
                    <td style={{ padding: '7px 8px' }}>{H.estadoBadge(d.estado)}</td>
                    <td className="font-mono" style={{ padding: '7px 8px', color: H.idadeColor(d.idade), fontWeight: 600 }}>{d.idade}d</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Block>
        )}

        {/* 6. Histórico pagamentos · 12m */}
        {c.pagamentos && (
          <Block title="Histórico pagamentos · 12 meses" sub="Verde = no prazo · vermelho = atraso ou em falta">
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 4 }}>
              {c.pagamentos.map((p, i) => (
                <div key={i} style={{
                  height: 36, borderRadius: 3,
                  background: p.on ? 'color-mix(in oklch, var(--success) 22%, transparent)' : 'color-mix(in oklch, var(--danger) 22%, transparent)',
                  border: '1px solid ' + (p.on ? 'color-mix(in oklch, var(--success) 30%, transparent)' : 'color-mix(in oklch, var(--danger) 30%, transparent)'),
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 10, fontFamily: 'var(--font-mono)',
                  color: p.on ? 'var(--success)' : 'var(--danger)',
                  fontWeight: 600,
                }}>{p.mes}</div>
              ))}
            </div>
            <div style={{ marginTop: 8, fontSize: 11, color: 'var(--text-muted)' }}>
              {c.pagamentos.filter(p => p.on).length}/12 meses no prazo · {c.pagamentos.filter(p => !p.on).length} atrasos.
            </div>
          </Block>
        )}

        {/* 7. Histórico Digi */}
        {c.historicoDigi && (
          <div className="ai-surface card" style={{ padding: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <span className="ai-chip"><span className="ai-dot" />Digi · histórico decisões neste cliente</span>
            </div>
            {c.historicoDigi.map((h, i) => (
              <div key={i} style={{
                padding: '10px 0', borderBottom: i < c.historicoDigi.length - 1 ? '1px solid var(--border)' : 'none',
                fontSize: 12, lineHeight: 1.5,
              }}>
                <div className="font-mono" style={{ fontSize: 10, color: 'var(--text-dim)', marginBottom: 3 }}>{h.ts}</div>
                <div style={{ color: 'var(--text-muted)', fontStyle: 'italic' }}>{h.preview}</div>
              </div>
            ))}
            <button className="btn btn-xs btn-ai" style={{ marginTop: 8 }} onClick={onOpenChat}>Continuar conversa →</button>
          </div>
        )}

        {/* 8. Acções */}
        <div className="card" style={{ padding: 14, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <button className="btn btn-sm">Ver no Primavera ↗</button>
          <button className="btn btn-sm">Ajustar limite interno</button>
          <button className="btn btn-sm">Pedir reforço Coface</button>
          <button className="btn btn-sm">Carta formal pré-litígio</button>
          {c.suspenso ? (
            <button className="btn btn-sm" style={{ background: 'color-mix(in oklch, var(--success) 14%, transparent)', color: 'var(--success)' }}>Levantar suspensão</button>
          ) : (
            <button className="btn btn-sm" style={{ color: 'var(--danger)' }}>Suspender cliente</button>
          )}
          <button className="btn btn-sm" onClick={onGoToQueue}>Ver queue desta empresa →</button>
        </div>
      </div>
    </div>
  );
};

// ─── helpers ─────────────────────────────────────────────────────────

const KpiTile = ({ label, v, sub, color }) => (
  <div style={{ padding: '10px 12px', background: 'var(--bg-sunken)', borderRadius: 5 }}>
    <div className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)', letterSpacing: '0.06em' }}>{label}</div>
    <div className="font-display" style={{ fontSize: 18, fontWeight: 600, marginTop: 2, color: color || 'var(--text)' }}>{v}</div>
    {sub && <div style={{ fontSize: 10, color: 'var(--text-dim)', marginTop: 1 }}>{sub}</div>}
  </div>
);

const Block = ({ title, sub, children }) => (
  <div className="card" style={{ padding: 16 }}>
    <div style={{ marginBottom: 12 }}>
      <div className="font-display" style={{ fontSize: 13, fontWeight: 600 }}>{title}</div>
      {sub && <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>{sub}</div>}
    </div>
    {children}
  </div>
);

const Param = ({ label, v, muted, wide }) => (
  <div style={{ gridColumn: wide ? 'span 2' : 'auto' }}>
    <div className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)', letterSpacing: '0.06em', marginBottom: 2 }}>{label}</div>
    <div style={{ fontSize: 12, color: muted ? 'var(--text-dim)' : 'var(--text)' }}>{v}</div>
  </div>
);

window.FinClientesView = FinClientesView;
