Loading data from network...
import { useMemo, useState } from 'react'
import useGroups from '../hooks/useGroups.js'
import useAjoContract from '../hooks/useAjoContract.js'
import useAjoFactory from '../hooks/useAjoFactory.js'
import { requestAiCommand } from '../services/aiAgent.js'
import { formatAddress } from '../utils/helpers.js'
import { DEFAULT_FREQUENCY_SECONDS } from '../utils/constants.js'
import { toBaseUnits } from '../utils/helpers.js'
import useNotifications from '../hooks/useNotifications.js'
import { postNotification } from '../services/notifications.js'
const suggestions = [
'Create an Ajo group for 5 people contributing 10 NGN weekly',
'Join the group called Lagos Savers',
'Who receives the next payout?'
]
export default function ChatAgent() {
const { groups, activeGroup, addGroup } = useGroups()
const { addNotification } = useNotifications()
const [open, setOpen] = useState(false)
const [messages, setMessages] = useState([
{ role: 'assistant', content: 'Hi, I can help you coordinate your savings circle. Ask me to create, join, or check payouts.' }
])
const [prompt, setPrompt] = useState('')
const selectedGroup = useMemo(() => {
if (activeGroup) return groups.find((group) => group.address === activeGroup)
return groups[0]
}, [groups, activeGroup])
const ajo = useAjoContract(selectedGroup?.address)
const factory = useAjoFactory()
const pushMessage = (message) => setMessages((prev) => [...prev, message])
const handleCommand = async (event) => {
event.preventDefault()
if (!prompt.trim()) return
pushMessage({ role: 'user', content: prompt })
const current = prompt
setPrompt('')
const command = await requestAiCommand(current)
if (command.action === 'createGroup') {
try {
pushMessage({ role: 'assistant', content: 'Creating your group on-chain...' })
const result = await factory.createGroup([
command.groupName || 'Cosave Circle',
toBaseUnits(command.amount || 10),
BigInt(command.members || 5),
BigInt(DEFAULT_FREQUENCY_SECONDS)
])
addGroup({
address: result.poolAddress,
name: command.groupName || 'Cosave Circle',
members: command.members || 5,
amount: command.amount || 10,
chainId: 'celo-sepolia'
})
const notification = {
id: Date.now(),
title: 'Circle created',
detail: `${command.groupName || 'Cosave Circle'} is live.`,
time: 'Just now',
read: false
}
addNotification(notification)
postNotification(notification)
pushMessage({
role: 'assistant',
content: `Group created. New contract: ${formatAddress(result.poolAddress)}.`
})
} catch (error) {
pushMessage({ role: 'assistant', content: error.shortMessage || error.message || 'Failed to create group.' })
}
return
}
if (command.action === 'joinGroup') {
if (!selectedGroup) {
pushMessage({ role: 'assistant', content: 'No group selected yet. Create or add a group address first.' })
return
}
try {
await ajo.joinGroup()
pushMessage({ role: 'assistant', content: `Joined ${selectedGroup.name}.` })
} catch (error) {
pushMessage({ role: 'assistant', content: error.shortMessage || error.message })
}
return
}
if (command.action === 'contribute') {
if (!selectedGroup) {
pushMessage({ role: 'assistant', content: 'Select a group to contribute to.' })
return
}
try {
await ajo.contribute()
pushMessage({ role: 'assistant', content: 'Contribution sent. Great job staying on schedule.' })
} catch (error) {
pushMessage({ role: 'assistant', content: error.shortMessage || error.message })
}
return
}
if (command.action === 'checkPayout') {
if (!selectedGroup) {
pushMessage({ role: 'assistant', content: 'No active group yet.' })
return
}
const members = ajo.members.data || []
const index = Number(ajo.payoutIndex.data || 0)
const next = members[index] ? formatAddress(members[index]) : 'Unknown'
pushMessage({ role: 'assistant', content: `Next payout is scheduled for ${next}.` })
return
}
if (command.action === 'sendReminder') {
if (!selectedGroup) {
pushMessage({ role: 'assistant', content: 'Select a group to send reminders.' })
return
}
pushMessage({
role: 'assistant',
content: 'Reminder queued. Members will receive a friendly nudge shortly.'
})
const notification = {
id: Date.now(),
title: 'Reminder sent',
detail: `${selectedGroup.name} • Members notified`,
time: 'Just now',
read: false
}
addNotification(notification)
postNotification(notification)
return
}
pushMessage({ role: 'assistant', content: 'I could not classify that request yet. Try asking to create, join, contribute, or check payouts.' })
}
return (
<div className="fixed bottom-24 right-6 z-50">
{open && (
<div className="mb-4 w-[320px] rounded-3xl border border-ink/10 bg-white/95 p-4 shadow-xl">
<div className="flex items-center justify-between">
<div>
<p className="text-xs uppercase tracking-[0.2em] text-ink/50">Cosave Agent</p>
<p className="text-sm font-semibold text-ocean">Autonomous circle assistant</p>
</div>
<button className="text-sm text-ink/50" onClick={() => setOpen(false)} type="button">Close</button>
</div>
<div className="mt-4 h-64 space-y-3 overflow-y-auto rounded-2xl border border-ink/5 bg-sand/60 p-3 text-sm">
{messages.map((message, index) => (
<div key={index} className={message.role === 'user' ? 'text-right' : 'text-left'}>
<p className={message.role === 'user' ? 'inline-block rounded-2xl bg-ocean px-3 py-2 text-white' : 'inline-block rounded-2xl bg-white px-3 py-2 text-ink/80'}>
{message.content}
</p>
</div>
))}
</div>
<form onSubmit={handleCommand} className="mt-3 flex items-center gap-2">
<input
className="flex-1 rounded-2xl border border-ink/10 bg-white/80 px-3 py-2 text-sm"
placeholder="Ask me to manage your group"
value={prompt}
onChange={(event) => setPrompt(event.target.value)}
/>
<button className="button-primary px-4 py-2" type="submit">Send</button>
</form>
<div className="mt-3 flex flex-wrap gap-2">
{suggestions.map((item) => (
<button
key={item}
className="rounded-full border border-ink/10 px-3 py-1 text-xs text-ink/70"
onClick={() => setPrompt(item)}
type="button"
>
{item}
</button>
))}
</div>
</div>
)}
<button
className="flex h-14 w-14 items-center justify-center rounded-full bg-ocean text-white shadow-glow"
onClick={() => setOpen((prev) => !prev)}
type="button"
>
AI
</button>
</div>
)
}