/* COMERCIAL · CARTEIRA — ecrã principal.
 * Filtros de saúde como chips primários + tabela + drawer lateral.
 * Quando vendedorId disponível, usa dados reais do FM (pipeline cacheado).
 * Campos Primavera (LTV, última compra, previsão) mostram **** até task #25.
 */

const fmtEurShort = (n) => n >= 1000 ? (n/1000).toFixed(1).replace('.0','') + 'k €' : n + ' €';

// ── Pipeline hook (servidor faz cache 10min) ──────────────────────────────────
const usePipelineCarteira = (vendedorId) => {
  const [state, setState] = React.useState({ data: null, loading: false, error: null });
  React.useEffect(() => {
    if (!vendedorId) return;
    setState(s => ({ ...s, loading: true, error: null }));
    fetch(`/api/pipeline/${vendedorId}`)
      .then(r => r.json())
      .then(json => {
        if (json.error) throw new Error(json.error);
        setState({ data: json, loading: false, error: null });
      })
      .catch(err => setState({ data: null, loading: false, error: err.message }));
  }, [vendedorId]);
  return state;
};

// ── Derivar clientes reais a partir dos records FM ────────────────────────────
const FM_STAGE_PRIORITY = { 'AG DECISAO': 6, 'AG FINANCEIRO': 5, 'DEMO': 4, 'EVENTO': 3, 'INTERESSE': 2, 'LEAD': 1 };
const FM_STAGE_HEALTH   = { 'AG DECISAO': 'saudavel', 'AG FINANCEIRO': 'saudavel', 'DEMO': 'saudavel', 'EVENTO': 'esfria', 'INTERESSE': 'esfria', 'LEAD': 'prospecto' };
const FM_STAGE_COLORS   = { 'LEAD': '#6366f1', 'INTERESSE': '#8b5cf6', 'EVENTO': '#f97316', 'DEMO': '#ea580c', 'AG FINANCEIRO': '#16a34a', 'AG DECISAO': '#15803d' };

const deriveLiveClients = (records) => {
  if (!records?.length) return null;
  const map = {};
  for (const r of records) {
    const key = r.ID_Entidade || r.Entidade_Nome;
    if (!key) continue;
    if (!map[key]) {
      const nm = r.Entidade_Nome || '?';
      const hue = [...key].reduce((a, c) => a + c.charCodeAt(0), 0) % 360;
      // Iniciais: primeiras letras de cada palavra
      const initials = nm.split(/\s+/).filter(Boolean).slice(0, 2).map(w => w[0].toUpperCase()).join('') || nm.slice(0, 2).toUpperCase();
      map[key] = {
        id: key, name: nm, logo: initials,
        logoBg: `hsl(${hue}, 45%, 48%)`,
        city: null, sector: null, brands: new Set(),
        ltv: null, health: null,
        lastBuy: null, nextBuy: null,
        ops: [], contact: null, activity: null, isLive: true,
      };
    }
    const c = map[key];
    if (r.Produto_Name) c.brands.add(r.Produto_Name);
    const val = Math.round((parseFloat(r.Produto_Valor_K) || 0) * 1000);
    const isActive = r.Status !== 'LOST';
    if (isActive && r.Stage_Name) {
      c.ops.push({
        id: r.ID_OPORTUNIDADE || String(Math.random()),
        stage: r.Stage_Name,
        stagePriority: FM_STAGE_PRIORITY[r.Stage_Name] || 0,
        value: val,
        product: r.Produto_Name || '—',
        days: parseInt(r.Age) || null,
      });
    }
  }
  return Object.values(map).map(c => {
    c.brands = [...c.brands];
    if (c.ops.length === 0) {
      c.health = 'esfria';
    } else {
      const top = [...c.ops].sort((a, b) => b.stagePriority - a.stagePriority)[0];
      c.health = FM_STAGE_HEALTH[top?.stage] || 'saudavel';
    }
    return c;
  }).sort((a, b) => {
    const va = a.ops.reduce((s, o) => s + o.value, 0);
    const vb = b.ops.reduce((s, o) => s + o.value, 0);
    return vb - va;
  });
};

const HealthPill = ({ h }) => {
  const meta = HEALTH_META[h];
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      padding: '3px 9px', borderRadius: 999, fontSize: 11, fontWeight: 600,
      background: `color-mix(in oklch, ${meta.color} 13%, transparent)`,
      color: meta.color,
      whiteSpace: 'nowrap',
    }}>
      <span style={{ fontSize: 10 }}>{meta.emoji}</span>{meta.short}
    </span>
  );
};

const StageMini = ({ stage }) => {
  // Numeric stages (mock Primavera) ou text stages (FM real)
  const numColors = { 65: 'var(--dgd-purple-500)', 80: 'var(--dgd-pumpkin-700)', 90: 'var(--dgd-green-700)' };
  const color = numColors[stage] || FM_STAGE_COLORS[stage] || 'var(--dgd-primary-500)';
  const label = stage === 'AG FINANCEIRO' ? 'AG FIN' : stage === 'AG DECISAO' ? 'AG DEC' : String(stage);
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center',
      padding: '1px 6px', borderRadius: 4, fontSize: 9.5,
      fontFamily: 'var(--dgd-font-mono)', fontWeight: 700,
      background: `color-mix(in oklch, ${color} 14%, transparent)`,
      color,
      whiteSpace: 'nowrap',
    }}>{label}</span>
  );
};

const FILTERS = [
  { id: 'todos', label: 'Todos', icon: null },
  { id: 'recompra', label: 'Pronto recompra', emoji: '⚡', color: '#a78bfa' },
  { id: 'saudavel', label: 'Saudáveis', emoji: '🟢', color: 'var(--dgd-green-700)' },
  { id: 'esfria', label: 'A esfriar', emoji: '🟡', color: 'var(--dgd-pumpkin-700)' },
  { id: 'risco', label: 'Risco churn', emoji: '🔴', color: 'var(--dgd-red-700)' },
  { id: 'atraso', label: 'Em atraso', emoji: '💳', color: '#64748b' },
  { id: 'crosssell', label: 'Cross-sell sugerido', emoji: '💡', color: 'var(--dgd-primary-500)' },
  { id: 'sem-contacto', label: 'Sem contacto 60d+', emoji: '🕰', color: 'var(--dgd-fg-2)' },
];

const ScreenComercialCarteira = ({ onNav, vendedorId }) => {
  const [filter, setFilter] = React.useState('todos');
  const [sort, setSort] = React.useState('atividade');
  const [query, setQuery] = React.useState('');
  const [selected, setSelected] = React.useState(null);

  const { data: pipelineData, loading: pipelineLoading } = usePipelineCarteira(vendedorId);
  const liveClients = React.useMemo(() => deriveLiveClients(pipelineData?.records), [pipelineData]);
  const isLive = !!liveClients;
  const source = liveClients || CARTEIRA_CLIENTES;

  const clientes = React.useMemo(() => {
    let list = [...source];
    // filter
    if (filter === 'sem-contacto') list = list.filter(c => c.activity !== null && c.activity >= 60);
    else if (filter === 'crosssell') list = list.filter(c => c.crossSell || c.brands.length <= 2);
    else if (filter !== 'todos') list = list.filter(c => c.health === filter);
    // search
    if (query) {
      const q = query.toLowerCase();
      list = list.filter(c => c.name.toLowerCase().includes(q) || (c.city && c.city.toLowerCase().includes(q)));
    }
    // sort
    if (sort === 'atividade') list.sort((a, b) => (b.activity || 999) - (a.activity || 999));
    if (sort === 'ltv') list.sort((a, b) => (b.ltv || b.ops.reduce((s,o)=>s+o.value,0)) - (a.ltv || a.ops.reduce((s,o)=>s+o.value,0)));
    if (sort === 'recompra') list.sort((a, b) => (b.nextBuy?.confidence || 0) - (a.nextBuy?.confidence || 0));
    return list;
  }, [filter, sort, query, source]);

  const counts = React.useMemo(() => {
    const c = { todos: source.length };
    FILTERS.slice(1).forEach(f => {
      if (f.id === 'sem-contacto') c[f.id] = source.filter(x => x.activity !== null && x.activity >= 60).length;
      else if (f.id === 'crosssell') c[f.id] = source.filter(x => x.crossSell || x.brands.length <= 2).length;
      else c[f.id] = source.filter(x => x.health === f.id).length;
    });
    return c;
  }, [source]);

  return (
    <div className="dgd-design-system scrollbar" style={{ position: 'relative', display: 'flex', flexDirection: 'column', minHeight: 'calc(100vh - var(--topbar-h))', background: 'var(--dgd-bg-app)' }}>
      {/* Page header */}
      <div style={{ padding: '24px 32px 18px', borderBottom: '1px solid var(--dgd-border-1)', background: 'var(--dgd-bg-app)' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 16, marginBottom: 16 }}>
          <div style={{ flex: 1 }}>
            <div className="font-display" style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-0.02em' }}>
              Carteira
              {pipelineLoading && <span style={{ fontSize: 12, fontWeight: 400, color: 'var(--dgd-fg-3)', marginLeft: 10, fontFamily: 'var(--dgd-font-mono)' }}>a carregar…</span>}
              {isLive && <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--dgd-green-700)', marginLeft: 10, fontFamily: 'var(--dgd-font-mono)', letterSpacing: '0.04em' }}>· dados reais</span>}
            </div>
            <div style={{ fontSize: 13, color: 'var(--dgd-fg-2)', marginTop: 4 }}>
              <strong style={{ color: 'var(--dgd-fg-1)' }}>{source.length}</strong> {isLive ? 'entidades com OPs activas' : 'clientes activos'} ·
              {isLive ? (
                <span style={{ marginLeft: 4 }}>LTV <strong>****</strong> · <span style={{ color: 'var(--dgd-fg-3)', fontSize: 11 }}>Primavera pendente (task #25)</span></span>
              ) : (
                <>LTV total <strong style={{ color: 'var(--dgd-fg-1)' }}>4,3M €</strong></>
              )}
              {!isLive && (
                <span style={{ color: 'var(--dgd-primary-500)', marginLeft: 6 }}>
                  <Icon name="sparkle" size={11} style={{ color: 'inherit' }} />
                  {' '}2 em risco, 4 prontas para recompra
                </span>
              )}
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-sm"><Icon name="download" size={12} />Exportar</button>
            <button className="btn btn-sm btn-primary"><Icon name="plus" size={12} />Adicionar cliente</button>
          </div>
        </div>

        {/* Search + sort */}
        <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 14 }}>
          <div style={{ position: 'relative', flex: 1, maxWidth: 380 }}>
            <Icon name="search" size={13} style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--dgd-fg-3)' }} />
            <input
              type="text"
              value={query}
              onChange={e => setQuery(e.target.value)}
              placeholder="Procurar por nome ou cidade…"
              style={{
                width: '100%', padding: '8px 12px 8px 30px',
                fontSize: 13, fontFamily: 'inherit',
                background: 'var(--dgd-bg-surface)', color: 'var(--dgd-fg-1)',
                border: '1px solid var(--dgd-border-1)', borderRadius: 8, outline: 'none',
              }}
            />
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'var(--dgd-fg-2)' }}>
            <span>Ordenar:</span>
            {[
              { id: 'atividade', label: 'Último contacto' },
              { id: 'ltv', label: 'LTV' },
              { id: 'recompra', label: 'Previsão recompra' },
            ].map(s => (
              <button key={s.id} onClick={() => setSort(s.id)} className="btn btn-xs" style={{
                background: sort === s.id ? 'var(--dgd-bg-app)' : 'transparent',
                color: sort === s.id ? 'var(--dgd-fg-1)' : 'var(--dgd-fg-2)',
                borderColor: sort === s.id ? 'var(--dgd-border-1)' : 'transparent',
              }}>{s.label}</button>
            ))}
          </div>
        </div>

        {/* Health filters */}
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {FILTERS.map(f => (
            <button key={f.id} onClick={() => setFilter(f.id)} style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '6px 12px', borderRadius: 8,
              fontSize: 12, fontWeight: 500, fontFamily: 'inherit',
              cursor: 'pointer', whiteSpace: 'nowrap',
              background: filter === f.id
                ? (f.color ? `color-mix(in oklch, ${f.color} 14%, transparent)` : 'var(--dgd-bg-app)')
                : 'transparent',
              color: filter === f.id ? (f.color || 'var(--dgd-fg-1)') : 'var(--dgd-fg-2)',
              border: `1px solid ${filter === f.id ? (f.color ? `color-mix(in oklch, ${f.color} 30%, var(--dgd-border-1))` : 'var(--dgd-border-1)') : 'var(--dgd-border-1)'}`,
              transition: 'all 0.12s',
            }}>
              {f.emoji && <span style={{ fontSize: 11 }}>{f.emoji}</span>}
              {f.label}
              <span className="font-mono" style={{
                fontSize: 10, opacity: 0.7,
                padding: '0 5px', borderRadius: 3,
                background: filter === f.id ? 'color-mix(in oklch, currentColor 12%, transparent)' : 'var(--dgd-bg-app)',
              }}>{counts[f.id]}</span>
            </button>
          ))}
        </div>
      </div>

      {/* Table */}
      <div style={{ flex: 1, padding: '16px 32px 32px', overflow: 'auto' }} className="scrollbar">
        <div style={{
          background: 'var(--dgd-bg-surface)',
          border: '1px solid var(--dgd-border-1)',
          borderRadius: 10,
          overflow: 'hidden',
        }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ background: 'var(--dgd-bg-app)', borderBottom: '1px solid var(--dgd-border-1)' }}>
                {['Cliente', 'Marcas', 'Última compra', 'Previsão recompra', 'OPs activas', 'Saúde', ''].map((h, i) => (
                  <th key={i} style={{
                    padding: '10px 14px', textAlign: 'left',
                    fontSize: 10.5, fontWeight: 600,
                    color: 'var(--dgd-fg-2)',
                    letterSpacing: '0.06em',
                    textTransform: 'uppercase',
                    fontFamily: 'var(--dgd-font-mono)',
                  }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {clientes.map((c, i) => {
                const isSelected = selected && selected.id === c.id;
                const hasAtraso = c.health === 'atraso';
                return (
                  <tr
                    key={c.id}
                    onClick={() => setSelected(c)}
                    style={{
                      borderBottom: i < clientes.length - 1 ? '1px solid var(--dgd-border-1)' : 'none',
                      cursor: 'pointer',
                      background: isSelected ? 'color-mix(in oklch, var(--dgd-primary-500) 6%, transparent)' : 'transparent',
                      transition: 'background 0.12s',
                    }}
                    onMouseEnter={e => { if (!isSelected) e.currentTarget.style.background = 'var(--dgd-bg-app)'; }}
                    onMouseLeave={e => { if (!isSelected) e.currentTarget.style.background = 'transparent'; }}
                  >
                    {/* Cliente */}
                    <td style={{ padding: '12px 14px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <div style={{
                          width: 30, height: 30, borderRadius: 7, flexShrink: 0,
                          background: c.logoBg, color: '#fff',
                          display: 'grid', placeItems: 'center',
                          fontFamily: 'var(--dgd-font-sans)', fontWeight: 700, fontSize: 11,
                        }}>{c.logo}</div>
                        <div style={{ minWidth: 0 }}>
                          <div style={{ fontWeight: 600, fontSize: 13, lineHeight: 1.3 }}>{c.name}</div>
                          <div style={{ fontSize: 11, color: 'var(--dgd-fg-2)', lineHeight: 1.3, marginTop: 2 }}>
                            {c.city || '****'}{c.sector ? ` · ${c.sector}` : ''}
                          </div>
                        </div>
                      </div>
                    </td>
                    {/* Marcas / Produtos */}
                    <td style={{ padding: '12px 14px', maxWidth: 170 }}>
                      {c.isLive && c.brands.length === 0 ? (
                        <span style={{ fontSize: 11, color: 'var(--dgd-fg-3)', fontFamily: 'var(--dgd-font-mono)' }}>****</span>
                      ) : (
                        <div style={{ display: 'flex', gap: 3, flexWrap: 'wrap' }}>
                          {c.brands.slice(0, 3).map(b => {
                            const concorrente = !c.isLive && b.includes('concorrência');
                            return (
                              <span key={b} style={{
                                padding: '2px 6px', fontSize: 10, borderRadius: 4,
                                background: concorrente ? 'transparent' : 'var(--dgd-bg-app)',
                                color: concorrente ? 'var(--dgd-red-700)' : 'var(--dgd-fg-2)',
                                border: `1px solid ${concorrente ? 'var(--dgd-red-700)' : 'var(--dgd-border-1)'}`,
                                whiteSpace: 'nowrap',
                              }}>{b.replace(' (concorrência)', '')}</span>
                            );
                          })}
                          {c.brands.length > 3 && <span style={{ fontSize: 10, color: 'var(--dgd-fg-3)', padding: '2px 4px' }}>+{c.brands.length - 3}</span>}
                        </div>
                      )}
                    </td>
                    {/* Última compra */}
                    <td style={{ padding: '12px 14px' }}>
                      {c.isLive ? (
                        <span style={{ fontSize: 11, color: 'var(--dgd-fg-3)', fontFamily: 'var(--dgd-font-mono)' }}>****</span>
                      ) : (
                        <>
                          <div style={{ fontSize: 12.5 }}>{c.lastBuy.date}</div>
                          <div style={{ fontSize: 10.5, color: c.lastBuy.daysAgo > 60 ? 'var(--dgd-pumpkin-700)' : 'var(--dgd-fg-2)', fontFamily: 'var(--dgd-font-mono)' }}>
                            {c.lastBuy.daysAgo !== null ? `há ${c.lastBuy.daysAgo}d` : '—'}
                          </div>
                        </>
                      )}
                    </td>
                    {/* Previsão */}
                    <td style={{ padding: '12px 14px' }}>
                      {c.isLive ? (
                        <span style={{ fontSize: 11, color: 'var(--dgd-fg-3)', fontFamily: 'var(--dgd-font-mono)' }}>****</span>
                      ) : (
                        <>
                          <div style={{ fontSize: 12.5 }}>{c.nextBuy.date}</div>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginTop: 2 }}>
                            <div style={{ width: 40, height: 3, background: 'var(--dgd-bg-app)', borderRadius: 2, overflow: 'hidden' }}>
                              <div style={{
                                width: `${c.nextBuy.confidence}%`, height: '100%',
                                background: c.nextBuy.confidence > 70 ? 'var(--dgd-green-700)' : c.nextBuy.confidence > 40 ? 'var(--dgd-pumpkin-700)' : 'var(--dgd-red-700)',
                              }} />
                            </div>
                            <span className="font-mono" style={{ fontSize: 10, color: 'var(--dgd-fg-2)' }}>{c.nextBuy.confidence}%</span>
                          </div>
                        </>
                      )}
                    </td>
                    {/* OPs */}
                    <td style={{ padding: '12px 14px' }}>
                      {c.ops.length === 0 ? (
                        <span style={{ fontSize: 11, color: 'var(--dgd-fg-3)' }}>—</span>
                      ) : (
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                          {c.ops.slice(0, 2).map((op, oi) => (
                            <div key={oi} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                              <StageMini stage={op.stage} />
                              <span style={{ fontSize: 12, fontWeight: 500 }}>{fmtEurShort(op.value)}</span>
                              {op.days > 7 && <span title={`${op.days}d parada`} style={{ fontSize: 11 }}>⚠️</span>}
                            </div>
                          ))}
                          {c.ops.length > 2 && <span style={{ fontSize: 10, color: 'var(--dgd-fg-3)' }}>+{c.ops.length - 2} mais</span>}
                        </div>
                      )}
                    </td>
                    {/* Saúde */}
                    <td style={{ padding: '12px 14px' }}>
                      <HealthPill h={c.health} />
                      {hasAtraso && (
                        <div style={{ fontSize: 10, color: 'var(--dgd-red-700)', fontFamily: 'var(--dgd-font-mono)', marginTop: 3 }}>
                          11.240 € · 45d
                        </div>
                      )}
                    </td>
                    {/* Actions */}
                    <td style={{ padding: '12px 14px', textAlign: 'right' }}>
                      <button
                        onClick={(e) => { e.stopPropagation(); onNav && onNav('clientes'); }}
                        className="btn btn-xs btn-ghost"
                        title="Abrir conversa"
                      >
                        <Icon name="chat" size={11} />
                      </button>
                      <Icon name="chevron-right" size={12} style={{ color: 'var(--dgd-fg-3)', marginLeft: 4 }} />
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {clientes.length === 0 && (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--dgd-fg-2)', fontSize: 13 }}>
            Sem clientes com este filtro.
          </div>
        )}
      </div>

      {selected && (
        <CarteiraDrawer
          cliente={selected}
          onClose={() => setSelected(null)}
          onOpenClientes={() => { setSelected(null); onNav && onNav('clientes'); }}
        />
      )}
    </div>
  );
};

window.ScreenComercialCarteira = ScreenComercialCarteira;
