/* COBRANÇAS · Vista 2 — PARA VALIDAR (queue de encomendas portal retidas)
   9 cards · filtros · keyboard shortcuts · drawer detalhe ao clicar */

const FinQueueView = ({ ctx, onGoTo }) => {
  const H = window.FinHelpers;
  const QUEUE = window.FIN_QUEUE;
  const CLIENTES = window.FIN_CLIENTES;

  const [filter, setFilter] = React.useState('all');   // all|sla|coface|aging|prepag
  const [empresaF, setEmpresaF] = React.useState(ctx.empresa || 'todas');
  const [selectedId, setSelectedId] = React.useState(null);

  // filter logic
  const filtered = QUEUE.filter(q => {
    if (empresaF !== 'todas' && q.empresa !== empresaF) return false;
    if (filter === 'all') return true;
    if (filter === 'sla') return q.slaState === 'late';
    if (filter === 'coface') return q.falhou.includes('limite_coface');
    if (filter === 'aging')  return q.falhou.includes('aging');
    if (filter === 'prepag') return q.falhou.includes('pre_pag');
    if (filter === 'limite') return q.falhou.includes('limite_interno') || q.falhou.includes('limite_coface');
    return true;
  });

  const totalValor = filtered.reduce((s, q) => s + q.valor, 0);
  const slaLate = filtered.filter(q => q.slaState === 'late').length;
  const slaWarn = filtered.filter(q => q.slaState === 'warn').length;

  // keyboard shortcuts (only when a card is selected)
  React.useEffect(() => {
    if (!selectedId) return;
    const onKey = (e) => {
      if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
      if (e.key === 'l' || e.key === 'L') console.log('Libertar', selectedId);
      if (e.key === 'n' || e.key === 'N') console.log('Libertar c/ nota', selectedId);
      if (e.key === 'p' || e.key === 'P') console.log('Pré-pagamento', selectedId);
      if (e.key === 's' || e.key === 'S') console.log('Suspender', selectedId);
      if (e.key === 'Escape') setSelectedId(null);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [selectedId]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', minHeight: 0 }}>

      {/* Top bar — filtros + KPIs queue */}
      <div className="card" style={{ padding: 14, marginBottom: 12, flexShrink: 0 }}>
        <div style={{ display: 'flex', gap: 24, alignItems: 'center', flexWrap: 'wrap' }}>
          {/* KPIs queue */}
          <div style={{ display: 'flex', gap: 20 }}>
            <Stat label="Na queue" v={filtered.length} unit="encomendas" />
            <Stat label="Valor total" v={H.fmtEUR(totalValor)} highlight />
            <Stat label="SLA expirado" v={slaLate} unit={slaLate === 1 ? 'card' : 'cards'} alert={slaLate > 0} />
            <Stat label="SLA <1h" v={slaWarn} unit={slaWarn === 1 ? 'card' : 'cards'} warn={slaWarn > 0} />
          </div>

          <div style={{ flex: 1 }} />

          {/* Filtro empresa */}
          <select className="input" value={empresaF} onChange={e => setEmpresaF(e.target.value)} style={{ width: 160 }}>
            {window.FIN_EMPRESAS.map(e => (
              <option key={e.id} value={e.id}>{e.label}</option>
            ))}
          </select>
        </div>

        {/* Filter chips */}
        <div style={{ display: 'flex', gap: 6, marginTop: 12, flexWrap: 'wrap' }}>
          <Chip active={filter === 'all'}    onClick={() => setFilter('all')}    label="Todas" count={QUEUE.length} />
          <Chip active={filter === 'sla'}    onClick={() => setFilter('sla')}    label="SLA expirado" count={QUEUE.filter(q => q.slaState === 'late').length} color="var(--danger)" />
          <Chip active={filter === 'limite'} onClick={() => setFilter('limite')} label="Limite excedido" count={QUEUE.filter(q => q.falhou.includes('limite_interno') || q.falhou.includes('limite_coface')).length} />
          <Chip active={filter === 'coface'} onClick={() => setFilter('coface')} label="Coface ≥85%" count={QUEUE.filter(q => q.falhou.includes('limite_coface')).length} color="#F59E0B" />
          <Chip active={filter === 'aging'}  onClick={() => setFilter('aging')}  label="Aging crítico" count={QUEUE.filter(q => q.falhou.includes('aging')).length} color="#F97316" />
          <Chip active={filter === 'prepag'} onClick={() => setFilter('prepag')} label="Pré-pagamento" count={QUEUE.filter(q => q.falhou.includes('pre_pag')).length} color="#A855F7" />
        </div>
      </div>

      {/* Grid de cards · 1 ou 2 colunas conforme drawer está aberto */}
      <div style={{ display: 'grid', gridTemplateColumns: selectedId ? 'minmax(0, 1fr) 480px' : 'minmax(0, 1fr)', gap: 12, flex: 1, minHeight: 0 }}>
        <div className="scrollbar" style={{ overflowY: 'auto', paddingRight: 4 }}>
          <div style={{ display: 'grid', gridTemplateColumns: selectedId ? '1fr' : 'repeat(2, 1fr)', gap: 10 }}>
            {filtered.map(q => (
              <QueueCard key={q.id} q={q}
                cliente={CLIENTES.find(c => c.id === q.clienteId)}
                selected={selectedId === q.id}
                onSelect={() => setSelectedId(q.id === selectedId ? null : q.id)} />
            ))}
            {filtered.length === 0 && (
              <div className="card" style={{ padding: 32, textAlign: 'center', color: 'var(--text-muted)', fontSize: 13, gridColumn: 'span 2' }}>
                Sem encomendas para os filtros activos.
              </div>
            )}
          </div>
        </div>

        {selectedId && (
          <DetailDrawer
            q={QUEUE.find(x => x.id === selectedId)}
            cliente={CLIENTES.find(c => c.id === QUEUE.find(x => x.id === selectedId).clienteId)}
            onClose={() => setSelectedId(null)}
            onGoToCliente={(id) => onGoTo('clientes', { focus: id })}
          />
        )}
      </div>

      {/* Footer · atalhos teclado */}
      <div style={{
        flexShrink: 0, marginTop: 10, padding: '10px 14px',
        background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 6,
        display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap',
        fontSize: 11, color: 'var(--text-muted)',
      }}>
        <span className="font-mono" style={{ fontSize: 9.5, letterSpacing: '0.08em', color: 'var(--text-dim)' }}>ATALHOS</span>
        <Kbd k="L" desc="libertar" />
        <Kbd k="N" desc="libertar c/ nota" />
        <Kbd k="P" desc="pré-pagamento" />
        <Kbd k="S" desc="suspender" />
        <Kbd k="↑↓" desc="navegar" />
        <Kbd k="ESC" desc="fechar" />
        <span style={{ flex: 1 }} />
        <span style={{ fontSize: 10, color: 'var(--text-dim)' }}>Selecciona um card para activar atalhos</span>
      </div>
    </div>
  );
};

// ─── card individual ──────────────────────────────────────────────────

const QueueCard = ({ q, cliente, selected, onSelect }) => {
  const H = window.FinHelpers;
  const slaConf = {
    ok:   { color: 'var(--success)', label: q.sla },
    warn: { color: '#F59E0B',         label: q.sla },
    late: { color: 'var(--danger)',  label: q.sla },
  }[q.slaState];

  const motivosLabel = {
    limite_interno: 'Limite interno',
    limite_coface:  'Coface',
    aging:          'Aging',
    suspenso:       'Suspenso',
    pre_pag:        'Pré-pagamento',
  };

  return (
    <button onClick={onSelect} style={{
      textAlign: 'left', cursor: 'pointer',
      background: selected ? 'color-mix(in oklch, var(--ai-500) 6%, var(--bg-elev))' : 'var(--bg-elev)',
      border: selected ? '1px solid var(--ai-500)' : '1px solid var(--border)',
      borderLeft: `3px solid ${slaConf.color}`,
      borderRadius: 6, padding: 14,
      transition: 'background 0.12s, border-color 0.12s',
    }}>
      {/* header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
        <span className="font-mono" style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-muted)' }}>#{q.id}</span>
        {H.empresaChip(q.empresa)}
        <span style={{ flex: 1 }} />
        <span className="font-mono" style={{ fontSize: 10, color: slaConf.color, fontWeight: 600 }}>{slaConf.label}</span>
      </div>

      {/* cliente + valor */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, marginBottom: 10 }}>
        <div>
          <div style={{ fontSize: 14, fontWeight: 600 }}>{cliente?.nome}</div>
          <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{cliente?.codigo} · {cliente?.localizacao || cliente?.pais}</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div className="font-display" style={{ fontSize: 20, fontWeight: 600 }}>{H.fmtEUR(q.valor)}</div>
        </div>
      </div>

      {/* mini-snapshot · 4 indicadores em linha */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6, marginBottom: 10 }}>
        <Indicator
          label="LIM int"
          v={q.snapshot.limiteInterno?.pct + '%'}
          fail={q.snapshot.limiteInterno?.fail}
          dim={!q.snapshot.limiteInterno}
        />
        <Indicator
          label="Coface"
          v={q.snapshot.limiteCoface ? q.snapshot.limiteCoface.pct + '%' : '—'}
          fail={q.snapshot.limiteCoface?.fail}
          dim={!q.snapshot.limiteCoface}
        />
        <Indicator
          label="Aging"
          v={q.snapshot.aging.idade + 'd'}
          fail={q.snapshot.aging.fail}
        />
        <Indicator
          label="Susp"
          v={q.snapshot.suspenso ? 'sim' : 'não'}
          fail={q.snapshot.suspenso}
        />
      </div>

      {/* motivos */}
      <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', marginBottom: 10 }}>
        {q.falhou.map(m => (
          <span key={m} className="font-mono" style={{
            fontSize: 9.5, padding: '1px 5px', borderRadius: 3,
            background: 'color-mix(in oklch, var(--danger) 10%, transparent)',
            color: 'var(--danger)',
            border: '1px solid color-mix(in oklch, var(--danger) 22%, transparent)',
          }}>✗ {motivosLabel[m]}</span>
        ))}
      </div>

      {/* recomendação Digi · linha curta */}
      <div className="ai-surface" style={{
        padding: '8px 10px', borderRadius: 5,
        fontSize: 11.5, lineHeight: 1.45,
        borderLeft: '2px solid var(--ai-500)',
      }}>
        <div className="font-mono" style={{ fontSize: 9, color: 'var(--ai-500)', letterSpacing: '0.06em', marginBottom: 3 }}>DIGI · RECOMENDA</div>
        {q.recomendacao}
      </div>

      {/* footer · comercial + acções */}
      <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
        <span style={{ fontSize: 10.5, color: 'var(--text-dim)' }}>📞 {q.comercial} · {q.comercialNotif}</span>
        <div style={{ display: 'flex', gap: 4 }}>
          <button className="btn btn-xs btn-ai" onClick={(e) => { e.stopPropagation(); }}>Libertar</button>
          <button className="btn btn-xs" onClick={(e) => { e.stopPropagation(); }}>Pré-pag.</button>
          <button className="btn btn-xs" onClick={(e) => { e.stopPropagation(); }}>Reter</button>
        </div>
      </div>
    </button>
  );
};

// ─── drawer detalhe ──────────────────────────────────────────────────

const DetailDrawer = ({ q, cliente, onClose, onGoToCliente }) => {
  const H = window.FinHelpers;
  return (
    <div className="card scrollbar" style={{
      padding: 18, overflow: 'auto',
      background: 'var(--bg-elev)',
      borderLeft: '2px solid var(--ai-500)',
    }}>
      {/* header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
        <span className="font-mono" style={{ fontSize: 12, fontWeight: 700 }}>#{q.id}</span>
        {H.empresaChip(q.empresa, { large: true })}
        <span style={{ flex: 1 }} />
        <button className="btn btn-xs" onClick={onClose}>ESC ✕</button>
      </div>

      {/* cliente header */}
      <div style={{ paddingBottom: 12, borderBottom: '1px solid var(--border)', marginBottom: 14 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 4 }}>
          <span className="font-display" style={{ fontSize: 18, fontWeight: 600 }}>{cliente?.nome}</span>
          <span className="font-mono" style={{ fontSize: 10.5, color: 'var(--text-dim)' }}>{cliente?.codigo}</span>
        </div>
        <div style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>
          {cliente?.localizacao} · Segmento {cliente?.segmento} · Score {cliente?.score} · Comercial {cliente?.comercial}
        </div>
      </div>

      {/* valor + recomendação destacada */}
      <div style={{ marginBottom: 14 }}>
        <div className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)', letterSpacing: '0.08em', marginBottom: 4 }}>VALOR DA ENCOMENDA</div>
        <div className="font-display" style={{ fontSize: 26, fontWeight: 600 }}>{H.fmtEUR(q.valor)}</div>
      </div>

      <div className="ai-surface" style={{ padding: 12, borderRadius: 5, marginBottom: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
          <span className="ai-chip"><span className="ai-dot" />Digi · análise</span>
        </div>
        <div style={{ fontSize: 12.5, lineHeight: 1.55 }}>{q.recomendacao}</div>
      </div>

      {/* 4 indicadores em detalhe */}
      <SectionTitle>Snapshot · 4 parâmetros</SectionTitle>
      <ParamRow
        title="Limite interno"
        ok={!q.snapshot.limiteInterno?.fail}
        valueLine={q.snapshot.limiteInterno
          ? `${H.fmtEUR(q.snapshot.limiteInterno.usado)} / ${H.fmtEUR(q.snapshot.limiteInterno.lim)}`
          : 'sem limite definido'}
        pct={q.snapshot.limiteInterno?.pct}
      />
      <ParamRow
        title="Limite Coface"
        ok={!q.snapshot.limiteCoface?.fail}
        valueLine={q.snapshot.limiteCoface
          ? `${H.fmtEUR(q.snapshot.limiteCoface.usado)} / ${H.fmtEUR(q.snapshot.limiteCoface.lim)}`
          : 'cliente sem cobertura Coface (mercado: ' + (cliente?.pais === 'PT' ? 'PT' : 'ES') + ')'}
        pct={q.snapshot.limiteCoface?.pct}
        muted={!q.snapshot.limiteCoface}
      />
      <ParamRow
        title="Aging mais antigo"
        ok={!q.snapshot.aging.fail}
        valueLine={`${H.fmtEUR(q.snapshot.aging.v)} a ${q.snapshot.aging.idade} dias`}
      />
      <ParamRow
        title="Suspenso · Pré-pag."
        ok={!q.snapshot.suspenso && !q.snapshot.prePag}
        valueLine={
          q.snapshot.suspenso ? 'Cliente suspenso (FAL)'
          : q.snapshot.prePag ? (q.snapshot.prePagMotivo || 'Encomenda em modo pré-pagamento')
          : 'Estado normal'
        }
        muted={!q.snapshot.suspenso && !q.snapshot.prePag}
      />

      {/* acções */}
      <SectionTitle style={{ marginTop: 18 }}>Acções</SectionTitle>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
        <ActionBtn primary k="L" label="Libertar" />
        <ActionBtn k="N" label="Libertar c/ nota" />
        <ActionBtn k="P" label="Pedir pré-pag. (HiPay)" />
        <ActionBtn k="S" label="Suspender" />
        <button className="btn btn-xs" style={{ gridColumn: 'span 2' }}>Devolver ao Daniel/Marta</button>
        <button className="btn btn-xs" style={{ gridColumn: 'span 2' }} onClick={() => onGoToCliente(cliente.id)}>
          Ver ficha cliente completa →
        </button>
      </div>

      {/* nota IA */}
      <div style={{ marginTop: 14, padding: 10, background: 'var(--bg-sunken)', borderRadius: 5, fontSize: 11, color: 'var(--text-muted)', lineHeight: 1.5 }}>
        💡 Cada acção fica registada na ficha do cliente. A Digi notifica o comercial com o motivo da decisão.
      </div>
    </div>
  );
};

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

const Stat = ({ label, v, unit, highlight, alert, warn }) => {
  const color = alert ? 'var(--danger)' : warn ? '#F59E0B' : highlight ? 'var(--text)' : 'var(--text)';
  return (
    <div>
      <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, color, marginTop: 1 }}>
        {v} {unit && <span style={{ fontSize: 10.5, color: 'var(--text-muted)', fontWeight: 400, marginLeft: 4 }}>{unit}</span>}
      </div>
    </div>
  );
};

const Chip = ({ active, label, count, color, onClick }) => (
  <button onClick={onClick} className="font-mono" style={{
    fontSize: 11, padding: '4px 10px', borderRadius: 999,
    background: active ? (color || 'var(--ai-500)') : 'var(--bg-sunken)',
    color: active ? '#fff' : (color || 'var(--text)'),
    border: '1px solid ' + (active ? 'transparent' : 'var(--border)'),
    cursor: 'pointer',
    display: 'inline-flex', alignItems: 'center', gap: 6,
  }}>
    {label}
    {count != null && <span style={{
      fontSize: 9.5, padding: '0 5px', borderRadius: 9,
      background: active ? 'rgba(255,255,255,0.22)' : 'var(--bg-elev)',
      color: 'inherit',
    }}>{count}</span>}
  </button>
);

const Indicator = ({ label, v, fail, dim }) => (
  <div style={{
    padding: '6px 8px', borderRadius: 4, textAlign: 'center',
    background: fail ? 'color-mix(in oklch, var(--danger) 10%, transparent)' : 'var(--bg-sunken)',
    border: '1px solid ' + (fail ? 'color-mix(in oklch, var(--danger) 22%, transparent)' : 'var(--border)'),
  }}>
    <div className="font-mono" style={{ fontSize: 9, color: dim ? 'var(--text-dim)' : 'var(--text-dim)', letterSpacing: '0.04em' }}>{label}</div>
    <div className="font-mono" style={{ fontSize: 12, fontWeight: 700, color: fail ? 'var(--danger)' : (dim ? 'var(--text-dim)' : 'var(--text)') }}>{v}</div>
  </div>
);

const ParamRow = ({ title, ok, valueLine, pct, muted }) => {
  const color = muted ? 'var(--text-dim)' : (ok ? 'var(--success)' : 'var(--danger)');
  return (
    <div style={{ padding: '10px 0', borderBottom: '1px solid var(--border)' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>
        <span style={{ fontSize: 12.5, fontWeight: 500 }}>{title}</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, color, fontFamily: 'var(--font-mono)', fontWeight: 600 }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: color }} />
          {muted ? '—' : (ok ? 'OK' : 'FALHA')}
        </span>
      </div>
      <div style={{ fontSize: 11.5, color: muted ? 'var(--text-dim)' : 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>{valueLine}</div>
      {pct != null && (
        <div style={{ marginTop: 6, height: 4, background: 'var(--bg-sunken)', borderRadius: 2, overflow: 'hidden' }}>
          <div style={{ height: '100%', width: Math.min(100, pct) + '%', background: ok ? 'var(--success)' : 'var(--danger)' }} />
        </div>
      )}
    </div>
  );
};

const SectionTitle = ({ children, style }) => (
  <div className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)', letterSpacing: '0.08em', marginBottom: 8, ...style }}>{children}</div>
);

const ActionBtn = ({ primary, k, label }) => (
  <button className={'btn btn-sm ' + (primary ? 'btn-ai' : '')} style={{
    display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 6,
  }}>
    <span>{label}</span>
    <kbd style={{
      fontSize: 9.5, padding: '1px 5px', borderRadius: 3,
      background: primary ? 'rgba(255,255,255,0.22)' : 'var(--bg-sunken)',
      color: primary ? '#fff' : 'var(--text-dim)',
      border: '1px solid ' + (primary ? 'transparent' : 'var(--border)'),
      fontFamily: 'var(--font-mono)',
    }}>{k}</kbd>
  </button>
);

const Kbd = ({ k, desc }) => (
  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
    <kbd style={{
      fontSize: 9.5, padding: '1px 5px', borderRadius: 3,
      background: 'var(--bg-sunken)', color: 'var(--text)',
      border: '1px solid var(--border)', fontFamily: 'var(--font-mono)', fontWeight: 600,
    }}>{k}</kbd>
    <span>{desc}</span>
  </span>
);

window.FinQueueView = FinQueueView;
