// Caririaçu Guincho — Vistoria Digital Screen

const { useState: useStateV, useEffect: useEffectV } = React;

const CHECKLIST_ITEMS = [
  'CD/Mp3','Auto-Falantes','Calotas','Faróis','Alarme','Estepe',
  'Macaco','Extintor','Documentos','Tapetes','Chave de Roda','Manual'
];
const FOTOS_CATS = ['Frente','Lateral Esq.','Lateral Dir.','Traseira','Painel','Motor','Outros'];

const VehicleView = ({ label, marks, onMark }) => {
  const [hov, setHov] = useStateV(false);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
      <span style={{ fontSize: 11, fontWeight: 600, color: '#64748B', textTransform: 'uppercase', letterSpacing: '0.5px' }}>{label}</span>
      <div
        onClick={e => {
          const rect = e.currentTarget.getBoundingClientRect();
          const x = Math.round(((e.clientX - rect.left) / rect.width) * 100);
          const y = Math.round(((e.clientY - rect.top) / rect.height) * 100);
          onMark(x, y, label);
        }}
        onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
        style={{ position: 'relative', cursor: 'crosshair', border: `2px solid ${hov ? '#3B82F6' : '#E2E8F0'}`, borderRadius: 10, background: '#F8FAFC', width: 140, height: 90, overflow: 'hidden', transition: 'border 0.15s' }}>
        <svg viewBox="0 0 140 90" width="140" height="90">
          {label === 'Frente' && <>
            <rect x="20" y="35" width="100" height="40" rx="6" fill="#CBD5E1" />
            <rect x="30" y="20" width="80" height="30" rx="8" fill="#94A3B8" />
            <rect x="25" y="60" width="20" height="14" rx="7" fill="#64748B" />
            <rect x="95" y="60" width="20" height="14" rx="7" fill="#64748B" />
            <rect x="28" y="37" width="30" height="16" rx="3" fill="#BFDBFE" />
            <rect x="82" y="37" width="30" height="16" rx="3" fill="#BFDBFE" />
            <rect x="55" y="58" width="30" height="6" rx="3" fill="#F59E0B" opacity="0.7" />
          </>}
          {label === 'Traseira' && <>
            <rect x="20" y="30" width="100" height="45" rx="6" fill="#CBD5E1" />
            <rect x="30" y="18" width="80" height="28" rx="6" fill="#94A3B8" />
            <rect x="25" y="60" width="20" height="14" rx="7" fill="#64748B" />
            <rect x="95" y="60" width="20" height="14" rx="7" fill="#64748B" />
            <rect x="28" y="32" width="30" height="14" rx="3" fill="#BFDBFE" />
            <rect x="82" y="32" width="30" height="14" rx="3" fill="#BFDBFE" />
            <rect x="45" y="57" width="50" height="8" rx="3" fill="#F87171" opacity="0.7" />
          </>}
          {(label === 'Lat. Esq.' || label === 'Lat. Dir.') && <>
            <ellipse cx="38" cy="68" rx="14" ry="14" fill="#64748B" />
            <ellipse cx="102" cy="68" rx="14" ry="14" fill="#64748B" />
            <ellipse cx="38" cy="68" rx="8" ry="8" fill="#94A3B8" />
            <ellipse cx="102" cy="68" rx="8" ry="8" fill="#94A3B8" />
            <rect x="20" y="30" width="100" height="38" rx="8" fill="#CBD5E1" />
            <rect x="30" y="16" width="65" height="28" rx="8" fill="#94A3B8" />
            <rect x="32" y="18" width="28" height="20" rx="4" fill="#BFDBFE" />
            <rect x="64" y="18" width="28" height="20" rx="4" fill="#BFDBFE" />
          </>}
        </svg>
        {marks.map((m, i) => (
          <div key={i} style={{
            position: 'absolute', left: `${m.x}%`, top: `${m.y}%`,
            transform: 'translate(-50%,-50%)', width: 16, height: 16,
            borderRadius: '50%', background: '#EF4444',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: '#fff', fontSize: 10, fontWeight: 700, boxShadow: '0 2px 6px rgba(239,68,68,0.5)',
            animation: 'popIn 0.2s ease', zIndex: 10
          }}>{i+1}</div>
        ))}
        {hov && <div style={{ position: 'absolute', inset: 0, background: 'rgba(59,130,246,0.06)', pointerEvents: 'none' }} />}
      </div>
    </div>
  );
};

const VistoriaScreen = () => {
  const [vistorias, setVistorias] = useStateV([]);
  const [loading, setLoading] = useStateV(true);
  const [tab, setTab] = useStateV(0);
  const [showForm, setShowForm] = useStateV(false);
  const [motoristas, setMotoristas] = useStateV([]);

  // Form state
  const [tipoVistoria, setTipoVistoria] = useStateV('Entrada');
  const [tipoVeiculo, setTipoVeiculo] = useStateV('Carro');
  const [placa, setPlaca] = useStateV('');
  const [marca, setMarca] = useStateV('');
  const [modelo, setModelo] = useStateV('');
  const [cor, setCor] = useStateV('');
  const [ano, setAno] = useStateV('');
  const [km, setKm] = useStateV('');
  const [motoristaId, setMotoristaId] = useStateV('');
  const [checklist, setChecklist] = useStateV({});
  const [combustivel, setCombustivel] = useStateV(50);
  const [damages, setDamages] = useStateV({ 'Frente': [], 'Traseira': [], 'Lat. Esq.': [], 'Lat. Dir.': [] });
  const [signGuin, setSignGuin] = useStateV(null);
  const [signCli, setSignCli] = useStateV(null);
  const [nomeGuin, setNomeGuin] = useStateV('');
  const [nomeCli, setNomeCli] = useStateV('');
  const [formStep, setFormStep] = useStateV(0);

  const TABS = ['Identificação','Checklist','Mapa de Avarias','Fotos','Assinaturas','Finalizar'];
  const VEICS = ['Carro','Moto','Caminhão','Utilitário'];

  const refresh = async () => {
    setLoading(true);
    setVistorias(await db.list('vistorias', { order: 'created_at' }));
    setLoading(false);
  };
  useEffectV(() => { refresh(); db.list('motoristas', { order: 'nome', asc: true }).then(setMotoristas); }, []);

  const resetForm = () => {
    setTipoVistoria('Entrada'); setTipoVeiculo('Carro'); setPlaca(''); setMarca(''); setModelo('');
    setCor(''); setAno(''); setKm(''); setMotoristaId(''); setChecklist({}); setCombustivel(50);
    setDamages({ 'Frente': [], 'Traseira': [], 'Lat. Esq.': [], 'Lat. Dir.': [] });
    setSignGuin(null); setSignCli(null); setNomeGuin(''); setNomeCli(''); setFormStep(0);
  };

  const addDamage = (x, y, view) => setDamages(d => ({ ...d, [view]: [...(d[view]||[]), { x, y, comment: '' }] }));
  const totalDamages = Object.values(damages).reduce((s, a) => s + a.length, 0);

  const salvarVistoria = async () => {
    if (!placa) { showToast('Informe a placa', 'warning'); return; }
    const motoristaSel = motoristas.find(m => m.id === parseInt(motoristaId));
    const created = await db.insert('vistorias', {
      tipo: tipoVistoria, tipo_veiculo: tipoVeiculo, placa, marca, modelo, cor, ano, km,
      veiculo: `${marca} ${modelo} ${cor}`.trim(),
      motorista_id: motoristaSel?.id || null,
      motorista_nome: motoristaSel?.nome || null,
      checklist, combustivel, damages,
      assinatura_guincheiro: signGuin, assinatura_cliente: signCli,
      nome_guincheiro: nomeGuin, nome_cliente: nomeCli,
      status: (signGuin && signCli) ? 'concluida' : 'pendente',
    });
    if (created) {
      showToast(`Vistoria ${created.numero} salva!`, 'success');
      resetForm();
      setShowForm(false);
      refresh();
    }
  };

  const filtradas = vistorias.filter(v => tab === 0 || (tab === 1 && v.status === 'pendente') || (tab === 2 && v.status === 'concluida'));

  if (showForm) return (
    <div style={{ padding: 28, display: 'flex', flexDirection: 'column', gap: 20, maxWidth: 800, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <Btn variant="ghost" size="sm" icon="chevronRight" onClick={() => { resetForm(); setShowForm(false); }} style={{ transform: 'rotate(180deg)' }}></Btn>
        <h1 style={{ margin: 0, fontSize: 22, fontWeight: 700, color: '#0F172A', fontFamily: 'DM Sans, sans-serif' }}>Nova Vistoria</h1>
      </div>

      <div style={{ display: 'flex', gap: 0, background: '#F8FAFC', borderRadius: 12, padding: 4, overflowX: 'auto' }}>
        {TABS.map((t, i) => (
          <button key={t} onClick={() => setFormStep(i)} style={{
            flex: 1, padding: '8px 6px', borderRadius: 8, border: 'none', cursor: 'pointer',
            background: formStep === i ? '#fff' : 'transparent',
            color: formStep === i ? '#F59E0B' : '#64748B',
            fontWeight: formStep === i ? 700 : 400, fontSize: 12, fontFamily: 'Inter, sans-serif',
            boxShadow: formStep === i ? '0 1px 4px rgba(0,0,0,0.08)' : 'none',
            transition: 'all 0.15s', whiteSpace: 'nowrap'
          }}>{i+1}. {t}</button>
        ))}
      </div>

      <Card style={{ padding: 24, minHeight: 320 }}>
        {formStep === 0 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <Select label="Tipo de Vistoria" value={tipoVistoria} onChange={e => setTipoVistoria(e.target.value)} options={[{value:'Entrada',label:'Entrada'},{value:'Saída',label:'Saída'}]} />
              <Select label="Motorista (opcional)" value={motoristaId} onChange={e => setMotoristaId(e.target.value)}
                options={[{value:'',label:'Selecione...'}, ...motoristas.map(m => ({ value: m.id, label: m.nome }))]} />
            </div>
            <div>
              <label style={{ fontSize: 13, fontWeight: 600, color: '#374151', marginBottom: 10, display: 'block' }}>Tipo de Veículo</label>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 10 }}>
                {VEICS.map(v => (
                  <button key={v} onClick={() => setTipoVeiculo(v)} style={{
                    padding: '14px 8px', borderRadius: 12, border: `2px solid ${tipoVeiculo===v ? '#F59E0B' : '#E2E8F0'}`,
                    background: tipoVeiculo===v ? '#FFF7ED' : '#F8FAFC', cursor: 'pointer',
                    display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
                    transition: 'all 0.15s'
                  }}>
                    <span style={{ fontSize: 22 }}>{v === 'Carro' ? '🚗' : v === 'Moto' ? '🏍️' : v === 'Caminhão' ? '🚛' : '🚐'}</span>
                    <span style={{ fontSize: 12, fontWeight: tipoVeiculo===v ? 700 : 400, color: tipoVeiculo===v ? '#B45309' : '#64748B' }}>{v}</span>
                  </button>
                ))}
              </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <Input label="Placa" placeholder="ABC-1D23" value={placa} onChange={e => setPlaca(e.target.value)} />
              <Input label="Marca" placeholder="Honda" value={marca} onChange={e => setMarca(e.target.value)} />
              <Input label="Modelo" placeholder="Civic EXL" value={modelo} onChange={e => setModelo(e.target.value)} />
              <Input label="Cor" placeholder="Preto" value={cor} onChange={e => setCor(e.target.value)} />
              <Input label="Ano/Mod" placeholder="2023/2024" value={ano} onChange={e => setAno(e.target.value)} />
              <Input label="Quilometragem" placeholder="45.230 km" value={km} onChange={e => setKm(e.target.value)} />
            </div>
          </div>
        )}

        {formStep === 1 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div>
              <label style={{ fontSize: 13, fontWeight: 600, color: '#374151', marginBottom: 12, display: 'block' }}>Acessórios Presentes</label>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8 }}>
                {CHECKLIST_ITEMS.map(item => {
                  const checked = checklist[item];
                  return (
                    <button key={item} onClick={() => setChecklist(c => ({ ...c, [item]: !c[item] }))} style={{
                      padding: '10px 12px', borderRadius: 8, cursor: 'pointer',
                      border: `2px solid ${checked ? '#10B981' : '#E2E8F0'}`,
                      background: checked ? 'rgba(16,185,129,0.08)' : '#F8FAFC',
                      display: 'flex', alignItems: 'center', gap: 8, transition: 'all 0.15s'
                    }}>
                      <div style={{ width: 18, height: 18, borderRadius: 4, border: `2px solid ${checked ? '#10B981' : '#CBD5E1'}`, background: checked ? '#10B981' : '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                        {checked && <span style={{ color: '#fff', fontSize: 11, fontWeight: 700 }}>✓</span>}
                      </div>
                      <span style={{ fontSize: 13, color: checked ? '#065F46' : '#64748B', fontWeight: checked ? 600 : 400 }}>{item}</span>
                    </button>
                  );
                })}
              </div>
            </div>
            <div>
              <label style={{ fontSize: 13, fontWeight: 600, color: '#374151', marginBottom: 12, display: 'block' }}>Nível de Combustível — <span style={{ color: '#F59E0B' }}>{combustivel}%</span></label>
              <div style={{ position: 'relative', background: '#F1F5F9', borderRadius: 10, height: 14, overflow: 'visible' }}>
                <div style={{ height: '100%', width: `${combustivel}%`, borderRadius: 10, background: combustivel > 50 ? '#10B981' : combustivel > 25 ? '#F59E0B' : '#EF4444', transition: 'width 0.3s, background 0.3s' }} />
              </div>
              <input type="range" min="0" max="100" value={combustivel} onChange={e => setCombustivel(+e.target.value)} style={{ width: '100%', marginTop: 8, accentColor: '#F59E0B' }} />
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: '#94A3B8' }}><span>E</span><span>1/4</span><span>1/2</span><span>3/4</span><span>F</span></div>
            </div>
          </div>
        )}

        {formStep === 2 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontSize: 14, fontWeight: 600, color: '#0F172A' }}>Mapa de Avarias</div>
                <div style={{ fontSize: 12, color: '#94A3B8' }}>Clique nas vistas para marcar avarias</div>
              </div>
              {totalDamages > 0 && <span style={{ background: 'rgba(239,68,68,0.1)', color: '#DC2626', borderRadius: 20, padding: '3px 10px', fontSize: 12, fontWeight: 600 }}>{totalDamages} avaria{totalDamages > 1 ? 's' : ''}</span>}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, justifyItems: 'center' }}>
              {Object.keys(damages).map(view => (
                <VehicleView key={view} label={view} marks={damages[view]} onMark={(x, y) => addDamage(x, y, view)} />
              ))}
            </div>
            {totalDamages > 0 && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: '#374151', marginBottom: 4 }}>Avarias Registradas</div>
                {Object.entries(damages).map(([view, marks]) => marks.map((m, i) => (
                  <div key={`${view}-${i}`} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', background: '#FEF2F2', borderRadius: 8 }}>
                    <span style={{ width: 20, height: 20, borderRadius: '50%', background: '#EF4444', color: '#fff', fontSize: 11, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{i+1}</span>
                    <span style={{ fontSize: 13, color: '#374151', flex: 1 }}>{view} — posição ({m.x}%, {m.y}%)</span>
                    <button onClick={() => setDamages(d => ({ ...d, [view]: d[view].filter((_,j) => j!==i) }))} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#EF4444', fontSize: 12 }}>✕</button>
                  </div>
                )))}
              </div>
            )}
          </div>
        )}

        {formStep === 3 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: '#0F172A' }}>Fotos do Veículo</div>
            <div style={{ background: '#FFFBEB', border: '1px solid #FED7AA', borderRadius: 10, padding: '12px 14px', fontSize: 12, color: '#92400E', display: 'flex', gap: 8, alignItems: 'center' }}>
              <Icon name="alert" size={14} color="#F59E0B" />
              Upload de fotos requer Supabase Storage configurado — em breve. Por enquanto, anexe externamente ao laudo PDF.
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 10 }}>
              {FOTOS_CATS.map(cat => (
                <div key={cat} style={{ display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'center' }}>
                  <div style={{
                    width: '100%', aspectRatio: '1', borderRadius: 10,
                    background: 'repeating-linear-gradient(45deg,#F1F5F9 0,#F1F5F9 8px,#E2E8F0 8px,#E2E8F0 16px)',
                    display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                    gap: 6, border: '2px dashed #CBD5E1', opacity: 0.6
                  }}>
                    <Icon name="camera" size={20} color="#94A3B8" />
                    <span style={{ fontSize: 10, color: '#94A3B8', fontFamily: 'monospace' }}>{cat}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {formStep === 4 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: '#0F172A' }}>Assinaturas Digitais</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                <Input label="Nome do Guincheiro" placeholder="Carlos Silva" value={nomeGuin} onChange={e => setNomeGuin(e.target.value)} />
                <SignaturePad label="Assinatura do Guincheiro" onSign={setSignGuin} />
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                <Input label="Nome do Cliente" placeholder="João da Silva" value={nomeCli} onChange={e => setNomeCli(e.target.value)} />
                <SignaturePad label="Assinatura do Cliente" onSign={setSignCli} />
              </div>
            </div>
            <div style={{ background: '#F8FAFC', borderRadius: 8, padding: '10px 14px', fontSize: 12, color: '#64748B', display: 'flex', gap: 8, alignItems: 'center' }}>
              <Icon name="calendar" size={14} color="#94A3B8" />
              Data/Hora automática: {new Date().toLocaleString('pt-BR')}
            </div>
          </div>
        )}

        {formStep === 5 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20, alignItems: 'center', textAlign: 'center' }}>
            <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'rgba(16,185,129,0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="check" size={32} color="#10B981" />
            </div>
            <div>
              <div style={{ fontSize: 20, fontWeight: 700, color: '#0F172A', fontFamily: 'DM Sans, sans-serif' }}>Vistoria Pronta!</div>
              <div style={{ fontSize: 14, color: '#64748B', marginTop: 6 }}>Revise o resumo e salve a vistoria</div>
            </div>
            <div style={{ background: '#F8FAFC', borderRadius: 12, padding: 20, width: '100%', textAlign: 'left', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              {[
                ['Tipo', tipoVistoria], ['Placa', placa || '—'],
                ['Veículo', `${marca} ${modelo}`.trim() || '—'], ['Combustível', `${combustivel}%`],
                ['Avarias', `${totalDamages} marcadas`], ['Motorista', motoristas.find(m => m.id === parseInt(motoristaId))?.nome || '—'],
                ['Assinatura Guincheiro', signGuin ? '✓ Assinado' : '— Pendente'],
                ['Assinatura Cliente', signCli ? '✓ Assinado' : '— Pendente'],
              ].map(([k,v]) => (
                <div key={k}>
                  <div style={{ fontSize: 11, color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: 2 }}>{k}</div>
                  <div style={{ fontSize: 14, color: '#0F172A', fontWeight: 500 }}>{v}</div>
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center' }}>
              <Btn variant="primary" icon="check" onClick={salvarVistoria}>Salvar Vistoria</Btn>
            </div>
          </div>
        )}
      </Card>

      {formStep < 5 && (
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <Btn variant="secondary" onClick={() => setFormStep(s => Math.max(0, s-1))} disabled={formStep === 0}>← Anterior</Btn>
          <Btn variant="blue" onClick={() => setFormStep(s => Math.min(5, s+1))}>Próximo →</Btn>
        </div>
      )}
    </div>
  );

  return (
    <div style={{ padding: 28, display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 22, fontWeight: 700, color: '#0F172A', fontFamily: 'DM Sans, sans-serif' }}>Vistoria Digital</h1>
          <span style={{ fontSize: 13, color: '#64748B' }}>Laudos e checklists dos veículos</span>
        </div>
        <Btn variant="primary" icon="plus" onClick={() => { resetForm(); setShowForm(true); }}>Nova Vistoria</Btn>
      </div>

      <div style={{ display: 'flex', gap: 6, background: '#F8FAFC', padding: 4, borderRadius: 10, alignSelf: 'flex-start' }}>
        {['Todas','Pendentes','Concluídas'].map((t, i) => (
          <button key={t} onClick={() => setTab(i)} style={{
            padding: '7px 16px', borderRadius: 7, border: 'none', cursor: 'pointer',
            background: tab === i ? '#fff' : 'transparent',
            color: tab === i ? '#F59E0B' : '#64748B',
            fontWeight: tab === i ? 600 : 400, fontSize: 13,
            boxShadow: tab === i ? '0 1px 4px rgba(0,0,0,0.08)' : 'none', transition: 'all 0.15s'
          }}>{t}</button>
        ))}
      </div>

      <Card style={{ padding: 0, overflow: 'hidden' }}>
        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#94A3B8', fontSize: 14 }}>Carregando vistorias...</div>
        ) : filtradas.length === 0 ? (
          <div style={{ padding: 60, textAlign: 'center' }}>
            <Icon name="search" size={48} color="#CBD5E1" />
            <div style={{ fontSize: 16, color: '#64748B', marginTop: 14, fontWeight: 600 }}>{vistorias.length === 0 ? 'Nenhuma vistoria registrada' : 'Nenhuma vistoria nesta categoria'}</div>
            <div style={{ fontSize: 13, color: '#94A3B8', marginTop: 4 }}>{vistorias.length === 0 ? 'Clique em "Nova Vistoria" para registrar a primeira' : 'Tente outra aba'}</div>
            {vistorias.length === 0 && <Btn variant="primary" icon="plus" onClick={() => { resetForm(); setShowForm(true); }} style={{ marginTop: 16 }}>Nova Vistoria</Btn>}
          </div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, fontFamily: 'Inter, sans-serif' }}>
            <thead>
              <tr style={{ background: '#F8FAFC' }}>
                {['Nº','Placa','Veículo','Data/Hora','Tipo','Motorista','Status'].map(h => (
                  <th key={h} style={{ padding: '11px 16px', textAlign: 'left', fontSize: 12, fontWeight: 600, color: '#64748B', borderBottom: '1px solid #E2E8F0', whiteSpace: 'nowrap' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtradas.map((v, i) => (
                <tr key={v.id} style={{ background: i % 2 ? '#F8FAFC' : '#fff' }}
                  onMouseEnter={e => e.currentTarget.style.background = '#EFF6FF'}
                  onMouseLeave={e => e.currentTarget.style.background = i % 2 ? '#F8FAFC' : '#fff'}>
                  <td style={{ padding: '11px 16px', fontFamily: 'DM Mono, monospace', fontSize: 12, color: '#3B82F6', fontWeight: 600 }}>{v.numero}</td>
                  <td style={{ padding: '11px 16px' }}>
                    <span style={{ background: '#F1F5F9', borderRadius: 5, padding: '2px 7px', fontFamily: 'DM Mono, monospace', fontSize: 12, fontWeight: 600 }}>{v.placa || '—'}</span>
                  </td>
                  <td style={{ padding: '11px 16px', color: '#374151' }}>{v.veiculo || '—'}</td>
                  <td style={{ padding: '11px 16px', color: '#64748B', fontSize: 12 }}>{new Date(v.created_at).toLocaleString('pt-BR')}</td>
                  <td style={{ padding: '11px 16px' }}>
                    <span style={{ padding: '3px 10px', borderRadius: 6, fontSize: 12, fontWeight: 600, background: v.tipo === 'Entrada' ? 'rgba(59,130,246,0.1)' : 'rgba(139,92,246,0.1)', color: v.tipo === 'Entrada' ? '#2563EB' : '#7C3AED' }}>{v.tipo}</span>
                  </td>
                  <td style={{ padding: '11px 16px', color: '#374151' }}>{v.motorista_nome || '—'}</td>
                  <td style={{ padding: '11px 16px' }}>
                    <StatusBadge status={v.status === 'pendente' ? 'aberta' : 'finalizada'} />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </Card>
    </div>
  );
};

Object.assign(window, { VistoriaScreen });
