// Perfil do licitante: a empresa do cliente descreve onde atua, o que fornece e em que faixa disputa.
// Grava em public.capability_profiles (RLS por organização/ambiente; colunas novas na migration 0095) e alimenta
// as Recomendações (public.bidder_recommendations). Os campos de capacidade operacional (equipamentos, equipe,
// experiência, documentos) continuam aqui porque o Go/No-Go usa o mesmo perfil.
const BPF_UFS = ['AC', 'AL', 'AM', 'AP', 'BA', 'CE', 'DF', 'ES', 'GO', 'MA', 'MG', 'MS', 'MT', 'PA', 'PB', 'PE', 'PI', 'PR', 'RJ', 'RN', 'RO', 'RR', 'RS', 'SC', 'SE', 'SP', 'TO'];
// Nomes como o PNCP publica (modalidadeNome), para casar com a modalidade da licitação.
const BPF_MODALIDADES = ['Pregão - Eletrônico', 'Pregão - Presencial', 'Concorrência - Eletrônica', 'Concorrência - Presencial', 'Dispensa de Licitação', 'Inexigibilidade', 'Credenciamento', 'Leilão - Eletrônico', 'Diálogo Competitivo', 'Concurso'];
const BPF_PORTES = [{ value: '', label: 'Não informar' }, { value: 'MEI', label: 'MEI' }, { value: 'ME', label: 'Microempresa (ME)' }, { value: 'EPP', label: 'Empresa de pequeno porte (EPP)' }, { value: 'DEMAIS', label: 'Demais portes' }];
const BPF_EMPTY = { name: 'Perfil principal', companySize: '', cnaes: '', baseUf: '', baseMunicipio: '', radiusKm: '', ufs: [], keywords: '', excludeKeywords: '', modalidades: [], minValue: '', maxValue: '', sectors: '', equipment: '', workforceCapacity: '', experience: '', validDocuments: '' };
const bpfCsv = v => (Array.isArray(v) ? v.join(', ') : '');
function bpfFromRow(r) {
  return { name: r.name || '', companySize: r.company_size || '', cnaes: bpfCsv(r.cnaes), baseUf: '', baseMunicipio: r.base_municipio_ibge ? String(r.base_municipio_ibge) : '', radiusKm: r.radius_km == null ? '' : String(r.radius_km), ufs: Array.isArray(r.ufs) ? r.ufs : [], keywords: bpfCsv(r.keywords), excludeKeywords: bpfCsv(r.exclude_keywords), modalidades: Array.isArray(r.modalidades) ? r.modalidades : [], minValue: r.min_value == null ? '' : String(r.min_value), maxValue: r.max_value == null ? '' : String(r.max_value), sectors: bpfCsv(r.sectors), equipment: bpfCsv(r.equipment), workforceCapacity: r.workforce_capacity ? String(r.workforce_capacity) : '', experience: bpfCsv(r.experience), validDocuments: bpfCsv(r.valid_documents) };
}

// ---- Elementos visuais do perfil: mapa de alcance, faixa de valor, chips e prévia de licitações abertas.
function bpfHav(la1, lo1, la2, lo2) {
  const r = Math.PI / 180, x = Math.sin((la2 - la1) * r / 2) ** 2 + Math.cos(la1 * r) * Math.cos(la2 * r) * Math.sin((lo2 - lo1) * r / 2) ** 2;
  return 12742 * Math.asin(Math.min(1, Math.sqrt(x)));
}
const bpfChipStyle = tone => {
  const c = tone === 'danger' ? 'var(--status-danger)' : 'var(--status-success)';
  return { display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 10px', borderRadius: 999, fontSize: 12.5, fontWeight: 500, color: 'var(--text-primary)', background: 'color-mix(in srgb, ' + c + ' 16%, transparent)', border: '1px solid color-mix(in srgb, ' + c + ' 48%, transparent)' };
};
const bpfMoney = v => {
  const n = Number(v);
  if (!(n > 0)) return '';
  if (n >= 1e6) return 'R$ ' + (n / 1e6).toLocaleString('pt-BR', { maximumFractionDigits: 1 }) + ' mi';
  if (n >= 1e3) return 'R$ ' + Math.round(n / 1e3).toLocaleString('pt-BR') + ' mil';
  return 'R$ ' + n.toLocaleString('pt-BR');
};

// Mapa de alcance: cada ponto é um município (IBGE). Verde = dentro do raio ou das UFs marcadas. Sem nada marcado, vale o Brasil inteiro.
function BidderReachMap({ geo, loading, baseId, radiusKm, ufs }) {
  const W = 520, H = 400;
  const m = React.useMemo(() => {
    if (!geo) return null;
    const base = baseId ? geo.find(g => String(g.id) === String(baseId)) : null;
    const r = base && Number(radiusKm) > 0 ? Number(radiusKm) : 0;
    const ufSet = new Set(ufs); if (base && !r) ufSet.add(base.uf);
    const all = !r && !ufSet.size, national = all || ufSet.size >= 27;
    let la0 = -33.9, la1 = 5.4, lo0 = -73.9, lo1 = -34.7;
    if (!national) {
      la0 = Infinity; la1 = -Infinity; lo0 = Infinity; lo1 = -Infinity;
      const add = (la, lo) => { la0 = Math.min(la0, la); la1 = Math.max(la1, la); lo0 = Math.min(lo0, lo); lo1 = Math.max(lo1, lo); };
      if (ufSet.size) geo.forEach(g => { if (ufSet.has(g.uf)) add(g.lat, g.lon); });
      if (r) { const d = r / 111.19, dl = d / Math.cos(base.lat * Math.PI / 180); add(base.lat - d, base.lon - dl); add(base.lat + d, base.lon + dl); }
      const pa = Math.max((la1 - la0) * .08, .15), po = Math.max((lo1 - lo0) * .08, .15);
      la0 -= pa; la1 += pa; lo0 -= po; lo1 += po;
    }
    const k = Math.cos((la0 + la1) / 2 * Math.PI / 180), dx = (lo1 - lo0) * k, dy = la1 - la0, sc = Math.min(W / dx, H / dy);
    const ox = (W - dx * sc) / 2, oy = (H - dy * sc) / 2;
    const px = lo => ox + (lo - lo0) * k * sc, py = la => oy + (la1 - la) * sc;
    let inn = '', out = '', count = 0, vis = 0;
    geo.forEach(g => {
      const hit = all || ufSet.has(g.uf) || (r > 0 && bpfHav(base.lat, base.lon, g.lat, g.lon) <= r);
      if (hit) count++;
      if (g.lat < la0 || g.lat > la1 || g.lon < lo0 || g.lon > lo1) return;
      vis++;
      const seg = 'M' + px(g.lon).toFixed(1) + ' ' + py(g.lat).toFixed(1) + 'h0';
      if (hit) inn += seg; else out += seg;
    });
    return { base, r, all, national, inn, out, count, cx: base ? px(base.lon) : 0, cy: base ? py(base.lat) : 0, cr: r ? r / 111.19 * sc : 0, dot: Math.max(2, Math.min(6, Math.sqrt(W * H / Math.max(vis, 1)) * .4)) };
  }, [geo, baseId, radiusKm, ufs.join(',')]);
  const shell = { borderRadius: 14, background: 'var(--surface-sunken)', border: '1px solid var(--border-faint)', overflow: 'hidden' };
  if (loading || !m) return <div style={{ ...shell, aspectRatio: '520 / 400', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-muted)', fontSize: 13 }}>{loading ? 'Carregando o mapa…' : 'Mapa indisponível agora.'}</div>;
  const label = m.all ? 'Brasil inteiro: nenhuma cidade, raio ou UF marcados' : m.national ? 'Brasil inteiro' : m.count.toLocaleString('pt-BR') + ' municípios no seu alcance';
  return <div style={{ display: 'grid', gap: 8 }}>
    <div style={shell}>
      <svg viewBox={'0 0 ' + W + ' ' + H} style={{ display: 'block', width: '100%', height: 'auto' }} role="img" aria-label={'Mapa de alcance: ' + label}>
        <path d={m.out} fill="none" stroke="var(--border-strong)" strokeOpacity=".55" strokeWidth={m.dot} strokeLinecap="round" />
        <path d={m.inn} fill="none" stroke="var(--status-success)" strokeWidth={m.dot * 1.25} strokeLinecap="round" />
        {m.r > 0 && <circle cx={m.cx} cy={m.cy} r={m.cr} fill="var(--action-primary-tint)" fillOpacity=".5" stroke="var(--action-selected-icon)" strokeWidth="1.5" />}
        {m.base && <g><circle cx={m.cx} cy={m.cy} r="6" fill="#fff" stroke="var(--surface-sunken)" strokeWidth="2" /><text x={m.cx + 10} y={m.cy - 8} fontSize="13" fontWeight="600" fill="var(--text-primary)" stroke="var(--surface-sunken)" strokeWidth="3" paintOrder="stroke">{m.base.nome}</text></g>}
      </svg>
    </div>
    <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>Cada ponto é um município. <span style={{ color: 'var(--status-success)', fontWeight: 600 }}>{label}.</span></span>
  </div>;
}

// Faixa de valor com duas alças em escala logarítmica (R$ 10 mil a R$ 100 mi). Ponta esquerda = sem mínimo; ponta direita = sem teto.
const BPF_LO = 1e4, BPF_SPAN = 4;
const bpfPos = v => (Number(v) > 0 ? Math.max(0, Math.min(100, Math.log10(Number(v) / BPF_LO) / BPF_SPAN * 100)) : null);
const bpfVal = p => { const raw = BPF_LO * Math.pow(10, p / 100 * BPF_SPAN), mag = Math.pow(10, Math.floor(Math.log10(raw)) - 1); return Math.round(raw / mag) * mag; };
function BidderValueRange({ min, max, onMin, onMax }) {
  const lo = bpfPos(min) == null ? 0 : bpfPos(min), hi = bpfPos(max) == null ? 100 : bpfPos(max);
  return <div style={{ display: 'grid', gap: 6 }}>
    <style>{'.vx-dual{position:relative;height:28px}.vx-dual .tr,.vx-dual .fl{position:absolute;top:11px;height:6px;border-radius:3px}.vx-dual .tr{left:0;right:0;background:var(--surface-track)}.vx-dual .fl{background:var(--action-selected-icon)}.vx-dual input{position:absolute;left:0;top:0;width:100%;height:28px;margin:0;background:none;pointer-events:none;-webkit-appearance:none;appearance:none}.vx-dual input::-webkit-slider-runnable-track{background:transparent;height:28px}.vx-dual input::-moz-range-track{background:transparent}.vx-dual input::-webkit-slider-thumb{pointer-events:auto;-webkit-appearance:none;width:18px;height:18px;margin-top:5px;border-radius:50%;background:#fff;border:2px solid var(--action-primary);cursor:grab;box-shadow:0 2px 6px rgba(0,0,0,.35)}.vx-dual input::-moz-range-thumb{pointer-events:auto;width:14px;height:14px;border-radius:50%;background:#fff;border:2px solid var(--action-primary);cursor:grab}.vx-dual input:focus-visible::-webkit-slider-thumb{outline:2px solid var(--border-focus);outline-offset:2px}'}</style>
    <span style={{ fontSize: 13, color: 'var(--text-secondary)' }}>Faixa de valor estimado das licitações</span>
    <div className="vx-dual">
      <div className="tr" /><div className="fl" style={{ left: lo + '%', width: Math.max(0, hi - lo) + '%' }} />
      <input type="range" min="0" max="100" step="0.5" value={lo} aria-label="Valor mínimo" onChange={e => { const p = Math.min(Number(e.target.value), hi - 2); onMin(p <= 0 ? '' : String(bpfVal(p))); }} />
      <input type="range" min="0" max="100" step="0.5" value={hi} aria-label="Valor máximo" onChange={e => { const p = Math.max(Number(e.target.value), lo + 2); onMax(p >= 100 ? '' : String(bpfVal(p))); }} />
    </div>
    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14, fontWeight: 600, color: 'var(--text-primary)' }}>
      <span>{bpfMoney(min) ? 'mín. ' + bpfMoney(min) : 'sem mínimo'}</span><span>{bpfMoney(max) ? 'máx. ' + bpfMoney(max) : 'sem teto'}</span>
    </div>
  </div>;
}

// Prévia: objetos reais de licitações abertas que citam as palavras-chave. As palavras a evitar aparecem riscadas.
function BidderKeywordPreview({ keywords, exclude }) {
  const rt = window.VxOpportunityRuntime;
  const kws = React.useMemo(() => window.VxNorm.list(keywords).filter(k => window.VxNorm.key(k).length >= 3), [keywords]);
  const ex = React.useMemo(() => window.VxNorm.list(exclude).map(window.VxNorm.key).filter(k => k.length >= 3), [exclude]);
  const [rows, setRows] = React.useState(null), [busy, setBusy] = React.useState(false);
  const kkey = kws.join('|');
  React.useEffect(() => {
    if (!kws.length) { setRows(null); return; }
    let alive = true; setBusy(true);
    const h = setTimeout(async () => { const r = await rt.previewObjetos(kws, 12); if (!alive) return; setBusy(false); setRows(r.error ? null : r.data); }, 600);
    return () => { alive = false; clearTimeout(h); };
  }, [kkey]);
  const box = { borderRadius: 14, background: 'var(--surface-sunken)', border: '1px solid var(--border-faint)', padding: 14, display: 'grid', gap: 8, alignContent: 'start' };
  const eyebrow = { fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--text-subtle)', fontWeight: 600 };
  const isEx = o => ex.some(e => window.VxNorm.key(o).includes(e));
  const shown = (rows || []).slice().sort((a, b) => isEx(a.objeto) - isEx(b.objeto)).slice(0, 5);
  return <div style={box}>
    <span style={eyebrow}>Licitações abertas que citam suas palavras</span>
    {!kws.length && <span style={{ fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.5 }}>Digite as palavras-chave e veja aqui exemplos reais de licitações abertas nos últimos 60 dias.</span>}
    {kws.length > 0 && rows == null && <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{busy ? 'Buscando exemplos…' : 'Prévia indisponível agora.'}</span>}
    {kws.length > 0 && rows && !rows.length && <span style={{ fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.5 }}>Nenhuma licitação aberta cita estas palavras agora. Tente termos mais gerais.</span>}
    {shown.map((o, i) => { const bad = isEx(o.objeto); return <div key={i} style={{ padding: '8px 12px', borderRadius: 10, fontSize: 13, lineHeight: 1.4, color: bad ? 'var(--text-muted)' : 'var(--text-primary)', textDecoration: bad ? 'line-through' : 'none', opacity: bad ? .65 : 1, background: bad ? 'var(--surface-card)' : 'color-mix(in srgb, var(--status-success) 10%, transparent)', border: '1px solid ' + (bad ? 'color-mix(in srgb, var(--status-danger) 40%, transparent)' : 'color-mix(in srgb, var(--status-success) 45%, transparent)') }}>{String(o.objeto || '').slice(0, 140)}{o.uf ? ' · ' + o.uf : ''}</div>; })}
    {rows && rows.length > 0 && <span style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.45 }}>Exemplos do PNCP. As recomendações também consideram local, valor e prazo.</span>}
  </div>;
}

function CapabilityProfilesScreen({ go }) {
  const { PageHeader, Card, CardHeader, Input, Select, Button, Badge, FilterChip, Checkbox, Alert, Toast } = window.VRticeDesignSystem_d763eb;
  const rt = window.VxOpportunityRuntime;
  const [rows, setRows] = React.useState([]), [selected, setSelected] = React.useState(''), [form, setForm] = React.useState(BPF_EMPTY);
  const [cities, setCities] = React.useState([]), [toast, setToast] = React.useState(''), [busy, setBusy] = React.useState(false), [loading, setLoading] = React.useState(true), [missing, setMissing] = React.useState(false);
  const [tour, setTour] = React.useState(false), [created, setCreated] = React.useState(false);
  const [geo, setGeo] = React.useState(null), [geoLoading, setGeoLoading] = React.useState(true);
  const set = (k, v) => setForm(s => ({ ...s, [k]: v }));
  const toggle = (k, v) => setForm(s => ({ ...s, [k]: s[k].includes(v) ? s[k].filter(x => x !== v) : [...s[k], v] }));

  const open = React.useCallback(async row => {
    if (!row) { setSelected(''); setForm(BPF_EMPTY); return; }
    setSelected(row.id);
    const f = bpfFromRow(row);
    if (row.base_municipio_ibge) { const m = await rt.getMunicipio(row.base_municipio_ibge); if (m.data) f.baseUf = m.data.uf; }
    setForm(f);
  }, []);
  const load = React.useCallback(async keepId => {
    setLoading(true);
    const r = await rt.listCapabilities();
    setLoading(false);
    if (r.error) { setToast(r.error); return; }
    const list = r.data || [];
    setRows(list);
    setMissing(list.length > 0 && !('keywords' in list[0]));
    await open(list.find(x => x.id === keepId) || list[0] || null);
  }, [open]);
  React.useEffect(() => { load(); }, [load]);
  React.useEffect(() => {
    let alive = true;
    if (!form.baseUf) { setCities([]); return; }
    rt.listMunicipios(form.baseUf).then(r => { if (!alive) return; if (r.error && /br_municipios|42P01|PGRST205/.test(r.error)) setMissing(true); setCities(r.data || []); });
    return () => { alive = false; };
  }, [form.baseUf]);

  React.useEffect(() => { let alive = true; rt.municipiosGeo().then(r => { if (!alive) return; setGeo(r.data || null); setGeoLoading(false); }); return () => { alive = false; }; }, []);

  const save = async () => {
    setBusy(true);
    const r = await rt.saveBidderProfile(form, selected || null);
    setBusy(false);
    if (r.error) { setToast(/column|schema cache/i.test(r.error) ? 'O banco ainda não tem os campos do perfil do licitante (migration 0095).' : r.error); return; }
    setToast('Perfil salvo. As recomendações já usam estes dados.');
    if (!selected) setCreated(true);
    vxOnbRefresh(); // marca o passo "Preencha o Perfil do licitante" nos Primeiros passos
    load(r.data.id);
  };

  const city = cities.find(c => String(c.codigo_ibge) === String(form.baseMunicipio));
  const reach = form.radiusKm && city ? 'Até ' + form.radiusKm + ' km de ' + city.nome + '/' + city.uf : '';
  const ufsText = form.ufs.length ? (form.ufs.length === 27 ? 'Brasil inteiro' : 'UFs inteiras: ' + form.ufs.join(', ')) : '';
  const section = (title, hint, step) => <div style={{ display: 'grid', gap: 4 }}>
    {step && <span style={{ fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--text-subtle)', fontWeight: 600 }}>Passo {step} de 3</span>}
    <CardHeader title={title} subtitle={hint} />
  </div>;
  const nationalOn = form.ufs.length === BPF_UFS.length;
  const kwList = window.VxNorm.list(form.keywords), exList = window.VxNorm.list(form.excludeKeywords);
  const whereSummary = reach || ufsText || 'Brasil inteiro (nenhuma cidade, raio ou UF marcados)';
  const valueSummary = [form.minValue || form.maxValue ? (bpfMoney(form.minValue) || 'sem mínimo') + ' a ' + (bpfMoney(form.maxValue) || 'sem teto') : 'qualquer valor', form.modalidades.length ? form.modalidades.length + ' modalidade(s)' : 'todas as modalidades'].join(' · ');
  const grid = { display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(220px,1fr))', gap: 12 };

  return <BlockGrid.Auto id="capability-profiles">
    <PageHeader eyebrow="Inteligência · sua empresa" title="Perfil do licitante"
      description="Conte onde sua empresa atua, o que fornece e em que faixa de valor disputa. O Vértice cruza esse perfil com as licitações abertas do PNCP e mostra recomendações com o motivo de cada uma."
      actions={<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        <Button variant="secondary" icon="ph-play" onClick={() => window.VxTutorials.open('perfil')}>Como preencher</Button>
        <Button variant="secondary" icon="ph-signpost" onClick={() => setTour(true)}>Tour guiado</Button>
        <Button variant="secondary" onClick={() => go('recomendacoes')}>Ver recomendações</Button>
      </div>} />
    {!loading && !rows.length && !created && <Alert tone="info" title="Primeira vez aqui? São 3 partes e leva uns 3 minutos">
      Preencha <strong>Onde você atende</strong>, <strong>O que você fornece</strong> e <strong>Como você disputa</strong> e clique em Criar perfil. O restante é opcional e pode ficar para depois.
      {' '}<a href="#" onClick={e => { e.preventDefault(); window.VxTutorials.open('perfil'); }} style={{ color: 'var(--text-link)' }}>Ver o tutorial</a> ou <a href="#" onClick={e => { e.preventDefault(); setTour(true); }} style={{ color: 'var(--text-link)' }}>fazer o tour guiado</a>.
    </Alert>}
    {created && <Alert tone="success" title="Perfil criado. Próximo passo: suas recomendações">
      O Vértice já cruzou o seu perfil com as licitações abertas do PNCP. <a href="#" onClick={e => { e.preventDefault(); go('recomendacoes', { id: selected }); }} style={{ color: 'var(--text-link)', fontWeight: 600 }}>Ver minhas recomendações</a>
    </Alert>}
    {missing && <Alert tone="warning" title="Campos novos ainda não ativados no banco">Falta aplicar as migrations 0095 e 0096. Até lá, cidade-base, raio e palavras-chave não são gravados.</Alert>}
    {rows.length > 1 && <Card variant="flat" padding={16}><div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
      {rows.map(r => <FilterChip key={r.id} label={r.name} selected={r.id === selected} onClick={() => open(r)} />)}
      <FilterChip label="+ Novo perfil" selected={!selected} onClick={() => open(null)} />
    </div></Card>}

    <Card variant="analysis" padding={24} gap={16}>
      {section('Empresa', 'Nome do perfil e dados de cadastro. O porte e os CNAEs ficam guardados para os próximos filtros (cota ME/EPP e atividade).')}
      <div style={grid}>
        <Input label="Nome do perfil" value={form.name} onChange={e => set('name', e.target.value)} placeholder="Perfil principal" />
        <Select label="Porte" options={BPF_PORTES} value={form.companySize} onChange={e => set('companySize', e.target.value)} />
        <Input label="CNAEs (separe por vírgula)" value={form.cnaes} onChange={e => set('cnaes', e.target.value)} placeholder="8121-4/00, 8129-0/00" />
      </div>
    </Card>

    <Card variant="analysis" padding={24} gap={16}>
      <span data-tour="onde" data-tour-parent="" style={{ display: 'none' }} />
      {section('Onde você atende', 'Use a cidade-base com um raio em km, marque UFs inteiras, ou os dois. Atende o país todo? Marque “Brasil inteiro”. Sem nada marcado, também vale o Brasil inteiro.', 1)}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(300px,1fr))', gap: 20, alignItems: 'start' }}>
        <div style={{ display: 'grid', gap: 14 }}>
          <div style={grid}>
            <Select label="UF da cidade-base" options={[{ value: '', label: 'Escolha' }, ...BPF_UFS.map(u => ({ value: u, label: u }))]} value={form.baseUf} onChange={e => setForm(s => ({ ...s, baseUf: e.target.value, baseMunicipio: '' }))} />
            <Select label="Cidade-base" disabled={!form.baseUf} options={[{ value: '', label: form.baseUf ? 'Escolha a cidade' : 'Escolha a UF antes' }, ...cities.map(c => ({ value: String(c.codigo_ibge), label: c.nome + (c.capital ? ' (capital)' : '') }))]} value={form.baseMunicipio} onChange={e => set('baseMunicipio', e.target.value)} />
          </div>
          <Input label="Raio de atendimento (km)" type="number" min="1" max="4500" value={form.radiusKm} onChange={e => set('radiusKm', e.target.value)} placeholder="Ex.: 150" hint="Distância em linha reta até a cidade do órgão." />
          <div style={{ display: 'grid', gap: 8 }}>
            <span style={{ fontSize: 13, color: 'var(--text-secondary)' }}>UFs inteiras em que você também atende</span>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              <FilterChip label="Brasil inteiro" selected={nationalOn} onClick={() => set('ufs', nationalOn ? [] : [...BPF_UFS])} />
              {BPF_UFS.map(u => <FilterChip key={u} label={u} selected={form.ufs.includes(u)} onClick={() => toggle('ufs', u)} />)}
            </div>
          </div>
          {(reach || ufsText) && <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{[reach, ufsText].filter(Boolean).join(' · ')}</span>}
        </div>
        <BidderReachMap geo={geo} loading={geoLoading} baseId={form.baseMunicipio} radiusKm={form.radiusKm} ufs={form.ufs} />
      </div>
    </Card>

    <Card variant="analysis" padding={24} gap={16}>
      <span data-tour="oque" data-tour-parent="" style={{ display: 'none' }} />
      {section('O que você fornece', 'Palavras que aparecem no objeto das licitações que interessam. Sem acento e sem diferença de maiúsculas.', 2)}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(300px,1fr))', gap: 20, alignItems: 'start' }}>
        <div style={{ display: 'grid', gap: 12 }}>
          <Input label="Palavras-chave (separe por vírgula)" value={form.keywords} onChange={e => set('keywords', e.target.value)} placeholder="limpeza, conservação, jardinagem" />
          {kwList.length > 0 && <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>{kwList.map(k => <span key={k} style={bpfChipStyle('ok')}>{k}</span>)}</div>}
          <Input label="Palavras a evitar" value={form.excludeKeywords} onChange={e => set('excludeKeywords', e.target.value)} placeholder="hospitalar, veículo" hint="Licitações com estas palavras não são recomendadas." />
          {exList.length > 0 && <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>{exList.map(k => <span key={k} style={bpfChipStyle('danger')}>{k}</span>)}</div>}
          <Input label="Setores" value={form.sectors} onChange={e => set('sectors', e.target.value)} placeholder="serviços, facilities" />
        </div>
        <BidderKeywordPreview keywords={form.keywords} exclude={form.excludeKeywords} />
      </div>
    </Card>

    <Card variant="analysis" padding={24} gap={16}>
      <span data-tour="como" data-tour-parent="" style={{ display: 'none' }} />
      {section('Como você disputa', 'Faixa de valor estimado e modalidades. Até 20% fora da faixa ainda aparece, com aviso.', 3)}
      <BidderValueRange min={form.minValue} max={form.maxValue} onMin={v => set('minValue', v)} onMax={v => set('maxValue', v)} />
      <div style={grid}>
        <Input label="Valor mínimo (R$)" type="number" min="0" value={form.minValue} onChange={e => set('minValue', e.target.value)} placeholder="50000" />
        <Input label="Valor máximo (R$)" type="number" min="0" value={form.maxValue} onChange={e => set('maxValue', e.target.value)} placeholder="2000000" />
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(220px,1fr))', gap: 8 }}>
        {BPF_MODALIDADES.map(m => <Checkbox key={m} label={m} checked={form.modalidades.includes(m)} onChange={() => toggle('modalidades', m)} />)}
      </div>
      <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{form.modalidades.length ? form.modalidades.length + ' modalidade(s) marcada(s).' : 'Nenhuma marcada: todas as modalidades entram.'}</span>
    </Card>

    <Card variant="analysis" padding={24} gap={16}>
      {section('Habilitação e capacidade', 'Usado no Go/No-Go de cada oportunidade.')}
      <div style={grid}>
        <Input label="Certidões e documentos válidos" value={form.validDocuments} onChange={e => set('validDocuments', e.target.value)} placeholder="CND federal, FGTS, CNDT, atestado de capacidade" />
        <Input label="Equipamentos" value={form.equipment} onChange={e => set('equipment', e.target.value)} />
        <Input label="Experiência (atestados)" value={form.experience} onChange={e => set('experience', e.target.value)} />
        <Input label="Capacidade de equipe (pessoas)" type="number" min="0" value={form.workforceCapacity} onChange={e => set('workforceCapacity', e.target.value)} />
      </div>
    </Card>

    <Card variant="flat" padding={20} gap={10}>
      <span style={{ fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--text-subtle)', fontWeight: 600 }}>Resumo do seu perfil</span>
      {[['Onde você atende', whereSummary, true], ['O que você fornece', kwList.length ? kwList.join(', ') + (exList.length ? ' · evita: ' + exList.join(', ') : '') : 'Sem palavras-chave: entra tudo da sua área de atuação', kwList.length > 0], ['Como você disputa', valueSummary, !!(form.minValue || form.maxValue || form.modalidades.length)]].map(([t, v, ok]) =>
        <div key={t} style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
          <i className={'ph ' + (ok ? 'ph-check-circle' : 'ph-circle')} style={{ fontSize: 20, color: ok ? 'var(--status-success)' : 'var(--text-subtle)', flex: 'none', marginTop: 1 }} />
          <div style={{ minWidth: 0 }}><div style={{ fontSize: 12.5, color: 'var(--text-muted)' }}>{t}</div><div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-primary)', marginTop: 2, wordBreak: 'break-word' }}>{v}</div></div>
        </div>)}
    </Card>

    <div data-tour="salvar" style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
      <Button onClick={save} disabled={busy || loading}>{busy ? 'Salvando…' : selected ? 'Salvar perfil' : 'Criar perfil'}</Button>
      {selected && <Button variant="secondary" onClick={() => go('recomendacoes', { id: selected })}>Ver recomendações deste perfil</Button>}
      {selected && <Badge tone="success">Perfil ativo</Badge>}
    </div>
    <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>Estes dados são da sua empresa e ficam visíveis só para a sua organização.</span>
    {toast && <Toast>{toast}</Toast>}
    {tour && <GuidedTour onClose={() => setTour(false)} steps={[
      { sel: '[data-tour="onde"]', title: 'Onde você atende', text: 'Escolha a UF e a cidade-base e informe o raio em km. Se atende estados inteiros, marque as UFs. Sem nada marcado, vale o Brasil inteiro.' },
      { sel: '[data-tour="oque"]', title: 'O que você fornece', text: 'Digite as palavras que aparecem no objeto das licitações que interessam, separadas por vírgula. Em “Palavras a evitar”, ponha o que você não quer receber.' },
      { sel: '[data-tour="como"]', title: 'Como você disputa', text: 'Informe o valor mínimo e o máximo e marque as modalidades em que participa. Sem modalidade marcada, todas entram.' },
      { sel: '[data-tour="salvar"]', title: 'Salve o perfil', text: 'Clique em Criar perfil. As recomendações passam a usar esses dados na hora, e você pode ajustar quando quiser.' },
    ]} />}
  </BlockGrid.Auto>;
}
window.CapabilityProfilesScreen = CapabilityProfilesScreen;
