fix(paciente) adicionei o chat interface

This commit is contained in:
Jonas Francisco 2025-11-13 13:39:51 -03:00
parent 20e3253472
commit 8ce02ac5ad
2 changed files with 356 additions and 626 deletions

View File

@ -1,512 +1,317 @@
"use client"; "use client";
import type React from "react"; import { useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import { useState, useRef } from "react"; import { Input } from "@/components/ui/input";
import { SimpleThemeToggle } from "@/components/ui/simple-theme-toggle";
import { import {
Search, Clock,
Mic, Info,
ArrowUp, Lock,
MessageCircle,
Plus, Plus,
FileText, Upload,
Code,
BookOpen,
PenTool,
BrainCircuit,
Sparkles,
} from "lucide-react"; } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
export function AIAssistantInterface() { interface HistoryEntry {
const [inputValue, setInputValue] = useState(""); id: string;
const [searchEnabled, setSearchEnabled] = useState(false); text: string;
const [deepResearchEnabled, setDeepResearchEnabled] = useState(false); createdAt: string;
const [reasonEnabled, setReasonEnabled] = useState(false); }
const [uploadedFiles, setUploadedFiles] = useState<string[]>([]);
const [showUploadAnimation, setShowUploadAnimation] = useState(false);
const [activeCommandCategory, setActiveCommandCategory] = useState<
string | null
>(null);
const inputRef = useRef<HTMLInputElement>(null);
const commandSuggestions = { interface AIAssistantInterfaceProps {
learn: [ onOpenDocuments?: () => void;
"Explain the Big Bang theory", onOpenChat?: () => void;
"How does photosynthesis work?", history?: HistoryEntry[];
"What are black holes?", onAddHistory?: (entry: HistoryEntry) => void;
"Explain quantum computing", onClearHistory?: () => void;
"How does the human brain work?", }
],
code: [
"Create a React component for a todo list",
"Write a Python function to sort a list",
"How to implement authentication in Next.js",
"Explain async/await in JavaScript",
"Create a CSS animation for a button",
],
write: [
"Write a professional email to a client",
"Create a product description for a smartphone",
"Draft a blog post about AI",
"Write a creative story about space exploration",
"Create a social media post about sustainability",
],
};
const handleUploadFile = () => { export function AIAssistantInterface({
setShowUploadAnimation(true); onOpenDocuments,
onOpenChat,
history: externalHistory,
onAddHistory,
onClearHistory,
}: AIAssistantInterfaceProps) {
const [question, setQuestion] = useState("");
const [drawerOpen, setDrawerOpen] = useState(false);
const [internalHistory, setInternalHistory] = useState<HistoryEntry[]>([]);
const history = externalHistory ?? internalHistory;
// Simulate file upload with timeout const showHistoryBadge = useMemo(() => history.length > 0, [history.length]);
setTimeout(() => {
const newFile = `Document.pdf`;
setUploadedFiles((prev) => [...prev, newFile]);
setShowUploadAnimation(false);
}, 1500);
};
const handleCommandSelect = (command: string) => { const handleDocuments = () => {
setInputValue(command); if (onOpenDocuments) {
setActiveCommandCategory(null); onOpenDocuments();
return;
if (inputRef.current) {
inputRef.current.focus();
} }
console.log("[ZoeIA] Abrir fluxo de documentos");
};
const handleOpenRealtimeChat = () => {
if (onOpenChat) {
onOpenChat();
return;
}
console.log("[ZoeIA] Abrir chat em tempo real");
}; };
const handleSendMessage = () => { const handleSendMessage = () => {
if (inputValue.trim()) { const trimmed = question.trim();
console.log("Sending message:", inputValue); if (!trimmed) return;
setInputValue("");
handlePersistHistory(trimmed);
console.log("[ZoeIA] Mensagem enviada para Zoe", trimmed);
setQuestion("");
};
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 handlePersistHistory = (text: string) => {
const entry: HistoryEntry = {
id: `hist-${Date.now()}`,
text,
createdAt: new Date().toISOString(),
};
if (onAddHistory) {
onAddHistory(entry);
} else {
setInternalHistory((prev) => [...prev, entry]);
}
setDrawerOpen(true);
};
const handleClearHistory = () => {
if (onClearHistory) {
onClearHistory();
} else {
setInternalHistory([]);
} }
}; };
const HistoryGlyph = () => (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
className="h-5 w-5"
fill="none"
>
<circle cx="16" cy="8" r="3" className="stroke-current" strokeWidth="1.6" />
<line x1="5" y1="8" x2="12" y2="8" className="stroke-current" strokeWidth="1.6" strokeLinecap="round" />
<line x1="5" y1="16" x2="19" y2="16" className="stroke-current" strokeWidth="1.6" strokeLinecap="round" />
<circle cx="9" cy="16" r="1" className="fill-current" />
</svg>
);
return ( return (
<div className="min-h-screen flex flex-col items-center justify-center bg-white p-6"> <div className="min-h-screen bg-background text-foreground">
<div className="w-full max-w-3xl mx-auto flex flex-col items-center"> <div className="mx-auto flex w-full max-w-3xl flex-col gap-8 px-4 py-10 sm:px-6 sm:py-12">
{/* Logo with animated gradient */} <header className="flex flex-col gap-6 sm:flex-row sm:items-center sm:justify-between">
<div className="mb-8 w-20 h-20 relative"> <div className="flex items-center gap-3">
<svg <Button
xmlns="http://www.w3.org/2000/svg" type="button"
fill="none" variant="ghost"
viewBox="0 0 200 200" size="icon"
width="100%" onClick={() => setDrawerOpen(true)}
height="100%" className="relative rounded-2xl border border-border/60 bg-card text-muted-foreground shadow-sm transition hover:text-primary"
className="w-full h-full"
>
<g clipPath="url(#cs_clip_1_ellipse-12)">
<mask
id="cs_mask_1_ellipse-12"
style={{ maskType: "alpha" }}
width="200"
height="200"
x="0"
y="0"
maskUnits="userSpaceOnUse"
>
<path
fill="#fff"
fillRule="evenodd"
d="M100 150c27.614 0 50-22.386 50-50s-22.386-50-50-50-50 22.386-50 50 22.386 50 50 50zm0 50c55.228 0 100-44.772 100-100S155.228 0 100 0 0 44.772 0 100s44.772 100 100 100z"
clipRule="evenodd"
></path>
</mask>
<g mask="url(#cs_mask_1_ellipse-12)">
<path fill="#fff" d="M200 0H0v200h200V0z"></path>
<path
fill="#0066FF"
fillOpacity="0.33"
d="M200 0H0v200h200V0z"
></path>
<g
filter="url(#filter0_f_844_2811)"
className="animate-gradient"
>
<path fill="#0066FF" d="M110 32H18v68h92V32z"></path>
<path fill="#0044FF" d="M188-24H15v98h173v-98z"></path>
<path fill="#0099FF" d="M175 70H5v156h170V70z"></path>
<path fill="#00CCFF" d="M230 51H100v103h130V51z"></path>
</g>
</g>
</g>
<defs>
<filter
id="filter0_f_844_2811"
width="385"
height="410"
x="-75"
y="-104"
colorInterpolationFilters="sRGB"
filterUnits="userSpaceOnUse"
>
<feFlood floodOpacity="0" result="BackgroundImageFix"></feFlood>
<feBlend
in="SourceGraphic"
in2="BackgroundImageFix"
result="shape"
></feBlend>
<feGaussianBlur
result="effect1_foregroundBlur_844_2811"
stdDeviation="40"
></feGaussianBlur>
</filter>
<clipPath id="cs_clip_1_ellipse-12">
<path fill="#fff" d="M0 0H200V200H0z"></path>
</clipPath>
</defs>
<g
style={{ mixBlendMode: "overlay" }}
mask="url(#cs_mask_1_ellipse-12)"
> >
<path <HistoryGlyph />
fill="gray" <span className="sr-only">Abrir histórico de interações</span>
stroke="transparent" {showHistoryBadge && (
d="M200 0H0v200h200V0z" <span className="absolute -top-1 -right-1 h-2.5 w-2.5 rounded-full bg-primary" />
filter="url(#cs_noise_1_ellipse-12)" )}
></path> </Button>
</g> <span className="flex h-12 w-12 items-center justify-center rounded-2xl bg-gradient-to-br from-primary via-sky-500 to-emerald-400 text-base font-semibold text-white shadow-lg">
<defs> Zoe
<filter </span>
id="cs_noise_1_ellipse-12" <div>
width="100%" <p className="text-sm font-semibold text-primary">Assistente Clínica Zoe</p>
height="100%" <h1 className="text-2xl font-bold tracking-tight">Olá, eu sou Zoe. Como posso ajudar hoje?</h1>
x="0%" </div>
y="0%" </div>
filterUnits="objectBoundingBox" <SimpleThemeToggle />
> </header>
<feTurbulence
baseFrequency="0.6" <div className="flex items-center gap-2 rounded-full border border-border px-4 py-2 text-xs text-muted-foreground shadow-sm">
numOctaves="5" <Lock className="h-4 w-4" />
result="out1" <span>Suas informações permanecem criptografadas e seguras com a equipe Zoe.</span>
seed="4"
></feTurbulence>
<feComposite
in="out1"
in2="SourceGraphic"
operator="in"
result="out2"
></feComposite>
<feBlend
in="SourceGraphic"
in2="out2"
mode="overlay"
result="out3"
></feBlend>
</filter>
</defs>
</svg>
</div> </div>
{/* Welcome message */} <section className="space-y-6 rounded-3xl border border-primary/15 bg-card/60 p-6 shadow-lg backdrop-blur">
<div className="mb-10 text-center"> <div className="rounded-3xl border border-primary/20 bg-primary/5 p-6 text-sm leading-relaxed text-muted-foreground">
<motion.div <div className="mb-4 flex items-center gap-3 text-primary">
initial={{ opacity: 0, y: 10 }} <Info className="h-5 w-5" />
animate={{ opacity: 1, y: 0 }} <span className="font-semibold">Informativo importante</span>
transition={{ duration: 0.3 }} </div>
className="flex flex-col items-center" <p>
> A Zoe é a assistente virtual da Clínica Zoe. Ela reúne informações sobre seus cuidados e orienta os próximos passos.
<h1 className="text-3xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-blue-600 to-blue-400 mb-2"> O atendimento é informativo e não substitui a avaliação de um profissional de saúde qualificado.
Ready to assist you
</h1>
<p className="text-gray-500 max-w-md">
Ask me anything or try one of the suggestions below
</p> </p>
</motion.div> <p className="mt-4">
Em situações de urgência, procure imediatamente o suporte médico presencial ou ligue para os serviços de emergência.
</p>
</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>
</section>
<div className="flex items-center gap-3 rounded-full border border-border bg-card/70 px-3 py-2 shadow-xl">
<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>
<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="border-none bg-transparent text-sm shadow-none focus-visible:ring-0"
/>
<div className="flex items-center 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>
{/* Input area with integrated functions and file upload */} {drawerOpen && (
<div className="w-full bg-white border border-gray-200 rounded-xl shadow-sm overflow-hidden mb-4"> <aside className="fixed inset-y-0 left-0 z-[120] w-[min(22rem,80vw)] bg-card shadow-2xl">
<div className="p-4"> <div className="flex h-full flex-col">
<input <div className="flex items-center justify-between border-b border-border px-4 py-4">
ref={inputRef} <div className="flex items-center gap-3">
type="text" <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">
placeholder="Ask me anything..." Zoe
value={inputValue} </span>
onChange={(e) => setInputValue(e.target.value)} <div>
className="w-full text-gray-700 text-base outline-none placeholder:text-gray-400" <h2 className="text-sm font-semibold text-foreground">Histórico da Zoe</h2>
/> <p className="text-xs text-muted-foreground">{history.length} registro{history.length === 1 ? "" : "s"}</p>
</div>
{/* Uploaded files */}
{uploadedFiles.length > 0 && (
<div className="px-4 pb-3">
<div className="flex flex-wrap gap-2">
{uploadedFiles.map((file, index) => (
<div
key={index}
className="flex items-center gap-2 bg-gray-50 py-1 px-2 rounded-md border border-gray-200"
>
<FileText className="w-3 h-3 text-blue-600" />
<span className="text-xs text-gray-700">{file}</span>
<button
onClick={() =>
setUploadedFiles((prev) =>
prev.filter((_, i) => i !== index)
)
}
className="text-gray-400 hover:text-gray-600"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="12"
height="12"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<line x1="18" y1="6" x2="6" y2="18"></line>
<line x1="6" y1="6" x2="18" y2="18"></line>
</svg>
</button>
</div> </div>
))} </div>
</div> <Button
</div> type="button"
)} variant="ghost"
size="icon"
{/* Search, Deep Research, Reason functions and actions */} onClick={() => setDrawerOpen(false)}
<div className="px-4 py-3 flex items-center justify-between"> className="rounded-full"
<div className="flex items-center gap-2">
<button
onClick={() => setSearchEnabled(!searchEnabled)}
className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium transition-colors ${
searchEnabled
? "bg-blue-50 text-blue-600 hover:bg-blue-100"
: "bg-gray-100 text-gray-400 hover:bg-gray-200"
}`}
>
<Search className="w-4 h-4" />
<span>Search</span>
</button>
<button
onClick={() => setDeepResearchEnabled(!deepResearchEnabled)}
className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium transition-colors ${
deepResearchEnabled
? "bg-blue-50 text-blue-600 hover:bg-blue-100"
: "bg-gray-100 text-gray-400 hover:bg-gray-200"
}`}
>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className={
deepResearchEnabled ? "text-blue-600" : "text-gray-400"
}
> >
<circle <span className="sr-only">Fechar histórico</span>
cx="8" ×
cy="8" </Button>
r="7" </div>
stroke="currentColor"
strokeWidth="2"
/>
<circle cx="8" cy="8" r="3" fill="currentColor" />
</svg>
<span>Deep Research</span>
</button>
<button
onClick={() => setReasonEnabled(!reasonEnabled)}
className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium transition-colors ${
reasonEnabled
? "bg-blue-50 text-blue-600 hover:bg-blue-100"
: "bg-gray-100 text-gray-400 hover:bg-gray-200"
}`}
>
<BrainCircuit
className={`w-4 h-4 ${
reasonEnabled ? "text-blue-600" : "text-gray-400"
}`}
/>
<span>Reason</span>
</button>
</div>
<div className="flex items-center gap-2">
<button className="p-2 text-gray-400 hover:text-gray-600 transition-colors">
<Mic className="w-5 h-5" />
</button>
<button
onClick={handleSendMessage}
disabled={!inputValue.trim()}
className={`w-8 h-8 flex items-center justify-center rounded-full transition-colors ${
inputValue.trim()
? "bg-blue-600 text-white hover:bg-blue-700"
: "bg-gray-100 text-gray-400 cursor-not-allowed"
}`}
>
<ArrowUp className="w-4 h-4" />
</button>
</div>
</div>
{/* Upload files */} <div className="flex items-center gap-2 border-b border-border px-4 py-3">
<div className="px-4 py-2 border-t border-gray-100"> <Button
<button type="button"
onClick={handleUploadFile} className="flex-1 justify-start gap-2 rounded-xl bg-primary text-primary-foreground shadow-md transition hover:shadow-lg"
className="flex items-center gap-2 text-gray-600 text-sm hover:text-gray-900 transition-colors" onClick={() => {
> handleClearHistory();
{showUploadAnimation ? ( setDrawerOpen(false);
<motion.div
className="flex space-x-1"
initial="hidden"
animate="visible"
variants={{
hidden: {},
visible: {
transition: {
staggerChildren: 0.1,
},
},
}} }}
> >
{[...Array(3)].map((_, i) => ( <Plus className="h-4 w-4" />
<motion.div Novo atendimento
key={i} </Button>
className="w-1.5 h-1.5 bg-blue-600 rounded-full"
variants={{
hidden: { opacity: 0, y: 5 },
visible: {
opacity: 1,
y: 0,
transition: {
duration: 0.4,
repeat: Infinity,
repeatType: "mirror",
delay: i * 0.1,
},
},
}}
/>
))}
</motion.div>
) : (
<Plus className="w-4 h-4" />
)}
<span>Upload Files</span>
</button>
</div>
</div>
{/* Command categories */}
<div className="w-full grid grid-cols-3 gap-4 mb-4">
<CommandButton
icon={<BookOpen className="w-5 h-5" />}
label="Learn"
isActive={activeCommandCategory === "learn"}
onClick={() =>
setActiveCommandCategory(
activeCommandCategory === "learn" ? null : "learn"
)
}
/>
<CommandButton
icon={<Code className="w-5 h-5" />}
label="Code"
isActive={activeCommandCategory === "code"}
onClick={() =>
setActiveCommandCategory(
activeCommandCategory === "code" ? null : "code"
)
}
/>
<CommandButton
icon={<PenTool className="w-5 h-5" />}
label="Write"
isActive={activeCommandCategory === "write"}
onClick={() =>
setActiveCommandCategory(
activeCommandCategory === "write" ? null : "write"
)
}
/>
</div>
{/* Command suggestions */}
<AnimatePresence>
{activeCommandCategory && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
exit={{ opacity: 0, height: 0 }}
className="w-full mb-6 overflow-hidden"
>
<div className="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">
<div className="p-3 border-b border-gray-100">
<h3 className="text-sm font-medium text-gray-700">
{activeCommandCategory === "learn"
? "Learning suggestions"
: activeCommandCategory === "code"
? "Coding suggestions"
: "Writing suggestions"}
</h3>
</div>
<ul className="divide-y divide-gray-100">
{commandSuggestions[
activeCommandCategory as keyof typeof commandSuggestions
].map((suggestion, index) => (
<motion.li
key={index}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: index * 0.03 }}
onClick={() => handleCommandSelect(suggestion)}
className="p-3 hover:bg-gray-50 cursor-pointer transition-colors duration-75"
>
<div className="flex items-center gap-3">
{activeCommandCategory === "learn" ? (
<BookOpen className="w-4 h-4 text-blue-600" />
) : activeCommandCategory === "code" ? (
<Code className="w-4 h-4 text-blue-600" />
) : (
<PenTool className="w-4 h-4 text-blue-600" />
)}
<span className="text-sm text-gray-700">
{suggestion}
</span>
</div>
</motion.li>
))}
</ul>
</div> </div>
</motion.div>
)} <div className="flex-1 overflow-y-auto px-4 py-4">
</AnimatePresence> {history.length === 0 ? (
<p className="text-sm text-muted-foreground">
Nenhuma conversa registrada ainda. Envie uma mensagem para começar um novo acompanhamento com a Zoe.
</p>
) : (
<ul className="flex flex-col gap-3 text-sm">
{[...history]
.reverse()
.map((entry) => (
<li
key={entry.id}
className="flex items-start gap-3 rounded-xl border border-border/60 bg-background/90 p-3 shadow-sm"
>
<span className="mt-0.5 text-primary">
<Clock className="h-4 w-4" />
</span>
<div className="flex-1">
<p className="font-medium text-foreground line-clamp-2">{entry.text}</p>
<p className="text-xs text-muted-foreground">
{new Date(entry.createdAt).toLocaleString("pt-BR", {
day: "2-digit",
month: "2-digit",
hour: "2-digit",
minute: "2-digit",
})}
</p>
</div>
</li>
))}
</ul>
)}
</div>
</div>
</aside>
)}
</div> </div>
</div> </div>
); );
} }
interface CommandButtonProps {
icon: React.ReactNode;
label: string;
isActive: boolean;
onClick: () => void;
}
function CommandButton({ icon, label, isActive, onClick }: CommandButtonProps) {
return (
<motion.button
onClick={onClick}
className={`flex flex-col items-center justify-center gap-2 p-4 rounded-xl border transition-all ${
isActive
? "bg-blue-50 border-blue-200 shadow-sm"
: "bg-white border-gray-200 hover:border-gray-300"
}`}
>
<div className={`${isActive ? "text-blue-600" : "text-gray-500"}`}>
{icon}
</div>
<span
className={`text-sm font-medium ${
isActive ? "text-blue-700" : "text-gray-700"
}`}
>
{label}
</span>
</motion.button>
);
}

View File

@ -1,58 +1,30 @@
"use client"; "use client";
import { useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { Sparkles, MessageCircle, X, Send } from "lucide-react"; import { ArrowLeft, Sparkles } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { AIAssistantInterface } from "@/components/ZoeIA/ai-assistant-interface";
const cannedSuggestions = [ interface HistoryEntry {
"Como remarcar minha consulta?",
"Quais documentos preciso levar?",
"Quero falar com suporte humano",
];
const supportAvailability = {
title: "Equipe disponível",
description: "SegSex das 08h às 18h",
};
interface ChatMessage {
id: string; id: string;
author: "assistant" | "user";
text: string; text: string;
timestamp: string; createdAt: string;
} }
export function ChatWidget() { export function ChatWidget() {
const [open, setOpen] = useState(false); const [assistantOpen, setAssistantOpen] = useState(false);
const [input, setInput] = useState(""); const [history, setHistory] = useState<HistoryEntry[]>([]);
const [messages, setMessages] = useState<ChatMessage[]>(() => [
{
id: "welcome",
author: "assistant",
text: "Olá! Sou sua assistente virtual. Posso ajudar a acompanhar consultas, exames e suporte geral.",
timestamp: new Date().toISOString(),
},
]);
const toggle = () => setOpen((prev) => !prev); useEffect(() => {
if (!assistantOpen) return;
const handleSend = () => { const original = document.body.style.overflow;
const trimmed = input.trim(); document.body.style.overflow = "hidden";
if (!trimmed) return;
const now = new Date().toISOString(); return () => {
setMessages((prev) => [ document.body.style.overflow = original;
...prev, };
{ id: `user-${now}`, author: "user", text: trimmed, timestamp: now }, }, [assistantOpen]);
{
id: `assistant-${now}`,
author: "assistant",
text: "Recebi sua mensagem! Nossa equipe retornará em breve.",
timestamp: now,
},
]);
setInput("");
};
const gradientRing = useMemo( const gradientRing = useMemo(
() => ( () => (
@ -64,119 +36,72 @@ export function ChatWidget() {
[] []
); );
const openAssistant = () => setAssistantOpen(true);
const closeAssistant = () => setAssistantOpen(false);
const handleOpenDocuments = () => {
console.log("[ChatWidget] Abrindo fluxo de documentos");
closeAssistant();
};
const handleOpenChat = () => {
console.log("[ChatWidget] Encaminhando para chat humano");
closeAssistant();
};
const handleAddHistory = (entry: HistoryEntry) => {
setHistory((prev) => [...prev, entry]);
};
const handleClearHistory = () => {
setHistory([]);
};
return ( return (
<div className="fixed bottom-6 right-6 z-50 flex flex-col items-end gap-2 sm:bottom-8 sm:right-8"> <>
{open && ( {assistantOpen && (
<div <div
id="chat-widget" id="ai-assistant-overlay"
className="w-[min(22rem,90vw)] rounded-3xl border border-primary/20 bg-background shadow-[0_20px_60px_rgba(30,64,175,0.25)] ring-1 ring-primary/10" className="fixed inset-0 z-[100] flex flex-col bg-background"
> >
<header className="flex items-start gap-3 rounded-t-3xl bg-gradient-to-r from-primary via-blue-600 to-emerald-500 px-5 py-4 text-primary-foreground"> <div className="flex items-center justify-between border-b border-border px-4 py-3">
<div className="flex h-12 w-12 items-center justify-center rounded-full bg-white/15"> <Button
<Sparkles className="h-6 w-6" aria-hidden />
</div>
<div className="flex-1">
<p className="text-sm font-semibold">Assistente RiseUp</p>
<p className="text-xs text-white/80">Pronta para ajudar no que você precisar</p>
</div>
<button
type="button" type="button"
onClick={toggle} variant="ghost"
className="rounded-full border border-white/20 p-1.5 text-white/80 transition hover:bg-white/10 hover:text-white" className="flex items-center gap-2"
aria-label="Fechar chat" onClick={closeAssistant}
> >
<X className="h-4 w-4" /> <ArrowLeft className="h-4 w-4" aria-hidden />
</button> <span className="text-sm">Voltar</span>
</header> </Button>
<div className="max-h-[22rem] overflow-y-auto px-5 py-4 space-y-3 text-sm">
{messages.map((message) => (
<div
key={message.id}
className={
message.author === "assistant"
? "flex items-start gap-3"
: "flex flex-row-reverse items-start gap-3"
}
>
<span
className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-full ${
message.author === "assistant"
? "bg-primary/10 text-primary"
: "bg-gradient-to-br from-primary/10 to-emerald-100 text-primary"
}`}
>
{message.author === "assistant" ? <Sparkles className="h-4 w-4" /> : <MessageCircle className="h-4 w-4" />}
</span>
<div
className={`rounded-2xl px-4 py-2 leading-relaxed shadow-sm ${
message.author === "assistant"
? "bg-primary/5 text-muted-foreground"
: "bg-primary text-primary-foreground"
}`}
>
{message.text}
</div>
</div>
))}
</div> </div>
<div className="flex-1 overflow-auto">
<div className="px-5 pb-4"> <AIAssistantInterface
<div className="mb-3 text-xs text-muted-foreground/80"> onOpenDocuments={handleOpenDocuments}
<p className="font-medium text-primary">{supportAvailability.title}</p> onOpenChat={handleOpenChat}
<p>{supportAvailability.description}</p> history={history}
</div> onAddHistory={handleAddHistory}
<div className="flex flex-wrap gap-2 pb-3"> onClearHistory={handleClearHistory}
{cannedSuggestions.map((suggestion) => ( />
<button
key={suggestion}
type="button"
onClick={() => setInput(suggestion)}
className="rounded-full border border-primary/20 px-3 py-1 text-xs text-muted-foreground transition hover:border-primary hover:text-primary"
>
{suggestion}
</button>
))}
</div>
<div className="flex items-center gap-2 rounded-full border border-border bg-background px-3 py-2 shadow-inner">
<Input
value={input}
onChange={(event) => setInput(event.target.value)}
placeholder="Escreva sua mensagem"
className="border-none px-0 text-sm focus-visible:ring-0"
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
handleSend();
}
}}
/>
<Button
size="icon"
className="rounded-full bg-primary text-primary-foreground shadow-md transition hover:bg-primary/90"
onClick={handleSend}
aria-label="Enviar mensagem"
>
<Send className="h-4 w-4" />
</Button>
</div>
</div> </div>
</div> </div>
)} )}
<button <div className="fixed bottom-6 right-6 z-50 sm:bottom-8 sm:right-8">
type="button" <button
onClick={toggle} type="button"
className="group relative flex h-16 w-16 items-center justify-center rounded-full" onClick={openAssistant}
aria-haspopup="dialog" 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-expanded={open} aria-haspopup="dialog"
aria-controls="chat-widget" 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"> {gradientRing}
<Sparkles className="h-7 w-7" /> <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">
</span> <Sparkles className="h-7 w-7" aria-hidden />
</button> </span>
</div> </button>
</div>
</>
); );
} }