// Caririaçu Guincho — Motoristas + Seguradoras Screens

const { useState: useStateM, useEffect: useEffectMC } = React;

// ── Modal de Detalhes do Motorista ───────────────────────────────────────
const MotoristaDetailModal = ({ motorista, onClose, onEdit, onToggleStatus }) => {
  const [assistencias, setAssist] = useStateM([]);
  const [frotaInfo, setFrotaInfo] = useStateM({});

  useEffectMC(() => {
    if (!motorista) return;
    db.list('assistencias', { eq: { motorista_id: motorista.id }, order: 'data' }).then(setAssist);
    if (motorista.guincho_code) {
      db.list('frota', { eq: { code: motorista.guincho_code } }).then(rows => setFrotaInfo(rows[0] || {}));
    } else setFrotaInfo({});
  }, [motorista?.id]);

  if (!motorista) return null;

  const sc = {
    disponivel:  { bg: 'linear-gradient(135deg,#10B981 0%,#059669 100%)', label: 'Disponível' },
    atendimento: { bg: 'linear-gradient(135deg,#F59E0B 0%,#D97706 100%)', label: 'Em Atendimento' },
    inativo:     { bg: 'linear-gradient(135deg,#64748B 0%,#475569 100%)', label: 'Inativo' },
  }[motorista.status] || { bg: 'linear-gradient(135deg,#3B82F6 0%,#2563EB 100%)', label: motorista.status };

  const faturamento = assistencias.filter(a => a.status === 'finalizada').reduce((s,a) => s + Number(a.valor || 0), 0);
  const finalizadas = assistencias.filter(a => a.status === 'finalizada').length;
  const taxa = assistencias.length > 0 ? Math.round(finalizadas / assistencias.length * 100) : 0;

  const venc = motorista.venc_cnh ? new Date(motorista.venc_cnh) : null;
  const hoje = new Date();
  const diasParaVenc = venc ? Math.ceil((venc - hoje) / (1000 * 60 * 60 * 24)) : null;
  const cnhAlerta = diasParaVenc !== null && diasParaVenc < 90;

  const KpiCard = ({ icon, label, value, color, sub }) => (
    <div style={{ background: '#fff', border: '1px solid #E2E8F0', borderRadius: 12, padding: 14, display: 'flex', flexDirection: 'column', gap: 6 }}>
      <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={14} color={color} />
        </div>
        <span style={{ fontSize: 11, color: '#64748B', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px' }}>{label}</span>
      </div>
      <div style={{ fontSize: 20, fontWeight: 700, color: '#0F172A', fontFamily: 'DM Mono, monospace' }}>{value}</div>
      {sub && <div style={{ fontSize: 11, color: '#94A3B8' }}>{sub}</div>}
    </div>
  );

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

  return (
    <Modal open={!!motorista} onClose={onClose} title={`Perfil do Motorista`} width={820} noPad>
      <div style={{ background: sc.bg, padding: '24px', color: '#fff', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', right: -30, top: -30, width: 160, height: 160, borderRadius: '50%', background: 'rgba(255,255,255,0.08)' }} />
        <div style={{ position: 'absolute', right: 60, bottom: -50, width: 110, height: 110, borderRadius: '50%', background: 'rgba(255,255,255,0.06)' }} />
        <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <div style={{
              width: 72, height: 72, borderRadius: '50%',
              background: 'rgba(255,255,255,0.22)', backdropFilter: 'blur(6px)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 26, fontWeight: 700, fontFamily: 'DM Sans, sans-serif',
              border: '3px solid rgba(255,255,255,0.35)'
            }}>{motorista.avatar || motorista.nome.split(' ').map(w => w[0]).join('').slice(0,2).toUpperCase()}</div>
            <div>
              <div style={{ fontSize: 22, fontWeight: 700, fontFamily: 'DM Sans, sans-serif', marginBottom: 2 }}>{motorista.nome}</div>
              <div style={{ fontSize: 13, opacity: 0.95, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
                <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}><Icon name="phone" size={12} color="#fff" />{motorista.telefone || '—'}</span>
                <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}><Icon name="truck" size={12} color="#fff" />{motorista.guincho_code || '—'}</span>
              </div>
            </div>
          </div>
          <div style={{ background: 'rgba(255,255,255,0.18)', borderRadius: 10, padding: '8px 14px', backdropFilter: 'blur(6px)', 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', maxHeight: '60vh', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 10 }}>
          <KpiCard icon="clipboard" label="Assistências" value={assistencias.length} color="#3B82F6" sub="histórico" />
          <KpiCard icon="check" label="Finalizadas" value={finalizadas} color="#10B981" sub={`${taxa}% taxa`} />
          <KpiCard icon="dollar" label="Faturamento" value={`R$ ${faturamento.toFixed(0)}`} color="#F59E0B" sub="finalizadas" />
          <KpiCard icon="calendar" label="Venc. CNH" value={venc ? venc.toLocaleDateString('pt-BR') : '—'} color={cnhAlerta ? '#EF4444' : '#8B5CF6'} sub={diasParaVenc !== null ? (diasParaVenc > 0 ? `${diasParaVenc} dias` : `vencida há ${-diasParaVenc} dias`) : '—'} />
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 14 }}>
          <InfoBlock icon="user" title="Documentação" color="#3B82F6">
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <Field label="Número CNH" value={motorista.cnh} mono />
              <Field label="Categoria" value={motorista.categoria ? `Cat. ${motorista.categoria}` : '—'} />
              <Field label="Vencimento" value={venc ? venc.toLocaleDateString('pt-BR') : '—'} color={cnhAlerta ? '#EF4444' : undefined} />
              <Field label="Situação" value={diasParaVenc !== null ? (diasParaVenc > 0 ? 'Regular' : 'Vencida') : '—'} color={diasParaVenc !== null && diasParaVenc > 0 ? '#10B981' : '#EF4444'} />
            </div>
            {cnhAlerta && diasParaVenc > 0 && (
              <div style={{ background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 8, padding: 10, display: 'flex', gap: 8, alignItems: 'center' }}>
                <Icon name="alert" size={14} color="#DC2626" />
                <span style={{ fontSize: 12, color: '#991B1B' }}>CNH vence em {diasParaVenc} dias — providenciar renovação</span>
              </div>
            )}
          </InfoBlock>

          <InfoBlock icon="truck" title="Guincho Vinculado" color="#F59E0B">
            {frotaInfo.placa ? (
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <Field label="Código" value={motorista.guincho_code} mono />
                <Field label="Placa" value={frotaInfo.placa} mono />
                <Field label="Modelo" value={frotaInfo.modelo} />
                <Field label="Ano / Cor" value={`${frotaInfo.ano || ''} · ${frotaInfo.cor || ''}`} />
              </div>
            ) : (
              <div style={{ padding: 8, color: '#94A3B8', fontSize: 13, textAlign: 'center', fontStyle: 'italic' }}>Sem guincho vinculado</div>
            )}
          </InfoBlock>
        </div>

        <InfoBlock icon="chart" title="Performance" color="#8B5CF6" full>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: '#64748B', marginBottom: 6 }}>
                <span>Taxa de Finalização</span>
                <span style={{ fontWeight: 700, color: '#0F172A' }}>{taxa}%</span>
              </div>
              <div style={{ height: 8, borderRadius: 4, background: '#E2E8F0', overflow: 'hidden' }}>
                <div style={{ height: '100%', width: `${taxa}%`, background: 'linear-gradient(90deg,#10B981,#059669)', transition: 'width 0.4s' }} />
              </div>
            </div>
            <div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: '#64748B', marginBottom: 6 }}>
                <span>Volume de Atendimentos</span>
                <span style={{ fontWeight: 700, color: '#0F172A' }}>{assistencias.length}</span>
              </div>
              <div style={{ height: 8, borderRadius: 4, background: '#E2E8F0', overflow: 'hidden' }}>
                <div style={{ height: '100%', width: `${Math.min(100, (assistencias.length / 100) * 100)}%`, background: 'linear-gradient(90deg,#3B82F6,#2563EB)', transition: 'width 0.4s' }} />
              </div>
            </div>
          </div>
        </InfoBlock>

        <div style={{ background: '#fff', border: '1px solid #E2E8F0', borderRadius: 12, overflow: 'hidden' }}>
          <div style={{ padding: '12px 16px', borderBottom: '1px solid #F1F5F9', display: 'flex', alignItems: 'center', gap: 8 }}>
            <Icon name="clipboard" size={14} color="#3B82F6" />
            <span style={{ fontSize: 12, fontWeight: 700, color: '#0F172A', textTransform: 'uppercase', letterSpacing: '0.5px' }}>Assistências recentes</span>
            <span style={{ fontSize: 11, color: '#94A3B8', marginLeft: 'auto' }}>{assistencias.length} registros</span>
          </div>
          {assistencias.length === 0 ? (
            <div style={{ padding: 24, textAlign: 'center', color: '#94A3B8', fontSize: 13 }}>Nenhuma assistência vinculada a este motorista.</div>
          ) : (
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
              <thead>
                <tr style={{ background: '#F8FAFC' }}>
                  {['Nº','Data','Cliente','Serviço','Valor','Status'].map(h => (
                    <th key={h} style={{ padding: '8px 14px', textAlign: 'left', fontSize: 11, fontWeight: 600, color: '#64748B', borderBottom: '1px solid #E2E8F0' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {assistencias.map((a,i) => (
                  <tr key={a.id} style={{ background: i % 2 ? '#F8FAFC' : '#fff' }}>
                    <td style={{ padding: '8px 14px', fontFamily: 'DM Mono, monospace', color: '#3B82F6', fontWeight: 600 }}>{a.numero || `#${a.id}`}</td>
                    <td style={{ padding: '8px 14px', color: '#64748B', whiteSpace: 'nowrap' }}>{new Date(a.data).toLocaleDateString('pt-BR')}</td>
                    <td style={{ padding: '8px 14px', color: '#374151' }}>{a.cliente}</td>
                    <td style={{ padding: '8px 14px', color: '#374151' }}>{a.servico}</td>
                    <td style={{ padding: '8px 14px', fontFamily: 'DM Mono, monospace', color: '#10B981', fontWeight: 600 }}>R$ {Number(a.valor).toFixed(2)}</td>
                    <td style={{ padding: '8px 14px' }}><StatusBadge status={a.status} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>

      <div style={{
        padding: '14px 20px', borderTop: '1px solid #E2E8F0', background: '#fff',
        display: 'flex', justifyContent: 'space-between', gap: 8, flexWrap: 'wrap',
        borderBottomLeftRadius: 20, borderBottomRightRadius: 20
      }}>
        <Btn variant="secondary" icon="phone" onClick={() => motorista.telefone ? window.location.href = `tel:${motorista.telefone}` : showToast('Sem telefone cadastrado','warning')}>Ligar</Btn>
        <div style={{ display: 'flex', gap: 8 }}>
          <Btn variant="secondary" icon={motorista.status === 'inativo' ? 'check' : 'x'} onClick={onToggleStatus}>
            {motorista.status === 'inativo' ? 'Ativar' : 'Inativar'}
          </Btn>
          <Btn variant="primary" icon="edit" onClick={onEdit}>Editar</Btn>
        </div>
      </div>
    </Modal>
  );
};

const MotoristasScreen = () => {
  const [motoristas, setMotoristas] = useStateM([]);
  const [loading, setLoading] = useStateM(true);
  const [modal, setModal] = useStateM(false);
  const [editItem, setEditItem] = useStateM(null);
  const [detailItem, setDetailItem] = useStateM(null);
  const [busca, setBusca] = useStateM('');
  const [form, setForm] = useStateM({ nome: '', telefone: '', cpf: '', cnh: '', categoria: 'E', venc_cnh: '', status: 'disponivel' });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

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

  const filtered = motoristas.filter(m => !busca || m.nome.toLowerCase().includes(busca.toLowerCase()));

  const openNew = () => { setEditItem(null); setForm({ nome: '', telefone: '', cpf: '', cnh: '', categoria: 'E', venc_cnh: '', status: 'disponivel' }); setModal(true); };
  const openEdit = (item) => { setEditItem(item); setForm({ nome: item.nome, telefone: item.telefone || '', cpf: item.cpf || '', cnh: item.cnh || '', categoria: item.categoria || 'E', venc_cnh: item.venc_cnh || '', status: item.status }); setModal(true); };

  const handleSave = async () => {
    if (!form.nome) { showToast('Informe o nome', 'warning'); return; }
    const av = form.nome.split(' ').map(w => w[0]).join('').slice(0,2).toUpperCase();
    const payload = { ...form, avatar: av, venc_cnh: form.venc_cnh || null };
    if (editItem) {
      const updated = await db.update('motoristas', editItem.id, payload);
      if (updated) { showToast('Motorista atualizado!', 'success'); refresh(); }
    } else {
      const created = await db.insert('motoristas', payload);
      if (created) { showToast('Motorista cadastrado!', 'success'); refresh(); }
    }
    setModal(false);
  };

  const toggleStatus = async (m) => {
    const novoStatus = m.status === 'inativo' ? 'disponivel' : 'inativo';
    const updated = await db.update('motoristas', m.id, { status: novoStatus });
    if (updated) { showToast('Status atualizado!', 'success'); refresh(); }
  };

  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' }}>Motoristas</h1>
          <span style={{ fontSize: 13, color: '#64748B' }}>{motoristas.length} motoristas · {motoristas.filter(m=>m.status==='disponivel').length} disponíveis</span>
        </div>
        <Btn variant="primary" icon="plus" onClick={openNew}>Novo Motorista</Btn>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(130px,1fr))', gap: 12 }}>
        {[
          { label: 'Disponíveis', val: motoristas.filter(m=>m.status==='disponivel').length, color: '#10B981' },
          { label: 'Em Atendimento', val: motoristas.filter(m=>m.status==='atendimento').length, color: '#F59E0B' },
          { label: 'Inativos', val: motoristas.filter(m=>m.status==='inativo').length, color: '#94A3B8' },
          { label: 'Total', val: motoristas.length, color: '#3B82F6' },
        ].map(s => (
          <Card key={s.label} style={{ padding: '14px 18px' }}>
            <div style={{ fontSize: 24, fontWeight: 700, color: s.color, fontFamily: 'DM Sans, sans-serif' }}>{s.val}</div>
            <div style={{ fontSize: 12, color: '#64748B', marginTop: 2 }}>{s.label}</div>
          </Card>
        ))}
      </div>

      <Card style={{ padding: 14 }}>
        <div style={{ position: 'relative' }}>
          <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)} placeholder="Buscar por nome..."
            style={{ width: '100%', paddingLeft: 34, paddingRight: 12, paddingTop: 9, paddingBottom: 9, borderRadius: 8, border: '1px solid #E2E8F0', fontSize: 13, fontFamily: 'Inter, sans-serif', outline: 'none', boxSizing: 'border-box' }} />
        </div>
      </Card>

      <Card style={{ padding: 0, overflow: 'hidden' }}>
        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#94A3B8', fontSize: 14 }}>Carregando...</div>
        ) : filtered.length === 0 ? (
          <div style={{ padding: 60, textAlign: 'center' }}>
            <Icon name="users" size={42} color="#CBD5E1" />
            <div style={{ fontSize: 15, color: '#64748B', marginTop: 12, fontWeight: 600 }}>{motoristas.length === 0 ? 'Nenhum motorista cadastrado' : 'Nenhum resultado'}</div>
            <div style={{ fontSize: 13, color: '#94A3B8', marginTop: 4 }}>{motoristas.length === 0 ? 'Cadastre o primeiro motorista clicando em "Novo Motorista"' : 'Tente outra busca'}</div>
          </div>
        ) : (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, fontFamily: 'Inter, sans-serif' }}>
              <thead>
                <tr style={{ background: '#F8FAFC' }}>
                  {['Motorista','Telefone','CNH','Categoria','Venc. CNH','Guincho','Assistências','Status','Ações'].map(h => (
                    <th key={h} style={{ padding: '11px 14px', textAlign: 'left', fontSize: 12, fontWeight: 600, color: '#64748B', borderBottom: '1px solid #E2E8F0', whiteSpace: 'nowrap' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {filtered.map((m, i) => (
                  <tr key={m.id} style={{ background: i%2 ? '#F8FAFC' : '#fff', transition: 'background 0.1s', cursor: 'pointer' }}
                    onClick={() => setDetailItem(m)}
                    onMouseEnter={e=>e.currentTarget.style.background='#EFF6FF'}
                    onMouseLeave={e=>e.currentTarget.style.background=i%2?'#F8FAFC':'#fff'}>
                    <td style={{ padding: '10px 14px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <Avatar initials={m.avatar || m.nome.split(' ').map(w=>w[0]).join('').slice(0,2).toUpperCase()} size={32} />
                        <span style={{ fontWeight: 600, color: '#0F172A' }}>{m.nome}</span>
                      </div>
                    </td>
                    <td style={{ padding: '10px 14px', color: '#64748B', fontFamily: 'DM Mono, monospace', fontSize: 12 }}>{m.telefone || '—'}</td>
                    <td style={{ padding: '10px 14px', color: '#64748B', fontFamily: 'DM Mono, monospace', fontSize: 12 }}>{m.cnh || '—'}</td>
                    <td style={{ padding: '10px 14px' }}>
                      <span style={{ background: '#EFF6FF', color: '#2563EB', borderRadius: 6, padding: '2px 8px', fontSize: 12, fontWeight: 700 }}>Cat. {m.categoria || '—'}</span>
                    </td>
                    <td style={{ padding: '10px 14px', color: '#64748B', fontSize: 12 }}>{m.venc_cnh ? new Date(m.venc_cnh).toLocaleDateString('pt-BR') : '—'}</td>
                    <td style={{ padding: '10px 14px', fontFamily: 'DM Mono, monospace', fontSize: 12, color: '#374151' }}>{m.guincho_code || '—'}</td>
                    <td style={{ padding: '10px 14px', fontFamily: 'DM Mono, monospace', fontWeight: 600, color: '#0F172A', textAlign: 'right' }}>{m.assistencias || 0}</td>
                    <td style={{ padding: '10px 14px' }}><StatusBadge status={m.status}/></td>
                    <td style={{ padding: '10px 14px' }} onClick={e => e.stopPropagation()}>
                      <div style={{ display: 'flex', gap: 4 }}>
                        <button title="Editar" onClick={() => openEdit(m)} 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={m.status==='inativo'?'Ativar':'Inativar'} onClick={() => toggleStatus(m)} style={{ background:'none',border:'none',cursor:'pointer',color:m.status==='inativo'?'#10B981':'#EF4444',padding:4,borderRadius:6 }} onMouseEnter={e=>e.currentTarget.style.background='#F8FAFC'} onMouseLeave={e=>e.currentTarget.style.background='none'}><Icon name={m.status==='inativo'?'check':'x'} size={15}/></button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>

      <MotoristaDetailModal
        motorista={detailItem}
        onClose={() => setDetailItem(null)}
        onEdit={() => { const m = detailItem; setDetailItem(null); openEdit(m); }}
        onToggleStatus={() => { const m = detailItem; setDetailItem(null); toggleStatus(m); }}
      />

      <Modal open={modal} onClose={() => setModal(false)} title={editItem ? 'Editar Motorista' : 'Novo Motorista'} width={520}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Input label="Nome Completo" placeholder="Carlos Silva" value={form.nome} onChange={e=>set('nome',e.target.value)} style={{gridColumn:'1/-1'}}/>
            <Input label="Telefone" placeholder="(88) 98765-4321" value={form.telefone} onChange={e=>set('telefone',e.target.value)}/>
            <Input label="CPF" placeholder="000.000.000-00" value={form.cpf} onChange={e=>set('cpf',e.target.value)}/>
            <Input label="Número CNH" placeholder="12345678900" value={form.cnh} onChange={e=>set('cnh',e.target.value)}/>
            <Select label="Categoria CNH" value={form.categoria} onChange={e=>set('categoria',e.target.value)} options={['B','C','D','E'].map(v=>({value:v,label:`Categoria ${v}`}))}/>
            <Input label="Vencimento CNH" type="date" value={form.venc_cnh || ''} onChange={e=>set('venc_cnh',e.target.value)}/>
            <Select label="Status" value={form.status} onChange={e=>set('status',e.target.value)} options={[{value:'disponivel',label:'Disponível'},{value:'atendimento',label:'Em Atendimento'},{value:'inativo',label:'Inativo'}]}/>
          </div>
          <div style={{ display:'flex', gap:10, justifyContent:'flex-end', paddingTop:8, borderTop:'1px solid #F1F5F9' }}>
            <Btn variant="secondary" onClick={()=>setModal(false)}>Cancelar</Btn>
            <Btn variant="primary" onClick={handleSave}>{editItem?'Salvar':'Cadastrar'}</Btn>
          </div>
        </div>
      </Modal>
    </div>
  );
};

// ── Modal de Detalhes da Seguradora ──────────────────────────────────────
const SeguradoraDetailModal = ({ seg, onClose, onEdit }) => {
  const [assistencias, setAssist] = useStateM([]);
  useEffectMC(() => {
    if (!seg) return;
    db.list('assistencias', { eq: { seguradora_id: seg.id }, order: 'data' }).then(setAssist);
  }, [seg?.id]);

  if (!seg) return null;
  const fmtBRL = v => Number(v || 0).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });

  const sc = seg.status === 'ativo'
    ? { bg: 'linear-gradient(135deg,#3B82F6 0%,#2563EB 100%)', label: 'Contrato Ativo' }
    : { bg: 'linear-gradient(135deg,#64748B 0%,#475569 100%)', label: 'Inativo' };

  const finalizadas = assistencias.filter(a => a.status === 'finalizada');
  const fatTotal = finalizadas.reduce((s,a) => s + Number(a.valor || 0), 0);
  const ticketMedio = finalizadas.length > 0 ? fatTotal / finalizadas.length : 0;
  const abertas = assistencias.filter(a => a.status === 'aberta' || a.status === 'atendimento').length;

  const porServico = {};
  assistencias.forEach(a => { porServico[a.servico] = (porServico[a.servico] || 0) + 1; });
  const servicoTop = Object.entries(porServico).sort((a,b) => b[1] - a[1])[0];

  const KpiCard = ({ icon, label, value, color, sub }) => (
    <div style={{ background: '#fff', border: '1px solid #E2E8F0', borderRadius: 12, padding: 14, display: 'flex', flexDirection: 'column', gap: 6 }}>
      <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={14} color={color} />
        </div>
        <span style={{ fontSize: 11, color: '#64748B', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px' }}>{label}</span>
      </div>
      <div style={{ fontSize: 18, fontWeight: 700, color: '#0F172A', fontFamily: 'DM Mono, monospace' }}>{value}</div>
      {sub && <div style={{ fontSize: 11, color: '#94A3B8' }}>{sub}</div>}
    </div>
  );

  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={!!seg} onClose={onClose} title={`Perfil da Seguradora`} width={840} noPad>
      <div style={{ background: sc.bg, padding: '24px', color: '#fff', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', right: -30, top: -30, width: 160, height: 160, borderRadius: '50%', background: 'rgba(255,255,255,0.08)' }} />
        <div style={{ position: 'absolute', right: 60, bottom: -50, width: 110, height: 110, borderRadius: '50%', background: 'rgba(255,255,255,0.06)' }} />
        <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <div style={{
              width: 64, height: 64, borderRadius: 14,
              background: 'rgba(255,255,255,0.22)', backdropFilter: 'blur(6px)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              border: '2px solid rgba(255,255,255,0.35)'
            }}>
              <Icon name="shield" size={28} color="#fff" />
            </div>
            <div>
              <div style={{ fontSize: 22, fontWeight: 700, fontFamily: 'DM Sans, sans-serif', marginBottom: 2 }}>{seg.nome}</div>
              <div style={{ fontSize: 13, opacity: 0.95, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
                <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}><Icon name="user" size={12} color="#fff" />{seg.contato || '—'}</span>
                <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}><Icon name="phone" size={12} color="#fff" />{seg.telefone || '—'}</span>
              </div>
            </div>
          </div>
          <div style={{ background: 'rgba(255,255,255,0.18)', borderRadius: 10, padding: '8px 14px', backdropFilter: 'blur(6px)', 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', maxHeight: '60vh', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 10 }}>
          <KpiCard icon="clipboard" label="Assist./mês" value={seg.assistencias_mes || 0} color="#3B82F6" sub={`${assistencias.length} no histórico`} />
          <KpiCard icon="dollar" label="Faturamento" value={fmtBRL(seg.faturamento)} color="#10B981" sub="receita total" />
          <KpiCard icon="trendUp" label="Ticket médio" value={ticketMedio > 0 ? fmtBRL(ticketMedio) : '—'} color="#F59E0B" sub="por atendimento" />
          <KpiCard icon="alert" label="Em aberto" value={abertas} color={abertas > 0 ? '#EF4444' : '#10B981'} sub={abertas > 0 ? 'aguardando' : 'tudo em dia'} />
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 14 }}>
          <InfoBlock icon="user" title="Contato Comercial" color="#3B82F6">
            <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 12 }}>
              <Field label="Responsável" value={seg.contato} />
              <Field label="Telefone" value={seg.telefone} mono />
              <Field label="E-mail" value={seg.email} />
            </div>
          </InfoBlock>

          <InfoBlock icon="chart" title="Resumo Operacional" color="#8B5CF6">
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <Field label="Total assistências" value={assistencias.length} />
              <Field label="Finalizadas" value={finalizadas.length} />
              <Field label="Em andamento" value={abertas} />
              <Field label="Serviço top" value={servicoTop ? `${servicoTop[0]} (${servicoTop[1]})` : '—'} />
            </div>
          </InfoBlock>
        </div>

        {Object.keys(porServico).length > 0 && (
          <InfoBlock icon="chart" title="Distribuição por Serviço" color="#F59E0B" full>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {Object.entries(porServico).sort((a,b) => b[1] - a[1]).map(([servico, qtd]) => {
                const pct = Math.round((qtd / assistencias.length) * 100);
                return (
                  <div key={servico}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 4 }}>
                      <span style={{ color: '#374151', fontWeight: 500 }}>{servico}</span>
                      <span style={{ color: '#64748B', fontFamily: 'DM Mono, monospace' }}>{qtd} · {pct}%</span>
                    </div>
                    <div style={{ height: 6, borderRadius: 3, background: '#E2E8F0', overflow: 'hidden' }}>
                      <div style={{ height: '100%', width: `${pct}%`, background: 'linear-gradient(90deg,#F59E0B,#D97706)' }} />
                    </div>
                  </div>
                );
              })}
            </div>
          </InfoBlock>
        )}

        <div style={{ background: '#fff', border: '1px solid #E2E8F0', borderRadius: 12, overflow: 'hidden' }}>
          <div style={{ padding: '12px 16px', borderBottom: '1px solid #F1F5F9', display: 'flex', alignItems: 'center', gap: 8 }}>
            <Icon name="clipboard" size={14} color="#3B82F6" />
            <span style={{ fontSize: 12, fontWeight: 700, color: '#0F172A', textTransform: 'uppercase', letterSpacing: '0.5px' }}>Assistências realizadas</span>
            <span style={{ fontSize: 11, color: '#94A3B8', marginLeft: 'auto' }}>{assistencias.length} registros</span>
          </div>
          {assistencias.length === 0 ? (
            <div style={{ padding: 24, textAlign: 'center', color: '#94A3B8', fontSize: 13 }}>Nenhuma assistência vinculada a esta seguradora.</div>
          ) : (
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
              <thead>
                <tr style={{ background: '#F8FAFC' }}>
                  {['Nº','Data','Veículo','Serviço','Motorista','Valor','Status'].map(h => (
                    <th key={h} style={{ padding: '8px 14px', textAlign: 'left', fontSize: 11, fontWeight: 600, color: '#64748B', borderBottom: '1px solid #E2E8F0' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {assistencias.map((a,i) => (
                  <tr key={a.id} style={{ background: i % 2 ? '#F8FAFC' : '#fff' }}>
                    <td style={{ padding: '8px 14px', fontFamily: 'DM Mono, monospace', color: '#3B82F6', fontWeight: 600 }}>{a.numero || `#${a.id}`}</td>
                    <td style={{ padding: '8px 14px', color: '#64748B', whiteSpace: 'nowrap' }}>{new Date(a.data).toLocaleDateString('pt-BR')}</td>
                    <td style={{ padding: '8px 14px', color: '#374151' }}>{a.veiculo}</td>
                    <td style={{ padding: '8px 14px', color: '#374151' }}>{a.servico}</td>
                    <td style={{ padding: '8px 14px', color: '#374151' }}>{(a.motorista_nome || '').split(' ')[0]}</td>
                    <td style={{ padding: '8px 14px', fontFamily: 'DM Mono, monospace', color: '#10B981', fontWeight: 600 }}>R$ {Number(a.valor).toFixed(2)}</td>
                    <td style={{ padding: '8px 14px' }}><StatusBadge status={a.status} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>

      <div style={{
        padding: '14px 20px', borderTop: '1px solid #E2E8F0', background: '#fff',
        display: 'flex', justifyContent: 'space-between', gap: 8, flexWrap: 'wrap',
        borderBottomLeftRadius: 20, borderBottomRightRadius: 20
      }}>
        <div style={{ display: 'flex', gap: 8 }}>
          <Btn variant="secondary" icon="phone" onClick={() => seg.telefone ? window.location.href = `tel:${seg.telefone}` : showToast('Sem telefone','warning')}>Ligar</Btn>
          <Btn variant="secondary" icon="mail" onClick={() => seg.email ? window.location.href = `mailto:${seg.email}` : showToast('Sem e-mail','warning')}>E-mail</Btn>
        </div>
        <Btn variant="primary" icon="edit" onClick={onEdit}>Editar</Btn>
      </div>
    </Modal>
  );
};

const SeguradorasScreen = () => {
  const [seguradoras, setSeguradoras] = useStateM([]);
  const [loading, setLoading] = useStateM(true);
  const [modal, setModal] = useStateM(false);
  const [editItem, setEditItem] = useStateM(null);
  const [detailItem, setDetailItem] = useStateM(null);
  const [form, setForm] = useStateM({ nome:'', contato:'', telefone:'', email:'', status:'ativo' });
  const set = (k,v) => setForm(f=>({...f,[k]:v}));
  const fmtBRL = v => Number(v || 0).toLocaleString('pt-BR',{style:'currency',currency:'BRL'});

  const refresh = async () => {
    setLoading(true);
    setSeguradoras(await db.list('seguradoras', { order: 'nome', asc: true }));
    setLoading(false);
  };
  useEffectMC(() => { refresh(); }, []);

  const openNew = () => { setEditItem(null); setForm({nome:'',contato:'',telefone:'',email:'',status:'ativo'}); setModal(true); };
  const openEdit = (s) => { setEditItem(s); setForm({nome:s.nome,contato:s.contato||'',telefone:s.telefone||'',email:s.email||'',status:s.status}); setModal(true); };
  const handleSave = async () => {
    if (!form.nome) { showToast('Informe o nome', 'warning'); return; }
    if (editItem) {
      const updated = await db.update('seguradoras', editItem.id, form);
      if (updated) { showToast('Seguradora atualizada!','success'); refresh(); }
    } else {
      const created = await db.insert('seguradoras', form);
      if (created) { showToast('Seguradora cadastrada!','success'); refresh(); }
    }
    setModal(false);
  };

  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' }}>Seguradoras</h1>
          <span style={{ fontSize:13, color:'#64748B' }}>{seguradoras.length} seguradoras cadastradas</span>
        </div>
        <Btn variant="primary" icon="plus" onClick={openNew}>Nova Seguradora</Btn>
      </div>

      <Card style={{ padding:0, overflow:'hidden' }}>
        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#94A3B8', fontSize: 14 }}>Carregando...</div>
        ) : seguradoras.length === 0 ? (
          <div style={{ padding: 60, textAlign: 'center' }}>
            <Icon name="shield" size={42} color="#CBD5E1" />
            <div style={{ fontSize: 15, color: '#64748B', marginTop: 12, fontWeight: 600 }}>Nenhuma seguradora cadastrada</div>
            <div style={{ fontSize: 13, color: '#94A3B8', marginTop: 4 }}>Cadastre a primeira clicando em "Nova Seguradora"</div>
          </div>
        ) : (
          <table style={{ width:'100%', borderCollapse:'collapse', fontSize:13, fontFamily:'Inter, sans-serif' }}>
            <thead>
              <tr style={{ background:'#F8FAFC' }}>
                {['Seguradora','Contato','Telefone','Email','Assist./mês','Faturamento','Status','Ações'].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>
              {seguradoras.map((s,i)=>(
                <tr key={s.id} style={{ background:i%2?'#F8FAFC':'#fff', transition:'background 0.1s', cursor: 'pointer' }}
                  onClick={() => setDetailItem(s)}
                  onMouseEnter={e=>e.currentTarget.style.background='#EFF6FF'}
                  onMouseLeave={e=>e.currentTarget.style.background=i%2?'#F8FAFC':'#fff'}>
                  <td style={{ padding:'12px 16px' }}>
                    <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                      <div style={{ width:34,height:34,borderRadius:9,background:'#EFF6FF',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0 }}>
                        <Icon name="shield" size={16} color="#3B82F6"/>
                      </div>
                      <span style={{ fontWeight:600, color:'#0F172A' }}>{s.nome}</span>
                    </div>
                  </td>
                  <td style={{ padding:'12px 16px', color:'#374151' }}>{s.contato || '—'}</td>
                  <td style={{ padding:'12px 16px', color:'#64748B', fontFamily:'DM Mono, monospace', fontSize:12 }}>{s.telefone || '—'}</td>
                  <td style={{ padding:'12px 16px', color:'#3B82F6', fontSize:12 }}>{s.email || '—'}</td>
                  <td style={{ padding:'12px 16px', fontFamily:'DM Mono, monospace', fontWeight:700, color:'#0F172A', textAlign:'right' }}>{s.assistencias_mes || 0}</td>
                  <td style={{ padding:'12px 16px', fontFamily:'DM Mono, monospace', color:'#10B981', fontWeight:700, textAlign:'right' }}>{fmtBRL(s.faturamento)}</td>
                  <td style={{ padding:'12px 16px' }}><StatusBadge status={s.status}/></td>
                  <td style={{ padding:'12px 16px' }} onClick={e => e.stopPropagation()}>
                    <div style={{ display:'flex', gap:4 }}>
                      <button title="Editar" onClick={()=>openEdit(s)} 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="Ver detalhes" onClick={()=>setDetailItem(s)} 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>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </Card>

      <SeguradoraDetailModal
        seg={detailItem}
        onClose={() => setDetailItem(null)}
        onEdit={() => { const s = detailItem; setDetailItem(null); openEdit(s); }}
      />

      <Modal open={modal} onClose={()=>setModal(false)} title={editItem?'Editar Seguradora':'Nova Seguradora'} width={480}>
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <Input label="Nome da Seguradora" placeholder="Porto Seguro" value={form.nome} onChange={e=>set('nome',e.target.value)}/>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
            <Input label="Contato Principal" placeholder="Ana Rodrigues" value={form.contato} onChange={e=>set('contato',e.target.value)}/>
            <Input label="Telefone" placeholder="(88) 3000-9000" value={form.telefone} onChange={e=>set('telefone',e.target.value)}/>
          </div>
          <Input label="E-mail" placeholder="operacional@seguradora.com.br" value={form.email} onChange={e=>set('email',e.target.value)}/>
          <Select label="Status do Contrato" value={form.status} onChange={e=>set('status',e.target.value)} options={[{value:'ativo',label:'Ativo'},{value:'inativo',label:'Inativo'}]}/>
          <div style={{ display:'flex', gap:10, justifyContent:'flex-end', paddingTop:8, borderTop:'1px solid #F1F5F9' }}>
            <Btn variant="secondary" onClick={()=>setModal(false)}>Cancelar</Btn>
            <Btn variant="primary" onClick={handleSave}>{editItem?'Salvar':'Cadastrar'}</Btn>
          </div>
        </div>
      </Modal>
    </div>
  );
};

Object.assign(window, { MotoristasScreen, SeguradorasScreen });
