/* COBRANÇAS · WRAPPER
   Vista principal do módulo Cobranças. Tabs de vistas + filtro empresa SGPS.
   Inclui as 5 vistas (resumo, queue, clientes, proactiva, config). */

const FinanceCobrancasModule = ({ onOpenChat }) => {
  const [view, setView] = React.useState('resumo');
  const [empresa, setEmpresa] = React.useState('todas');
  const [extra, setExtra] = React.useState({});  // payload p/ vistas (filtros pré-aplicados, foco, etc)

  const goTo = (v, payload = {}) => {
    setView(v);
    setExtra(payload);
    if (payload.empresa) setEmpresa(payload.empresa);
  };

  const ctx = { empresa, ...extra };

  const VIEWS = [
    { id: 'resumo',    label: 'Resumo',           kbd: '1', desc: 'KPIs · aging · Coface · calendário' },
    { id: 'queue',     label: 'Para validar',     kbd: '2', desc: 'encomendas portal retidas', badge: 9 },
    { id: 'clientes',  label: 'Clientes',         kbd: '3', desc: 'lista + ficha completa' },
    { id: 'proactiva', label: 'Cobrança proactiva', kbd: '4', desc: 'agenda do dia · 15 itens', badge: 15 },
    { id: 'config',    label: 'Configuração',     kbd: '5', desc: 'thresholds · permissões · integrações' },
  ];

  // keyboard shortcuts for view tabs
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.isContentEditable) return;
      const map = { '1': 'resumo', '2': 'queue', '3': 'clientes', '4': 'proactiva', '5': 'config' };
      if (map[e.key]) { setView(map[e.key]); setExtra({}); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  return (
    <div data-screen-label="Finance · Cobranças" style={{
      padding: 'var(--pad-screen)', display: 'flex', flexDirection: 'column',
      gap: 14, height: '100%', minHeight: 0,
    }}>
      {/* head — title + empresa filter */}
      <HeadBar empresa={empresa} setEmpresa={setEmpresa} view={view} />

      {/* tabs row */}
      <ViewTabs views={VIEWS} active={view} onChange={(v) => { setView(v); setExtra({}); }} />

      {/* active view */}
      <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
        {view === 'resumo'    && <window.FinResumoView    ctx={ctx} onGoTo={goTo} />}
        {view === 'queue'     && <window.FinQueueView     ctx={ctx} onGoTo={goTo} />}
        {view === 'clientes'  && <window.FinClientesView  ctx={ctx} onGoTo={goTo} onOpenChat={onOpenChat} />}
        {view === 'proactiva' && <window.FinProactivaView ctx={ctx} onGoTo={goTo} onOpenChat={onOpenChat} />}
        {view === 'config'    && <window.FinConfigView />}
      </div>
    </div>
  );
};

// ─── head bar ────────────────────────────────────────────────────

const HeadBar = ({ empresa, setEmpresa, view }) => {
  const E = window.FIN_EMPRESAS;
  const sel = E.find(e => e.id === empresa);
  const subtitles = {
    resumo:    'visão agregada da SGPS · DSO 56d · sync Primavera há 12 min',
    queue:     '9 encomendas portal aguardam decisão · 2 com SLA expirado',
    clientes:  '16 clientes activos · ordenado por exposição',
    proactiva: '15 cobranças no dia · sugestão Digi de ordem por criticidade',
    config:    'parâmetros do módulo · só Patrícia + Etelvina podem editar',
  };
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, flexShrink: 0 }}>
      <div>
        <div className="font-mono" style={{ fontSize: 10.5, color: 'var(--text-dim)', letterSpacing: '0.08em' }}>
          FINANCEIRO · CRÉDITO & COBRANÇAS · PATRÍCIA MOTA
        </div>
        <h2 className="font-display" style={{ margin: '4px 0 0', fontSize: 26, fontWeight: 500, letterSpacing: '-0.01em' }}>
          Cobranças <span style={{ color: 'var(--text-muted)', fontWeight: 400 }}>· {sel.label}</span>
        </h2>
        <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginTop: 2 }}>{subtitles[view]}</div>
      </div>

      {/* empresa pills */}
      <div className="card" style={{ padding: 4, display: 'flex', gap: 2, alignItems: 'center', flexShrink: 0 }}>
        {E.map(e => {
          const active = empresa === e.id;
          return (
            <button key={e.id} onClick={() => setEmpresa(e.id)} style={{
              padding: '6px 10px', borderRadius: 4,
              fontSize: 11, fontFamily: 'var(--font-mono)', fontWeight: 600,
              background: active ? `color-mix(in oklch, ${e.color} 18%, transparent)` : 'transparent',
              color: active ? e.color : 'var(--text-muted)',
              border: active ? `1px solid color-mix(in oklch, ${e.color} 36%, transparent)` : '1px solid transparent',
              cursor: 'pointer',
              letterSpacing: '0.04em',
            }}>{e.short}</button>
          );
        })}
      </div>
    </div>
  );
};

// ─── view tabs ───────────────────────────────────────────────────

const ViewTabs = ({ views, active, onChange }) => (
  <div className="card" style={{ padding: 0, overflow: 'hidden', flexShrink: 0 }}>
    <div style={{ display: 'grid', gridTemplateColumns: `repeat(${views.length}, 1fr)` }}>
      {views.map((v, i) => {
        const isActive = active === v.id;
        return (
          <button key={v.id} onClick={() => onChange(v.id)} style={{
            padding: '12px 14px', textAlign: 'left',
            background: isActive ? 'color-mix(in oklch, var(--ai-500) 6%, transparent)' : 'transparent',
            borderBottom: isActive ? '2px solid var(--ai-500)' : '2px solid transparent',
            borderRight: i < views.length - 1 ? '1px solid var(--border)' : 'none',
            cursor: 'pointer',
            display: 'flex', flexDirection: 'column', gap: 2,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontSize: 13, fontWeight: 600 }}>{v.label}</span>
              {v.badge != null && (
                <span className="font-mono" style={{
                  fontSize: 9.5, padding: '1px 6px', borderRadius: 3,
                  background: 'color-mix(in oklch, var(--ai-500) 14%, transparent)',
                  color: 'var(--ai-500)', fontWeight: 700,
                }}>{v.badge}</span>
              )}
              <span style={{ flex: 1 }} />
              <kbd style={{
                fontSize: 9.5, padding: '0 5px', borderRadius: 3,
                background: 'var(--bg-sunken)', color: 'var(--text-dim)',
                border: '1px solid var(--border)', fontFamily: 'var(--font-mono)',
              }}>{v.kbd}</kbd>
            </div>
            <div style={{ fontSize: 10.5, color: 'var(--text-muted)' }}>{v.desc}</div>
          </button>
        );
      })}
    </div>
  </div>
);

window.FinanceCobrancasModule = FinanceCobrancasModule;
