// Caririaçu Guincho — Assistências Screen

const { useState: useStateA, useEffect: useEffectA } = React;

const SERVICOS = ['Guincho Leve','Guincho Pesado','Pane Seca','Bateria','Chaveiro','Outros'];
const STATUSES = ['aberta','atendimento','agendada','finalizada','cancelada'];

// ── Modal Nova Assistência ───────────────────────────────────────────────
const NewAssistModal = ({ open, onClose, onSave }) => {
  const [step, setStep] = useStateA(1);
  const [motoristas, setMotoristas] = useStateA([]);
  const [frota, setFrota] = useStateA([]);
  const [seguradoras, setSeguradoras] = useStateA([]);
  const [form, setForm] = useStateA({
    cliente: 'Particular', servico: 'Guincho Leve',
    data: new Date().toISOString().slice(0,16),
    placa: '', veiculo: '',
    origem: '', destino: '',
    motorista_id: '', valor: '', obs: ''
  });

  useEffectA(() => {
    if (!open) return;
    db.list('motoristas', { eq: { status: 'disponivel' }, order: 'nome', asc: true }).then(setMotoristas);
    db.list('frota', { eq: { status: 'ativo' }, order: 'code', asc: true }).then(setFrota);
    db.list('seguradoras', { eq: { status: 'ativo' }, order: 'nome', asc: true }).then(setSeguradoras);
    setStep(1);
    setForm({
      cliente: 'Particular', servico: 'Guincho Leve',
      data: new Date().toISOString().slice(0,16),
      placa: '', veiculo: '', origem: '', destino: '',
      motorista_id: '', valor: '', obs: ''
    });
  }, [open]);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const totalSteps = 4;
  const stepLabels = ['Chamado','Veículo','Operação','Confirmação'];

  const handleSave = async () => {
    const motoristaSel = motoristas.find(m => m.id === parseInt(form.motorista_id));
    const seguradoraSel = seguradoras.find(s => s.nome === form.cliente);
    const payload = {
      data: form.data,
      cliente: form.cliente,
      seguradora_id: seguradoraSel?.id || null,
      servico: form.servico,
      placa: form.placa,
      veiculo: form.veiculo,
      origem: form.origem,
      destino: form.destino,
      motorista_id: motoristaSel?.id || null,
      motorista_nome: motoristaSel?.nome || null,
      motorista_avatar: motoristaSel?.avatar || null,
      valor: parseFloat(form.valor) || 0,
      obs: form.obs,
      status: 'aberta',
    };
    const created = await db.insert('assistencias', payload);
    if (created) {
      showToast(`Assistência ${created.numero || '#' + created.id} criada com sucesso!`, 'success');
      onSave?.(created);
      onClose();
    }
  };

  return (
    <Modal open={open} onClose={onClose} title="Nova Assistência" width={720} noPad>
      <div style={{ padding: '16px 24px', borderBottom: '1px solid #F1F5F9', flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 0 }}>
          {stepLabels.map((l, i) => {
            const n = i + 1;
            const done = n < step, active = n === step;
            return (
              <React.Fragment key={n}>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                  <div style={{
                    width: 28, height: 28, borderRadius: '50%', display: 'flex',
                    alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700,
                    background: done ? '#10B981' : active ? '#F59E0B' : '#E2E8F0',
                    color: done || active ? '#fff' : '#94A3B8', transition: 'all 0.3s'
                  }}>{done ? '✓' : n}</div>
                  <span style={{ fontSize: 11, color: active ? '#F59E0B' : done ? '#10B981' : '#94A3B8', fontWeight: active ? 600 : 400, whiteSpace: 'nowrap' }}>{l}</span>
                </div>
                {i < totalSteps - 1 && (
                  <div style={{ flex: 1, height: 2, background: n < step ? '#10B981' : '#E2E8F0', margin: '0 8px', marginBottom: 18, transition: 'all 0.3s' }} />
                )}
              </React.Fragment>
            );
          })}
        </div>
      </div>

      <div style={{ padding: 24 }}>
        {step === 1 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <Select label="Cliente / Seguradora" value={form.cliente} onChange={e => set('cliente', e.target.value)}
              options={['Particular', ...seguradoras.map(s => s.nome)].map(v => ({ value: v, label: v }))} />
            <div>
              <label style={{ fontSize: 13, fontWeight: 500, color: '#374151', marginBottom: 8, display: 'block' }}>Categoria do Serviço</label>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8 }}>
                {SERVICOS.map(s => (
                  <button key={s} onClick={() => set('servico', s)} style={{
                    padding: '10px 8px', borderRadius: 10, border: `2px solid ${form.servico === s ? '#F59E0B' : '#E2E8F0'}`,
                    background: form.servico === s ? '#FFF7ED' : '#F8FAFC', cursor: 'pointer',
                    fontSize: 13, fontWeight: form.servico === s ? 600 : 400,
                    color: form.servico === s ? '#B45309' : '#64748B', transition: 'all 0.15s'
                  }}>{s}</button>
                ))}
              </div>
            </div>
            <Input label="Data e Hora de Abertura" type="datetime-local" value={form.data} onChange={e => set('data', e.target.value)} />
          </div>
        )}

        {step === 2 && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <Input label="Placa" placeholder="ABC-1234" value={form.placa} onChange={e => set('placa', e.target.value)} />
            <Input label="Veículo (modelo + cor)" placeholder="Honda Civic Preto" value={form.veiculo} onChange={e => set('veiculo', e.target.value)} />
          </div>
        )}

        {step === 3 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <Input label="Endereço de Origem" placeholder="Av. Principal, 1000 — Caririaçu, CE" value={form.origem} onChange={e => set('origem', e.target.value)} />
            <Input label="Endereço de Destino" placeholder="Oficina Central — Av. Industrial, 500" value={form.destino} onChange={e => set('destino', e.target.value)} />
            <Select label="Motorista Responsável" value={form.motorista_id} onChange={e => set('motorista_id', e.target.value)}
              options={[{value:'',label:'Selecione um motorista'}, ...motoristas.map(m => ({ value: m.id, label: `${m.nome} — ${m.guincho_code || 'sem guincho'}` }))]} />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 16 }}>
              <Input label="Valor do Serviço (R$)" placeholder="280.00" value={form.valor} onChange={e => set('valor', e.target.value)} />
              <Input label="Observações" placeholder="Informações adicionais..." value={form.obs} onChange={e => set('obs', e.target.value)} />
            </div>
          </div>
        )}

        {step === 4 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div style={{ background: '#F8FAFC', borderRadius: 12, padding: 20, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              {[
                ['Cliente', form.cliente], ['Categoria', form.servico],
                ['Data/Hora', form.data?.replace('T',' ')], ['Veículo', `${form.veiculo} ${form.placa}`],
                ['Origem', form.origem], ['Destino', form.destino],
                ['Motorista', motoristas.find(m => m.id === parseInt(form.motorista_id))?.nome || '—'],
                ['Valor', form.valor ? `R$ ${form.valor}` : '—'],
              ].map(([k,v]) => (
                <div key={k}>
                  <div style={{ fontSize: 11, color: '#94A3B8', fontWeight: 500, textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: 2 }}>{k}</div>
                  <div style={{ fontSize: 14, color: '#0F172A', fontWeight: 500 }}>{v || '—'}</div>
                </div>
              ))}
            </div>
            <div style={{ background: '#FFF7ED', borderRadius: 10, padding: 14, display: 'flex', gap: 10, alignItems: 'flex-start', border: '1px solid #FED7AA' }}>
              <Icon name="alert" size={16} color="#F59E0B" />
              <span style={{ fontSize: 13, color: '#92400E' }}>Confirme os dados antes de salvar. O número da assistência será gerado automaticamente.</span>
            </div>
          </div>
        )}

        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 24, paddingTop: 20, borderTop: '1px solid #F1F5F9' }}>
          <Btn variant="secondary" onClick={() => step > 1 ? setStep(s => s-1) : onClose()}>
            {step > 1 ? '← Anterior' : 'Cancelar'}
          </Btn>
          <Btn variant={step === totalSteps ? 'primary' : 'blue'} onClick={() => step < totalSteps ? setStep(s => s+1) : handleSave()}>
            {step === totalSteps ? '✓ Salvar Assistência' : 'Próximo →'}
          </Btn>
        </div>
      </div>
    </Modal>
  );
};

// ── Modal Finalizar com Assinatura ──────────────────────────────────────
const FinalizeAssistModal = ({ assist, onClose, onFinalized }) => {
  const [signGuin, setSignGuin] = useStateA(null);
  const [signCli, setSignCli] = useStateA(null);
  const [nomeGuin, setNomeGuin] = useStateA('');
  const [nomeCli, setNomeCli] = useStateA('');
  const [saving, setSaving] = useStateA(false);

  useEffectA(() => {
    if (assist) {
      setSignGuin(null); setSignCli(null);
      setNomeGuin(assist.motorista_nome || '');
      setNomeCli('');
    }
  }, [assist?.id]);

  if (!assist) return null;

  const handleFinalizar = async () => {
    if (!signGuin || !signCli) {
      showToast('Coletar as 2 assinaturas antes de finalizar', 'warning');
      return;
    }
    if (!nomeCli.trim()) {
      showToast('Informe o nome do cliente', 'warning');
      return;
    }
    setSaving(true);
    const updated = await db.update('assistencias', assist.id, {
      status: 'finalizada',
      assinatura_guincheiro: signGuin,
      assinatura_cliente: signCli,
      nome_guincheiro: nomeGuin || assist.motorista_nome,
      nome_cliente: nomeCli,
      data_finalizacao: new Date().toISOString(),
    });
    setSaving(false);
    if (updated) {
      showToast(`${assist.numero || '#' + assist.id} finalizada com assinaturas`, 'success');
      onFinalized?.();
      onClose();
    }
  };

  return (
    <Modal open={!!assist} onClose={onClose} title={`Finalizar ${assist.numero || '#' + assist.id}`} width={680}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div style={{ background: '#F8FAFC', borderRadius: 10, padding: 14, fontSize: 13, color: '#374151' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
            <span style={{ color: '#94A3B8', fontWeight: 600 }}>Veículo:</span>
            <strong>{assist.veiculo} · {assist.placa}</strong>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
            <span style={{ color: '#94A3B8', fontWeight: 600 }}>Cliente:</span>
            <strong>{assist.cliente}</strong>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <span style={{ color: '#94A3B8', fontWeight: 600 }}>Valor:</span>
            <strong style={{ color: '#10B981' }}>R$ {Number(assist.valor).toFixed(2)}</strong>
          </div>
        </div>

        <div style={{ background: '#FFFBEB', border: '1px solid #FED7AA', borderRadius: 10, padding: '10px 14px', fontSize: 12, color: '#92400E', display: 'flex', gap: 8, alignItems: 'center' }}>
          <Icon name="alert" size={14} color="#F59E0B" />
          Coletar as duas assinaturas no celular do guincheiro antes de finalizar.
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 18 }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <Input label="Nome do Guincheiro" placeholder={assist.motorista_nome} value={nomeGuin} onChange={e => setNomeGuin(e.target.value)} />
            <SignaturePad label="✍️ Assinatura do Guincheiro" onSign={setSignGuin} height={140} />
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <Input label="Nome do Cliente" placeholder="Nome completo de quem recebeu o veículo" value={nomeCli} onChange={e => setNomeCli(e.target.value)} />
            <SignaturePad label="✍️ Assinatura do Cliente" onSign={setSignCli} height={140} />
          </div>
        </div>

        <div style={{ background: '#F8FAFC', borderRadius: 8, padding: '8px 12px', fontSize: 11, color: '#64748B', textAlign: 'center' }}>
          📅 Data de finalização será registrada em {new Date().toLocaleString('pt-BR')}
        </div>

        <div style={{ display: 'flex', gap: 10, justifyContent: 'space-between', paddingTop: 8, borderTop: '1px solid #F1F5F9', flexWrap: 'wrap' }}>
          <Btn variant="secondary" onClick={onClose} disabled={saving}>Cancelar</Btn>
          <Btn variant="primary" icon="check" onClick={handleFinalizar} disabled={saving || !signGuin || !signCli}>
            {saving ? 'Salvando...' : 'Finalizar com Assinaturas'}
          </Btn>
        </div>
      </div>
    </Modal>
  );
};

// ── Modal Editar Assistência ─────────────────────────────────────────────
const EditAssistModal = ({ assist, onClose, onSave }) => {
  const [form, setForm] = useStateA({});
  const [motoristas, setMotoristas] = useStateA([]);
  const [seguradoras, setSeguradoras] = useStateA([]);
  useEffectA(() => {
    if (!assist) return;
    setForm({
      servico: assist.servico, cliente: assist.cliente, status: assist.status,
      motorista_id: assist.motorista_id || '', valor: assist.valor,
      origem: assist.origem || '', destino: assist.destino || '',
      placa: assist.placa, veiculo: assist.veiculo, obs: assist.obs || ''
    });
    db.list('motoristas', { order: 'nome', asc: true }).then(setMotoristas);
    db.list('seguradoras', { eq: { status: 'ativo' } }).then(setSeguradoras);
  }, [assist?.id]);

  if (!assist) return null;
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSave = async () => {
    const motoristaSel = motoristas.find(m => m.id === parseInt(form.motorista_id));
    const seguradoraSel = seguradoras.find(s => s.nome === form.cliente);
    const payload = {
      servico: form.servico, cliente: form.cliente, status: form.status,
      seguradora_id: seguradoraSel?.id || null,
      motorista_id: motoristaSel?.id || null,
      motorista_nome: motoristaSel?.nome || null,
      motorista_avatar: motoristaSel?.avatar || null,
      valor: parseFloat(form.valor) || 0,
      origem: form.origem, destino: form.destino,
      placa: form.placa, veiculo: form.veiculo, obs: form.obs,
    };
    const updated = await db.update('assistencias', assist.id, payload);
    if (updated) {
      onSave?.(updated);
      onClose();
    }
  };

  return (
    <Modal open={!!assist} onClose={onClose} title={`Editar ${assist.numero || '#' + assist.id}`} width={680}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <Select label="Serviço" value={form.servico} onChange={e => set('servico', e.target.value)}
            options={SERVICOS.map(v => ({ value: v, label: v }))} />
          <Select label="Status" value={form.status} onChange={e => set('status', e.target.value)}
            options={STATUSES.map(v => ({ value: v, label: v.charAt(0).toUpperCase() + v.slice(1) }))} />
          <Input label="Placa" value={form.placa} onChange={e => set('placa', e.target.value)} />
          <Input label="Veículo (modelo + cor)" value={form.veiculo} onChange={e => set('veiculo', e.target.value)} />
          <Select label="Cliente / Seguradora" value={form.cliente} onChange={e => set('cliente', e.target.value)}
            options={['Particular', ...seguradoras.map(s => s.nome)].map(v => ({ value: v, label: v }))} />
          <Select label="Motorista" value={form.motorista_id} onChange={e => set('motorista_id', e.target.value)}
            options={[{value:'',label:'Sem motorista'}, ...motoristas.map(m => ({ value: m.id, label: `${m.nome} — ${m.guincho_code || ''}` }))]} />
        </div>
        <Input label="Endereço de Origem" value={form.origem} onChange={e => set('origem', e.target.value)} />
        <Input label="Endereço de Destino" value={form.destino} onChange={e => set('destino', e.target.value)} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 14 }}>
          <Input label="Valor (R$)" type="number" value={form.valor} onChange={e => set('valor', e.target.value)} />
          <Input label="Observações" value={form.obs} onChange={e => set('obs', e.target.value)} />
        </div>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', paddingTop: 8, borderTop: '1px solid #F1F5F9' }}>
          <Btn variant="secondary" onClick={onClose}>Cancelar</Btn>
          <Btn variant="primary" icon="check" onClick={handleSave}>Salvar Alterações</Btn>
        </div>
      </div>
    </Modal>
  );
};

// ── Geradores de PDF ─────────────────────────────────────────────────────
const gerarAssistenciaPDF = async (assist) => {
  const motoristaInfo = assist.motorista_id ? await db.one('motoristas', assist.motorista_id) : null;
  const seguradoraInfo = assist.seguradora_id ? await db.one('seguradoras', assist.seguradora_id) : null;
  const dataEmissao = new Date().toLocaleDateString('pt-BR');
  const numDoc = assist.numero || `ASS-${assist.id}`;

  const STATUS_BG = {
    aberta: 'linear-gradient(135deg,#3B82F6,#2563EB)',
    atendimento: 'linear-gradient(135deg,#F59E0B,#D97706)',
    agendada: 'linear-gradient(135deg,#8B5CF6,#7C3AED)',
    finalizada: 'linear-gradient(135deg,#10B981,#059669)',
    cancelada: 'linear-gradient(135deg,#EF4444,#DC2626)',
  };
  const STATUS_LABEL = { aberta: 'Aberta', atendimento: 'Em Atendimento', agendada: 'Agendada', finalizada: 'Finalizada', cancelada: 'Cancelada' };

  const html = `<!DOCTYPE html>
<html lang="pt-BR"><head><meta charset="UTF-8"><title>Ordem de Serviço ${numDoc}</title>
<link rel="icon" type="image/png" href="${window.location.origin}/logo.png" />
<style>
  * { margin:0; padding:0; box-sizing:border-box; }
  body { font-family:'Segoe UI',Arial,sans-serif; color:#0F172A; padding:40px; background:#fff; }
  .doc { max-width:760px; margin:0 auto; border:2px solid #0F172A; }
  .header { background:linear-gradient(135deg,#1E293B,#0F172A); color:#fff; padding:24px 28px; display:flex; justify-content:space-between; align-items:center; }
  .header h1 { font-size:22px; font-weight:700; }
  .header .logo { display:flex; align-items:center; gap:12px; }
  .header .logo img { width:56px; height:56px; border-radius:50%; object-fit:cover; transform:scale(1.08); box-shadow:0 0 0 2px rgba(245,158,11,0.6); }
  .header .logo-text { font-size:11px; opacity:0.8; letter-spacing:1px; text-transform:uppercase; }
  .status-banner { background:${STATUS_BG[assist.status]}; color:#fff; padding:18px 28px; display:flex; justify-content:space-between; align-items:center; }
  .status-banner .id { font-size:24px; font-family:'Courier New',monospace; font-weight:700; letter-spacing:1px; }
  .status-banner .meta { font-size:13px; opacity:0.95; margin-top:4px; }
  .status-pill { background:rgba(255,255,255,0.22); padding:8px 14px; border-radius:8px; text-align:center; }
  .section { padding:18px 28px; border-bottom:1px solid #E2E8F0; }
  .section h2 { font-size:13px; color:#64748B; text-transform:uppercase; letter-spacing:0.8px; margin-bottom:12px; font-weight:700; border-bottom:2px solid #F59E0B; padding-bottom:6px; display:inline-block; }
  .grid-2 { display:grid; grid-template-columns:repeat(2,1fr); gap:14px; }
  .grid-4 { display:grid; grid-template-columns:repeat(4,1fr); gap:14px; }
  .info-label { font-size:10px; color:#94A3B8; font-weight:600; text-transform:uppercase; letter-spacing:0.5px; }
  .info-value { font-size:13px; color:#0F172A; font-weight:600; margin-top:2px; }
  .route { padding:14px; background:#F8FAFC; border-radius:8px; margin-top:8px; }
  .route .leg { padding:8px 0; display:flex; gap:12px; }
  .route .dot { width:12px; height:12px; border-radius:50%; flex-shrink:0; margin-top:5px; }
  .totals { padding:20px 28px; background:#F8FAFC; }
  .totals-row { display:flex; justify-content:space-between; padding:6px 0; font-size:14px; }
  .totals-row.liquido { border-top:2px solid #0F172A; margin-top:10px; padding-top:14px; font-size:18px; font-weight:800; }
  .liquido-value { font-family:'Courier New',monospace; color:#10B981; }
  .signatures { display:grid; grid-template-columns:1fr 1fr; gap:60px; margin-top:50px; padding:0 28px 30px; }
  .sig { text-align:center; border-top:1px solid #0F172A; padding-top:8px; font-size:12px; color:#374151; }
  .footer { padding:20px 28px; text-align:center; font-size:11px; color:#94A3B8; }
  .print-btn { position:fixed; top:20px; right:20px; background:#F59E0B; color:#0F172A; border:none; padding:12px 22px; border-radius:8px; font-size:14px; font-weight:700; cursor:pointer; box-shadow:0 4px 12px rgba(0,0,0,0.15); }
  @media print { body { padding:0; } .print-btn { display:none; } .doc { border:1px solid #0F172A; } }
</style></head><body>
<button class="print-btn" onclick="window.print()">📥 Salvar como PDF / Imprimir</button>
<div class="doc">
  <div class="header">
    <div class="logo">
      <img src="${window.location.origin}/logo.png" alt="Caririaçu Guincho" />
      <div><h1>Caririaçu Guincho</h1><div class="logo-text">Ordem de Serviço de Assistência</div></div>
    </div>
    <div style="text-align:right; font-size:12px;">
      <div style="opacity:0.8;">${numDoc}</div>
      <div style="margin-top:4px; font-weight:600;">${dataEmissao}</div>
    </div>
  </div>
  <div class="status-banner">
    <div>
      <div class="id">${numDoc}</div>
      <div class="meta">${assist.servico} · ${new Date(assist.data).toLocaleString('pt-BR')}</div>
    </div>
    <div class="status-pill">
      <div style="font-size:10px; opacity:0.85; letter-spacing:0.5px; text-transform:uppercase;">Status</div>
      <div style="font-size:14px; font-weight:700; margin-top:2px;">${STATUS_LABEL[assist.status] || assist.status}</div>
    </div>
  </div>
  <div class="section">
    <h2>Veículo Atendido</h2>
    <div class="grid-2">
      <div><div class="info-label">Placa</div><div class="info-value" style="font-family:'Courier New',monospace;">${assist.placa || '—'}</div></div>
      <div><div class="info-label">Modelo / Cor</div><div class="info-value">${assist.veiculo || '—'}</div></div>
    </div>
  </div>
  <div class="section">
    <h2>Cliente / Seguradora</h2>
    <div class="grid-2">
      <div><div class="info-label">Nome</div><div class="info-value">${assist.cliente || '—'}</div></div>
      <div><div class="info-label">Contato</div><div class="info-value">${seguradoraInfo?.contato || '—'}</div></div>
      <div><div class="info-label">Telefone</div><div class="info-value">${seguradoraInfo?.telefone || '—'}</div></div>
      <div><div class="info-label">E-mail</div><div class="info-value">${seguradoraInfo?.email || '—'}</div></div>
    </div>
  </div>
  <div class="section">
    <h2>Rota do Serviço</h2>
    <div class="route">
      <div class="leg"><div class="dot" style="background:#10B981;"></div><div><div class="info-label" style="color:#10B981;">Origem</div><div class="info-value">${assist.origem || '—'}</div></div></div>
      <div class="leg"><div class="dot" style="background:#EF4444;"></div><div><div class="info-label" style="color:#EF4444;">Destino</div><div class="info-value">${assist.destino || '—'}</div></div></div>
    </div>
  </div>
  <div class="section">
    <h2>Motorista Responsável</h2>
    <div class="grid-4">
      <div><div class="info-label">Nome</div><div class="info-value">${assist.motorista_nome || '—'}</div></div>
      <div><div class="info-label">Telefone</div><div class="info-value">${motoristaInfo?.telefone || '—'}</div></div>
      <div><div class="info-label">CNH</div><div class="info-value">Cat. ${motoristaInfo?.categoria || '—'}</div></div>
      <div><div class="info-label">Guincho</div><div class="info-value">${motoristaInfo?.guincho_code || '—'}</div></div>
    </div>
  </div>
  <div class="totals">
    <div class="totals-row"><span>Categoria</span><span style="font-weight:600;">${assist.servico}</span></div>
    <div class="totals-row"><span>Data de Abertura</span><span style="font-weight:600;">${new Date(assist.data).toLocaleString('pt-BR')}</span></div>
    <div class="totals-row liquido"><span>VALOR DO SERVIÇO</span><span class="liquido-value">R$ ${Number(assist.valor).toFixed(2).replace('.', ',')}</span></div>
  </div>
  ${assist.obs ? `<div class="section"><h2>Observações</h2><div style="font-size:13px; color:#374151; line-height:1.5;">${assist.obs}</div></div>` : ''}
  ${(assist.assinatura_guincheiro || assist.assinatura_cliente) ? `
  <div class="section">
    <h2>Assinaturas Coletadas</h2>
    <div style="display:grid; grid-template-columns:1fr 1fr; gap:24px; margin-top:8px;">
      <div style="text-align:center;">
        ${assist.assinatura_guincheiro ? `<img src="${assist.assinatura_guincheiro}" style="max-width:100%; max-height:80px; border-bottom:1px solid #0F172A; padding-bottom:4px; margin-bottom:6px;" />` : '<div style="height:80px; border-bottom:1px solid #0F172A; margin-bottom:6px;"></div>'}
        <div style="font-size:11px; color:#0F172A; font-weight:600;">${assist.nome_guincheiro || assist.motorista_nome || 'Guincheiro'}</div>
        <div style="font-size:10px; color:#64748B;">Assinatura do Guincheiro</div>
      </div>
      <div style="text-align:center;">
        ${assist.assinatura_cliente ? `<img src="${assist.assinatura_cliente}" style="max-width:100%; max-height:80px; border-bottom:1px solid #0F172A; padding-bottom:4px; margin-bottom:6px;" />` : '<div style="height:80px; border-bottom:1px solid #0F172A; margin-bottom:6px;"></div>'}
        <div style="font-size:11px; color:#0F172A; font-weight:600;">${assist.nome_cliente || 'Cliente'}</div>
        <div style="font-size:10px; color:#64748B;">Assinatura do Cliente</div>
      </div>
    </div>
    ${assist.data_finalizacao ? `<div style="text-align:center; margin-top:12px; font-size:11px; color:#64748B;">📅 Finalizado em ${new Date(assist.data_finalizacao).toLocaleString('pt-BR')}</div>` : ''}
  </div>
  ` : `<div class="signatures">
    <div class="sig">Assinatura do Cliente</div>
    <div class="sig">Assinatura do Motorista</div>
  </div>`}
  <div class="footer">Documento gerado em ${dataEmissao} · Caririaçu Guincho · Rapidez · Segurança · Confiança · ${numDoc}</div>
</div>
<script>setTimeout(() => window.print(), 400);</script>
</body></html>`;

  const win = window.open('', '_blank', 'width=860,height=900');
  if (!win) { showToast('Habilite popups para gerar o PDF', 'warning'); return; }
  win.document.write(html); win.document.close();
  showToast(`OS de ${numDoc} pronta`, 'success');
};

const gerarListaAssistenciasPDF = (rows) => {
  const dataEmissao = new Date().toLocaleDateString('pt-BR');
  const numDoc = `LIST-${Date.now().toString().slice(-6)}`;
  const total = rows.reduce((s, a) => s + Number(a.valor || 0), 0);
  const finalizadas = rows.filter(r => r.status === 'finalizada').length;
  const STATUS_LABEL = { aberta: 'Aberta', atendimento: 'Em Atend.', agendada: 'Agendada', finalizada: 'Finalizada', cancelada: 'Cancelada' };

  const linhas = rows.map(a => `
    <tr>
      <td style="font-family:'Courier New',monospace; color:#3B82F6; font-weight:600;">${a.numero || '#' + a.id}</td>
      <td style="white-space:nowrap; color:#64748B;">${new Date(a.data).toLocaleDateString('pt-BR')}</td>
      <td style="font-family:'Courier New',monospace;">${a.placa || ''}</td>
      <td>${a.veiculo || ''}</td>
      <td>${a.servico}</td>
      <td>${a.cliente}</td>
      <td>${(a.motorista_nome || '').split(' ')[0]}</td>
      <td class="r" style="color:#10B981; font-family:'Courier New',monospace;">R$ ${Number(a.valor).toFixed(2)}</td>
      <td><span class="badge badge-${a.status}">${STATUS_LABEL[a.status] || a.status}</span></td>
    </tr>`).join('');

  const html = `<!DOCTYPE html><html lang="pt-BR"><head><meta charset="UTF-8"><title>Lista de Assistências</title>
<link rel="icon" type="image/png" href="${window.location.origin}/logo.png" />
<style>
  * { margin:0; padding:0; box-sizing:border-box; }
  body { font-family:'Segoe UI',Arial,sans-serif; color:#0F172A; padding:30px; background:#fff; }
  .doc { max-width:1100px; margin:0 auto; border:2px solid #0F172A; }
  .header { background:linear-gradient(135deg,#1E293B,#0F172A); color:#fff; padding:20px 28px; display:flex; justify-content:space-between; align-items:center; }
  .header h1 { font-size:20px; font-weight:700; }
  .header .logo { display:flex; align-items:center; gap:12px; }
  .header .logo img { width:48px; height:48px; border-radius:50%; object-fit:cover; transform:scale(1.08); box-shadow:0 0 0 2px rgba(245,158,11,0.6); }
  .header .logo-text { font-size:11px; opacity:0.8; letter-spacing:1px; text-transform:uppercase; }
  .summary { padding:16px 28px; background:#F8FAFC; border-bottom:1px solid #E2E8F0; display:grid; grid-template-columns:repeat(4,1fr); gap:12px; }
  .summary-item .l { font-size:11px; color:#64748B; text-transform:uppercase; letter-spacing:0.5px; font-weight:600; }
  .summary-item .v { font-size:18px; font-weight:700; color:#0F172A; font-family:'Courier New',monospace; margin-top:2px; }
  table { width:100%; border-collapse:collapse; font-size:11px; }
  th { background:#F8FAFC; padding:10px 12px; text-align:left; font-size:11px; color:#64748B; text-transform:uppercase; letter-spacing:0.5px; border-bottom:2px solid #E2E8F0; }
  th.r { text-align:right; }
  td { padding:8px 12px; font-size:11px; border-bottom:1px solid #F1F5F9; color:#374151; }
  td.r { text-align:right; font-weight:600; }
  .badge { display:inline-block; padding:2px 7px; border-radius:5px; font-size:10px; font-weight:700; }
  .badge-aberta { background:#EFF6FF; color:#2563EB; }
  .badge-atendimento { background:#FFFBEB; color:#B45309; }
  .badge-finalizada { background:#ECFDF5; color:#047857; }
  .badge-cancelada { background:#FEF2F2; color:#DC2626; }
  .badge-agendada { background:#F5F3FF; color:#7C3AED; }
  .footer { padding:16px 28px; text-align:center; font-size:11px; color:#94A3B8; }
  .print-btn { position:fixed; top:20px; right:20px; background:#F59E0B; color:#0F172A; border:none; padding:12px 22px; border-radius:8px; font-size:14px; font-weight:700; cursor:pointer; box-shadow:0 4px 12px rgba(0,0,0,0.15); }
  @media print { body { padding:0; } .print-btn { display:none; } .doc { border:1px solid #0F172A; } @page { size: landscape; } }
</style></head><body>
<button class="print-btn" onclick="window.print()">📥 Salvar como PDF / Imprimir</button>
<div class="doc">
  <div class="header">
    <div class="logo"><img src="${window.location.origin}/logo.png" alt="Caririaçu Guincho" /><div><h1>Caririaçu Guincho</h1><div class="logo-text">Relatório de Assistências</div></div></div>
    <div style="text-align:right; font-size:12px;"><div style="opacity:0.8;">Nº ${numDoc}</div><div style="margin-top:4px; font-weight:600;">${dataEmissao}</div></div>
  </div>
  <div class="summary">
    <div class="summary-item"><div class="l">Total de Registros</div><div class="v">${rows.length}</div></div>
    <div class="summary-item"><div class="l">Finalizadas</div><div class="v" style="color:#10B981;">${finalizadas}</div></div>
    <div class="summary-item"><div class="l">Faturamento Total</div><div class="v" style="color:#10B981;">R$ ${total.toFixed(2)}</div></div>
    <div class="summary-item"><div class="l">Ticket Médio</div><div class="v">R$ ${(total / (rows.length || 1)).toFixed(2)}</div></div>
  </div>
  <div style="padding:16px 28px;">
    <table>
      <thead><tr><th>Nº</th><th>Data</th><th>Placa</th><th>Veículo</th><th>Serviço</th><th>Cliente</th><th>Motorista</th><th class="r">Valor</th><th>Status</th></tr></thead>
      <tbody>${linhas || `<tr><td colspan="9" style="text-align:center; color:#94A3B8; padding:20px;">Nenhuma assistência registrada</td></tr>`}</tbody>
    </table>
  </div>
  <div class="footer">Relatório gerado em ${dataEmissao} · Caririaçu Guincho · Rapidez · Segurança · Confiança · ${numDoc}</div>
</div>
<script>setTimeout(() => window.print(), 400);</script>
</body></html>`;

  const win = window.open('', '_blank', 'width=1100,height=900');
  if (!win) { showToast('Habilite popups para gerar o PDF', 'warning'); return; }
  win.document.write(html); win.document.close();
  showToast('Lista exportada — selecione "Salvar como PDF"', 'success');
};

// ── Modal de Detalhes da Assistência ─────────────────────────────────────
const ViewAssistModal = ({ assist, onClose, onEdit, onCancel, onComplete }) => {
  const [motoristaInfo, setMotoristaInfo] = useStateA({});
  const [seguradoraInfo, setSeguradoraInfo] = useStateA({});
  const [frotaInfo, setFrotaInfo] = useStateA({});

  useEffectA(() => {
    if (!assist) return;
    (async () => {
      const m = assist.motorista_id ? await db.one('motoristas', assist.motorista_id) : null;
      const s = assist.seguradora_id ? await db.one('seguradoras', assist.seguradora_id) : null;
      setMotoristaInfo(m || {});
      setSeguradoraInfo(s || {});
      if (m?.guincho_code) {
        const fr = await db.list('frota', { eq: { code: m.guincho_code } });
        setFrotaInfo(fr[0] || {});
      } else setFrotaInfo({});
    })();
  }, [assist?.id]);

  if (!assist) return null;

  const STATUS_COLORS = {
    aberta:      { bg: 'linear-gradient(135deg,#3B82F6 0%,#2563EB 100%)', label: 'Aberta' },
    atendimento: { bg: 'linear-gradient(135deg,#F59E0B 0%,#D97706 100%)', label: 'Em Atendimento' },
    agendada:    { bg: 'linear-gradient(135deg,#8B5CF6 0%,#7C3AED 100%)', label: 'Agendada' },
    finalizada:  { bg: 'linear-gradient(135deg,#10B981 0%,#059669 100%)', label: 'Finalizada' },
    cancelada:   { bg: 'linear-gradient(135deg,#EF4444 0%,#DC2626 100%)', label: 'Cancelada' },
  };
  const sc = STATUS_COLORS[assist.status] || STATUS_COLORS.aberta;

  const buildTimeline = () => {
    const t = new Date(assist.data).toLocaleString('pt-BR');
    const base = [{ icon: 'plus', label: 'Chamado registrado', desc: `Origem: ${assist.cliente}`, time: t, color: '#3B82F6' }];
    if (['atendimento','finalizada','cancelada'].includes(assist.status)) {
      base.push({ icon: 'user', label: 'Motorista designado', desc: `${assist.motorista_nome || '—'}`, time: t, color: '#8B5CF6' });
    }
    if (['atendimento','finalizada'].includes(assist.status)) {
      base.push({ icon: 'truck', label: 'Em atendimento', desc: `Saída para ${assist.origem}`, time: t, color: '#F59E0B' });
    }
    if (assist.status === 'finalizada') {
      base.push({ icon: 'check', label: 'Serviço finalizado', desc: `Entregue em ${assist.destino}`, time: t, color: '#10B981' });
    }
    if (assist.status === 'cancelada') {
      base.push({ icon: 'x', label: 'Assistência cancelada', desc: 'Cancelamento registrado', time: t, color: '#EF4444' });
    }
    return base;
  };

  const InfoBlock = ({ icon, title, color, children, full }) => (
    <div style={{ background: '#fff', border: '1px solid #E2E8F0', borderRadius: 12, padding: 16, gridColumn: full ? '1 / -1' : 'auto', display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{ width: 28, height: 28, borderRadius: 8, background: `${color}15`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name={icon} size={15} color={color} />
        </div>
        <span style={{ fontSize: 12, fontWeight: 700, color: '#0F172A', textTransform: 'uppercase', letterSpacing: '0.5px' }}>{title}</span>
      </div>
      {children}
    </div>
  );

  const Field = ({ label, value, mono }) => (
    <div>
      <div style={{ fontSize: 11, color: '#94A3B8', fontWeight: 500, marginBottom: 2 }}>{label}</div>
      <div style={{ fontSize: 13, color: '#0F172A', fontWeight: 500, fontFamily: mono ? 'DM Mono, monospace' : 'Inter, sans-serif' }}>{value || '—'}</div>
    </div>
  );

  return (
    <Modal open={!!assist} onClose={onClose} title={`Detalhes ${assist.numero || '#' + assist.id}`} width={820} noPad>
      <div style={{ background: sc.bg, padding: '20px 24px', color: '#fff', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', right: -20, top: -20, width: 140, height: 140, borderRadius: '50%', background: 'rgba(255,255,255,0.08)' }} />
        <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, opacity: 0.85, letterSpacing: '0.5px', textTransform: 'uppercase', marginBottom: 4 }}>Identificador</div>
            <div style={{ fontSize: 24, fontFamily: 'DM Mono, monospace', fontWeight: 700, marginBottom: 6 }}>{assist.numero || `#${assist.id}`}</div>
            <div style={{ display: 'flex', gap: 16, fontSize: 12, opacity: 0.95, flexWrap: 'wrap' }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}><Icon name="calendar" size={13} color="#fff" /> {new Date(assist.data).toLocaleString('pt-BR')}</span>
              <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}><Icon name="truck" size={13} color="#fff" /> {assist.servico}</span>
            </div>
          </div>
          <div style={{ background: 'rgba(255,255,255,0.18)', borderRadius: 10, padding: '8px 14px', textAlign: 'center' }}>
            <div style={{ fontSize: 10, fontWeight: 600, opacity: 0.85, letterSpacing: '0.5px', textTransform: 'uppercase', marginBottom: 2 }}>Status</div>
            <div style={{ fontSize: 15, fontWeight: 700 }}>{sc.label}</div>
          </div>
        </div>
      </div>

      <div style={{ padding: 20, background: '#F8FAFC', display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 14, maxHeight: '55vh', overflowY: 'auto' }}>
        <InfoBlock icon="clipboard" title="Serviço" color="#F59E0B">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <Field label="Categoria" value={assist.servico} />
            <Field label="Abertura" value={new Date(assist.data).toLocaleString('pt-BR')} />
          </div>
        </InfoBlock>

        <InfoBlock icon="dollar" title="Financeiro" color="#10B981">
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
            <span style={{ fontSize: 11, color: '#94A3B8', fontWeight: 500 }}>R$</span>
            <span style={{ fontSize: 26, fontWeight: 700, color: '#10B981', fontFamily: 'DM Mono, monospace' }}>{Number(assist.valor).toFixed(2)}</span>
          </div>
          <div style={{ fontSize: 11, color: '#64748B' }}>Valor cobrado pelo serviço</div>
        </InfoBlock>

        <InfoBlock icon="truck" title="Veículo Atendido" color="#3B82F6">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <Field label="Placa" value={assist.placa} mono />
            <Field label="Modelo / Cor" value={assist.veiculo} />
          </div>
        </InfoBlock>

        <InfoBlock icon="building" title="Cliente / Seguradora" color="#8B5CF6">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <Field label="Nome" value={assist.cliente} />
            <Field label="Contato" value={seguradoraInfo.contato} />
            <Field label="Telefone" value={seguradoraInfo.telefone} mono />
            <Field label="E-mail" value={seguradoraInfo.email} />
          </div>
        </InfoBlock>

        <InfoBlock icon="map" title="Rota do Serviço" color="#EF4444" full>
          <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', paddingTop: 4 }}>
              <div style={{ width: 12, height: 12, borderRadius: '50%', background: '#10B981', boxShadow: '0 0 0 3px #10B98130' }} />
              <div style={{ width: 2, flex: 1, background: 'repeating-linear-gradient(to bottom,#CBD5E1 0,#CBD5E1 4px,transparent 4px,transparent 8px)', minHeight: 28 }} />
              <div style={{ width: 12, height: 12, borderRadius: '50%', background: '#EF4444', boxShadow: '0 0 0 3px #EF444430' }} />
            </div>
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div>
                <div style={{ fontSize: 11, color: '#10B981', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px' }}>Origem</div>
                <div style={{ fontSize: 14, color: '#0F172A', fontWeight: 500 }}>{assist.origem || '—'}</div>
              </div>
              <div>
                <div style={{ fontSize: 11, color: '#EF4444', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px' }}>Destino</div>
                <div style={{ fontSize: 14, color: '#0F172A', fontWeight: 500 }}>{assist.destino || '—'}</div>
              </div>
            </div>
          </div>
        </InfoBlock>

        <InfoBlock icon="user" title="Motorista Responsável" color="#0EA5E9" full>
          {assist.motorista_id ? (
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <Avatar initials={assist.motorista_avatar || (assist.motorista_nome || '').split(' ').map(w=>w[0]).join('').slice(0,2).toUpperCase()} size={52} />
              <div style={{ flex: 1, display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 12 }}>
                <Field label="Nome" value={assist.motorista_nome} />
                <Field label="Telefone" value={motoristaInfo.telefone} mono />
                <Field label="CNH (categoria)" value={motoristaInfo.categoria ? `Cat. ${motoristaInfo.categoria}` : '—'} />
                <Field label="Guincho" value={motoristaInfo.guincho_code ? `${motoristaInfo.guincho_code} · ${frotaInfo.placa || ''}` : '—'} mono />
              </div>
            </div>
          ) : (
            <div style={{ padding: 12, color: '#94A3B8', fontSize: 13, textAlign: 'center', fontStyle: 'italic' }}>Sem motorista designado</div>
          )}
        </InfoBlock>

        <InfoBlock icon="chart" title="Linha do Tempo" color="#64748B" full>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
            {buildTimeline().map((ev, i, arr) => (
              <div key={i} style={{ display: 'flex', gap: 12 }}>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                  <div style={{ width: 32, height: 32, borderRadius: '50%', background: `${ev.color}15`, border: `2px solid ${ev.color}`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <Icon name={ev.icon} size={14} color={ev.color} />
                  </div>
                  {i < arr.length - 1 && <div style={{ width: 2, flex: 1, background: '#E2E8F0', minHeight: 16, margin: '4px 0' }} />}
                </div>
                <div style={{ flex: 1, paddingBottom: i < arr.length - 1 ? 16 : 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: '#0F172A' }}>{ev.label}</div>
                  <div style={{ fontSize: 12, color: '#64748B', marginTop: 2 }}>{ev.desc}</div>
                  <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 2, fontFamily: 'DM Mono, monospace' }}>{ev.time}</div>
                </div>
              </div>
            ))}
          </div>
        </InfoBlock>

        <InfoBlock icon="fileText" title="Observações" color="#94A3B8" full>
          <div style={{ padding: 12, background: '#F8FAFC', borderRadius: 8, fontSize: 13, color: assist.obs ? '#0F172A' : '#94A3B8', fontStyle: assist.obs ? 'normal' : 'italic', lineHeight: 1.5 }}>{assist.obs || 'Nenhuma observação registrada.'}</div>
        </InfoBlock>
      </div>

      <div style={{ padding: '14px 20px', borderTop: '1px solid #E2E8F0', background: '#fff', display: 'flex', gap: 8, justifyContent: 'space-between', flexWrap: 'wrap', borderBottomLeftRadius: 20, borderBottomRightRadius: 20 }}>
        <Btn variant="secondary" icon="download" onClick={() => gerarAssistenciaPDF(assist)}>Imprimir</Btn>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {assist.status !== 'cancelada' && assist.status !== 'finalizada' && (
            <Btn variant="secondary" icon="x" onClick={onCancel}>Cancelar</Btn>
          )}
          {assist.status !== 'finalizada' && assist.status !== 'cancelada' && (
            <Btn variant="blue" icon="check" onClick={onComplete}>Finalizar</Btn>
          )}
          <Btn variant="primary" icon="edit" onClick={onEdit}>Editar</Btn>
        </div>
      </div>
    </Modal>
  );
};

const AssistenciasScreen = () => {
  const [rows, setRows] = useStateA([]);
  const [loading, setLoading] = useStateA(true);
  const [busca, setBusca] = useStateA('');
  const [filtroStatus, setFiltroStatus] = useStateA('');
  const [filtroServ, setFiltroServ] = useStateA('');
  const [page, setPage] = useStateA(1);
  const [modalNew, setModalNew] = useStateA(false);
  const [viewing, setViewing] = useStateA(null);
  const [editing, setEditing] = useStateA(null);
  const [finalizing, setFinalizing] = useStateA(null);
  const PER = 6;

  const refresh = async () => {
    setLoading(true);
    setRows(await db.list('assistencias', { order: 'data' }));
    setLoading(false);
  };
  useEffectA(() => { refresh(); }, []);

  const filtered = rows.filter(r => {
    const q = busca.toLowerCase();
    const matchQ = !q || (r.numero || '').toLowerCase().includes(q) || (r.placa || '').toLowerCase().includes(q) || (r.cliente || '').toLowerCase().includes(q) || (r.motorista_nome || '').toLowerCase().includes(q);
    const matchS = !filtroStatus || r.status === filtroStatus;
    const matchSv = !filtroServ || r.servico === filtroServ;
    return matchQ && matchS && matchSv;
  });
  const paged = filtered.slice((page-1)*PER, page*PER);

  const handleCancel = async (id) => {
    const updated = await db.update('assistencias', id, { status: 'cancelada' });
    if (updated) { showToast('Assistência cancelada', 'warning'); refresh(); }
  };

  const openFinalize = (a) => setFinalizing(a);

  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' }}>Assistências</h1>
          <span style={{ fontSize: 13, color: '#64748B' }}>{rows.length} assistências cadastradas</span>
        </div>
        <Btn variant="primary" icon="plus" onClick={() => setModalNew(true)}>Nova Assistência</Btn>
      </div>

      <Card style={{ padding: 16 }}>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
          <div style={{ position: 'relative', flex: 1, minWidth: 200 }}>
            <Icon name="search" size={15} color="#94A3B8" style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)' }} />
            <input value={busca} onChange={e => { setBusca(e.target.value); setPage(1); }}
              placeholder="Buscar por número, placa, cliente..."
              style={{ width: '100%', paddingLeft: 34, paddingRight: 12, paddingTop: 9, paddingBottom: 9, borderRadius: 8, border: '1px solid #E2E8F0', fontSize: 13, color: '#0F172A', fontFamily: 'Inter, sans-serif', outline: 'none', boxSizing: 'border-box' }} />
          </div>
          <select value={filtroStatus} onChange={e => { setFiltroStatus(e.target.value); setPage(1); }} style={{ padding: '9px 12px', borderRadius: 8, border: '1px solid #E2E8F0', fontSize: 13, color: '#374151', outline: 'none', background: '#fff', cursor: 'pointer' }}>
            <option value="">Todos os status</option>
            {STATUSES.map(s => <option key={s} value={s}>{s.charAt(0).toUpperCase()+s.slice(1)}</option>)}
          </select>
          <select value={filtroServ} onChange={e => { setFiltroServ(e.target.value); setPage(1); }} style={{ padding: '9px 12px', borderRadius: 8, border: '1px solid #E2E8F0', fontSize: 13, color: '#374151', outline: 'none', background: '#fff', cursor: 'pointer' }}>
            <option value="">Todas as categorias</option>
            {SERVICOS.map(s => <option key={s} value={s}>{s}</option>)}
          </select>
          <Btn variant="secondary" size="sm" icon="download" onClick={() => gerarListaAssistenciasPDF(filtered)}>Exportar PDF</Btn>
        </div>
      </Card>

      <Card style={{ padding: 0, overflow: 'hidden' }}>
        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#94A3B8', fontSize: 14 }}>Carregando assistências...</div>
        ) : paged.length === 0 ? (
          <div style={{ padding: 60, textAlign: 'center' }}>
            <Icon name="clipboard" size={48} color="#CBD5E1" />
            <div style={{ fontSize: 16, color: '#64748B', marginTop: 14, fontWeight: 600 }}>{rows.length === 0 ? 'Nenhuma assistência cadastrada' : 'Nenhuma assistência encontrada'}</div>
            <div style={{ fontSize: 13, color: '#94A3B8', marginTop: 4 }}>{rows.length === 0 ? 'Clique em "Nova Assistência" para começar' : 'Tente ajustar os filtros'}</div>
            {rows.length === 0 && <Btn variant="primary" icon="plus" onClick={() => setModalNew(true)} style={{ marginTop: 16 }}>Nova Assistência</Btn>}
          </div>
        ) : (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, fontFamily: 'Inter, sans-serif' }}>
              <thead>
                <tr style={{ background: '#F8FAFC' }}>
                  {['Nº','Data/Hora','Placa','Veículo','Serviço','Cliente','Motorista','Valor','Status','Ações'].map(h => (
                    <th key={h} style={{ padding: '11px 14px', textAlign: 'left', fontSize: 12, fontWeight: 600, color: '#64748B', whiteSpace: 'nowrap', borderBottom: '1px solid #E2E8F0' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {paged.map((a, i) => (
                  <tr key={a.id} style={{ background: i % 2 ? '#F8FAFC' : '#fff', transition: 'background 0.1s', cursor: 'pointer' }}
                    onClick={() => setViewing(a)}
                    onMouseEnter={e => e.currentTarget.style.background = '#EFF6FF'}
                    onMouseLeave={e => e.currentTarget.style.background = i % 2 ? '#F8FAFC' : '#fff'}>
                    <td style={{ padding: '10px 14px', fontFamily: 'DM Mono, monospace', fontSize: 12, color: '#3B82F6', fontWeight: 600 }}>{a.numero || `#${a.id}`}</td>
                    <td style={{ padding: '10px 14px', color: '#64748B', whiteSpace: 'nowrap', fontSize: 12 }}>{new Date(a.data).toLocaleString('pt-BR')}</td>
                    <td style={{ padding: '10px 14px' }}>
                      <span style={{ background: '#F1F5F9', borderRadius: 5, padding: '2px 7px', fontFamily: 'DM Mono, monospace', fontSize: 12, color: '#374151', fontWeight: 600 }}>{a.placa || '—'}</span>
                    </td>
                    <td style={{ padding: '10px 14px', color: '#374151', whiteSpace: 'nowrap' }}>{a.veiculo || '—'}</td>
                    <td style={{ padding: '10px 14px', color: '#374151', whiteSpace: 'nowrap' }}>{a.servico}</td>
                    <td style={{ padding: '10px 14px', color: '#374151', whiteSpace: 'nowrap' }}>{a.cliente}</td>
                    <td style={{ padding: '10px 14px' }}>
                      {a.motorista_nome ? (
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                          <Avatar initials={a.motorista_avatar || a.motorista_nome.split(' ').map(w=>w[0]).join('').slice(0,2).toUpperCase()} size={24} />
                          <span style={{ color: '#374151', whiteSpace: 'nowrap' }}>{a.motorista_nome.split(' ')[0]}</span>
                        </div>
                      ) : <span style={{ color: '#94A3B8' }}>—</span>}
                    </td>
                    <td style={{ padding: '10px 14px', fontFamily: 'DM Mono, monospace', color: '#10B981', fontWeight: 600, textAlign: 'right', whiteSpace: 'nowrap' }}>R$ {Number(a.valor).toFixed(2)}</td>
                    <td style={{ padding: '10px 14px' }}><StatusBadge status={a.status} /></td>
                    <td style={{ padding: '10px 14px' }} onClick={e => e.stopPropagation()}>
                      <div style={{ display: 'flex', gap: 4 }}>
                        <button title="Ver" onClick={() => setViewing(a)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#3B82F6', padding: 4, borderRadius: 6 }} onMouseEnter={e=>e.currentTarget.style.background='#EFF6FF'} onMouseLeave={e=>e.currentTarget.style.background='none'}><Icon name="eye" size={15} /></button>
                        <button title="Editar" onClick={() => setEditing(a)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#64748B', padding: 4, borderRadius: 6 }} onMouseEnter={e=>e.currentTarget.style.background='#F1F5F9'} onMouseLeave={e=>e.currentTarget.style.background='none'}><Icon name="edit" size={15} /></button>
                        <button title="Cancelar" onClick={() => handleCancel(a.id)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#EF4444', padding: 4, borderRadius: 6 }} onMouseEnter={e=>e.currentTarget.style.background='#FEF2F2'} onMouseLeave={e=>e.currentTarget.style.background='none'}><Icon name="x" size={15} /></button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        <div style={{ padding: '14px 20px', borderTop: '1px solid #F1F5F9', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
          <span style={{ fontSize: 13, color: '#64748B' }}>Mostrando {Math.min(filtered.length, PER)} de {filtered.length} registros</span>
          <Pagination page={page} total={filtered.length} perPage={PER} onChange={setPage} />
        </div>
      </Card>

      <NewAssistModal open={modalNew} onClose={() => setModalNew(false)} onSave={() => refresh()} />

      <EditAssistModal
        assist={editing}
        onClose={() => setEditing(null)}
        onSave={() => { showToast('Assistência atualizada!', 'success'); refresh(); }}
      />

      <ViewAssistModal
        assist={viewing}
        onClose={() => setViewing(null)}
        onEdit={() => { const a = viewing; setViewing(null); setEditing(a); }}
        onCancel={() => { handleCancel(viewing.id); setViewing(null); }}
        onComplete={() => { const a = viewing; setViewing(null); openFinalize(a); }}
      />

      <FinalizeAssistModal
        assist={finalizing}
        onClose={() => setFinalizing(null)}
        onFinalized={refresh}
      />

      <button onClick={() => setModalNew(true)} style={{
        position: 'fixed',
        bottom: 'max(28px, calc(env(safe-area-inset-bottom) + 16px))',
        right: 'max(28px, calc(env(safe-area-inset-right) + 16px))',
        width: 52, height: 52,
        borderRadius: '50%', background: '#F59E0B', border: 'none', cursor: 'pointer',
        boxShadow: '0 4px 16px rgba(245,158,11,0.5)', display: 'flex',
        alignItems: 'center', justifyContent: 'center', zIndex: 400,
        transition: 'transform 0.2s, box-shadow 0.2s'
      }}
      onMouseEnter={e=>{ e.currentTarget.style.transform='scale(1.08)'; e.currentTarget.style.boxShadow='0 6px 20px rgba(245,158,11,0.6)'; }}
      onMouseLeave={e=>{ e.currentTarget.style.transform='scale(1)'; e.currentTarget.style.boxShadow='0 4px 16px rgba(245,158,11,0.5)'; }}>
        <Icon name="plus" size={22} color="#0F172A" />
      </button>
    </div>
  );
};

Object.assign(window, { AssistenciasScreen });
