/* COMERCIAL · CARTEIRA — ecrã principal.
 * Filtros de saúde como chips primários + tabela + drawer lateral.
 */

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

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 }) => {
  const colors = { 65: 'var(--accent-500)', 80: 'var(--warning)', 90: 'var(--success)' };
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center',
      padding: '1px 6px', borderRadius: 4, fontSize: 10,
      fontFamily: 'var(--font-mono)', fontWeight: 700,
      background: `color-mix(in oklch, ${colors[stage]} 14%, transparent)`,
      color: colors[stage],
    }}>{stage}</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(--success)' },
  { id: 'esfria', label: 'A esfriar', emoji: '🟡', color: 'var(--warning)' },
  { id: 'risco', label: 'Risco churn', emoji: '🔴', color: 'var(--danger)' },
  { id: 'atraso', label: 'Em atraso', emoji: '💳', color: '#64748b' },
  { id: 'crosssell', label: 'Cross-sell sugerido', emoji: '💡', color: 'var(--ai-500)' },
  { id: 'sem-contacto', label: 'Sem contacto 60d+', emoji: '🕰', color: 'var(--text-muted)' },
];

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

  const clientes = React.useMemo(() => {
    let list = [...CARTEIRA_CLIENTES];
    // 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.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 - a.ltv);
    if (sort === 'recompra') list.sort((a, b) => b.nextBuy.confidence - a.nextBuy.confidence);
    return list;
  }, [filter, sort, query]);

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

  return (
    <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', minHeight: 'calc(100vh - var(--topbar-h))', background: 'var(--bg)' }}>
      {/* Page header */}
      <div style={{ padding: '24px 32px 18px', borderBottom: '1px solid var(--border)', background: 'var(--bg)' }}>
        <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</div>
            <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 4 }}>
              <strong style={{ color: 'var(--text)' }}>{CARTEIRA_CLIENTES.length}</strong> clientes activos ·
              LTV total <strong style={{ color: 'var(--text)' }}>4,3M €</strong> ·
              <span style={{ color: 'var(--ai-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(--text-dim)' }} />
            <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(--bg-elev)', color: 'var(--text)',
                border: '1px solid var(--border)', borderRadius: 8, outline: 'none',
              }}
            />
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'var(--text-muted)' }}>
            <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(--bg-sunken)' : 'transparent',
                color: sort === s.id ? 'var(--text)' : 'var(--text-muted)',
                borderColor: sort === s.id ? 'var(--border)' : '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(--bg-sunken)')
                : 'transparent',
              color: filter === f.id ? (f.color || 'var(--text)') : 'var(--text-muted)',
              border: `1px solid ${filter === f.id ? (f.color ? `color-mix(in oklch, ${f.color} 30%, var(--border))` : 'var(--border)') : 'var(--border)'}`,
              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(--bg-sunken)',
              }}>{counts[f.id]}</span>
            </button>
          ))}
        </div>
      </div>

      {/* Table */}
      <div style={{ flex: 1, padding: '16px 32px 32px', overflow: 'auto' }} className="scrollbar">
        <div style={{
          background: 'var(--bg-elev)',
          border: '1px solid var(--border)',
          borderRadius: 10,
          overflow: 'hidden',
        }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ background: 'var(--bg-sunken)', borderBottom: '1px solid var(--border)' }}>
                {['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(--text-muted)',
                    letterSpacing: '0.06em',
                    textTransform: 'uppercase',
                    fontFamily: 'var(--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(--border)' : 'none',
                      cursor: 'pointer',
                      background: isSelected ? 'color-mix(in oklch, var(--ai-500) 6%, transparent)' : 'transparent',
                      transition: 'background 0.12s',
                    }}
                    onMouseEnter={e => { if (!isSelected) e.currentTarget.style.background = 'var(--bg-sunken)'; }}
                    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(--font-display)', 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(--text-muted)', lineHeight: 1.3, marginTop: 2 }}>{c.city} · {c.sector}</div>
                        </div>
                      </div>
                    </td>
                    {/* Marcas */}
                    <td style={{ padding: '12px 14px', maxWidth: 170 }}>
                      <div style={{ display: 'flex', gap: 3, flexWrap: 'wrap' }}>
                        {c.brands.slice(0, 3).map(b => {
                          const concorrente = b.includes('concorrência');
                          return (
                            <span key={b} style={{
                              padding: '2px 6px', fontSize: 10, borderRadius: 4,
                              background: concorrente ? 'transparent' : 'var(--bg-sunken)',
                              color: concorrente ? 'var(--danger)' : 'var(--text-muted)',
                              border: `1px solid ${concorrente ? 'var(--danger)' : 'var(--border)'}`,
                              whiteSpace: 'nowrap',
                            }}>{b.replace(' (concorrência)', '')}</span>
                          );
                        })}
                        {c.brands.length > 3 && <span style={{ fontSize: 10, color: 'var(--text-dim)', padding: '2px 4px' }}>+{c.brands.length - 3}</span>}
                      </div>
                    </td>
                    {/* Última compra */}
                    <td style={{ padding: '12px 14px' }}>
                      <div style={{ fontSize: 12.5 }}>{c.lastBuy.date}</div>
                      <div style={{ fontSize: 10.5, color: c.lastBuy.daysAgo > 60 ? 'var(--warning)' : 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>
                        {c.lastBuy.daysAgo !== null ? `há ${c.lastBuy.daysAgo}d` : '—'}
                      </div>
                    </td>
                    {/* Previsão */}
                    <td style={{ padding: '12px 14px' }}>
                      <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(--bg-sunken)', borderRadius: 2, overflow: 'hidden' }}>
                          <div style={{
                            width: `${c.nextBuy.confidence}%`, height: '100%',
                            background: c.nextBuy.confidence > 70 ? 'var(--success)' : c.nextBuy.confidence > 40 ? 'var(--warning)' : 'var(--danger)',
                          }} />
                        </div>
                        <span className="font-mono" style={{ fontSize: 10, color: 'var(--text-muted)' }}>{c.nextBuy.confidence}%</span>
                      </div>
                    </td>
                    {/* OPs */}
                    <td style={{ padding: '12px 14px' }}>
                      {c.ops.length === 0 ? (
                        <span style={{ fontSize: 11, color: 'var(--text-dim)' }}>—</span>
                      ) : (
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                          <StageMini stage={c.ops[0].stage} />
                          <span style={{ fontSize: 12, fontWeight: 500 }}>{fmtEurShort(c.ops[0].value)}</span>
                          {c.ops[0].days > 7 && (
                            <span title={`${c.ops[0].days}d parada`} style={{ fontSize: 11 }}>⚠️</span>
                          )}
                        </div>
                      )}
                    </td>
                    {/* Saúde */}
                    <td style={{ padding: '12px 14px' }}>
                      <HealthPill h={c.health} />
                      {hasAtraso && (
                        <div style={{ fontSize: 10, color: 'var(--danger)', fontFamily: 'var(--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(--text-dim)', marginLeft: 4 }} />
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {clientes.length === 0 && (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-muted)', 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;
