import { useEffect, useRef } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import {
CopilotChat,
useAgent,
useConfigureSuggestions,
useCopilotKit,
} from "@copilotkit/react-core/v2";
import { useCopilotAction } from "@copilotkit/react-core";
import { Sparkles } from "lucide-react";
import { SpendingSummaryCard, type SpendingSummaryArgs } from "@/components/chat/ChatCards";
const STATIC_SUGGESTIONS = {
available: "before-first-message" as const,
suggestions: [
{ title: "¿Cuál es mi saldo neto hoy?", message: "¿Cuál es mi saldo neto hoy?" },
{ title: "¿Cuánto gasté en el ciclo anterior?", message: "¿Cuánto gasté en el ciclo anterior?" },
{ title: "Últimas 10 transacciones", message: "Muéstrame mis últimas 10 transacciones" },
{ title: "¿Cómo va mi pensión?", message: "¿Cómo va mi pensión?" },
],
};
export default function Asistente() {
useConfigureSuggestions(STATIC_SUGGESTIONS);
// A question typed on the Inicio dashboard arrives via router state:
// append it as a user message and run the agent once.
const location = useLocation();
const navigate = useNavigate();
const { agent } = useAgent();
const { copilotkit } = useCopilotKit();
const sentRef = useRef(false);
useEffect(() => {
const ask = (location.state as { ask?: string } | null)?.ask;
if (!ask || sentRef.current || !agent) return;
sentRef.current = true;
// Clear the state so back/refresh doesn't re-send the question.
navigate(location.pathname, { replace: true, state: null });
agent.addMessage({
id: crypto.randomUUID(),
role: "user",
content: ask,
});
void copilotkit.runAgent({ agent });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [agent]);
useCopilotAction({
name: "render_spending_summary",
description:
"Render a visual spending summary card with source breakdown and category progress bars. " +
"Call this for any cycle summary, spending totals, or category breakdown.",
parameters: [
{ name: "title", type: "string", description: "Card title (e.g. 'Ciclo actual')" },
{ name: "period", type: "string", description: "Human-readable period (e.g. '18 mar → 18 abr 2026')" },
{ name: "total_crc", type: "number", description: "Total spend in CRC" },
{
name: "by_source",
type: "object[]",
description: "Breakdown by payment source",
attributes: [
{ name: "source", type: "string" },
{ name: "total_crc", type: "number" },
{ name: "count", type: "number" },
],
},
{
name: "by_category",
type: "object[]",
required: false,
description: "Top spending categories with CRC amounts",
attributes: [
{ name: "category", type: "string" },
{ name: "amount_crc", type: "number" },
{ name: "count", type: "number" },
],
},
],
handler: async () => "ok",
render: (props) => (
Pregúntale a WealthySmart sobre tus finanzas.