function HubScreen({ go }) {
  const { PageHeader, Tag, Card, Badge, Input, Button, ProgressBar, Alert, Toast } = window.VRticeDesignSystem_d763eb;
  const [phase, setPhase] = React.useState('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 - SP', 'high', 'Exemplo fictício'],
    ['Modalidade', 'Concorrência 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 reset = () => { setPhase('upload'); setError(''); setPct(0); setInfo(null); setFields([]); setChecklist([]); };
  const startDemo = () => {
    setInfo({ name: 'Edital_Concorrencia_012-2026_Campinas.pdf', size: 0, pages: 0, ocrPages: 0, demo: true });
    setFields(SAMPLE_FIELDS);
    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('');
    setInfo({ name: file.name, size: file.size, pages: 0, ocrPages: 0, demo: false });
    setPhase('processing');
    try {
      const r = await window.VXEdital.readPdf(file, { 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 });
      setFields(r.fields.map(f => [f.label, f.value, f.confidence, f.source]));
      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 stepIdx = { 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 lowCount = fields.filter(f => f[2] === 'low').length;
  const file = info ? info.name : '';
  return (
    <BlockGrid.Auto id="hub">
      <PageHeader eyebrow="Intelligence Hub" title="Processar edital" description="Envie o PDF do edital. O Vértice lê o documento, extrai os dados principais e monta o checklist de habilitação." actions={
        <div style={{ display: 'flex', gap: 8 }}>{steps.map((s, i) => { const done = i < stepIdx, on = i === stepIdx; return (
          <div key={s} 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 === '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" onClick={e => { e.preventDefault(); inputRef.current && inputRef.current.click(); }} 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} type="file" accept="application/pdf,.pdf" onChange={pickFile} style={{ display: 'none' }} />
          <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).</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}>
            <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 === '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 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' && <div style={{ display: 'flex', flexWrap: 'wrap', gap: 24, alignItems: 'flex-start' }}>
        <Card variant="analysis" padding={32} gap={28} style={{ flex: '999 1 560px' }}>
          <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 EXTRAÍDOS</span>
              <span style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em' }}>Confira antes de salvar</span>
              <span style={{ fontSize: 14, color: 'var(--text-muted)' }}>Campos em amarelo tiveram baixa confiança na leitura. Clique em qualquer valor para editar.</span>
            </div>
            <span style={{ fontSize: 13, color: 'var(--text-secondary)', background: 'var(--overlay-05)', padding: '8px 12px', borderRadius: 10 }}>{file}</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(min(100%, 260px), 1fr))', gap: '20px 24px' }}>
            {fields.map(([l, v, c, src], i) => (
              <div key={l} style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}><span style={{ fontSize: 12, letterSpacing: '0.12em', color: 'var(--text-secondary)' }}>{l.toUpperCase()}</span><Badge variant="meta" tone={c === 'high' ? 'success' : 'warning'}>{c === 'high' ? 'Alta confiança' : 'Baixa confiança'}</Badge></div>
                <Input size="lg" value={v} state={c === 'low' ? 'warning' : undefined} onChange={e => setFields(fs => fs.map((f, j) => j === i ? [f[0], e.target.value, 'high', f[3]] : f))} />
                <span style={{ fontSize: 12, color: 'var(--text-subtle)' }}>{src}</span>
              </div>
            ))}
          </div>
        </Card>
        <div style={{ flex: '1 1 320px', display: 'flex', flexDirection: 'column', gap: 16 }}>
          {info && info.demo && <Alert tone="info" title="Exemplo fictício">Estes dados não vieram de um documento. Envie um PDF para ver a leitura real.</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 {fields.filter(f => f[2] === 'low').map(f => f[0].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. Clique para marcar os que a empresa já tem.' : 'Nenhum documento de habilitação foi reconhecido no texto. Confira o edital.'}</span>
            {checklist.map((c, i) => <div key={c.label} role="button" tabIndex={0} onClick={() => setChecklist(cs => cs.map((x, j) => j === i ? { ...x, have: !x.have } : x))} onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setChecklist(cs => cs.map((x, j) => j === i ? { ...x, have: !x.have } : x)); } }} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 14, cursor: 'pointer' }}><i className={'ph ' + (c.have ? 'ph-check-circle' : 'ph-circle-dashed')} style={{ fontSize: 18, color: c.have ? 'var(--status-success)' : 'var(--status-warning)' }} /><span style={{ flex: 1 }}>{c.label}</span>{c.page && <span style={{ fontSize: 12, color: 'var(--text-subtle)' }}>pág. {c.page}</span>}</div>)}
          </Card>
          <Button block onClick={() => go('score')}>Ir para Go/No-Go</Button>
          <Button variant="ghost" block onClick={reset}>Enviar outro edital</Button>
        </div>
      </div>}
      {toast && <Toast>{toast}</Toast>}
    </BlockGrid.Auto>
  );
}
window.HubScreen = HubScreen;
