Files
scoreodonto.com/frontend/views/LancarGTO.tsx
T
VPS 4 Builder fbaf478eaf feat(lancar-gto): faces/obs por dente, campo descricao_mobile e layout mobile em 3 slides
- Cada dente selecionado tem seu próprio input de face e observação (não mais unificado)
- ADICIONAR ITEM cria um GTOItem por dente com face/obs individual
- Layout mobile em 3 páginas: pág 1 paciente/especialidade/dentista, pág 2 odontograma, pág 3 faces/obs + rascunho
- Navegação mobile com footer fixo: VOLTAR | indicador de página | PRÓXIMO / FINALIZAR
- Campo descricao_mobile no cadastro de procedimentos (versão curta para celular)
- ALTER TABLE procedimentos ADD COLUMN descricao_mobile TEXT (já executado no DB)
- Desktop mantém layout coluna dupla original sem mudança

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 04:43:50 +02:00

878 lines
46 KiB
TypeScript

import React, { useState, useEffect, useMemo } from 'react';
import {
Users,
Trash2,
Check,
Building2,
AlertCircle,
PlusCircle,
Camera,
Stethoscope,
ChevronRight,
ChevronLeft,
Search,
X
} from 'lucide-react';
import { PageHeader } from '../components/PageHeader.tsx';
import { HybridBackend } from '../services/backend.ts';
import { Paciente, Dentista, Procedimento, Especialidade } from '../types.ts';
import { useToast } from '../contexts/ToastContext.tsx';
import { create } from 'zustand';
// --- STORES ---
interface GTOItem {
id: string;
procedimentoId: string;
codigoTUSS: string;
codigoInterno: string;
descricao: string;
dente?: string;
face?: string;
arco?: string;
quantidade: number;
valorUnitario: number;
valorTotal: number;
observacao?: string;
}
interface GTOStore {
paciente: Paciente | null;
dentista: Dentista | null;
credenciada: string;
items: GTOItem[];
pendingSearch: string;
setPaciente: (p: Paciente | null) => void;
setDentista: (d: Dentista | null) => void;
setCredenciada: (c: string) => void;
addItem: (item: GTOItem) => void;
removeItem: (id: string) => void;
clear: () => void;
setPendingSearch: (s: string) => void;
}
const useGTOStore = create<GTOStore>((set) => ({
paciente: null,
dentista: null,
credenciada: 'CASSEMS - SEDE CENTRAL',
items: [],
pendingSearch: '',
setPaciente: (paciente) => set({ paciente }),
setDentista: (dentista) => set({ dentista }),
setCredenciada: (credenciada) => set({ credenciada }),
addItem: (item) => set((state) => ({
items: [...state.items, item].slice(0, 20)
})),
removeItem: (id) => set((state) => ({
items: state.items.filter(i => i.id !== id)
})),
clear: () => set({ paciente: null, dentista: null, items: [] }),
setPendingSearch: (pendingSearch) => set({ pendingSearch }),
}));
export { useGTOStore };
// --- ODONTOGRAM DATA (4x2 Grid Layout) ---
const DENTES_ADULTO = {
q1: [14, 13, 12, 11, 18, 17, 16, 15],
q2: [21, 22, 23, 24, 25, 26, 27, 28],
q4: [44, 43, 42, 41, 48, 47, 46, 45],
q3: [31, 32, 33, 34, 35, 36, 37, 38],
extras: { q1: 19, q2: 29, q4: 49, q3: 39 }
};
const DENTES_CRIANCA = {
q1: [null, 53, 52, 51, null, null, 55, 54],
q2: [61, 62, 63, null, 64, 65, null, null],
q4: [null, 83, 82, 81, null, null, 85, 84],
q3: [71, 72, 73, null, 74, 75, null, null]
};
const normalize = (s: string) =>
s.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().trim();
// --- COMPONENT ---
export const LancarGTO: React.FC = () => {
const store = useGTOStore();
const toast = useToast();
const [pacientes, setPacientes] = useState<Paciente[]>([]);
const [dentistas, setDentistas] = useState<Dentista[]>([]);
const [especialidades, setEspecialidades] = useState<Especialidade[]>([]);
const [procedimentos, setProcedimentos] = useState<Procedimento[]>([]);
const [selectedEsp, setSelectedEsp] = useState<string>('');
const [selectedProc, setSelectedProc] = useState<Procedimento | null>(null);
const [pacienteTipo, setPacienteTipo] = useState<'ADULTO' | 'CRIANCA'>('ADULTO');
const [showMixed, setShowMixed] = useState(false);
const [selectedDentes, setSelectedDentes] = useState<string[]>([]);
const [selectedArco, setSelectedArco] = useState<'AI' | 'AS' | null>(null);
// Per-tooth face/obs
const [denteInputs, setDenteInputs] = useState<Record<string, { face: string; obs: string }>>({});
// Arco/Geral face/obs (single)
const [arcoFace, setArcoFace] = useState('');
const [arcoObs, setArcoObs] = useState('');
const [mobilePage, setMobilePage] = useState<1 | 2 | 3>(1);
const [patientSearchOpen, setPatientSearchOpen] = useState(false);
const [patientSearchTerm, setPatientSearchTerm] = useState('');
useEffect(() => {
const load = async () => {
const p = await HybridBackend.getPacientes();
const d = await HybridBackend.getDentistas();
const es = await HybridBackend.getEspecialidades();
const pr = await HybridBackend.getProcedimentos();
setPacientes(Array.isArray(p) ? p : (p?.data ?? []));
setDentistas(d ?? []);
setEspecialidades(es ?? []);
setProcedimentos(pr ?? []);
};
load();
}, []);
const filteredProcedimentos = useMemo(() => {
if (!selectedEsp) return [];
return procedimentos.filter(p => p.especialidadeId === selectedEsp);
}, [selectedEsp, procedimentos]);
const filteredPatients = useMemo(() => {
if (!patientSearchTerm) return pacientes.slice(0, 30);
const term = normalize(patientSearchTerm);
return pacientes.filter(p =>
normalize(p.nome).includes(term) ||
(p.cpf && p.cpf.includes(patientSearchTerm.replace(/\D/g, '')))
).slice(0, 30);
}, [pacientes, patientSearchTerm]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
const { pendingSearch } = store;
if (!pendingSearch || pacientes.length === 0) return;
const term = normalize(pendingSearch);
const matches = pacientes.filter(p => {
const n = normalize(p.nome);
return n === term || n.includes(term) || term.includes(n);
});
if (matches.length === 1) {
store.setPaciente(matches[0]);
} else if (matches.length > 1) {
setPatientSearchTerm(pendingSearch);
setPatientSearchOpen(true);
} else {
setPatientSearchOpen(true);
}
store.setPendingSearch('');
}, [pacientes, store.pendingSearch]); // eslint-disable-line react-hooks/exhaustive-deps
const resetProcSelection = () => {
setSelectedDentes([]);
setSelectedArco(null);
setDenteInputs({});
setArcoFace('');
setArcoObs('');
};
const toggleDente = (num: string) => {
if (selectedProc?.tipo_regiao !== 'DENTE') {
toast.error("ESTE PROCEDIMENTO NÃO PERMITE SELEÇÃO DE DENTE INDIVIDUAL.");
return;
}
setSelectedArco(null);
if (selectedDentes.includes(num)) {
setDenteInputs(di => { const next = { ...di }; delete next[num]; return next; });
setSelectedDentes(prev => prev.filter(d => d !== num));
} else {
setDenteInputs(di => ({ ...di, [num]: { face: '', obs: '' } }));
setSelectedDentes(prev => [...prev, num]);
}
};
const selectArco = (arco: 'AI' | 'AS') => {
if (selectedProc?.tipo_regiao !== 'ARCO') {
toast.error("ESTE PROCEDIMENTO NÃO PERMITE SELEÇÃO DE ARCO.");
return;
}
setSelectedDentes([]);
setDenteInputs({});
setSelectedArco(arco);
};
const handleAddItem = () => {
if (!selectedProc) {
toast.error("SELECIONE UM PROCEDIMENTO PRIMEIRO.");
return;
}
if (selectedProc.tipo_regiao === 'DENTE' && selectedDentes.length === 0) {
toast.error("ESTE PROCEDIMENTO EXIGE A SELEÇÃO DE AO MENOS UM DENTE.");
return;
}
if (selectedProc.tipo_regiao === 'ARCO' && !selectedArco) {
toast.error("ESTE PROCEDIMENTO EXIGE A SELEÇÃO DE UM ARCO (AI/AS).");
return;
}
if (selectedProc.tipo_regiao === 'DENTE') {
if (selectedProc.exige_face) {
const semFace = selectedDentes.filter(d => !denteInputs[d]?.face?.trim());
if (semFace.length > 0) {
toast.error(`FACE OBRIGATÓRIA PARA: ${semFace.join(', ')}`);
return;
}
}
selectedDentes.forEach(dente => {
const inp = denteInputs[dente] || { face: '', obs: '' };
store.addItem({
id: Math.random().toString(36).substring(7),
procedimentoId: selectedProc.id,
codigoTUSS: selectedProc.codigo || '000000',
codigoInterno: selectedProc.codigoInterno || '',
descricao: selectedProc.nome,
dente,
face: inp.face,
quantidade: 1,
valorUnitario: selectedProc.valorParticular || 0,
valorTotal: selectedProc.valorParticular || 0,
observacao: inp.obs || undefined,
});
});
toast.success(`${selectedDentes.length} ITEM(S) ADICIONADO(S) AO RASCUNHO.`);
} else {
if (selectedProc.exige_face && !arcoFace.trim()) {
toast.error("A FACE É OBRIGATÓRIA PARA ESTE PROCEDIMENTO.");
return;
}
store.addItem({
id: Math.random().toString(36).substring(7),
procedimentoId: selectedProc.id,
codigoTUSS: selectedProc.codigo || '000000',
codigoInterno: selectedProc.codigoInterno || '',
descricao: selectedProc.nome,
arco: selectedArco || undefined,
face: arcoFace,
quantidade: 1,
valorUnitario: selectedProc.valorParticular || 0,
valorTotal: selectedProc.valorParticular || 0,
observacao: arcoObs || undefined,
});
toast.success("ADICIONADO AO RASCUNHO.");
}
resetProcSelection();
};
const handleFinalize = async () => {
if (!store.paciente || !store.dentista || store.items.length === 0) {
toast.error("PACIENTE, DENTISTA E PELO MENOS 1 ITEM SÃO OBRIGATÓRIOS.");
return;
}
try {
toast.success("GTO GERADA COM SUCESSO!");
store.clear();
setSelectedEsp('');
setSelectedProc(null);
resetProcSelection();
} catch {
toast.error("ERRO AO GERAR GTO.");
}
};
const totalGeral = store.items.reduce((sum, i) => sum + i.valorTotal, 0);
const toggleMixed = () => {
if (showMixed) {
if (pacienteTipo === 'ADULTO') {
const toRemove = selectedDentes.filter(d => parseInt(d) >= 50);
setDenteInputs(di => { const next = { ...di }; toRemove.forEach(d => delete next[d]); return next; });
setSelectedDentes(prev => prev.filter(d => parseInt(d) < 50));
} else {
const toRemove = selectedDentes.filter(d => parseInt(d) < 50);
setDenteInputs(di => { const next = { ...di }; toRemove.forEach(d => delete next[d]); return next; });
setSelectedDentes(prev => prev.filter(d => parseInt(d) >= 50));
}
}
setShowMixed(prev => !prev);
};
const renderDenteBtn = (num: number | string | null, keyIdx?: number) => {
if (num === null) return <div key={`empty-${keyIdx}`} className="w-7 h-7 sm:w-9 sm:h-9" />;
const sStr = num.toString();
const isDeciduo = parseInt(sStr) >= 50;
const isSelected = selectedDentes.includes(sStr);
const isDisabled = !!selectedProc && selectedProc.tipo_regiao !== 'DENTE';
return (
<button
key={sStr}
onClick={() => toggleDente(sStr)}
disabled={isDisabled}
className={`w-7 h-7 sm:w-9 sm:h-9 rounded-lg border-2 text-[9px] sm:text-[11px] font-black transition-all shadow-sm flex items-center justify-center
${isSelected
? isDeciduo
? 'bg-amber-500 border-amber-600 text-white scale-110 z-10'
: 'bg-blue-600 border-blue-700 text-white scale-110 z-10'
: isDisabled
? 'bg-gray-50 border-gray-100 text-gray-300 cursor-not-allowed opacity-50'
: isDeciduo
? 'bg-white border-amber-200 text-amber-700 hover:border-amber-400 hover:bg-amber-50'
: 'bg-white border-gray-200 text-gray-700 hover:border-blue-400 hover:bg-blue-50'}
`}
>
{sStr}
</button>
);
};
// ─── JSX SECTIONS ───────────────────────────────────────────────
const step1Card = (
<div className="bg-white p-6 rounded-3xl border border-gray-100 shadow-xl space-y-4">
<div className="flex items-center gap-3 text-blue-600 font-black text-base uppercase tracking-wider">
<Users size={20} strokeWidth={3} /> 01. Paciente
</div>
{store.paciente ? (
<div className="flex items-center justify-between bg-blue-50 border-2 border-blue-200 rounded-2xl px-4 py-3">
<div className="flex items-center gap-3 min-w-0">
<div className="w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center text-white font-black text-xs flex-shrink-0">
{store.paciente.nome.charAt(0)}
</div>
<span className="font-black text-blue-800 text-sm uppercase truncate">{store.paciente.nome}</span>
</div>
<button
onClick={() => store.setPaciente(null)}
className="text-xs font-bold text-blue-500 hover:text-red-500 transition-colors flex-shrink-0 ml-3 uppercase"
>
ALTERAR
</button>
</div>
) : (
<button
onClick={() => setPatientSearchOpen(true)}
className="w-full p-4 bg-gray-50 border-2 border-dashed border-blue-200 rounded-2xl font-black text-blue-400 text-sm hover:bg-blue-50 hover:border-blue-400 transition-all uppercase flex items-center justify-center gap-2"
>
<Search size={16} /> SELECIONAR BENEFICIÁRIO
</button>
)}
</div>
);
const step2Card = (
<div className="bg-white p-6 rounded-3xl border border-gray-100 shadow-xl space-y-5">
<div className="flex items-center gap-3 text-orange-500 font-black text-base uppercase tracking-wider">
<Stethoscope size={20} strokeWidth={3} /> 02. Especialidade
</div>
<div className="space-y-3">
<select
value={selectedEsp}
onChange={(e) => {
setSelectedEsp(e.target.value);
setSelectedProc(null);
resetProcSelection();
}}
className="w-full p-4 bg-gray-50 border-2 border-gray-100 rounded-2xl font-black text-gray-700 text-sm focus:border-orange-400 outline-none transition-all uppercase"
>
<option value="">ESCOLHA A ÁREA...</option>
{especialidades.map(es => <option key={es.id} value={es.id}>{es.nome}</option>)}
</select>
{selectedEsp && (
<div className="space-y-2">
<select
value={selectedProc?.id || ''}
onChange={(e) => {
const pr = procedimentos.find(p => p.id === e.target.value);
setSelectedProc(pr || null);
resetProcSelection();
}}
className="w-full p-4 bg-white border-2 border-orange-100 rounded-2xl font-black text-gray-800 text-sm shadow-inner uppercase"
>
<option value="">BUSCAR PROCEDIMENTO</option>
{filteredProcedimentos.map(p => <option key={p.id} value={p.id}>{p.nome}</option>)}
</select>
{selectedProc && (
<div className="bg-orange-50 p-3 rounded-xl border border-orange-100 animate-in fade-in slide-in-from-top-1 duration-300">
<p className="text-[9px] font-black text-orange-600 uppercase mb-1">REGRAS DE SELEÇÃO</p>
<div className="flex flex-col gap-1">
<span className="text-[10px] font-bold text-orange-800 flex items-center gap-1">
<ChevronRight size={10} />
{selectedProc.tipo_regiao === 'DENTE' ? 'EXIGE DENTE(S)' : selectedProc.tipo_regiao === 'ARCO' ? 'EXIGE ARCO (AI/AS)' : 'PROCEDIMENTO GERAL'}
</span>
{selectedProc.exige_face && (
<span className="text-[10px] font-bold text-red-600 flex items-center gap-1">
<ChevronRight size={10} /> EXIGE FACE CLÍNICA
</span>
)}
</div>
</div>
)}
</div>
)}
</div>
</div>
);
const step3Card = (
<div className="bg-white p-6 rounded-3xl border border-gray-100 shadow-xl space-y-4">
<div className="flex items-center gap-3 text-[#2d6a4f] font-black text-base uppercase tracking-wider">
<Check size={20} strokeWidth={3} className="bg-green-100 p-1 rounded-full text-green-700" /> 03. Dentista Executor
</div>
<select
value={store.dentista?.id || ''}
onChange={(e) => {
const d = dentistas.find(d => d.id === e.target.value);
store.setDentista(d || null);
}}
className="w-full p-4 bg-gray-50 border-2 border-gray-100 rounded-2xl font-black text-gray-800 text-sm focus:border-green-500 outline-none transition-all uppercase"
>
<option value="">SELECIONE O PROFISSIONAL</option>
{dentistas.map(d => <option key={d.id} value={d.id}>{d.nome}</option>)}
</select>
</div>
);
// Per-tooth inputs (DENTE procedure) or unified (ARCO/GERAL)
const isPerTooth = selectedProc?.tipo_regiao === 'DENTE' && selectedDentes.length > 0;
const step4Card = (
<div className="bg-white p-6 rounded-3xl border border-gray-100 shadow-xl space-y-4">
<div className="flex items-center justify-between">
<p className="text-[10px] font-black text-gray-400 uppercase tracking-widest">
04. {isPerTooth ? `Face / Obs por Dente (${selectedDentes.length})` : 'Face & Observações'}
</p>
{selectedProc?.exige_face && (
<span className="text-red-500 text-[9px] font-black animate-pulse">* OBRIGATÓRIO</span>
)}
</div>
{isPerTooth ? (
<div className="space-y-3 max-h-64 overflow-y-auto pr-1">
{selectedDentes.map(dente => {
const isDeciduo = parseInt(dente) >= 50;
const inp = denteInputs[dente] || { face: '', obs: '' };
return (
<div key={dente} className="bg-gray-50 rounded-2xl p-3 border border-gray-100 space-y-2">
<div className="flex items-center gap-2">
<span className={`w-8 h-8 rounded-lg flex items-center justify-center text-[11px] font-black flex-shrink-0
${isDeciduo ? 'bg-amber-100 text-amber-700 border border-amber-200' : 'bg-blue-100 text-blue-700 border border-blue-200'}`}>
{dente}
</span>
<span className="text-[10px] font-bold text-gray-500 uppercase truncate flex-1">
{selectedProc?.descricao_mobile || selectedProc?.nome}
</span>
</div>
<div className="grid grid-cols-2 gap-2">
<input
type="text"
value={inp.face}
onChange={e => setDenteInputs(prev => ({
...prev,
[dente]: { ...(prev[dente] || {}), face: e.target.value.toUpperCase() }
}))}
placeholder={selectedProc?.exige_face ? 'FACE *' : 'O,M,D,V,L,P'}
className={`p-2 border-2 rounded-xl text-[11px] font-black outline-none transition-all
${selectedProc?.exige_face && !inp.face
? 'border-red-200 bg-red-50 focus:border-red-400'
: 'border-gray-200 bg-white focus:border-amber-400'}`}
/>
<input
type="text"
value={inp.obs}
onChange={e => setDenteInputs(prev => ({
...prev,
[dente]: { ...(prev[dente] || {}), obs: e.target.value }
}))}
placeholder="OBS"
className="p-2 border-2 border-gray-200 bg-white rounded-xl text-[11px] outline-none focus:border-amber-400 transition-all"
/>
</div>
</div>
);
})}
</div>
) : (
<div className="grid grid-cols-1 gap-4">
<div>
<label className="block text-[10px] font-black text-gray-400 uppercase tracking-widest mb-2">
Face (O, M, D, V, L, P)
</label>
<input
type="text"
value={arcoFace}
onChange={e => setArcoFace(e.target.value.toUpperCase())}
disabled={selectedProc?.tipo_regiao === 'GERAL' && !selectedProc?.exige_face}
className={`w-full p-4 border-2 rounded-2xl text-sm font-black outline-none transition-all
${selectedProc?.exige_face ? 'bg-red-50 border-red-100 focus:border-red-400' : 'bg-gray-50 border-gray-100 focus:border-amber-400'}
`}
placeholder={selectedProc?.exige_face ? "DIGITE AS FACES..." : "OPCIONAL"}
/>
</div>
<div>
<label className="block text-[10px] font-black text-gray-400 uppercase tracking-widest mb-2 italic">Observações Clínicas</label>
<div className="relative">
<textarea
value={arcoObs}
onChange={e => setArcoObs(e.target.value)}
className="w-full p-4 bg-gray-50 border-2 border-gray-100 rounded-2xl text-[11px] h-20 focus:border-amber-400 outline-none transition-all"
/>
<PlusCircle size={24} className="absolute bottom-4 right-4 text-green-500 opacity-50" />
</div>
</div>
</div>
)}
</div>
);
const actionsDesktop = (
<div className="grid grid-cols-4 gap-4 p-2">
<button
onClick={handleAddItem}
className="col-span-3 bg-[#2d6a4f] text-white py-5 rounded-3xl font-black text-lg uppercase shadow-2xl shadow-green-200 hover:bg-[#1b4332] active:scale-95 transition-all flex items-center justify-center gap-3 group"
>
ADICIONAR ITEM <ChevronRight className="group-hover:translate-x-1 transition-transform" />
</button>
<button
onClick={handleFinalize}
className="col-span-1 bg-gray-900 text-white py-5 rounded-3xl flex items-center justify-center shadow-xl hover:bg-black active:scale-95 transition-all"
title="FINALIZAR GTO"
>
<Check size={32} strokeWidth={4} />
</button>
</div>
);
const actionsMobile = (
<button
onClick={handleAddItem}
className="w-full bg-[#2d6a4f] text-white py-5 rounded-3xl font-black text-lg uppercase shadow-2xl shadow-green-200 hover:bg-[#1b4332] active:scale-95 transition-all flex items-center justify-center gap-3 group"
>
ADICIONAR ITEM <ChevronRight className="group-hover:translate-x-1 transition-transform" />
</button>
);
const odontogramCard = (
<div className="bg-white rounded-3xl border border-gray-100 shadow-xl p-3 sm:p-8 space-y-4 sm:space-y-6">
<div className="flex justify-center mb-2 sm:mb-4">
<div className="inline-flex bg-gray-100 p-1 rounded-xl shadow-inner">
<button
onClick={() => { setPacienteTipo('ADULTO'); setSelectedDentes([]); setDenteInputs({}); setShowMixed(false); }}
className={`px-5 sm:px-8 py-2 rounded-lg text-xs font-black transition-all uppercase ${pacienteTipo === 'ADULTO' ? 'bg-blue-600 text-white shadow-md scale-105' : 'text-gray-500 hover:text-gray-800'}`}
>
Adulto
</button>
<button
onClick={() => { setPacienteTipo('CRIANCA'); setSelectedDentes([]); setDenteInputs({}); setShowMixed(false); }}
className={`px-5 sm:px-8 py-2 rounded-lg text-xs font-black transition-all uppercase ${pacienteTipo === 'CRIANCA' ? 'bg-blue-600 text-white shadow-md scale-105' : 'text-gray-500 hover:text-gray-800'}`}
>
Criança
</button>
</div>
</div>
<div className="relative border-t border-b border-gray-50 py-6 sm:py-10">
<div className="absolute left-1/2 top-4 bottom-4 w-[2px] bg-gray-200 -translate-x-1/2"></div>
<div className="absolute top-1/2 left-2 right-2 h-[2px] bg-gray-200 -translate-y-1/2"></div>
<div className="grid grid-cols-2 gap-x-2 sm:gap-x-12 gap-y-6 sm:gap-y-16">
<div className="flex justify-end items-center gap-1 sm:gap-2 pr-1 sm:pr-2">
{pacienteTipo === 'ADULTO' && renderDenteBtn(DENTES_ADULTO.extras.q1)}
<div className="grid grid-cols-4 gap-1 sm:gap-2">
{(pacienteTipo === 'ADULTO' ? DENTES_ADULTO.q1 : DENTES_CRIANCA.q1).map((d, i) => renderDenteBtn(d, i))}
</div>
</div>
<div className="flex justify-start items-center gap-1 sm:gap-2 pl-1 sm:pl-2">
<div className="grid grid-cols-4 gap-1 sm:gap-2">
{(pacienteTipo === 'ADULTO' ? DENTES_ADULTO.q2 : DENTES_CRIANCA.q2).map((d, i) => renderDenteBtn(d, i))}
</div>
{pacienteTipo === 'ADULTO' && renderDenteBtn(DENTES_ADULTO.extras.q2)}
</div>
<div className="flex justify-end items-center gap-1 sm:gap-2 pr-1 sm:pr-2">
{pacienteTipo === 'ADULTO' && renderDenteBtn(DENTES_ADULTO.extras.q4)}
<div className="grid grid-cols-4 gap-1 sm:gap-2">
{(pacienteTipo === 'ADULTO' ? DENTES_ADULTO.q4 : DENTES_CRIANCA.q4).map((d, i) => renderDenteBtn(d, i))}
</div>
</div>
<div className="flex justify-start items-center gap-1 sm:gap-2 pl-1 sm:pl-2">
<div className="grid grid-cols-4 gap-1 sm:gap-2">
{(pacienteTipo === 'ADULTO' ? DENTES_ADULTO.q3 : DENTES_CRIANCA.q3).map((d, i) => renderDenteBtn(d, i))}
</div>
{pacienteTipo === 'ADULTO' && renderDenteBtn(DENTES_ADULTO.extras.q3)}
</div>
</div>
</div>
{showMixed && (
<div className="border-t-2 border-dashed border-amber-200 pt-4 space-y-3 animate-in fade-in slide-in-from-top-2 duration-200">
<p className="text-[9px] font-black text-amber-500 uppercase tracking-widest text-center">
{pacienteTipo === 'ADULTO' ? '— DENTES DECÍDUOS —' : '— DENTES PERMANENTES —'}
</p>
<div className="relative py-4 sm:py-6">
<div className="absolute left-1/2 top-2 bottom-2 w-[2px] bg-amber-100 -translate-x-1/2"></div>
<div className="absolute top-1/2 left-2 right-2 h-[2px] bg-amber-100 -translate-y-1/2"></div>
<div className="grid grid-cols-2 gap-x-2 sm:gap-x-12 gap-y-6 sm:gap-y-16">
<div className="flex justify-end items-center gap-1 sm:gap-2 pr-1 sm:pr-2">
{pacienteTipo === 'CRIANCA' && renderDenteBtn(DENTES_ADULTO.extras.q1)}
<div className="grid grid-cols-4 gap-1 sm:gap-2">
{(pacienteTipo === 'ADULTO' ? DENTES_CRIANCA.q1 : DENTES_ADULTO.q1).map((d, i) => renderDenteBtn(d, i))}
</div>
</div>
<div className="flex justify-start items-center gap-1 sm:gap-2 pl-1 sm:pl-2">
<div className="grid grid-cols-4 gap-1 sm:gap-2">
{(pacienteTipo === 'ADULTO' ? DENTES_CRIANCA.q2 : DENTES_ADULTO.q2).map((d, i) => renderDenteBtn(d, i))}
</div>
{pacienteTipo === 'CRIANCA' && renderDenteBtn(DENTES_ADULTO.extras.q2)}
</div>
<div className="flex justify-end items-center gap-1 sm:gap-2 pr-1 sm:pr-2">
{pacienteTipo === 'CRIANCA' && renderDenteBtn(DENTES_ADULTO.extras.q4)}
<div className="grid grid-cols-4 gap-1 sm:gap-2">
{(pacienteTipo === 'ADULTO' ? DENTES_CRIANCA.q4 : DENTES_ADULTO.q4).map((d, i) => renderDenteBtn(d, i))}
</div>
</div>
<div className="flex justify-start items-center gap-1 sm:gap-2 pl-1 sm:pl-2">
<div className="grid grid-cols-4 gap-1 sm:gap-2">
{(pacienteTipo === 'ADULTO' ? DENTES_CRIANCA.q3 : DENTES_ADULTO.q3).map((d, i) => renderDenteBtn(d, i))}
</div>
{pacienteTipo === 'CRIANCA' && renderDenteBtn(DENTES_ADULTO.extras.q3)}
</div>
</div>
</div>
</div>
)}
<button
onClick={toggleMixed}
className={`w-full py-2.5 rounded-2xl border-2 font-black text-[11px] uppercase transition-all flex items-center justify-center gap-2
${showMixed
? 'border-amber-300 text-amber-600 bg-amber-50 hover:bg-amber-100'
: 'border-dashed border-amber-200 text-amber-400 hover:border-amber-400 hover:bg-amber-50'}`}
>
{showMixed
? <><X size={13} /> {pacienteTipo === 'ADULTO' ? 'REMOVER DECÍDUOS' : 'REMOVER PERMANENTES'}</>
: <><PlusCircle size={13} /> {pacienteTipo === 'ADULTO' ? '+ INCLUIR DENTES DECÍDUOS' : '+ INCLUIR DENTES PERMANENTES'}</>
}
</button>
<div className="flex justify-center gap-4 pt-4">
<button
onClick={() => selectArco('AI')}
disabled={!!selectedProc && selectedProc.tipo_regiao !== 'ARCO'}
className={`px-10 py-3 rounded-2xl border-2 font-black text-sm uppercase transition-all shadow-sm
${selectedArco === 'AI' ? 'bg-amber-500 border-amber-600 text-white' :
(!!selectedProc && selectedProc.tipo_regiao !== 'ARCO') ? 'bg-gray-50 border-gray-100 text-gray-300 cursor-not-allowed opacity-50' :
'bg-white border-gray-100 text-gray-500 hover:border-amber-400'}`}
>
AI - Inferior
</button>
<button
onClick={() => selectArco('AS')}
disabled={!!selectedProc && selectedProc.tipo_regiao !== 'ARCO'}
className={`px-10 py-3 rounded-2xl border-2 font-black text-sm uppercase transition-all shadow-sm
${selectedArco === 'AS' ? 'bg-amber-500 border-amber-600 text-white' :
(!!selectedProc && selectedProc.tipo_regiao !== 'ARCO') ? 'bg-gray-50 border-gray-100 text-gray-300 cursor-not-allowed opacity-50' :
'bg-white border-gray-100 text-gray-500 hover:border-amber-400'}`}
>
AS - Superior
</button>
</div>
</div>
);
const rascunhoCard = (
<div className="bg-white rounded-3xl border border-gray-100 overflow-hidden shadow-xl">
<div className="bg-[#d49a4a] p-4 text-white font-black text-sm uppercase flex justify-between items-center tracking-widest">
<span>PROCEDIMENTOS DO RASCUNHO</span>
<div className="bg-white/20 px-3 py-1 rounded-full text-[10px]">{store.items.length}/20 ITENS</div>
</div>
<div className="p-6 space-y-4">
{store.items.length === 0 && (
<div className="py-16 text-center text-gray-300 font-bold uppercase flex flex-col items-center gap-4">
<div className="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center outline outline-gray-100 outline-offset-4">
<AlertCircle size={32} />
</div>
NÃO ITENS ADICIONADOS
</div>
)}
{store.items.map((item) => (
<div key={item.id} className="border border-gray-100 rounded-2xl p-5 bg-gray-50/30 hover:bg-white transition-all shadow-sm group">
<div className="flex justify-between items-start mb-4">
<div className="space-y-1">
<div className="flex items-center gap-3">
<span className="bg-blue-600 text-white text-[10px] font-black px-2 py-1 rounded-md uppercase shadow-sm">COD {item.codigoTUSS}</span>
<h4 className="font-black text-gray-900 text-sm uppercase tracking-tight">{item.descricao}</h4>
</div>
<div className="flex items-center gap-2 text-[10px] text-gray-400 font-bold uppercase">
<Users size={12} /> {store.paciente?.nome}
</div>
</div>
<button onClick={() => store.removeItem(item.id)} className="text-gray-300 hover:text-red-600 p-2 transition-colors">
<Trash2 size={20} />
</button>
</div>
<div className="grid grid-cols-4 gap-6 text-[11px] font-black text-gray-500 uppercase tracking-wider mb-4 border-t border-gray-100 pt-4">
<div>DENTE: <span className="text-blue-600 ml-1">{item.dente || '--'}</span></div>
<div>ARCO: <span className="text-amber-600 ml-1">{item.arco || '--'}</span></div>
<div>FACE: <span className="text-gray-900 ml-1">{item.face || '--'}</span></div>
<div>VALOR: <span className="text-green-600 ml-1 text-xs">R$ {item.valorTotal.toFixed(2)}</span></div>
</div>
{item.observacao && (
<div className="text-[11px] text-gray-500 bg-white p-3 border border-gray-100 rounded-xl leading-relaxed">
<span className="font-black text-gray-400 uppercase mr-2 opacity-50">OBS:</span> {item.observacao}
</div>
)}
</div>
))}
<div className="pt-6 border-t-2 border-dotted border-gray-200 flex justify-between items-center">
<button className="flex items-center gap-2 text-blue-600 font-black text-[11px] uppercase hover:bg-blue-50 px-4 py-2 rounded-xl transition-all">
<Camera size={16} /> ANEXAR DOCUMENTOS
</button>
<div className="text-right">
<p className="text-[10px] font-black text-gray-400 uppercase tracking-[0.2em] mb-1">TOTAL ACUMULADO</p>
<h3 className="text-3xl font-black text-gray-900 p-2 bg-gray-50 rounded-2xl border border-gray-100 shadow-inner">R$ {totalGeral.toFixed(2)}</h3>
</div>
</div>
</div>
</div>
);
// ─── RENDER ─────────────────────────────────────────────────────
return (
<div className="space-y-6 pb-20 lg:pb-0">
<PageHeader
title="LANÇAR GTO"
description="MONTAGEM DINÂMICA DE GUIA ODONTOLÓGICA (GTO)."
/>
{/* ─── DESKTOP LAYOUT ─────────────────────────────── */}
<div className="hidden lg:grid grid-cols-12 gap-6 items-start">
<div className="col-span-8 space-y-6">
{odontogramCard}
{rascunhoCard}
</div>
<div className="col-span-4 space-y-4 sticky top-6">
{step1Card}
{step2Card}
{step3Card}
{step4Card}
{actionsDesktop}
</div>
</div>
{/* ─── MOBILE LAYOUT (3 páginas) ──────────────────── */}
<div className="lg:hidden">
{mobilePage === 1 && (
<div className="space-y-4">
{step1Card}
{step2Card}
{step3Card}
</div>
)}
{mobilePage === 2 && odontogramCard}
{mobilePage === 3 && (
<div className="space-y-4">
{step4Card}
{actionsMobile}
{rascunhoCard}
</div>
)}
</div>
{/* ─── MOBILE FOOTER NAV ──────────────────────────── */}
<div className="fixed bottom-0 left-0 right-0 z-40 lg:hidden bg-white/95 backdrop-blur-sm border-t border-gray-200 shadow-xl px-4 py-3 flex items-center justify-between gap-2">
{mobilePage > 1 ? (
<button
onClick={() => setMobilePage(p => (p - 1) as 1 | 2 | 3)}
className="flex items-center gap-1.5 px-4 py-2.5 rounded-2xl border-2 border-gray-200 font-black text-xs text-gray-500 hover:bg-gray-50 transition-all uppercase"
>
<ChevronLeft size={14} /> VOLTAR
</button>
) : (
<div className="w-24" />
)}
<div className="flex items-center gap-2">
{([1, 2, 3] as const).map(p => (
<button
key={p}
onClick={() => setMobilePage(p)}
className={`transition-all rounded-full ${mobilePage === p ? 'w-6 h-2.5 bg-blue-600' : 'w-2.5 h-2.5 bg-gray-200 hover:bg-gray-400'}`}
/>
))}
</div>
{mobilePage < 3 ? (
<button
onClick={() => setMobilePage(p => (p + 1) as 1 | 2 | 3)}
className="flex items-center gap-1.5 px-4 py-2.5 rounded-2xl bg-blue-600 text-white font-black text-xs hover:bg-blue-700 active:scale-95 transition-all uppercase shadow-md"
>
PRÓXIMO <ChevronRight size={14} />
</button>
) : (
<button
onClick={handleFinalize}
className="flex items-center gap-1.5 px-4 py-2.5 rounded-2xl bg-gray-900 text-white font-black text-xs hover:bg-black active:scale-95 transition-all uppercase shadow-md"
>
FINALIZAR <Check size={14} />
</button>
)}
</div>
{/* ─── PATIENT SEARCH MODAL ───────────────────────── */}
{patientSearchOpen && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center backdrop-blur-sm p-4">
<div className="bg-white rounded-3xl shadow-2xl w-full max-w-md flex flex-col overflow-hidden animate-in fade-in zoom-in-50 duration-200">
<div className="px-6 py-5 border-b border-gray-100 flex justify-between items-center">
<h3 className="font-black text-gray-900 uppercase tracking-wide text-sm flex items-center gap-2">
<Search size={16} className="text-blue-600" /> BUSCAR PACIENTE
</h3>
<button
onClick={() => { setPatientSearchOpen(false); setPatientSearchTerm(''); }}
className="text-gray-400 hover:text-gray-600 p-1 hover:bg-gray-100 rounded-full transition-colors"
>
<X size={20} />
</button>
</div>
<div className="p-5 space-y-3">
<input
autoFocus
type="text"
value={patientSearchTerm}
onChange={e => setPatientSearchTerm(e.target.value.toUpperCase())}
placeholder="NOME OU CPF..."
className="w-full p-4 bg-gray-50 border-2 border-gray-100 rounded-2xl font-black text-gray-800 text-sm focus:border-blue-500 outline-none transition-all uppercase"
/>
<div className="max-h-72 overflow-y-auto space-y-1">
{filteredPatients.length === 0 ? (
<div className="py-10 text-center text-gray-300 font-bold uppercase text-xs">
{patientSearchTerm ? 'NENHUM PACIENTE ENCONTRADO' : 'CARREGANDO...'}
</div>
) : (
filteredPatients.map(p => (
<button
key={p.id}
onClick={() => {
store.setPaciente(p);
setPatientSearchOpen(false);
setPatientSearchTerm('');
}}
className="w-full text-left px-4 py-3 hover:bg-blue-50 rounded-xl transition-all flex items-center gap-3 group"
>
<div className="w-9 h-9 bg-blue-100 rounded-full flex items-center justify-center text-blue-600 font-black text-sm flex-shrink-0 group-hover:bg-blue-600 group-hover:text-white transition-colors">
{p.nome.charAt(0)}
</div>
<div className="min-w-0">
<div className="font-black text-sm text-gray-800 uppercase truncate">{p.nome}</div>
{p.cpf && <div className="text-[10px] text-gray-400 font-bold">{p.cpf}</div>}
</div>
</button>
))
)}
</div>
</div>
</div>
</div>
)}
</div>
);
};