Merge branch 'backup/dark-mode' into fix/mode-dark

This commit is contained in:
M-Gabrielly 2025-11-13 18:09:35 -03:00
commit c7ffb568f5
14 changed files with 1599 additions and 88 deletions

View File

@ -0,0 +1,11 @@
import type { ReactNode } from "react";
import { ChatWidget } from "@/components/features/pacientes/chat-widget";
export default function PacientesLayout({ children }: { children: ReactNode }) {
return (
<>
{children}
<ChatWidget />
</>
);
}

View File

@ -5,7 +5,7 @@ import { useRouter } from 'next/navigation';
import ProtectedRoute from '@/components/shared/ProtectedRoute';
import { useAuth } from '@/hooks/useAuth';
import { useToast } from '@/hooks/use-toast';
import { listarPacientes, buscarMedicos } from '@/lib/api';
import { listarPacientes, buscarMedicos, getUserInfo } from '@/lib/api';
import { useReports } from '@/hooks/useReports';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@ -186,25 +186,49 @@ export default function LaudosEditorPage() {
// Se já temos um nome razoável, não sobrescrever
if (solicitanteNome && solicitanteNome.trim().length > 1) return;
if (!user) return;
// Buscar médicos por email (buscarMedicos aceita termos com @ e faz a busca por email)
if (user.email && user.email.includes('@')) {
const docs = await buscarMedicos(user.email).catch(() => []);
// First try: query doctors index with any available identifier (email, id or username)
try {
const term = (user.email && user.email.trim()) || user.name || user.id || '';
if (term && term.length > 1) {
const docs = await buscarMedicos(term).catch(() => []);
if (!mounted) return;
if (Array.isArray(docs) && docs.length > 0) {
const d = docs[0];
if (d && (d.full_name || (d as any).nome)) {
setSolicitanteNome((d.full_name as string) || ((d as any).nome as string) || user.name || user.email || '');
setSolicitanteId(user.id || solicitanteId);
return;
}
}
}
} catch (err) {
// non-fatal, continue to next fallback
}
// Second try: fetch consolidated user-info (may contain profile.full_name)
try {
const info = await getUserInfo().catch(() => null);
if (!mounted) return;
if (Array.isArray(docs) && docs.length > 0) {
const d = docs[0];
// Preferir full_name do médico quando disponível
if (d && (d.full_name || (d as any).nome)) {
setSolicitanteNome((d.full_name as string) || ((d as any).nome as string) || user.name || user.email || '');
if (info && (info.profile as any)?.full_name) {
const full = (info.profile as any).full_name as string;
if (full && full.trim().length > 1) {
setSolicitanteNome(full);
setSolicitanteId(user.id || solicitanteId);
return;
}
}
} catch (err) {
// ignore and fallback
}
// Fallbacks: usar user.name se existir; caso contrário, email completo
// Final fallback: use name from auth user or email/username
setSolicitanteNome(user.name || user.email || '');
setSolicitanteId(user.id || solicitanteId);
} catch (err) {
// em caso de erro, manter o fallback
setSolicitanteNome(user?.name || user?.email || '');
setSolicitanteId(user?.id || solicitanteId);
}
}
@ -480,15 +504,9 @@ export default function LaudosEditorPage() {
</div>
)}
{/* Solicitante e Prazo */}
{/* Prazo */}
{pacienteSelecionado && (
<div className="mt-3 sm:mt-4 grid grid-cols-1 sm:grid-cols-2 gap-2 sm:gap-3">
<div>
<Label htmlFor="solicitante" className="text-xs sm:text-sm">
Solicitante
</Label>
<Input id="solicitante" value={solicitanteNome} readOnly disabled className="text-xs sm:text-sm mt-1 h-8 sm:h-10" />
</div>
<div className="mt-3 sm:mt-4">
<div>
<Label htmlFor="prazoDate" className="text-xs sm:text-sm">
Prazo do Laudo

View File

@ -0,0 +1,11 @@
import type { ReactNode } from "react";
import { ChatWidget } from "@/components/features/pacientes/chat-widget";
export default function PacienteLayout({ children }: { children: ReactNode }) {
return (
<>
{children}
<ChatWidget />
</>
);
}

View File

@ -482,7 +482,8 @@ export default function PacientePage() {
}
console.log('[DashboardCards] Especialidades encontradas:', specs)
setEspecialidades(specs.length > 0 ? specs.sort() : [])
// Ordenação alfabética usando localeCompare para suportar acentuação (português)
setEspecialidades(specs.length > 0 ? specs.sort((a, b) => a.localeCompare(b, 'pt', { sensitivity: 'base' })) : [])
} catch (e) {
console.error('[DashboardCards] erro ao carregar especialidades', e)
if (mounted) setEspecialidades([])
@ -574,20 +575,21 @@ export default function PacientePage() {
<div className="space-y-3 sm:space-y-4">
<p className="text-sm sm:text-base font-semibold opacity-90">Especialidades populares</p>
{especialidadesLoading ? (
<div className="flex gap-2 flex-wrap">
<div className="grid grid-cols-2 sm:grid-cols-4 md:grid-cols-6 gap-2">
{[1, 2, 3, 4, 5, 6].map((i) => (
<div key={i} className="h-10 w-24 bg-white/20 rounded-full animate-pulse"></div>
<div key={i} className="h-12 w-full bg-white/20 rounded-full animate-pulse" />
))}
</div>
) : especialidades && especialidades.length > 0 ? (
<div className="flex flex-wrap gap-2 sm:gap-3">
// Grid responsivo com botões arredondados e tamanho uniforme
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 xl:grid-cols-8 gap-2 sm:gap-3">
{especialidades.map((esp) => (
<button
key={esp}
onClick={() => handleEspecialidadeClick(esp)}
className="px-4 sm:px-5 py-2 sm:py-2.5 rounded-full bg-white/20 hover:bg-white/30 text-white font-medium text-xs sm:text-sm transition-colors border border-white/30 whitespace-nowrap"
className="w-full min-h-[44px] sm:min-h-[48px] flex items-center justify-center rounded-full bg-white/10 hover:bg-white/20 text-white font-medium text-sm transition-colors border border-white/20 px-3 py-2 text-center break-words"
>
{esp}
<span className="leading-tight">{esp}</span>
</button>
))}
</div>

View File

@ -53,7 +53,6 @@ export default function ResultadosClient() {
// Filtros/controles da UI - initialize with defaults to avoid hydration mismatch
const [tipoConsulta, setTipoConsulta] = useState<TipoConsulta>('teleconsulta')
const [especialidadeHero, setEspecialidadeHero] = useState<string>('Psicólogo')
const [convenio, setConvenio] = useState<string>('Todos')
const [bairro, setBairro] = useState<string>('Todos')
// Busca por nome do médico
const [searchQuery, setSearchQuery] = useState<string>('')
@ -649,11 +648,27 @@ export default function ResultadosClient() {
}
}
// Filtro visual (convenio/bairro são cosméticos; quando sem dado, mantemos tudo)
// Extrair bairros únicos dos médicos
const bairrosDisponiveis = useMemo(() => {
const neighborhoods = new Set<string>();
(medicos || []).forEach((m: any) => {
if (m.neighborhood) {
neighborhoods.add(String(m.neighborhood))
}
})
return Array.from(neighborhoods).sort()
}, [medicos])
// Filtro visual (bairro é o único filtro; quando sem dado, mantemos tudo)
const profissionais = useMemo(() => {
let filtered = (medicos || []).filter((m: any) => {
if (convenio !== 'Todos' && m.convenios && !m.convenios.includes(convenio)) return false
if (bairro !== 'Todos' && m.neighborhood && String(m.neighborhood).toLowerCase() !== String(bairro).toLowerCase()) return false
// Se um bairro específico foi selecionado, filtrar rigorosamente
if (bairro !== 'Todos') {
// Se o médico não tem neighborhood, não incluir
if (!m.neighborhood) return false
// Se tem neighborhood, deve corresponder ao filtro
if (String(m.neighborhood).toLowerCase() !== String(bairro).toLowerCase()) return false
}
return true
})
@ -668,7 +683,7 @@ export default function ResultadosClient() {
}
return filtered
}, [medicos, convenio, bairro, medicoFiltro])
}, [medicos, bairro, medicoFiltro])
// Paginação local para a lista de médicos
const [currentPage, setCurrentPage] = useState(1)
@ -824,23 +839,6 @@ export default function ResultadosClient() {
{/* divider visual */}
<div className="sm:col-span-12 h-px bg-border/60 my-1" />
{/* Convênio */}
<div className="sm:col-span-6 lg:col-span-4">
<Select value={convenio} onValueChange={setConvenio}>
<SelectTrigger className="h-10 w-full rounded-full border border-primary/30 bg-primary/5 text-primary hover:border-primary focus:ring-2 focus:ring-primary">
<SelectValue placeholder="Convênio" />
</SelectTrigger>
<SelectContent>
<SelectItem value="Todos">Todos os convênios</SelectItem>
<SelectItem value="Amil">Amil</SelectItem>
<SelectItem value="Unimed">Unimed</SelectItem>
<SelectItem value="SulAmérica">SulAmérica</SelectItem>
<SelectItem value="Bradesco Saúde">Bradesco Saúde</SelectItem>
<SelectItem value="Particular">Particular</SelectItem>
</SelectContent>
</Select>
</div>
{/* Bairro */}
<div className="sm:col-span-6 lg:col-span-4">
<Select value={bairro} onValueChange={setBairro}>
@ -849,9 +847,11 @@ export default function ResultadosClient() {
</SelectTrigger>
<SelectContent>
<SelectItem value="Todos">Todos os bairros</SelectItem>
<SelectItem value="Centro">Centro</SelectItem>
<SelectItem value="Jardins">Jardins</SelectItem>
<SelectItem value="Farolândia">Farolândia</SelectItem>
{bairrosDisponiveis.map((b: string) => (
<SelectItem key={b} value={b}>
{b}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
@ -977,48 +977,13 @@ export default function ResultadosClient() {
<span className="ml-auto text-sm font-semibold text-primary">{precoTipoConsulta}</span>
</div>
{/* Próximos horários */}
{!isLoadingAgenda && (
<div className="space-y-2">
<p className="text-xs font-semibold text-muted-foreground">Próximos horários disponíveis:</p>
{proximos3Horarios.length > 0 ? (
<div className="flex gap-2 flex-wrap">
{proximos3Horarios.map(slot => (
<button
key={slot.iso}
type="button"
className="px-3 py-1.5 text-xs font-medium rounded-lg bg-primary/10 text-primary hover:bg-primary hover:text-primary-foreground transition"
onClick={() => openConfirmDialog(id, slot.iso)}
>
{slot.label}
</button>
))}
</div>
) : (
<p className="text-xs text-muted-foreground">Carregando horários...</p>
)}
</div>
)}
{/* Ações */}
<div className="flex gap-2 pt-2">
<Button
className="flex-1 h-10 rounded-full bg-primary text-primary-foreground hover:bg-primary/90"
onClick={async () => {
if (!agendaByDoctor[id]) {
const nearest = await loadAgenda(id)
if (nearest) {
openConfirmDialog(id, nearest.iso)
return
}
}
const nearest = nearestSlotByDoctor[id]
if (nearest) {
openConfirmDialog(id, nearest.iso)
} else {
setMoreTimesForDoctor(id)
void fetchSlotsForDate(id, moreTimesDate)
}
setMoreTimesForDoctor(id)
void fetchSlotsForDate(id, moreTimesDate)
}}
>
Agendar
@ -1057,6 +1022,8 @@ export default function ResultadosClient() {
<SelectItem value="5">5</SelectItem>
<SelectItem value="10">10</SelectItem>
<SelectItem value="20">20</SelectItem>
<SelectItem value="50">50</SelectItem>
<SelectItem value="100">100</SelectItem>
</SelectContent>
</Select>
<span>Mostrando {startItem} a {endItem} de {profissionais.length}</span>

View File

@ -0,0 +1,685 @@
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { motion } from "framer-motion";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { SimpleThemeToggle } from "@/components/ui/simple-theme-toggle";
import { Clock, Info, Lock, MessageCircle, Plus, Upload } from "lucide-react";
const API_ENDPOINT = "https://n8n.jonasbomfim.store/webhook/cd7d10e6-bcfc-4f3a-b649-351d12b714f1";
const FALLBACK_RESPONSE = "Tive um problema para responder agora. Tente novamente em alguns instantes.";
export interface ChatMessage {
id: string;
sender: "user" | "assistant";
content: string;
createdAt: string;
}
export interface ChatSession {
id: string;
startedAt: string;
updatedAt: string;
topic: string;
messages: ChatMessage[];
}
interface AIAssistantInterfaceProps {
onOpenDocuments?: () => void;
onOpenChat?: () => void;
history?: ChatSession[];
onAddHistory?: (session: ChatSession) => void;
onClearHistory?: () => void;
}
export function AIAssistantInterface({
onOpenDocuments,
onOpenChat,
history: externalHistory,
onAddHistory,
onClearHistory,
}: AIAssistantInterfaceProps) {
const [question, setQuestion] = useState("");
const [internalHistory, setInternalHistory] = useState<ChatSession[]>(externalHistory ?? []);
const [activeSessionId, setActiveSessionId] = useState<string | null>(null);
const [manualSelection, setManualSelection] = useState(false);
const [historyPanelOpen, setHistoryPanelOpen] = useState(false);
const messageListRef = useRef<HTMLDivElement | null>(null);
const history = internalHistory;
const historyRef = useRef<ChatSession[]>(history);
const baseGreeting = "Olá, eu sou Zoe. Como posso ajudar hoje?";
const greetingWords = useMemo(() => baseGreeting.split(" "), [baseGreeting]);
const [typedGreeting, setTypedGreeting] = useState("");
const [typedIndex, setTypedIndex] = useState(0);
const [isTypingGreeting, setIsTypingGreeting] = useState(true);
const [gradientGreeting, plainGreeting] = useMemo(() => {
if (!typedGreeting) return ["", ""] as const;
const separatorIndex = typedGreeting.indexOf("Como");
if (separatorIndex === -1) {
return [typedGreeting, ""] as const;
}
const gradientPart = typedGreeting.slice(0, separatorIndex).trimEnd();
const plainPart = typedGreeting.slice(separatorIndex).trimStart();
return [gradientPart, plainPart] as const;
}, [typedGreeting]);
useEffect(() => {
if (externalHistory) {
setInternalHistory(externalHistory);
}
}, [externalHistory]);
useEffect(() => {
historyRef.current = history;
}, [history]);
const activeSession = useMemo(
() => history.find((session) => session.id === activeSessionId) ?? null,
[history, activeSessionId]
);
const activeMessages = activeSession?.messages ?? [];
const formatDateTime = useCallback(
(value: string) =>
new Date(value).toLocaleString("pt-BR", {
day: "2-digit",
month: "2-digit",
hour: "2-digit",
minute: "2-digit",
}),
[]
);
const formatTime = useCallback(
(value: string) =>
new Date(value).toLocaleTimeString("pt-BR", {
hour: "2-digit",
minute: "2-digit",
}),
[]
);
useEffect(() => {
if (history.length === 0) {
setActiveSessionId(null);
setManualSelection(false);
return;
}
if (!activeSessionId && !manualSelection) {
setActiveSessionId(history[history.length - 1].id);
return;
}
const exists = history.some((session) => session.id === activeSessionId);
if (!exists && !manualSelection) {
setActiveSessionId(history[history.length - 1].id);
}
}, [history, activeSessionId, manualSelection]);
useEffect(() => {
if (!messageListRef.current) return;
messageListRef.current.scrollTo({
top: messageListRef.current.scrollHeight,
behavior: "smooth",
});
}, [activeMessages.length]);
useEffect(() => {
setTypedGreeting("");
setTypedIndex(0);
setIsTypingGreeting(true);
}, []);
useEffect(() => {
if (!isTypingGreeting) return;
if (typedIndex >= greetingWords.length) {
setIsTypingGreeting(false);
return;
}
const timeout = window.setTimeout(() => {
setTypedGreeting((previous) =>
previous
? `${previous} ${greetingWords[typedIndex]}`
: greetingWords[typedIndex]
);
setTypedIndex((previous) => previous + 1);
}, 260);
return () => window.clearTimeout(timeout);
}, [greetingWords, isTypingGreeting, typedIndex]);
const handleDocuments = () => {
if (onOpenDocuments) {
onOpenDocuments();
return;
}
console.log("[ZoeIA] Abrir fluxo de documentos");
};
const handleOpenRealtimeChat = () => {
if (onOpenChat) {
onOpenChat();
return;
}
console.log("[ZoeIA] Abrir chat em tempo real");
};
const buildSessionTopic = useCallback((content: string) => {
const normalized = content.trim();
if (!normalized) return "Atendimento";
return normalized.length > 60 ? `${normalized.slice(0, 57)}` : normalized;
}, []);
const upsertSession = useCallback(
(session: ChatSession) => {
if (onAddHistory) {
onAddHistory(session);
} else {
setInternalHistory((previous) => {
const index = previous.findIndex((item) => item.id === session.id);
if (index >= 0) {
const updated = [...previous];
updated[index] = session;
return updated;
}
return [...previous, session];
});
}
setActiveSessionId(session.id);
setManualSelection(false);
},
[onAddHistory]
);
const sendMessageToAssistant = useCallback(
async (prompt: string, baseSession: ChatSession) => {
const sessionId = baseSession.id;
const appendAssistantMessage = (content: string) => {
const createdAt = new Date().toISOString();
const latestSession =
historyRef.current.find((session) => session.id === sessionId) ?? baseSession;
const assistantMessage: ChatMessage = {
id: `msg-assistant-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
sender: "assistant",
content,
createdAt,
};
const updatedSession: ChatSession = {
...latestSession,
updatedAt: assistantMessage.createdAt,
messages: [...latestSession.messages, assistantMessage],
};
upsertSession(updatedSession);
};
try {
const response = await fetch(API_ENDPOINT, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ message: prompt }),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const rawPayload = await response.text();
let replyText = "";
if (rawPayload.trim().length > 0) {
try {
const parsed = JSON.parse(rawPayload) as { reply?: unknown };
replyText = typeof parsed.reply === "string" ? parsed.reply.trim() : "";
} catch (parseError) {
console.error("[ZoeIA] Resposta JSON inválida", parseError, rawPayload);
}
}
appendAssistantMessage(replyText || FALLBACK_RESPONSE);
} catch (error) {
console.error("[ZoeIA] Falha ao obter resposta da API", error);
appendAssistantMessage(FALLBACK_RESPONSE);
}
},
[upsertSession]
);
const handleSendMessage = () => {
const trimmed = question.trim();
if (!trimmed) return;
const now = new Date();
const userMessage: ChatMessage = {
id: `msg-user-${now.getTime()}`,
sender: "user",
content: trimmed,
createdAt: now.toISOString(),
};
const existingSession = history.find((session) => session.id === activeSessionId) ?? null;
const sessionToPersist: ChatSession = existingSession
? {
...existingSession,
updatedAt: userMessage.createdAt,
topic:
existingSession.messages.length === 0
? buildSessionTopic(trimmed)
: existingSession.topic,
messages: [...existingSession.messages, userMessage],
}
: {
id: `session-${now.getTime()}`,
startedAt: now.toISOString(),
updatedAt: userMessage.createdAt,
topic: buildSessionTopic(trimmed),
messages: [userMessage],
};
upsertSession(sessionToPersist);
console.log("[ZoeIA] Mensagem registrada na Zoe", trimmed);
setQuestion("");
setHistoryPanelOpen(false);
void sendMessageToAssistant(trimmed, sessionToPersist);
};
const RealtimeTriggerButton = () => (
<button
type="button"
onClick={handleOpenRealtimeChat}
className="flex h-12 w-12 items-center justify-center rounded-full bg-white text-foreground shadow-sm transition hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background dark:bg-zinc-900 dark:text-white"
aria-label="Abrir chat Zoe em tempo real"
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
className="h-5 w-5"
fill="currentColor"
aria-hidden
>
<rect x="4" y="7" width="2" height="10" rx="1" />
<rect x="8" y="5" width="2" height="14" rx="1" />
<rect x="12" y="7" width="2" height="10" rx="1" />
<rect x="16" y="9" width="2" height="6" rx="1" />
<rect x="20" y="8" width="2" height="8" rx="1" />
</svg>
</button>
);
const handleClearHistory = () => {
if (onClearHistory) {
onClearHistory();
} else {
setInternalHistory([]);
}
setActiveSessionId(null);
setManualSelection(false);
setQuestion("");
setHistoryPanelOpen(false);
};
const handleSelectSession = useCallback((sessionId: string) => {
setManualSelection(true);
setActiveSessionId(sessionId);
setHistoryPanelOpen(false);
}, []);
const startNewConversation = useCallback(() => {
setManualSelection(true);
setActiveSessionId(null);
setQuestion("");
setHistoryPanelOpen(false);
}, []);
return (
<div className="min-h-screen bg-background text-foreground">
<div className="mx-auto flex w-full max-w-3xl flex-col gap-8 px-4 py-10 sm:px-6 sm:py-12">
<motion.section
initial={{ opacity: 0, y: -14 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.6, ease: "easeOut" }}
className="rounded-3xl border border-primary/10 bg-gradient-to-br from-primary/15 via-background to-background/95 p-6 shadow-xl backdrop-blur-sm"
>
<div className="flex flex-col gap-6">
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div className="flex items-center gap-4">
<span className="flex h-12 w-12 items-center justify-center rounded-3xl bg-gradient-to-br from-primary via-indigo-500 to-sky-500 text-base font-semibold text-white shadow-lg">
Zoe
</span>
<div className="space-y-1">
<p className="text-xs font-semibold uppercase tracking-[0.24em] text-primary/80">
Assistente Clínica Zoe
</p>
<motion.h1
key={typedGreeting}
className="text-2xl font-semibold tracking-tight text-foreground sm:text-3xl"
initial={{ opacity: 0.6 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.3 }}
>
{gradientGreeting && (
<span className="bg-gradient-to-r from-sky-400 via-primary to-indigo-500 bg-clip-text text-transparent">
{gradientGreeting}
{plainGreeting ? " " : ""}
</span>
)}
{plainGreeting && <span className="text-foreground">{plainGreeting}</span>}
<span
className={`ml-1 inline-block h-6 w-[0.12rem] align-middle ${
isTypingGreeting ? "animate-pulse bg-primary" : "bg-transparent"
}`}
/>
</motion.h1>
</div>
</div>
<div className="flex flex-wrap items-center justify-end gap-2 sm:justify-end">
{history.length > 0 && (
<Button
type="button"
variant="ghost"
className="rounded-full px-4 py-2 text-xs font-semibold uppercase tracking-[0.18em] text-primary transition hover:bg-primary/10"
onClick={() => setHistoryPanelOpen(true)}
>
Ver históricos
</Button>
)}
{history.length > 0 && (
<Button
type="button"
variant="ghost"
className="rounded-full px-4 py-2 text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground transition hover:text-destructive"
onClick={handleClearHistory}
>
Limpar histórico
</Button>
)}
<Button
type="button"
variant="outline"
className="rounded-full border-primary/40 px-4 py-2 text-xs font-semibold uppercase tracking-[0.18em] text-primary shadow-sm transition hover:bg-primary/10"
onClick={startNewConversation}
>
Novo atendimento
</Button>
<SimpleThemeToggle />
</div>
</div>
<motion.p
className="max-w-2xl text-sm text-muted-foreground"
initial={{ opacity: 0, y: -6 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.3, duration: 0.4 }}
>
Organizamos exames, orientações e tarefas assistenciais em um painel único para acelerar decisões clínicas. Utilize a Zoe para revisar resultados, registrar percepções e alinhar próximos passos com a equipe de saúde.
</motion.p>
</div>
</motion.section>
<motion.div
initial={{ opacity: 0, y: -8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.15, duration: 0.4 }}
className="flex items-center gap-2 rounded-full border border-primary/20 bg-primary/5 px-4 py-2 text-xs text-primary shadow-sm"
>
<Lock className="h-4 w-4" />
<span>Suas informações permanecem criptografadas e seguras com a equipe Zoe.</span>
</motion.div>
<motion.section
className="space-y-6 rounded-3xl border border-primary/15 bg-card/70 p-6 shadow-lg backdrop-blur"
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2, duration: 0.5 }}
>
<motion.div
className="rounded-3xl border border-primary/25 bg-gradient-to-br from-primary/10 via-background/50 to-background p-6 text-sm leading-relaxed text-muted-foreground"
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.25, duration: 0.4 }}
>
<div className="mb-4 flex items-center gap-3 text-primary">
<Info className="h-5 w-5" />
<span className="text-base font-semibold">Informativo importante</span>
</div>
<p>
A Zoe acompanha toda a jornada clínica, consolida exames e registra orientações para que você tenha clareza em cada etapa do cuidado.
As respostas são informativas e complementam a avaliação de um profissional de saúde qualificado.
</p>
<p className="mt-4 font-medium text-foreground">
Em situações de urgência, entre em contato com a equipe médica presencial ou acione os serviços de emergência da sua região.
</p>
</motion.div>
<div className="grid gap-3 sm:grid-cols-2">
<Button
onClick={handleDocuments}
size="lg"
className="justify-start gap-3 rounded-2xl bg-primary text-primary-foreground shadow-md transition hover:shadow-xl"
>
<Upload className="h-5 w-5" />
Enviar documentos clínicos
</Button>
<Button
onClick={handleOpenRealtimeChat}
size="lg"
variant="outline"
className="justify-start gap-3 rounded-2xl border-primary/40 bg-background shadow-md transition hover:border-primary hover:text-primary"
>
<MessageCircle className="h-5 w-5" />
Conversar com a equipe Zoe
</Button>
</div>
<div className="rounded-2xl border border-border bg-background/80 p-4 shadow-inner">
<p className="text-sm text-muted-foreground">
Estamos reunindo o histórico da sua jornada. Enquanto isso, você pode anexar exames, enviar dúvidas ou solicitar contato com a equipe Zoe.
</p>
</div>
</motion.section>
<motion.section
className="flex flex-col gap-5 rounded-3xl border border-primary/10 bg-card/70 p-6 shadow-lg backdrop-blur"
initial={{ opacity: 0, y: 14 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.25, duration: 0.45 }}
>
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
{activeSession ? "Atendimento em andamento" : "Inicie uma conversa"}
</p>
<p className="text-sm font-semibold text-foreground sm:text-base">
{activeSession?.topic ?? "O primeiro contato orienta nossas recomendações clínicas"}
</p>
</div>
{activeSession && (
<span className="mt-1 inline-flex items-center rounded-full bg-primary/10 px-3 py-1 text-xs font-medium text-primary shadow-inner sm:mt-0">
Atualizado às {formatTime(activeSession.updatedAt)}
</span>
)}
</div>
<div
ref={messageListRef}
className="flex max-h-[45vh] min-h-[220px] flex-col gap-3 overflow-y-auto rounded-2xl border border-border/40 bg-background/70 p-4"
>
{activeMessages.length > 0 ? (
activeMessages.map((message) => (
<div
key={message.id}
className={`flex ${message.sender === "user" ? "justify-end" : "justify-start"}`}
>
<div
className={`max-w-[80%] rounded-2xl px-4 py-3 text-sm leading-relaxed shadow-sm ${
message.sender === "user"
? "bg-primary text-primary-foreground"
: "border border-border/60 bg-background text-foreground"
}`}
>
<p className="whitespace-pre-wrap text-sm leading-relaxed">{message.content}</p>
<span
className={`mt-2 block text-[0.68rem] uppercase tracking-[0.18em] ${
message.sender === "user"
? "text-primary-foreground/75"
: "text-muted-foreground"
}`}
>
{formatTime(message.createdAt)}
</span>
</div>
</div>
))
) : (
<div className="flex flex-1 flex-col items-center justify-center rounded-2xl border border-dashed border-primary/25 bg-background/80 px-6 py-12 text-center text-sm text-muted-foreground">
<p className="text-sm font-medium text-foreground">Envie sua primeira mensagem</p>
<p className="mt-2 max-w-md text-sm text-muted-foreground">
Compartilhe uma dúvida, exame ou orientação que deseja revisar. A Zoe registra o pedido e te retorna com um resumo organizado para a equipe de saúde.
</p>
</div>
)}
</div>
</motion.section>
<div className="flex flex-col gap-3 rounded-3xl border border-border bg-card/70 px-4 py-3 shadow-xl sm:flex-row sm:items-center">
<div className="flex items-center gap-2">
<Button
type="button"
variant="ghost"
size="icon"
className="rounded-full border border-border/40 bg-background/60 text-muted-foreground transition hover:text-primary"
onClick={handleDocuments}
>
<Plus className="h-5 w-5" />
</Button>
</div>
<Input
value={question}
onChange={(event) => setQuestion(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
handleSendMessage();
}
}}
placeholder="Pergunte qualquer coisa para a Zoe"
className="w-full flex-1 border-none bg-transparent text-sm shadow-none focus-visible:ring-0"
/>
<div className="flex items-center justify-end gap-2">
<Button
type="button"
className="rounded-full bg-primary px-5 text-primary-foreground shadow-md transition hover:bg-primary/90"
onClick={handleSendMessage}
>
Enviar
</Button>
<RealtimeTriggerButton />
</div>
</div>
</div>
{historyPanelOpen && (
<aside className="fixed inset-y-0 right-0 z-[160] w-[min(22rem,80vw)] border-l border-border bg-card shadow-2xl">
<div className="flex h-full flex-col">
<div className="flex items-center justify-between border-b border-border px-4 py-4">
<div className="flex items-center gap-3">
<span className="flex h-9 w-9 items-center justify-center rounded-2xl bg-gradient-to-br from-primary via-sky-500 to-emerald-400 text-sm font-semibold text-white shadow-md">
Zoe
</span>
<div>
<h2 className="text-sm font-semibold text-foreground">Históricos de atendimento</h2>
<p className="text-xs text-muted-foreground">{history.length} registro{history.length === 1 ? "" : "s"}</p>
</div>
</div>
<Button
type="button"
variant="ghost"
size="icon"
className="rounded-full"
onClick={() => setHistoryPanelOpen(false)}
>
<span aria-hidden>×</span>
<span className="sr-only">Fechar históricos</span>
</Button>
</div>
<div className="border-b border-border px-4 py-3">
<Button
type="button"
className="w-full justify-start gap-2 rounded-xl bg-primary text-primary-foreground shadow-md transition hover:shadow-lg"
onClick={startNewConversation}
>
<Plus className="h-4 w-4" />
Novo atendimento
</Button>
</div>
<div className="flex-1 overflow-y-auto px-4 py-4">
{history.length === 0 ? (
<p className="text-sm text-muted-foreground">
Nenhum atendimento registrado ainda. Envie uma mensagem para começar um acompanhamento.
</p>
) : (
<ul className="flex flex-col gap-3 text-sm">
{[...history].reverse().map((session) => {
const lastMessage = session.messages[session.messages.length - 1];
const isActive = session.id === activeSessionId;
return (
<li key={session.id}>
<button
type="button"
onClick={() => handleSelectSession(session.id)}
className={`flex w-full flex-col gap-2 rounded-xl border px-3 py-3 text-left shadow-sm transition hover:border-primary hover:shadow-md ${
isActive ? "border-primary/60 bg-primary/10" : "border-border/60 bg-background/90"
}`}
>
<div className="flex items-center justify-between gap-3">
<p className="font-semibold text-foreground line-clamp-2">{session.topic}</p>
<span className="text-xs text-muted-foreground">{formatDateTime(session.updatedAt)}</span>
</div>
{lastMessage && (
<p className="text-xs text-muted-foreground line-clamp-2">
{lastMessage.sender === "assistant" ? "Zoe: " : "Você: "}
{lastMessage.content}
</p>
)}
<div className="flex items-center gap-2 text-[0.68rem] uppercase tracking-[0.18em] text-muted-foreground">
<Clock className="h-4 w-4" />
<span>
{session.messages.length} mensagem{session.messages.length === 1 ? "" : "s"}
</span>
</div>
</button>
</li>
);
})}
</ul>
)}
</div>
{history.length > 0 && (
<div className="border-t border-border px-4 py-3">
<Button
type="button"
variant="ghost"
className="w-full justify-center text-xs font-medium text-muted-foreground transition hover:text-destructive"
onClick={handleClearHistory}
>
Limpar todo o histórico
</Button>
</div>
)}
</div>
</aside>
)}
</div>
);
}

View File

@ -0,0 +1,107 @@
"use client";
import { useEffect, useState } from "react";
import { VoicePoweredOrb } from "@/components/ZoeIA/voice-powered-orb";
import { AIAssistantInterface } from "@/components/ZoeIA/ai-assistant-interface";
import { Button } from "@/components/ui/button";
import { ArrowLeft, Mic, MicOff } from "lucide-react";
export default function VoicePoweredOrbPage() {
const [isRecording, setIsRecording] = useState(false);
const [voiceDetected, setVoiceDetected] = useState(false);
const [assistantOpen, setAssistantOpen] = useState(false);
const toggleRecording = () => {
setIsRecording(!isRecording);
};
useEffect(() => {
if (!assistantOpen) return;
const original = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => {
document.body.style.overflow = original;
};
}, [assistantOpen]);
const openAssistant = () => setAssistantOpen(true);
const closeAssistant = () => setAssistantOpen(false);
return (
<div className="min-h-screen d flex items-center justify-center p-8">
<div className="flex flex-col items-center space-y-8">
{assistantOpen && (
<div className="fixed inset-0 z-50 flex flex-col bg-background">
<div className="flex items-center justify-between border-b border-border px-4 py-3">
<Button
type="button"
variant="ghost"
className="flex items-center gap-2"
onClick={closeAssistant}
>
<ArrowLeft className="h-4 w-4" />
Voltar
</Button>
</div>
<div className="flex-1 overflow-auto">
<AIAssistantInterface />
</div>
</div>
)}
{/* Orb */}
<div
className="w-96 h-96 relative cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2"
role="button"
tabIndex={0}
aria-label="Abrir assistente virtual"
onClick={openAssistant}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
openAssistant();
}
}}
>
<VoicePoweredOrb
enableVoiceControl={isRecording}
className="rounded-xl overflow-hidden shadow-2xl"
onVoiceDetected={setVoiceDetected}
/>
{voiceDetected && (
<span className="absolute bottom-4 right-4 rounded-full bg-primary/90 px-3 py-1 text-xs font-medium text-primary-foreground shadow-lg">
Ouvindo
</span>
)}
</div>
{/* Control Button */}
<Button
onClick={toggleRecording}
variant={isRecording ? "destructive" : "default"}
size="lg"
className="px-8 py-3"
>
{isRecording ? (
<>
<MicOff className="w-5 h-5 mr-3" />
Stop Recording
</>
) : (
<>
<Mic className="w-5 h-5 mr-3" />
Start Recording
</>
)}
</Button>
{/* Simple Instructions */}
<p className="text-muted-foreground text-center max-w-md">
Click the button to enable voice control. Speak to see the orb respond to your voice with subtle movements.
</p>
</div>
</div>
);
}

View File

@ -0,0 +1,10 @@
import * as React from "react"
import { AIAssistantInterface } from "@/components/ZoeIA/ai-assistant-interface"
export function Demo() {
return (
<div className="w-screen">
<AIAssistantInterface />
</div>
)
}

View File

@ -0,0 +1,493 @@
"use client";
import React, { useEffect, useRef, FC } from "react";
import { Renderer, Program, Mesh, Triangle, Vec3 } from "ogl";
import { cn } from "@/lib/utils";
interface VoicePoweredOrbProps {
className?: string;
hue?: number;
enableVoiceControl?: boolean;
voiceSensitivity?: number;
maxRotationSpeed?: number;
maxHoverIntensity?: number;
onVoiceDetected?: (detected: boolean) => void;
}
export const VoicePoweredOrb: FC<VoicePoweredOrbProps> = ({
className,
hue = 0,
enableVoiceControl = true,
voiceSensitivity = 1.5,
maxRotationSpeed = 1.2,
maxHoverIntensity = 0.8,
onVoiceDetected,
}) => {
const ctnDom = useRef<HTMLDivElement>(null);
const audioContextRef = useRef<AudioContext | null>(null);
const analyserRef = useRef<AnalyserNode | null>(null);
const microphoneRef = useRef<MediaStreamAudioSourceNode | null>(null);
const dataArrayRef = useRef<Uint8Array | null>(null);
const animationFrameRef = useRef<number>();
const mediaStreamRef = useRef<MediaStream | null>(null);
const vert = /* glsl */ `
precision highp float;
attribute vec2 position;
attribute vec2 uv;
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4(position, 0.0, 1.0);
}
`;
const frag = /* glsl */ `
precision highp float;
uniform float iTime;
uniform vec3 iResolution;
uniform float hue;
uniform float hover;
uniform float rot;
uniform float hoverIntensity;
varying vec2 vUv;
vec3 rgb2yiq(vec3 c) {
float y = dot(c, vec3(0.299, 0.587, 0.114));
float i = dot(c, vec3(0.596, -0.274, -0.322));
float q = dot(c, vec3(0.211, -0.523, 0.312));
return vec3(y, i, q);
}
vec3 yiq2rgb(vec3 c) {
float r = c.x + 0.956 * c.y + 0.621 * c.z;
float g = c.x - 0.272 * c.y - 0.647 * c.z;
float b = c.x - 1.106 * c.y + 1.703 * c.z;
return vec3(r, g, b);
}
vec3 adjustHue(vec3 color, float hueDeg) {
float hueRad = hueDeg * 3.14159265 / 180.0;
vec3 yiq = rgb2yiq(color);
float cosA = cos(hueRad);
float sinA = sin(hueRad);
float i = yiq.y * cosA - yiq.z * sinA;
float q = yiq.y * sinA + yiq.z * cosA;
yiq.y = i;
yiq.z = q;
return yiq2rgb(yiq);
}
vec3 hash33(vec3 p3) {
p3 = fract(p3 * vec3(0.1031, 0.11369, 0.13787));
p3 += dot(p3, p3.yxz + 19.19);
return -1.0 + 2.0 * fract(vec3(
p3.x + p3.y,
p3.x + p3.z,
p3.y + p3.z
) * p3.zyx);
}
float snoise3(vec3 p) {
const float K1 = 0.333333333;
const float K2 = 0.166666667;
vec3 i = floor(p + (p.x + p.y + p.z) * K1);
vec3 d0 = p - (i - (i.x + i.y + i.z) * K2);
vec3 e = step(vec3(0.0), d0 - d0.yzx);
vec3 i1 = e * (1.0 - e.zxy);
vec3 i2 = 1.0 - e.zxy * (1.0 - e);
vec3 d1 = d0 - (i1 - K2);
vec3 d2 = d0 - (i2 - K1);
vec3 d3 = d0 - 0.5;
vec4 h = max(0.6 - vec4(
dot(d0, d0),
dot(d1, d1),
dot(d2, d2),
dot(d3, d3)
), 0.0);
vec4 n = h * h * h * h * vec4(
dot(d0, hash33(i)),
dot(d1, hash33(i + i1)),
dot(d2, hash33(i + i2)),
dot(d3, hash33(i + 1.0))
);
return dot(vec4(31.316), n);
}
vec4 extractAlpha(vec3 colorIn) {
float a = max(max(colorIn.r, colorIn.g), colorIn.b);
return vec4(colorIn.rgb / (a + 1e-5), a);
}
const vec3 baseColor1 = vec3(0.611765, 0.262745, 0.996078);
const vec3 baseColor2 = vec3(0.298039, 0.760784, 0.913725);
const vec3 baseColor3 = vec3(0.062745, 0.078431, 0.600000);
const float innerRadius = 0.6;
const float noiseScale = 0.65;
float light1(float intensity, float attenuation, float dist) {
return intensity / (1.0 + dist * attenuation);
}
float light2(float intensity, float attenuation, float dist) {
return intensity / (1.0 + dist * dist * attenuation);
}
vec4 draw(vec2 uv) {
vec3 color1 = adjustHue(baseColor1, hue);
vec3 color2 = adjustHue(baseColor2, hue);
vec3 color3 = adjustHue(baseColor3, hue);
float ang = atan(uv.y, uv.x);
float len = length(uv);
float invLen = len > 0.0 ? 1.0 / len : 0.0;
float n0 = snoise3(vec3(uv * noiseScale, iTime * 0.5)) * 0.5 + 0.5;
float r0 = mix(mix(innerRadius, 1.0, 0.4), mix(innerRadius, 1.0, 0.6), n0);
float d0 = distance(uv, (r0 * invLen) * uv);
float v0 = light1(1.0, 10.0, d0);
v0 *= smoothstep(r0 * 1.05, r0, len);
float cl = cos(ang + iTime * 2.0) * 0.5 + 0.5;
float a = iTime * -1.0;
vec2 pos = vec2(cos(a), sin(a)) * r0;
float d = distance(uv, pos);
float v1 = light2(1.5, 5.0, d);
v1 *= light1(1.0, 50.0, d0);
float v2 = smoothstep(1.0, mix(innerRadius, 1.0, n0 * 0.5), len);
float v3 = smoothstep(innerRadius, mix(innerRadius, 1.0, 0.5), len);
vec3 col = mix(color1, color2, cl);
col = mix(color3, col, v0);
col = (col + v1) * v2 * v3;
col = clamp(col, 0.0, 1.0);
return extractAlpha(col);
}
vec4 mainImage(vec2 fragCoord) {
vec2 center = iResolution.xy * 0.5;
float size = min(iResolution.x, iResolution.y);
vec2 uv = (fragCoord - center) / size * 2.0;
float angle = rot;
float s = sin(angle);
float c = cos(angle);
uv = vec2(c * uv.x - s * uv.y, s * uv.x + c * uv.y);
uv.x += hover * hoverIntensity * 0.1 * sin(uv.y * 10.0 + iTime);
uv.y += hover * hoverIntensity * 0.1 * sin(uv.x * 10.0 + iTime);
return draw(uv);
}
void main() {
vec2 fragCoord = vUv * iResolution.xy;
vec4 col = mainImage(fragCoord);
gl_FragColor = vec4(col.rgb * col.a, col.a);
}
`;
// Voice analysis function
const analyzeAudio = () => {
if (!analyserRef.current || !dataArrayRef.current) return 0;
// To avoid type incompatibilities between different ArrayBuffer-like types
// (Uint8Array<ArrayBufferLike> vs Uint8Array<ArrayBuffer>), create a
// standard Uint8Array copy with an ArrayBuffer backing it. This satisfies
// the Web Audio API typing and is safe (small cost to copy).
const src = dataArrayRef.current as Uint8Array;
const buffer = Uint8Array.from(src);
analyserRef.current.getByteFrequencyData(buffer);
// Calculate RMS (Root Mean Square) for better voice detection
let sum = 0;
for (let i = 0; i < buffer.length; i++) {
const value = buffer[i] / 255;
sum += value * value;
}
const rms = Math.sqrt(sum / buffer.length);
// Apply sensitivity and boost the signal
const level = Math.min(rms * voiceSensitivity * 3.0, 1);
return level;
};
// Stop microphone and cleanup
const stopMicrophone = () => {
try {
// Stop all tracks in the media stream
if (mediaStreamRef.current) {
mediaStreamRef.current.getTracks().forEach(track => {
track.stop();
});
mediaStreamRef.current = null;
}
// Disconnect and cleanup audio nodes
if (microphoneRef.current) {
microphoneRef.current.disconnect();
microphoneRef.current = null;
}
if (analyserRef.current) {
analyserRef.current.disconnect();
analyserRef.current = null;
}
// Close audio context
if (audioContextRef.current && audioContextRef.current.state !== 'closed') {
audioContextRef.current.close();
audioContextRef.current = null;
}
dataArrayRef.current = null;
console.log('Microphone stopped and cleaned up');
} catch (error) {
console.warn('Error stopping microphone:', error);
}
};
// Initialize microphone access
const initMicrophone = async () => {
try {
// Clean up any existing microphone first
stopMicrophone();
const stream = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: false,
noiseSuppression: false,
autoGainControl: false,
sampleRate: 44100,
},
});
mediaStreamRef.current = stream;
audioContextRef.current = new (window.AudioContext || (window as any).webkitAudioContext)();
if (audioContextRef.current.state === 'suspended') {
await audioContextRef.current.resume();
}
analyserRef.current = audioContextRef.current.createAnalyser();
microphoneRef.current = audioContextRef.current.createMediaStreamSource(stream);
analyserRef.current.fftSize = 512;
analyserRef.current.smoothingTimeConstant = 0.3;
analyserRef.current.minDecibels = -90;
analyserRef.current.maxDecibels = -10;
microphoneRef.current.connect(analyserRef.current);
dataArrayRef.current = new Uint8Array(analyserRef.current.frequencyBinCount);
console.log('Microphone initialized successfully');
return true;
} catch (error) {
console.warn("Microphone access denied or not available:", error);
return false;
}
};
useEffect(() => {
const container = ctnDom.current;
if (!container) return;
let rendererInstance: any = null;
let glContext: WebGLRenderingContext | WebGL2RenderingContext | null = null;
let rafId: number;
let program: any = null;
try {
rendererInstance = new Renderer({
alpha: true,
premultipliedAlpha: false,
antialias: true,
dpr: window.devicePixelRatio || 1
});
glContext = rendererInstance.gl as WebGLRenderingContext;
glContext.clearColor(0, 0, 0, 0);
glContext.enable((glContext as any).BLEND);
glContext.blendFunc((glContext as any).SRC_ALPHA, (glContext as any).ONE_MINUS_SRC_ALPHA);
while (container.firstChild) {
container.removeChild(container.firstChild);
}
container.appendChild((glContext as any).canvas);
const geometry = new Triangle(glContext as any);
program = new Program(glContext as any, {
vertex: vert,
fragment: frag,
uniforms: {
iTime: { value: 0 },
iResolution: {
value: new Vec3(
(glContext as any).canvas.width,
(glContext as any).canvas.height,
(glContext as any).canvas.width / (glContext as any).canvas.height
),
},
hue: { value: hue },
hover: { value: 0 },
rot: { value: 0 },
hoverIntensity: { value: 0 },
},
});
const mesh = new Mesh(glContext as any, { geometry, program });
const resize = () => {
if (!container || !rendererInstance || !glContext) return;
const dpr = window.devicePixelRatio || 1;
const width = container.clientWidth;
const height = container.clientHeight;
if (width === 0 || height === 0) return;
rendererInstance.setSize(width * dpr, height * dpr);
(glContext as any).canvas.style.width = width + "px";
(glContext as any).canvas.style.height = height + "px";
if (program) {
program.uniforms.iResolution.value.set(
(glContext as any).canvas.width,
(glContext as any).canvas.height,
(glContext as any).canvas.width / (glContext as any).canvas.height
);
}
};
window.addEventListener("resize", resize);
resize();
let lastTime = 0;
let currentRot = 0;
let voiceLevel = 0;
const baseRotationSpeed = 0.3;
let isMicrophoneInitialized = false;
if (enableVoiceControl) {
initMicrophone().then((success) => {
isMicrophoneInitialized = success;
});
} else {
stopMicrophone();
isMicrophoneInitialized = false;
}
const update = (t: number) => {
rafId = requestAnimationFrame(update);
if (!program) return;
const dt = (t - lastTime) * 0.001;
lastTime = t;
program.uniforms.iTime.value = t * 0.001;
program.uniforms.hue.value = hue;
if (enableVoiceControl && isMicrophoneInitialized) {
voiceLevel = analyzeAudio();
if (onVoiceDetected) {
onVoiceDetected(voiceLevel > 0.1);
}
const voiceRotationSpeed = baseRotationSpeed + (voiceLevel * maxRotationSpeed * 2.0);
if (voiceLevel > 0.05) {
currentRot += dt * voiceRotationSpeed;
}
program.uniforms.hover.value = Math.min(voiceLevel * 2.0, 1.0);
program.uniforms.hoverIntensity.value = Math.min(voiceLevel * maxHoverIntensity * 0.8, maxHoverIntensity);
} else {
program.uniforms.hover.value = 0;
program.uniforms.hoverIntensity.value = 0;
if (onVoiceDetected) {
onVoiceDetected(false);
}
}
program.uniforms.rot.value = currentRot;
if (rendererInstance && glContext) {
glContext.clear((glContext as any).COLOR_BUFFER_BIT | (glContext as any).DEPTH_BUFFER_BIT);
rendererInstance.render({ scene: mesh });
}
};
rafId = requestAnimationFrame(update);
return () => {
cancelAnimationFrame(rafId);
window.removeEventListener("resize", resize);
try {
if (container && glContext && (glContext as any).canvas) {
if (container.contains((glContext as any).canvas)) {
container.removeChild((glContext as any).canvas);
}
}
} catch (error) {
console.warn("Canvas cleanup error:", error);
}
stopMicrophone();
if (glContext) {
(glContext as any).getExtension("WEBGL_lose_context")?.loseContext();
}
};
} catch (error) {
console.error("Error initializing Voice Powered Orb:", error);
if (container && container.firstChild) {
container.removeChild(container.firstChild);
}
return () => {
window.removeEventListener("resize", () => {});
};
}
}, [
hue,
enableVoiceControl,
voiceSensitivity,
maxRotationSpeed,
maxHoverIntensity,
vert,
frag,
]);
useEffect(() => {
let isMounted = true;
const handleMicrophoneState = async () => {
if (enableVoiceControl) {
const success = await initMicrophone();
if (!isMounted) return;
} else {
stopMicrophone();
}
};
handleMicrophoneState();
return () => {
isMounted = false;
};
}, [enableVoiceControl]);
return (
<div
ref={ctnDom}
className={cn(
"w-full h-full relative",
className
)}
>
</div>
);
};

View File

@ -0,0 +1,197 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { ArrowLeft, Mic, MicOff, Sparkles } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
AIAssistantInterface,
ChatSession,
} from "@/components/ZoeIA/ai-assistant-interface";
import { VoicePoweredOrb } from "@/components/ZoeIA/voice-powered-orb";
export function ChatWidget() {
const [assistantOpen, setAssistantOpen] = useState(false);
const [realtimeOpen, setRealtimeOpen] = useState(false);
const [isRecording, setIsRecording] = useState(false);
const [voiceDetected, setVoiceDetected] = useState(false);
const [history, setHistory] = useState<ChatSession[]>([]);
useEffect(() => {
if (!assistantOpen && !realtimeOpen) return;
const original = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => {
document.body.style.overflow = original;
};
}, [assistantOpen, realtimeOpen]);
const gradientRing = useMemo(
() => (
<span
aria-hidden
className="absolute inset-0 rounded-full bg-gradient-to-br from-primary via-sky-500 to-emerald-400 opacity-90 blur-sm transition group-hover:blur group-hover:opacity-100"
/>
),
[]
);
const openAssistant = () => setAssistantOpen(true);
const closeAssistant = () => setAssistantOpen(false);
const openRealtime = () => setRealtimeOpen(true);
const closeRealtime = () => {
setRealtimeOpen(false);
setAssistantOpen(true);
setIsRecording(false);
setVoiceDetected(false);
};
const toggleRecording = () => {
setIsRecording((prev) => {
const next = !prev;
if (!next) {
setVoiceDetected(false);
}
return next;
});
};
const handleOpenDocuments = () => {
console.log("[ChatWidget] Abrindo fluxo de documentos");
closeAssistant();
};
const handleOpenChat = () => {
console.log("[ChatWidget] Encaminhando para chat em tempo real");
setAssistantOpen(false);
openRealtime();
};
const handleUpsertHistory = (session: ChatSession) => {
setHistory((previous) => {
const index = previous.findIndex((item) => item.id === session.id);
if (index >= 0) {
const updated = [...previous];
updated[index] = session;
return updated;
}
return [...previous, session];
});
};
const handleClearHistory = () => {
setHistory([]);
};
return (
<>
{assistantOpen && (
<div
id="ai-assistant-overlay"
className="fixed inset-0 z-[100] flex flex-col bg-background"
>
<div className="flex items-center justify-between border-b border-border px-4 py-3">
<Button
type="button"
variant="ghost"
className="flex items-center gap-2"
onClick={closeAssistant}
>
<ArrowLeft className="h-4 w-4" aria-hidden />
<span className="text-sm">Voltar</span>
</Button>
</div>
<div className="flex-1 overflow-auto">
<AIAssistantInterface
onOpenDocuments={handleOpenDocuments}
onOpenChat={handleOpenChat}
history={history}
onAddHistory={handleUpsertHistory}
onClearHistory={handleClearHistory}
/>
</div>
</div>
)}
{realtimeOpen && (
<div
id="ai-realtime-overlay"
className="fixed inset-0 z-[110] flex flex-col bg-background"
>
<div className="flex items-center justify-between border-b border-border px-4 py-3">
<Button
type="button"
variant="ghost"
className="flex items-center gap-2"
onClick={closeRealtime}
>
<ArrowLeft className="h-4 w-4" aria-hidden />
<span className="text-sm">Voltar para a Zoe</span>
</Button>
</div>
<div className="flex-1 overflow-auto">
<div className="mx-auto flex h-full w-full max-w-4xl flex-col items-center justify-center gap-8 px-6 py-10 text-center">
<div className="relative w-full max-w-md aspect-square">
<VoicePoweredOrb
enableVoiceControl={isRecording}
className="h-full w-full rounded-3xl shadow-2xl"
onVoiceDetected={setVoiceDetected}
/>
{voiceDetected && (
<span className="absolute bottom-6 right-6 rounded-full bg-primary/90 px-3 py-1 text-xs font-semibold text-primary-foreground shadow-lg">
Ouvindo
</span>
)}
</div>
<div className="flex flex-col items-center gap-4">
<Button
onClick={toggleRecording}
size="lg"
className="px-8 py-3"
variant={isRecording ? "destructive" : "default"}
>
{isRecording ? (
<>
<MicOff className="mr-2 h-5 w-5" aria-hidden />
Parar captura de voz
</>
) : (
<>
<Mic className="mr-2 h-5 w-5" aria-hidden />
Iniciar captura de voz
</>
)}
</Button>
<p className="max-w-md text-sm text-muted-foreground">
Ative a captura para falar com a equipe em tempo real. Assim que sua voz for detectada, a Zoe sinaliza visualmente e encaminha o atendimento.
</p>
</div>
</div>
</div>
</div>
)}
<div className="fixed bottom-6 right-6 z-50 sm:bottom-8 sm:right-8">
<button
type="button"
onClick={openAssistant}
className="group relative flex h-16 w-16 items-center justify-center rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2"
aria-haspopup="dialog"
aria-expanded={assistantOpen}
aria-controls="ai-assistant-overlay"
>
{gradientRing}
<span className="relative flex h-16 w-16 items-center justify-center rounded-full bg-background text-primary shadow-[0_12px_30px_rgba(37,99,235,0.25)] ring-1 ring-primary/10 transition group-hover:scale-[1.03] group-active:scale-95">
<Sparkles className="h-7 w-7" aria-hidden />
</span>
</button>
</div>
</>
);
}

View File

@ -1826,7 +1826,7 @@ export async function buscarMedicos(termo: string): Promise<Medico[]> {
// Executa as buscas e combina resultados únicos
for (const query of queries) {
try {
const url = `${REST}/doctors?${query}&limit=10`;
const url = `${REST}/doctors?${query}&limit=100`;
const headers = baseHeaders();
const res = await fetch(url, { method: 'GET', headers });
const arr = await parse<Medico[]>(res);
@ -1844,7 +1844,7 @@ export async function buscarMedicos(termo: string): Promise<Medico[]> {
}
}
return results.slice(0, 20); // Limita a 20 resultados
return results.slice(0, 100); // Limita a 100 resultados
}
export async function listarTodosMedicos(): Promise<Medico[]> {

View File

@ -58,6 +58,7 @@
"jspdf": "^3.0.3",
"lucide-react": "^0.454.0",
"next-themes": "latest",
"ogl": "^1.0.11",
"react": "^18",
"react-day-picker": "latest",
"react-dom": "^18",

View File

@ -152,6 +152,9 @@ importers:
next-themes:
specifier: latest
version: 0.4.6(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
ogl:
specifier: ^1.0.11
version: 1.0.11
react:
specifier: ^18
version: 18.3.1
@ -2809,6 +2812,9 @@ packages:
resolution: {integrity: sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==}
engines: {node: '>= 0.4'}
ogl@1.0.11:
resolution: {integrity: sha512-kUpC154AFfxi16pmZUK4jk3J+8zxwTWGPo03EoYA8QPbzikHoaC82n6pNTbd+oEaJonaE8aPWBlX7ad9zrqLsA==}
optionator@0.9.4:
resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==}
engines: {node: '>= 0.8.0'}
@ -6089,6 +6095,8 @@ snapshots:
define-properties: 1.2.1
es-object-atoms: 1.1.1
ogl@1.0.11: {}
optionator@0.9.4:
dependencies:
deep-is: 0.1.4

1
susconecta/types/ogl.d.ts vendored Normal file
View File

@ -0,0 +1 @@
declare module 'ogl';