const HUB_SOURCE_LABELS = { native_text: 'Texto do PDF', tesseract_ocr: 'OCR no navegador', deterministic_rule: 'Regra de extração', manual: 'Informado manualmente', edited_by_user: 'Editado por você' };
function hubSourceLabel(src) { return (src && HUB_SOURCE_LABELS[src]) || src || ''; }
// Uma única página por campo: a do trecho de evidência ou, na falta dela, a citada pela regra de leitura ("Página 4 · cabeçalho").
function hubFieldPage(f) {
  const ev = f[6];
  if (ev && Number.isInteger(ev.page) && ev.page > 0) return ev.page;
  const m = String(f[3] || '').match(/^P[áa]gina\s+(\d+)/i);
  return m ? Number(m[1]) : null;
}
// Descrição da origem sem repetir a página ("Página 4 · cabeçalho" -> "cabeçalho").
function hubSourceDescription(src) {
  return hubSourceLabel(src).replace(/^P[áa]gina\s+\d+\s*(?:[·\-–]\s*)?/i, '').trim();
}
// O estado da revisão humana tem precedência sobre a confiança do leitor: um campo corrigido não volta a ser "baixa confiança".
function hubFieldBadge(confidence, status, value) {
  if (status === 'edited_by_user') return { tone: 'accent', label: 'Editado por você' };
  if (status === 'user_confirmed') return { tone: 'success', label: 'Conferido' };
  if (hubFieldReviewed([null, value, confidence, null, null, status])) return { tone: 'success', label: 'Não consta no edital' };
  if (status === 'ambiguous' && !value) return { tone: 'warning', label: 'Vários valores encontrados' };
  if (status === 'not_found' || !value) return { tone: 'warning', label: 'Sem evidência' };
  return confidence === 'high' ? { tone: 'active', label: 'Sugerido · alta confiança' } : { tone: 'warning', label: 'Sugerido · baixa confiança' };
}
// Um campo conta como conferido quando a pessoa o confirmou, corrigiu ou afirmou que o edital não o define.
// "Não consta" é gravado como not_found com confiança 1 (o leitor grava not_found com confiança baixa).
function hubFieldReviewed(f) {
  return f[5] === 'user_confirmed' || f[5] === 'edited_by_user' || (f[5] === 'not_found' && !f[1] && f[2] === 'high');
}
// Valores vindos de página com OCR fraco nunca aparecem como alta confiança.
function hubEffectiveConfidence(f, pageStates) {
  const page = f[6] && f[6].page;
  const ps = page ? (pageStates || []).find(p => p.page === page) : null;
  if (ps && ps.extractionMethod === 'tesseract_ocr' && (ps.status === 'ocr_low_text' || (Number.isFinite(ps.confidence) && ps.confidence < 70))) return 'low';
  return f[2];
}
function hubOcrQuality(ps) {
  if (ps.status === 'ocr_low_text') return 'OCR com pouco texto legível';
  return Number.isFinite(ps.confidence) ? 'qualidade do OCR ' + Math.round(ps.confidence) + '%' : 'lida por OCR';
}
// Campos da revisão. Os essenciais aparecem sempre (vazios se o leitor ainda não os extrai); os opcionais a pessoa adiciona.
// As chaves seguem public.canonical_document_fields; ME/EPP ainda não tem chave canônica (field_key nulo, identificado pelo rótulo).
const HUB_FIELD_CATALOG = [
  { key: 'procurement_method', label: 'Modalidade', group: 'essential', column: 'Edital' },
  { key: 'procurement_number', label: 'Número da licitação', group: 'essential' },
  { key: 'process_number', label: 'Número do processo', group: 'essential' },
  { key: 'buyer_name', label: 'Órgão', group: 'essential', column: 'Órgão' },
  { key: 'buyer_city', label: 'Cidade', group: 'essential', column: 'Cidade' },
  { key: 'buyer_state', label: 'UF', group: 'essential' },
  { key: 'estimated_value', label: 'Valor estimado', group: 'essential', column: 'Valor' },
  { key: 'opening_datetime', label: 'Abertura da sessão', group: 'essential', aliases: ['Prazo'], column: 'Prazo' },
  { key: 'procurement_object', label: 'Objeto', group: 'essential', column: 'Objeto' },
  { key: 'judgment_criteria', label: 'Critério de julgamento', group: 'essential' },
  { key: 'clarification_deadline', label: 'Prazo para esclarecimentos', group: 'essential' },
  { key: 'challenge_deadline', label: 'Prazo para impugnação', group: 'essential' },
  { key: null, label: 'Participação ME/EPP', group: 'essential' },
  { key: 'site_visit_requirement', label: 'Visita técnica', group: 'essential' },
  { key: 'technical_qualification', label: 'Qualificação técnica', group: 'essential' },
  { key: 'economic_financial_qualification', label: 'Qualificação econômico-financeira', group: 'essential' },
  { key: 'minimum_bid_decrement', label: 'Intervalo mínimo de lances', group: 'optional' },
  { key: 'dispute_mode', label: 'Modo de disputa', group: 'optional' },
  { key: 'dispute_platform', label: 'Plataforma de disputa', group: 'optional' },
  { key: 'submission_deadline', label: 'Prazo final para propostas', group: 'optional' },
  { key: 'maximum_acceptable_price', label: 'Preço máximo aceitável', group: 'optional' },
  { key: 'lot_count', label: 'Quantidade de lotes', group: 'optional' },
  { key: 'delivery_deadline', label: 'Prazo de entrega/execução', group: 'optional' },
  { key: 'delivery_location', label: 'Local de entrega/execução', group: 'optional' },
  { key: 'contract_term', label: 'Vigência contratual', group: 'optional' },
  { key: 'proposal_validity', label: 'Validade da proposta', group: 'optional' },
  { key: 'sample_requirement', label: 'Amostra ou prova de conceito', group: 'optional' },
  { key: 'performance_guarantee', label: 'Garantia de execução', group: 'optional' },
  { key: 'payment_terms', label: 'Condições de pagamento', group: 'optional' },
  { key: 'penalties', label: 'Multas e sanções', group: 'optional' },
  { key: 'appeal_deadline', label: 'Prazo recursal', group: 'optional' }
];
function hubCatalogEntry(f) {
  return HUB_FIELD_CATALOG.find(c => (c.key && c.key === f[4]) || (!c.key && c.label === f[0]) || (!f[4] && (c.label === f[0] || (c.aliases || []).includes(f[0]))));
}
function hubFieldLabel(f) { const c = hubCatalogEntry(f); return c ? c.label : f[0]; }
function hubFieldGroup(f) { const c = hubCatalogEntry(f); return c ? c.group : 'optional'; }
function hubCatalogOrder(f) { const c = hubCatalogEntry(f); const i = c ? HUB_FIELD_CATALOG.indexOf(c) : -1; return i < 0 ? 999 : i; }
// Garante todos os essenciais na ordem do catálogo, sem perder nada que o leitor ou a pessoa já tenha registrado.
function hubArrangeFields(fields) {
  const rest = (fields || []).slice();
  const out = [];
  HUB_FIELD_CATALOG.forEach(c => {
    const idx = rest.findIndex(f => hubCatalogEntry(f) === c);
    if (idx >= 0) out.push(rest.splice(idx, 1)[0]);
    else if (c.group === 'essential') out.push([c.label, '', 'low', 'Leitura automática ainda não disponível para este campo', c.key, 'not_found', null]);
  });
  return out.concat(rest);
}
// A pessoa decide o que aparece no formulário: "×" oculta (vai para o pool) e clicar numa tag do pool adiciona.
// Sem escolha da pessoa, essenciais aparecem sempre e opcionais só quando têm valor, foram conferidos ou são ambíguos.
function hubFieldVisible(f, added, hidden) {
  const c = hubCatalogEntry(f);
  if (!c) return true;
  if ((hidden || []).includes(c.label)) return false;
  if ((added || []).includes(c.label)) return true;
  if (c.group === 'essential') return true;
  return Boolean(f[1]) || hubFieldReviewed(f) || f[5] === 'ambiguous';
}
// Pool: campos do catálogo fora do formulário. Essenciais primeiro, depois adicionais; cada grupo em ordem alfabética.
function hubPoolFields(fields, added, hidden) {
  const inForm = c => (fields || []).some(f => hubCatalogEntry(f) === c && hubFieldVisible(f, added, hidden));
  const byName = (a, b) => a.label.localeCompare(b.label, 'pt-BR');
  const pool = HUB_FIELD_CATALOG.filter(c => !inForm(c));
  return pool.filter(c => c.group === 'essential').sort(byName).concat(pool.filter(c => c.group !== 'essential').sort(byName));
}
// Soma dos valores de lotes/itens distintos. É só uma opção calculada para a pessoa escolher; nunca é sugerida sozinha.
function hubSumParts(candidates) {
  const parts = (candidates || []).filter(c => c.kind === 'part');
  const byLabel = new Map();
  parts.forEach(c => { if (!byLabel.has(c.label)) byLabel.set(c.label, c); });
  if (byLabel.size < 2) return null;
  let cents = 0;
  for (const c of byLabel.values()) {
    const digits = String(c.value).replace(/[^\d,]/g, '').split(',');
    if (digits.length !== 2) return null;
    cents += Number(digits[0]) * 100 + Number(digits[1].padEnd(2, '0').slice(0, 2));
  }
  const reais = Math.floor(cents / 100).toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.');
  return { value: 'R$ ' + reais + ',' + String(cents % 100).padStart(2, '0'), count: byLabel.size };
}
// Avisos de formato não bloqueiam: apenas indicam que o valor talvez não seja aproveitado no Go/No-Go.
function hubFieldHint(canonicalKey, value) {
  const v = String(value || '').trim();
  if (!v) return '';
  if (canonicalKey === 'estimated_value' && typeof gngParseBrl === 'function' && gngParseBrl(v) === null) return 'Valor não reconhecido como reais (ex.: R$ 3.658.050,00).';
  if (canonicalKey === 'opening_datetime' && !/\d{1,2}\/\d{1,2}\/\d{2,4}/.test(v)) return 'Data não reconhecida (ex.: 31/07/2019 às 14h).';
  return '';
}

function HubScreen({ go, params = {} }) {
  const { PageHeader, Tag, Card, Badge, Input, Button, ProgressBar, Alert, Toast } = window.VRticeDesignSystem_d763eb;
  const [phase, setPhase] = React.useState(params.reopenAnalysis ? 'loading' : 'upload');
  const [pct, setPct] = React.useState(0);
  const [stage, setStage] = React.useState('load');
  const [toast, setToast] = React.useState('');
  const [error, setError] = React.useState('');
  const [drag, setDrag] = React.useState(false);
  const [info, setInfo] = React.useState(null); // { name, size, pages, ocrPages, demo }
  const [checklist, setChecklist] = React.useState([]);
  const [progressNote, setProgressNote] = React.useState('');
  const inputRef = React.useRef(null);
  const fmtSize = n => n >= 1048576 ? (n / 1048576).toFixed(1).replace('.', ',') + ' MB' : Math.max(1, Math.round(n / 1024)) + ' KB';
  const SAMPLE_FIELDS = [
    ['Órgão', 'Prefeitura Municipal de Campinas', 'high', 'Exemplo fictício'], ['Cidade', 'Campinas', 'high', 'Exemplo fictício'], ['UF', 'SP', 'high', 'Exemplo fictício'],
    ['Modalidade', 'Concorrência', 'high', 'Exemplo fictício'], ['Número da licitação', '012/2026', 'high', 'Exemplo fictício'], ['Prazo', '28/04/2026 às 09h', 'high', 'Exemplo fictício'],
    ['Valor estimado', 'R$ 3.500.000,00', 'low', 'Exemplo fictício'], ['Visita técnica', 'Facultativa', 'low', 'Exemplo fictício'],
  ];
  const [fields, setFields] = React.useState([]);
  const [identity, setIdentity] = React.useState(null);
  const [identityCorrection, setIdentityCorrection] = React.useState({ portalId: '', portalLabel: '', disputePlatform: '', buyerName: '', familyId: '', templateLabel: '', sourceUrl: '', notes: '' });
  const [pageStates, setPageStates] = React.useState([]);
  const [extractionStatus, setExtractionStatus] = React.useState('');
  const [selectedFile, setSelectedFile] = React.useState(null);
  const [analysisResult, setAnalysisResult] = React.useState(null);
  const [originalIdentity, setOriginalIdentity] = React.useState(null);
  const [savedAnalysisId, setSavedAnalysisId] = React.useState('');
  const [saving, setSaving] = React.useState(false);
  const [history, setHistory] = React.useState([]);
  const [historyLoading, setHistoryLoading] = React.useState(false);
  const [historyError, setHistoryError] = React.useState('');
  const [sourceUrlInput, setSourceUrlInput] = React.useState('');
  const [showOrigin, setShowOrigin] = React.useState(false);
  const [addedFields, setAddedFields] = React.useState([]);
  // Campos que a pessoa tirou do formulário (vão para o pool). Guardado só neste navegador; não afeta a análise salva.
  const [hiddenFields, setHiddenFields] = React.useState(() => { try { const v = JSON.parse(localStorage.getItem('vx-hub-hidden-fields') || '[]'); return Array.isArray(v) ? v : []; } catch (e) { return []; } });
  const [fieldNote, setFieldNote] = React.useState('');
  const pendingFocus = React.useRef(null);
  const saveHidden = next => { setHiddenFields(next); try { if (next.length) localStorage.setItem('vx-hub-hidden-fields', JSON.stringify(next)); else localStorage.removeItem('vx-hub-hidden-fields'); } catch (e) {} };
  const removeFromForm = f => {
    const label = hubFieldLabel(f);
    saveHidden(hiddenFields.includes(label) ? hiddenFields : hiddenFields.concat(label));
    setAddedFields(a => a.filter(x => x !== label));
    setFieldNote(label + ' removido do formulário. Está disponível no pool de campos.');
    pendingFocus.current = { pool: true };
  };
  const ensureFieldRef = React.useRef(null);
  const resetLayout = () => { saveHidden([]); setAddedFields([]); setFieldNote('Formulário restaurado ao padrão.'); };
  React.useEffect(() => {
    const t = pendingFocus.current;
    if (!t) return;
    pendingFocus.current = null;
    const el = t.pool ? document.getElementById('vx-field-pool') : document.querySelector('[data-vx-field="' + t.label + '"] input');
    if (el) el.focus();
  });
  // URL local (blob) do próprio PDF da pessoa, para abrir a página de onde o valor saiu. O arquivo não sai do navegador.
  const [pdfUrl, setPdfUrl] = React.useState('');
  React.useEffect(() => {
    if (!selectedFile || typeof URL === 'undefined' || !URL.createObjectURL) { setPdfUrl(''); return; }
    const url = URL.createObjectURL(selectedFile);
    setPdfUrl(url);
    return () => URL.revokeObjectURL(url);
  }, [selectedFile]);
  const pdfPageLink = (page, label, text) => pdfUrl && page ? <a href={pdfUrl + '#page=' + page} target="_blank" rel="noopener noreferrer" aria-label={label + ': abrir o PDF na página ' + page + ' (nova aba)'} style={{ fontSize: 12, color: 'var(--text-accent)', textDecoration: 'underline', whiteSpace: 'nowrap' }}>{text || 'Abrir no PDF, página ' + page}</a> : null;
  const [draft, setDraft] = React.useState({ status: '', at: null, error: '' });
  const dirtyFields = React.useRef(new Set());
  const dirtyChecklist = React.useRef(false);
  const autoSaveTried = React.useRef(false);
  const refreshHistory = async () => {
    if (!window.VxDocumentIntelligence || !window.VxDocumentIntelligence.listAnalyses) return;
    setHistoryLoading(true);
    setHistoryError('');
    const result = await window.VxDocumentIntelligence.listAnalyses({ limit: 30 });
    setHistoryLoading(false);
    if (result.error) { setHistoryError(result.error); return; }
    setHistory(result.data || []);
  };
  const openSavedAnalysis = async analysisId => {
    setHistoryLoading(true); setError('');
    const result = await window.VxDocumentIntelligence.loadAnalysis(analysisId);
    setHistoryLoading(false);
    if (result.error) { setError(result.error); if (phase === 'loading') setPhase('upload'); return; }
    const d = result.data;
    setSelectedFile(d.file); setInfo({ name: d.analysis.document_name, size: d.analysis.file_size_bytes, pages: (d.pageStates || []).length, ocrPages: (d.pageStates || []).filter(p => p.extractionMethod === 'tesseract_ocr').length, demo: false });
    setIdentity(d.identity); setOriginalIdentity(d.identity); setFields(hubArrangeFields(d.fields)); setAddedFields([]); setChecklist(d.checklist);
    setPageStates(d.pageStates); setExtractionStatus(d.analysis.extraction_status);
    setAnalysisResult({ identity: d.identity, pages: (d.pageStates || []).length, pageStates: d.pageStates, extractionStatus: d.analysis.extraction_status });
    setSavedAnalysisId(d.analysis.id);
    dirtyFields.current = new Set(); dirtyChecklist.current = false; autoSaveTried.current = true;
    setDraft({ status: 'saved', at: null, error: '' });
    setIdentityCorrection({ portalId: d.identity?.portal?.id || '', portalLabel: d.identity?.portal?.label || '', disputePlatform: d.identity?.disputePlatform?.label || '', buyerName: d.identity?.buyer?.value || d.analysis.buyer_name || '', familyId: d.identity?.documentFamily?.id || '', templateLabel: d.identity?.template?.label || '', sourceUrl: d.identity?.sourceUrl || '', notes: '' });
    setPhase('review');
  };
  React.useEffect(() => { refreshHistory(); if (params.reopenAnalysis) openSavedAnalysis(params.reopenAnalysis); }, []);
  const reset = () => { setPhase('upload'); setError(''); setPct(0); setInfo(null); setFields([]); setChecklist([]); setIdentity(null); setIdentityCorrection({ portalId: '', portalLabel: '', disputePlatform: '', buyerName: '', familyId: '', templateLabel: '', sourceUrl: '', notes: '' }); setPageStates([]); setExtractionStatus(''); setSelectedFile(null); setAnalysisResult(null); setOriginalIdentity(null); setSavedAnalysisId(''); setSaving(false); setSourceUrlInput(''); setShowOrigin(false); setAddedFields([]); setDraft({ status: '', at: null, error: '' }); dirtyFields.current = new Set(); dirtyChecklist.current = false; autoSaveTried.current = false; };
  const startDemo = () => {
    setSelectedFile(null); setAnalysisResult(null); setOriginalIdentity(null); setSavedAnalysisId('');
    setInfo({ name: 'Edital_Concorrencia_012-2026_Campinas.pdf', size: 0, pages: 0, ocrPages: 0, demo: true });
    setIdentity({ portal: { label: 'Não identificado', status: 'unknown' }, buyer: { value: 'Exemplo fictício' }, documentFamily: { label: 'Edital', status: 'suggested' }, template: { label: 'Modelo demonstrativo', status: 'suggested' }, recognizerVersion: 'demo' });
    setFields(hubArrangeFields(SAMPLE_FIELDS)); setAddedFields([]);
    setChecklist(['CND Federal', 'Certidão de FGTS', 'CND Trabalhista', 'Atestado de capacidade técnica', 'Balanço patrimonial'].map(label => ({ label, page: null, have: false })));
    setPhase('review');
  };
  const handleFile = async file => {
    if (!file) return;
    setError(''); setPct(0); setStage('load'); setProgressNote('');
    setSelectedFile(file); setAnalysisResult(null); setOriginalIdentity(null); setSavedAnalysisId('');
    dirtyFields.current = new Set(); dirtyChecklist.current = false; autoSaveTried.current = false; setDraft({ status: '', at: null, error: '' });
    setInfo({ name: file.name, size: file.size, pages: 0, ocrPages: 0, demo: false });
    setPhase('processing');
    try {
      // Mesmo PDF já analisado: reabre a análise salva sem refazer a leitura/OCR.
      const known = await window.VxDocumentIntelligence?.findExistingByFile?.(file, window.VXEdital.RECOGNIZER_VERSION);
      if (known?.data?.analysisId) {
        await openSavedAnalysis(known.data.analysisId);
        setToast('Este PDF já foi analisado em ' + new Date(known.data.createdAt).toLocaleDateString('pt-BR') + '. A análise salva foi reaberta, sem refazer a leitura.');
        return;
      }
      const r = await window.VXEdital.readPdf(file, { sourceUrl: sourceUrlInput.trim(), onProgress: e => {
        setStage(e.stage); setPct(e.pct);
        if (e.stage === 'read') setProgressNote('Lendo página ' + e.page + ' de ' + e.total);
        else if (e.stage === 'ocr') setProgressNote('OCR da página ' + e.page + ' de ' + e.total + ' (documento escaneado)');
        else setProgressNote('');
      } });
      setInfo({ name: r.fileName, size: r.size, pages: r.pages, ocrPages: r.ocrPages, scannedPages: r.scannedPages, demo: false });
      setAnalysisResult(r);
      setOriginalIdentity(r.identity || null);
      setIdentity(r.identity || null);
      setIdentityCorrection({ portalId: r.identity?.portal?.id || '', portalLabel: r.identity?.portal?.label || '', disputePlatform: '', buyerName: r.identity?.buyer?.value || '', familyId: r.identity?.documentFamily?.id || '', templateLabel: r.identity?.template?.label || '', sourceUrl: '', notes: '' });
      setPageStates(r.pageStates || []);
      setExtractionStatus(r.extractionStatus || 'unknown');
      setFields(hubArrangeFields(r.fields.map(f => [f.label, f.value, f.confidence === 'high' ? 'high' : 'low', f.source, f.canonicalKey || null, f.status || 'suggested', f.evidence || null]))); setAddedFields([]);
      setChecklist(r.checklist.map(c => ({ ...c, have: false })));
      setPct(100);
      setTimeout(() => setPhase('review'), 300);
    } catch (e) {
      setError(String(e && e.message || e));
      setPhase('upload');
    }
  };
  const pickFile = e => { const f = e.target.files && e.target.files[0]; e.target.value = ''; handleFile(f); };
    const lastPersistError = React.useRef('');
  const failPersist = msg => { lastPersistError.current = msg || ''; setError(msg || ''); };
  const persistAnalysis = async (nextIdentity, correctionNote = '', nextFields = fields, opts = {}) => {
    if (info?.demo) return true;
    if (savedAnalysisId) {
      setSaving(true); setError(''); lastPersistError.current = '';
      const updated = await window.VxDocumentIntelligence.updateAnalysisFields({ analysisId: savedAnalysisId, fields: nextFields, previousIdentity: originalIdentity, identity: nextIdentity, checklist, correctionNote });
      setSaving(false);
      if (updated.error) { failPersist(updated.error); return false; }
      setOriginalIdentity(nextIdentity); setDraft({ status: 'saved', at: new Date(), error: '' }); setToast('Alterações salvas e registradas na auditoria.');
      return savedAnalysisId || true;
    }
    if (!selectedFile || !analysisResult) { failPersist('Selecione e processe um PDF antes de salvar.'); return false; }
    if (!window.VxDocumentIntelligence || typeof window.VxDocumentIntelligence.saveAnalysis !== 'function') {
      failPersist('O módulo seguro de persistência documental não foi carregado. Atualize a página e tente novamente.');
      return false;
    }
    setSaving(true); setError(''); lastPersistError.current = '';
    if (opts.auto) setDraft({ status: 'saving', at: null, error: '' });
    const saved = await window.VxDocumentIntelligence.saveAnalysis({
      file: selectedFile,
      result: analysisResult,
      identity: nextIdentity,
      previousIdentity: originalIdentity || analysisResult.identity,
      correctionNote,
      fields: nextFields,
      checklist
    });
    setSaving(false);
    if (saved.error) {
      if (opts.auto) { lastPersistError.current = saved.error; setDraft({ status: 'error', at: null, error: saved.error }); return false; }
      failPersist(saved.error); return false;
    }
    if (saved.data.existing) {
      const when = saved.data.existingCreatedAt ? new Date(saved.data.existingCreatedAt).toLocaleDateString('pt-BR') : '';
      await openSavedAnalysis(saved.data.analysisId);
      setToast('Este edital já foi analisado' + (when ? ' em ' + when : '') + '. Abrimos a análise existente em vez de criar outra.');
      return saved.data.analysisId;
    }
    setSavedAnalysisId(saved.data.analysisId);
    if (saved.data.fieldIds) setFields(fs => fs.map((f, i) => saved.data.fieldIds[i] ? [f[0], f[1], f[2], f[3], f[4], f[5], f[6], saved.data.fieldIds[i]] : f));
    refreshHistory();
    setDraft({ status: 'saved', at: new Date(), error: '' });
    if (!opts.auto) setToast('Análise salva com segurança na organização ativa.');
    return saved.data.analysisId || true;
  };
  // Ações de revisão por campo. Cada ação marca o campo para a gravação automática do rascunho.
  const updateField = (i, value) => { dirtyFields.current.add(i); setFields(fs => fs.map((f, j) => j === i ? [f[0], value, f[2], f[3], f[4], 'edited_by_user', f[6], f[7]] : f)); };
  const confirmField = i => { dirtyFields.current.add(i); setFields(fs => fs.map((f, j) => j === i ? [f[0], f[1], f[2], f[3], f[4], f[1] ? 'user_confirmed' : f[5], f[6], f[7]] : f)); };
  const markAbsent = i => { dirtyFields.current.add(i); setFields(fs => fs.map((f, j) => j === i ? [f[0], '', 'high', f[3], f[4], 'not_found', f[6], f[7]] : f)); };
  const chooseCandidate = (i, c) => { dirtyFields.current.add(i); setFields(fs => fs.map((f, j) => j === i ? [f[0], c.value, f[2], f[3], f[4], 'user_confirmed', { ...(f[6] || {}), page: c.page || (f[6] && f[6].page) || null, excerpt: c.context || (f[6] && f[6].excerpt) || '' }, f[7]] : f)); };
  const ensureField = c => setFields(fs => fs.some(f => hubCatalogEntry(f) === c) ? fs : fs.concat([[c.label, '', 'low', 'Adicionado por você', c.key, 'not_found', null]]));
  ensureFieldRef.current = ensureField;
  const addField = label => {
    const c = HUB_FIELD_CATALOG.find(x => x.label === label);
    if (!c) return;
    // O campo só vira definitivo quando a pessoa informa e confirma o valor; vazio, não é gravado.
    saveHidden(hiddenFields.filter(x => x !== label));
    setAddedFields(a => a.includes(label) ? a : a.concat(label));
    setFields(fs => fs.some(f => hubCatalogEntry(f) === c) ? fs : fs.concat([[c.label, '', 'low', 'Adicionado por você', c.key, 'not_found', null]]));
    setFieldNote(label + ' adicionado ao formulário.');
    pendingFocus.current = { label };
  };
  const toggleChecklist = i => { dirtyChecklist.current = true; setChecklist(cs => cs.map((x, j) => j === i ? { ...x, have: !x.have } : x)); };
  // Grava só os campos alterados desde a última gravação, para não repetir registros de auditoria.
  const flushDraft = async () => {
    if (!savedAnalysisId || info?.demo || !window.VxDocumentIntelligence) return true;
    const fresh = [...dirtyFields.current].filter(i => fields[i] && !fields[i][7]);
    if (fresh.length && window.VxDocumentIntelligence.addAnalysisFields) {
      fresh.forEach(i => dirtyFields.current.delete(i));
      setDraft(d => ({ ...d, status: 'saving', error: '' }));
      const added = await window.VxDocumentIntelligence.addAnalysisFields({ analysisId: savedAnalysisId, fields: fresh.map(i => fields[i]) });
      if (added.error) { fresh.forEach(i => dirtyFields.current.add(i)); setDraft({ status: 'error', at: null, error: added.error }); return false; }
      setFields(fs => fs.map((f, i) => { const k = fresh.indexOf(i); return k >= 0 && added.data.fieldIds[k] ? [f[0], f[1], f[2], f[3], f[4], f[5], f[6], added.data.fieldIds[k]] : f; }));
    }
    const idx = [...dirtyFields.current].filter(i => fields[i] && fields[i][7]);
    if (!idx.length && !dirtyChecklist.current) { if (fresh.length) setDraft({ status: 'saved', at: new Date(), error: '' }); return true; }
    idx.forEach(i => dirtyFields.current.delete(i)); dirtyChecklist.current = false;
    setDraft(d => ({ ...d, status: 'saving', error: '' }));
    const r = await window.VxDocumentIntelligence.updateAnalysisFields({ analysisId: savedAnalysisId, fields: idx.map(i => fields[i]), previousIdentity: originalIdentity, identity, checklist, correctionNote: '' });
    if (r.error) { idx.forEach(i => dirtyFields.current.add(i)); setDraft({ status: 'error', at: null, error: r.error }); return false; }
    setDraft({ status: 'saved', at: new Date(), error: '' });
    return true;
  };
  React.useEffect(() => {
    if (phase !== 'review' || info?.demo || savedAnalysisId || autoSaveTried.current || !analysisResult || !selectedFile) return;
    autoSaveTried.current = true;
    persistAnalysis(identity, '', fields, { auto: true }).catch(e => setDraft({ status: 'error', at: null, error: (e && e.message) || 'Falha inesperada ao salvar.' }));
  }, [phase, savedAnalysisId, analysisResult]);
  React.useEffect(() => {
    if (!savedAnalysisId || (!dirtyFields.current.size && !dirtyChecklist.current)) return;
    const t = setTimeout(() => { flushDraft(); }, 1200);
    return () => clearTimeout(t);
  }, [fields, checklist, savedAnalysisId]);
  // A navegação nunca depende do resultado da gravação: se salvar falhar (ou lançar), os campos revisados seguem
  // para o Go/No-Go e o aviso de falha aparece lá.
  const goToGoNoGo = async () => {
    let persistenceResult = savedAnalysisId || false;
    let persistenceError = '';
    if (savedAnalysisId) { try { if (!(await flushDraft())) persistenceError = 'as últimas alterações não foram gravadas'; } catch (e) { persistenceError = 'as últimas alterações não foram gravadas'; } }
    if (!info?.demo && !savedAnalysisId) {
      const generic = identity && identity.status === 'suggested'
        ? { ...identity, status: 'unknown', portal: { ...(identity.portal || {}), id: null, label: 'Origem não identificada', status: 'unknown' }, template: { ...(identity.template || {}), id: null, label: 'Modelo genérico', status: 'unknown' } }
        : identity;
      try {
        persistenceResult = await persistAnalysis(generic, 'Análise encaminhada ao Go/No-Go sem confirmação explícita da origem; usar apenas os campos e evidências revisados.');
      } catch (e) {
        persistenceResult = false; setSaving(false);
        persistenceError = (e && e.message) || 'Falha inesperada ao salvar.';
      }
    }
    const context = {
      fileName: info?.name || 'Edital processado',
      analysisId: typeof persistenceResult === 'string' ? persistenceResult : savedAnalysisId || null,
      persistenceSaved: Boolean(persistenceResult && !info?.demo),
      persistenceError: persistenceResult ? persistenceError : (persistenceError || lastPersistError.current || 'motivo não informado'),
      demo: Boolean(info?.demo),
      identity: identity || null,
      fields: fields.filter(f => hubFieldVisible(f, addedFields, hiddenFields)).map(f => ({ label: hubFieldLabel(f), value: f[1], confidence: f[2], source: [hubSourceDescription(f[3]), hubFieldPage(f) ? 'página ' + hubFieldPage(f) : ''].filter(Boolean).join(' · '), canonicalKey: f[4] || null, status: f[5] || null, reviewed: hubFieldReviewed(f) })),
      checklist: checklist.map(c => ({ label: c.label, page: c.page, have: Boolean(c.have) }))
    };
    window.VxGoNoGoDocumentContext = context;
    try { sessionStorage.setItem('vx-go-no-go-document-context', JSON.stringify(context)); } catch (e) {}
    go('score', { documentAnalysis: true });
  };
  const confirmRecognition = async () => {
    if (!identity) return;
    const portalId = identityCorrection.portalId;
    const knownPortalLabels = { pncp: 'PNCP', compras_gov: 'Compras.gov.br', bec_sp: 'BEC/SP', licitacoes_e: 'Licitações-e', portal_compras_publicas: 'Portal de Compras Públicas' };
    const portalLabel = knownPortalLabels[portalId] || (portalId === 'none' ? 'Sem portal identificável' : identityCorrection.portalLabel.trim() || 'Origem não identificada');
    const portalAnswered = !!portalId && (portalId !== 'other' || !!identityCorrection.portalLabel.trim());
    const platformAnswered = !!identityCorrection.disputePlatform.trim();
    const buyerAnswered = !!identityCorrection.buyerName.trim();
    const familyAnswered = !!identityCorrection.familyId;
    const templateAnswered = !!identityCorrection.templateLabel.trim();
    const answered = portalAnswered || platformAnswered || buyerAnswered || familyAnswered || templateAnswered;
    const next = {
      ...identity,
      status: answered ? 'corrected_by_user' : 'unknown',
      portal: { ...(identity.portal || {}), id: knownPortalLabels[portalId] ? portalId : null, label: portalLabel, status: portalAnswered ? 'corrected_by_user' : 'unknown' },
      disputePlatform: platformAnswered ? { label: identityCorrection.disputePlatform.trim(), status: 'corrected_by_user' } : null,
      buyer: { ...(identity.buyer || {}), value: identityCorrection.buyerName.trim() || null, status: buyerAnswered ? 'corrected_by_user' : 'unknown' },
      documentFamily: { ...(identity.documentFamily || {}), id: identityCorrection.familyId || null, label: identityCorrection.familyId || 'Tipo não identificado', status: familyAnswered ? 'corrected_by_user' : 'unknown' },
      template: { ...(identity.template || {}), id: null, label: identityCorrection.templateLabel.trim() || 'Modelo não identificado', status: templateAnswered ? 'corrected_by_user' : 'unknown' },
      sourceUrl: identityCorrection.sourceUrl.trim() || sourceUrlInput.trim() || identity.sourceUrl || null,
      correction: identityCorrection
    };
    setIdentity(next);
    const ok = await persistAnalysis(next, identityCorrection.notes || '');
    if (ok) setShowOrigin(false);
  };

  const stepIdx = { loading: 2, upload: 0, processing: 1, review: 2 }[phase];
  const steps = ['Enviar PDF', 'Leitura', 'Revisão'];
  const order = ['load', 'read', 'ocr', 'identify', 'extract', 'checklist'];
  const phases = [['Leitura do PDF e OCR', ['load', 'read', 'ocr']], ['Identificação do órgão e objeto', ['identify']], ['Extração de prazos e valores', ['extract']], ['Checklist de habilitação', ['checklist']]];
  const visibleFields = fields.filter(f => hubFieldVisible(f, addedFields, hiddenFields));
  const lowFields = visibleFields.filter(f => f[1] && hubEffectiveConfidence(f, pageStates) === 'low' && !hubFieldReviewed(f));
  const lowCount = lowFields.length;
  const reviewedCount = visibleFields.filter(hubFieldReviewed).length;
  const pendingCount = visibleFields.length - reviewedCount;
  const poolFields = hubPoolFields(fields, addedFields, hiddenFields);
  const originSummary = [
    (identity?.portal?.label || 'Origem não identificada') + (identity?.portal?.status === 'suggested' ? ' (sugerida)' : ''),
    identity?.documentFamily?.label && identity.documentFamily.label !== 'Tipo não identificado' ? identity.documentFamily.label : '',
    identity?.disputePlatform?.label ? 'disputa em ' + identity.disputePlatform.label : ''
  ].filter(Boolean).join(' · ');
  const originLabel = { display: 'block', fontSize: 12, color: 'var(--text-muted)', marginBottom: 6 };
  const originControl = { width: '100%', padding: 10, borderRadius: 9, background: 'var(--surface-raised)', color: 'var(--text-primary)', border: '1px solid var(--overlay-14)' };
  const pageIncompleteCount = pageStates.filter(p => !['native_text', 'ocr_completed'].includes(p.status)).length;
  const file = info ? info.name : '';
  const historyCard = (
<Card variant="flat" padding={24} gap={14} style={{ marginTop: 20 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
        <div><span style={{ fontSize: 12, letterSpacing: '0.16em', color: 'var(--text-muted)' }}>HISTÓRICO DE ANÁLISES</span><div style={{ fontSize: 17, fontWeight: 600, marginTop: 5 }}>Documentos da organização</div></div>
        <Button variant="ghost" disabled={historyLoading} onClick={refreshHistory}>{historyLoading ? 'Carregando...' : 'Atualizar histórico'}</Button>
      </div>
      {history.length === 0 ? <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>O histórico aparecerá aqui após a primeira análise salva. Atualize para consultar registros existentes.</span> :
        history.map(item => <div key={item.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderTop: '1px solid var(--overlay-08)', flexWrap: 'wrap' }}>
          <div style={{ flex: '1 1 240px', minWidth: 0 }}><div style={{ fontSize: 14, fontWeight: 600 }}>{item.document_name}</div><div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{item.buyer_name || 'Órgão não identificado'} · {new Date(item.created_at).toLocaleString('pt-BR')}</div></div>
          <Badge variant="meta" tone={item.analysis_status === 'ready_for_review' ? 'success' : 'warning'}>{item.analysis_status === 'ready_for_review' ? 'Pronto para revisão' : item.analysis_status}</Badge>
          <Button size="sm" variant="secondary" disabled={historyLoading} onClick={() => openSavedAnalysis(item.id)}>Reabrir</Button>
        </div>)}
      {historyError && <Alert tone="danger" title="Histórico indisponível">{historyError}</Alert>}
    </Card>
  );
  return (
    <BlockGrid.Auto id="hub">
      <style>{'.vx-drop:focus-within { outline: 3px solid #38bdf8 !important; outline-offset: 4px; }'}</style>
      <PageHeader eyebrow="Intelligence Hub" title="Processar edital" description="Envie o PDF, confira os campos e o checklist e salve a análise. Depois, avance para Go/No-Go; decisões “Participar” e “Avaliar” aparecem em Oportunidades." actions={
        <div style={{ display: 'flex', gap: 8 }}>{steps.map((s, i) => { const done = i < stepIdx, on = i === stepIdx; return (
          <div key={s} aria-current={on ? 'step' : undefined} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 14px 8px 8px', borderRadius: 999, border: '1px solid ' + (on ? 'rgba(59,130,246,0.5)' : 'var(--overlay-10)'), background: on ? 'rgba(37,99,235,0.14)' : 'transparent' }}>
            <span style={{ width: 24, height: 24, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700, background: done ? '#34d399' : on ? '#2563eb' : 'var(--overlay-06)', color: done ? '#0a0f1c' : on ? '#ffffff' : 'var(--text-muted)' }}>{done ? '✓' : i + 1}</span>
            <span style={{ fontSize: 13, color: on || done ? 'var(--text-primary)' : 'var(--text-muted)' }}>{s}</span>
          </div>); })}</div>} />
      {phase === 'loading' && <Card variant="flat" padding={24} role="status"><span style={{ fontSize: 14, color: 'var(--text-secondary)' }}>Reabrindo a análise salva…</span></Card>}
      {phase === 'upload' && error && <Alert tone="danger" title="Não foi possível ler o edital">{error}</Alert>}
      {phase === 'upload' && <div style={{ display: 'flex', flexWrap: 'wrap', gap: 24, alignItems: 'flex-start' }}>
        <label className="vx-drop" onDragOver={e => { e.preventDefault(); setDrag(true); }} onDragLeave={() => setDrag(false)} onDrop={e => { e.preventDefault(); setDrag(false); handleFile(e.dataTransfer.files && e.dataTransfer.files[0]); }} style={{ minHeight: 380, flex: '999 1 480px', minWidth: 0, outline: drag ? '2px dashed #38bdf8' : undefined }}>
          <input ref={inputRef} aria-label="Selecionar arquivo PDF" type="file" accept="application/pdf,.pdf" onChange={pickFile} style={{ position: 'absolute', width: 1, height: 1, padding: 0, margin: -1, overflow: 'hidden', clip: 'rect(0, 0, 0, 0)', whiteSpace: 'nowrap', border: 0 }} />
          <span style={{ width: 64, height: 64, borderRadius: 18, background: 'rgba(37,99,235,0.18)', color: 'var(--action-selected-icon)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-mono)', fontSize: 15, fontWeight: 500 }}>PDF</span>
          <span style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em' }}>Arraste o edital aqui ou clique para selecionar</span>
          <span style={{ fontSize: 14, color: 'var(--text-muted)' }}>Um arquivo PDF, até 50 MB. PDFs escaneados também são lidos (OCR); páginas não processadas serão sinalizadas.</span>
          <span style={{ marginTop: 8, background: '#2563eb', color: '#ffffff', fontSize: 14, fontWeight: 600, padding: '12px 22px', borderRadius: 10 }}>Selecionar PDF</span>
        </label>
        <div style={{ flex: '1 1 320px', minWidth: 0, display: 'flex', flexDirection: 'column', gap: 16 }}>
          <Card variant="flat" padding={24} gap={16}>
            <label htmlFor="vx-source-url" style={{ fontSize: 12, letterSpacing: '0.16em', color: 'var(--text-muted)' }}>ORIGEM DA LICITAÇÃO</label>
            <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>Cole o link de onde você encontrou a oportunidade. Isso ajuda o reconhecimento, mas não é obrigatório.</span>
            <Input id="vx-source-url" aria-label="Link de origem da licitação" size="lg" value={sourceUrlInput} onChange={e => setSourceUrlInput(e.target.value)} placeholder="https://portal-da-licitacao.gov.br/..." />
            <span style={{ fontSize: 12, letterSpacing: '0.16em', color: 'var(--text-muted)' }}>O QUE SERÁ EXTRAÍDO</span>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>{['Órgão', 'Cidade', 'Modalidade', 'Prazo', 'Valor estimado', 'Visita técnica', 'Documentos obrigatórios'].map(t => <Tag key={t}>{t}</Tag>)}</div>
          </Card>
          <Card as="button" variant="flat" padding={24} gap={6} interactive onClick={startDemo} style={{ cursor: 'pointer', textAlign: 'left', color: 'var(--text-primary)', fontFamily: 'inherit' }}>
            <span style={{ fontSize: 12, letterSpacing: '0.16em', color: 'var(--text-accent)' }}>SEM ARQUIVO À MÃO?</span>
            <span style={{ fontSize: 16, fontWeight: 600 }}>Usar edital de exemplo</span>
            <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>Dados fictícios, só para conhecer a tela. Nenhum arquivo é lido.</span>
          </Card>
        </div>
      </div>}
      {phase === 'upload' && historyCard}
      {phase === 'processing' && <Card variant="analysis" padding={40} gap={32} style={{ maxWidth: 760 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <span style={{ width: 48, height: 48, borderRadius: 14, background: 'rgba(37,99,235,0.18)', color: 'var(--action-selected-icon)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-mono)', fontSize: 12 }}>PDF</span>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}><span style={{ fontSize: 16, fontWeight: 600 }}>{file}</span><span role="status" aria-live="polite" style={{ fontSize: 13, color: 'var(--text-muted)' }}>{info ? fmtSize(info.size) : ''}{progressNote ? ' · ' + progressNote : ''}</span></div>
          <span style={{ marginLeft: 'auto', fontFamily: 'var(--font-mono)', fontSize: 20 }}>{pct}%</span>
        </div>
        <ProgressBar value={pct} tone="gradient" />
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>{phases.map(([l, sts], i) => { const cur = order.indexOf(stage); const last = Math.max(...sts.map(x => order.indexOf(x))); const first = Math.min(...sts.map(x => order.indexOf(x))); const done = pct >= 100 || cur > last, on = !done && cur >= first; return (
          <div key={l} style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <span style={{ width: 22, height: 22, borderRadius: '50%', flex: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700, background: done ? '#34d399' : 'transparent', color: '#0a0f1c', border: '2px solid ' + (done ? '#34d399' : on ? '#38bdf8' : 'var(--overlay-14)'), boxSizing: 'border-box' }}>{done ? '✓' : ''}</span>
            <span style={{ fontSize: 15, color: done || on ? 'var(--text-primary)' : 'var(--text-subtle)' }}>{l}</span>
            <span style={{ marginLeft: 'auto', fontSize: 13, color: 'var(--text-muted)' }}>{done ? 'Concluído' : on ? 'Em andamento' : 'Aguardando'}</span>
          </div>); })}</div>
      </Card>}
      {phase === 'review' && <Card variant="analysis" padding={16} gap={10}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
            <span style={{ fontSize: 11, letterSpacing: '0.16em', color: 'var(--text-muted)' }}>{info && info.demo ? 'EDITAL DE EXEMPLO' : 'EDITAL EM REVISÃO'}</span>
            <strong style={{ fontSize: 15, overflowWrap: 'anywhere' }}>{file || 'Edital'}</strong>
          </div>
          <Button variant="secondary" onClick={reset}>Trocar PDF / enviar outro edital</Button>
        </div>
        {!(info && info.demo) && <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>Enviou o arquivo errado? Troque o PDF. A análise atual continua salva no histórico e você volta à tela inicial para enviar outro.</span>}
      </Card>}
      {phase === 'review' && <div style={{ display: 'flex', flexWrap: 'wrap', gap: 24, alignItems: 'flex-start' }}>
        <div style={{ flex: '999 1 560px', minWidth: 0, display: 'flex', flexDirection: 'column', gap: 16 }}>
          {info && info.demo ? <Alert tone="info" title="Exemplo fictício">Estes dados não vieram de um documento e não são salvos. Envie um PDF para ver a leitura real.</Alert> :
          <Card variant="flat" padding={20} gap={12}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4, minWidth: 0 }}>
                <span style={{ fontSize: 12, letterSpacing: '0.16em', color: 'var(--text-muted)' }}>ORIGEM DO DOCUMENTO</span>
                <span style={{ fontSize: 15, fontWeight: 600 }}>{originSummary}</span>
              </div>
              <Button variant="ghost" size="sm" aria-expanded={showOrigin} aria-controls="vx-origin-panel" onClick={() => setShowOrigin(v => !v)}>{showOrigin ? 'Fechar' : 'Alterar origem'}</Button>
            </div>
            {showOrigin && <div id="vx-origin-panel" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>Opcional. Não é preciso conhecer o portal para processar o edital; a correção ajuda o reconhecimento de documentos parecidos.</span>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 220px), 1fr))', gap: 14 }}>
                <div><label htmlFor="vx-portal-id" style={originLabel}>Portal de divulgação</label><select id="vx-portal-id" value={identityCorrection.portalId} onChange={e => setIdentityCorrection(v => ({ ...v, portalId: e.target.value }))} style={originControl}><option value="">Não sei / não identificado</option><option value="pncp">PNCP</option><option value="compras_gov">Compras.gov.br</option><option value="bec_sp">BEC/SP</option><option value="licitacoes_e">Licitações-e</option><option value="portal_compras_publicas">Portal de Compras Públicas</option><option value="other">Outro portal</option><option value="none">Sem portal identificável</option></select></div>
                {identityCorrection.portalId === 'other' && <div><label htmlFor="vx-portal-label" style={originLabel}>Nome do outro portal</label><input id="vx-portal-label" value={identityCorrection.portalLabel} onChange={e => setIdentityCorrection(v => ({ ...v, portalLabel: e.target.value }))} placeholder="Informe o nome, se souber" style={originControl}/></div>}
                <div><label htmlFor="vx-dispute-platform" style={originLabel}>Plataforma de disputa</label><input id="vx-dispute-platform" value={identityCorrection.disputePlatform} onChange={e => setIdentityCorrection(v => ({ ...v, disputePlatform: e.target.value }))} placeholder="Ex.: Compras.gov.br" style={originControl}/></div>
                <div><label htmlFor="vx-family-id" style={originLabel}>Tipo de documento</label><select id="vx-family-id" value={identityCorrection.familyId} onChange={e => setIdentityCorrection(v => ({ ...v, familyId: e.target.value }))} style={originControl}><option value="">Não identificado</option><option value="tender_notice">Edital</option><option value="terms_of_reference">Termo de Referência</option><option value="procurement_notice">Aviso de contratação</option><option value="technical_annex">Anexo técnico</option><option value="minutes">Ata</option><option value="contract">Contrato</option><option value="other">Outro</option></select></div>
                <div><label htmlFor="vx-corrected-source-url" style={originLabel}>Link de origem</label><input id="vx-corrected-source-url" value={identityCorrection.sourceUrl} onChange={e => setIdentityCorrection(v => ({ ...v, sourceUrl: e.target.value }))} placeholder="https://..." style={originControl}/></div>
                <div style={{ gridColumn: '1 / -1' }}><label htmlFor="vx-correction-notes" style={originLabel}>Observação</label><textarea id="vx-correction-notes" value={identityCorrection.notes} onChange={e => setIdentityCorrection(v => ({ ...v, notes: e.target.value }))} placeholder="Conte o que estava incorreto ou como você reconheceu o documento..." rows={2} style={originControl}/></div>
              </div>
              <div style={{ display: 'flex', justifyContent: 'flex-end' }}><Button disabled={saving} onClick={confirmRecognition}>{saving ? 'Salvando...' : 'Salvar origem'}</Button></div>
            </div>}
          </Card>}
          <Card variant="analysis" padding={28} gap={20}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16, flexWrap: 'wrap' }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <span style={{ fontSize: 12, letterSpacing: '0.16em', color: 'var(--text-muted)' }}>DADOS DO EDITAL</span>
                <span style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em' }}>Confira cada campo</span>
                <span style={{ fontSize: 14, color: 'var(--text-muted)' }}>Compare com o trecho do edital e confirme, corrija ou indique que o edital não define o campo. Só campos conferidos contam como verificados no Go/No-Go.</span>
              </div>
              <span role="status" aria-live="polite" style={{ fontSize: 13, fontWeight: 600, color: pendingCount ? 'var(--text-secondary)' : 'var(--status-success)', background: 'var(--overlay-05)', padding: '8px 12px', borderRadius: 10 }}>{reviewedCount} de {visibleFields.length} campos conferidos</span>
            </div>
            {[['essential', 'Campos essenciais'], ['optional', 'Campos adicionais']].map(([group, title]) => { const rows = fields.map((f, i) => [f, i]).filter(([f]) => hubFieldVisible(f, addedFields, hiddenFields) && hubFieldGroup(f) === group).sort((a, b) => hubCatalogOrder(a[0]) - hubCatalogOrder(b[0])); if (!rows.length && group === 'optional') return null; return (
            <section key={group} aria-label={title} style={{ display: 'flex', flexDirection: 'column', gap: 12, padding: 16, borderRadius: 16, background: 'var(--surface-inset)', border: '1px solid var(--border-subtle)' }}>
            <span style={{ fontSize: 12, letterSpacing: '0.16em', color: 'var(--text-muted)', textTransform: 'uppercase' }}>{title}</span>
            <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 12 }}>
              {rows.map(([f, i], ri) => { const [, v, , src, canonicalKey, fieldStatus, evidence] = f; const l = hubFieldLabel(f); const page = hubFieldPage(f); const conf = hubEffectiveConfidence(f, pageStates); const b = hubFieldBadge(conf, fieldStatus, v); const hint = hubFieldHint(canonicalKey, v); const ps = page ? (pageStates || []).find(p => p.page === page) : null; const reviewed = hubFieldReviewed(f); return (
                <li key={l} data-vx-field={hubCatalogEntry(f) ? hubCatalogEntry(f).label : undefined} style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: 16, borderRadius: 12, background: 'var(--surface-flat)', border: '1px solid var(--border-default)' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}><label htmlFor={'vx-extracted-field-' + i} style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-secondary)' }}>{l}{hubCatalogEntry(f) && hubCatalogEntry(f).column && <span title={'Este campo preenche a coluna ' + hubCatalogEntry(f).column + ' na tabela de Licitações'} style={{ marginLeft: 8, fontSize: 11, fontWeight: 500, color: 'var(--text-subtle)', border: '1px solid var(--border-subtle)', borderRadius: 999, padding: '1px 7px' }}>Licitações · {hubCatalogEntry(f).column}</span>}</label><span style={{ display: 'flex', alignItems: 'center', gap: 8 }}><Badge variant="meta" tone={b.tone}>{b.label}</Badge>{hubCatalogEntry(f) && <button type="button" onClick={() => removeFromForm(f)} aria-label={'Remover ' + l + ' do formulário'} title="Remover do formulário" style={{ border: '1px solid var(--overlay-14)', background: 'transparent', color: 'var(--text-secondary)', borderRadius: 8, fontSize: 14, lineHeight: 1, padding: '3px 9px', cursor: 'pointer' }}>×</button>}</span></div>
                  <Input id={'vx-extracted-field-' + i} size="lg" value={v} placeholder={fieldStatus === 'not_found' ? (reviewed ? 'Não consta no edital' : 'Não encontrado; preencha se o edital definir') : ''} state={!reviewed && (conf === 'low' || hint) ? 'warning' : undefined} aria-describedby={'vx-field-meta-' + i} onChange={e => updateField(i, e.target.value)} />
                  <div id={'vx-field-meta-' + i} style={{ display: 'flex', flexDirection: 'column', gap: 4, fontSize: 12, color: 'var(--text-subtle)' }}>
                    <span>{[hubSourceDescription(src), !pdfUrl && page ? 'página ' + page : '', ps && ps.extractionMethod === 'tesseract_ocr' ? hubOcrQuality(ps) : ''].filter(Boolean).join(' · ')}</span>
                    {hint && <span style={{ color: 'var(--status-warning)' }}>{hint}</span>}
                  </div>
                  {evidence && evidence.candidates && evidence.candidates.length > 0 && (() => { const sum = hubSumParts(evidence.candidates); return (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                      <label htmlFor={'vx-candidates-' + i} style={{ fontSize: 12, color: 'var(--text-secondary)' }}>{evidence.candidates.length === 1 ? 'Valor encontrado no edital' : evidence.candidates.length + ' valores encontrados no edital. Escolha o que corresponde ao ' + l.toLowerCase() + ':'}</label>
                      <select id={'vx-candidates-' + i} value="" onChange={e => { const k = e.target.value; if (k === 'sum' && sum) chooseCandidate(i, { value: sum.value, page: null, context: 'Soma calculada de ' + sum.count + ' lotes/itens' }); else if (k !== '') chooseCandidate(i, evidence.candidates[Number(k)]); }} style={{ width: '100%', padding: 10, borderRadius: 9, background: 'var(--surface-raised)', color: 'var(--text-primary)', border: '1px solid var(--overlay-14)' }}>
                        <option value="">Selecionar um valor encontrado…</option>
                        {evidence.candidates.map((c, k) => <option key={k} value={k}>{c.value} · {c.label} · página {c.page}</option>)}
                        {sum && <option value="sum">{sum.value} · soma de {sum.count} lotes/itens (calculada)</option>}
                      </select>
                      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>{[...new Set(evidence.candidates.map(c => c.page))].slice(0, 6).map(pg => <React.Fragment key={pg}>{pdfPageLink(pg, l)}</React.Fragment>)}</div>
                    </div>); })()}
                  {page && !(evidence && evidence.candidates && evidence.candidates.length) && pdfPageLink(page, l)}
                  {evidence && evidence.excerpt && <details><summary style={{ fontSize: 12, cursor: 'pointer', color: 'var(--text-secondary)' }}>Ver trecho do edital</summary><blockquote style={{ margin: '6px 0 0', padding: '8px 12px', borderLeft: '3px solid var(--overlay-14)', fontSize: 13, color: 'var(--text-secondary)', whiteSpace: 'pre-wrap' }}>{String(evidence.excerpt).replace(/\s+/g, ' ').trim()}</blockquote></details>}
                  {!reviewed && <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                    {v && <Button size="sm" variant="secondary" onClick={() => confirmField(i)} aria-label={'Confirmar ' + l}>Confirmar</Button>}
                    <Button size="sm" variant="ghost" onClick={() => markAbsent(i)} aria-label={l + ': não consta no edital'}>Não consta no edital</Button>
                  </div>}
                </li>); })}
            </ul>
            </section>); })}
            <section aria-labelledby="vx-field-pool" style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <span id="vx-field-pool" tabIndex={-1} style={{ fontSize: 12, letterSpacing: '0.16em', color: 'var(--text-muted)', textTransform: 'uppercase', outline: 'none' }}>Pool de campos</span>
              <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{poolFields.length ? 'Clique em um campo para adicioná-lo ao formulário. Campos adicionados só são gravados depois que você informar e confirmar o valor.' : 'Todos os campos disponíveis já estão no formulário.'}</span>
              {poolFields.length > 0 && <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {poolFields.map(c => { const found = fields.some(f => hubCatalogEntry(f) === c && f[1]); return (
                  <li key={c.label}><button type="button" onClick={() => addField(c.label)} aria-label={'Adicionar ' + c.label + ' ao formulário' + (c.group === 'essential' ? ' (campo essencial)' : '') + (found ? '; o leitor encontrou um valor' : '')} style={{ border: '1px solid var(--overlay-14)', background: 'var(--overlay-05)', color: 'var(--text-primary)', borderRadius: 999, fontSize: 13, padding: '6px 12px', cursor: 'pointer', fontWeight: c.group === 'essential' ? 600 : 400 }}>{found && <span aria-hidden="true" style={{ display: 'inline-block', width: 6, height: 6, borderRadius: 3, background: 'var(--status-success)', marginRight: 6, verticalAlign: 'middle' }} />}+ {c.label}</button></li>); })}
              </ul>}
              {(hiddenFields.length > 0 || addedFields.length > 0) && <button type="button" onClick={resetLayout} style={{ alignSelf: 'flex-start', border: 0, background: 'transparent', color: 'var(--text-accent)', fontSize: 12, textDecoration: 'underline', cursor: 'pointer', padding: 0 }}>Restaurar formulário padrão</button>}
            </section>
            <span role="status" aria-live="polite" style={{ position: 'absolute', width: 1, height: 1, overflow: 'hidden', clip: 'rect(0 0 0 0)', whiteSpace: 'nowrap' }}>{fieldNote}</span>
          </Card>
        </div>
        <div style={{ flex: '1 1 320px', minWidth: 0, display: 'flex', flexDirection: 'column', gap: 16 }}>
          {!info?.demo && <div role="status" aria-live="polite" style={{ fontSize: 13, color: 'var(--text-muted)' }}>{draft.status === 'saving' ? 'Salvando rascunho…' : draft.status === 'saved' ? 'Rascunho salvo na organização' + (draft.at ? ' às ' + draft.at.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' }) : '') + '.' : ''}</div>}
          {draft.status === 'error' && <Alert tone="danger" title="Rascunho não salvo">{draft.error} Você pode continuar revisando; tentaremos salvar de novo ao avaliar.</Alert>}
          {error && <Alert tone="danger" title="Não foi possível salvar a análise">{error}</Alert>}
          {pageIncompleteCount > 0 && <Alert tone="warning" title={pageIncompleteCount + ' página(s) precisam de revisão'}>O leitor não confirmou a extração integral de todas as páginas. A análise não deve ser tratada como completa.</Alert>}
          {info && !info.demo && info.ocrPages > 0 && <Alert tone="info" title="Leitura por OCR">{info.ocrPages} página(s) escaneada(s) foram lidas por OCR; confira os valores com o PDF original.</Alert>}
          {lowCount > 0 && <Alert tone="warning" title={lowCount + (lowCount === 1 ? ' campo com baixa confiança' : ' campos com baixa confiança')}>Confira {lowFields.map(f => hubFieldLabel(f).toLowerCase()).join(', ')} no PDF original.</Alert>}
          <Card variant="flat" padding={24} gap={14}>
            <span style={{ fontSize: 12, letterSpacing: '0.16em', color: 'var(--text-muted)' }}>CHECKLIST DE HABILITAÇÃO</span>
            <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{checklist.length ? 'Documentos citados no edital. Marque os que a empresa já tem.' : 'Nenhum documento de habilitação foi reconhecido no texto. Confira o edital.'}</span>
            {checklist.map((c, i) => <label key={c.label} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 14, cursor: 'pointer' }}><input type="checkbox" checked={Boolean(c.have)} onChange={() => toggleChecklist(i)} style={{ width: 18, height: 18, accentColor: 'var(--status-success)' }} /><span style={{ flex: 1 }}>{c.label}{c.page && !pdfUrl ? <span style={{ fontSize: 12, color: 'var(--text-subtle)' }}>{', página ' + c.page}</span> : null}</span>{c.page && pdfPageLink(c.page, c.label, 'pág. ' + c.page)}</label>)}
          </Card>
          {pendingCount > 0 && <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{pendingCount === 1 ? '1 campo ainda não foi conferido e chegará ao Go/No-Go marcado como não conferido.' : pendingCount + ' campos ainda não foram conferidos e chegarão ao Go/No-Go marcados como não conferidos.'}</span>}
          <Button block disabled={saving} onClick={goToGoNoGo}>{saving ? 'Salvando...' : 'Avaliar no Go/No-Go'}</Button>
          <Button variant="ghost" block onClick={reset}>Enviar outro edital</Button>
        </div>
      </div>}
      {phase === 'review' && historyCard}
      {toast && <Toast>{toast}</Toast>}
    </BlockGrid.Auto>
  );
}
window.HubScreen = HubScreen;
