'use client'; import { useCallback, useEffect, useState } from 'react'; import { useTranslations } from 'next-intl'; import { toast } from 'sonner'; import { NotePencil, PencilSimple } from '@phosphor-icons/react'; import { Button } from '@/components/ui/button'; import { useAuth } from '@/components/auth-provider'; const API_URL = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3100'; interface ProfileNoteProps { did: string; } export function ProfileNote({ did }: ProfileNoteProps) { const tn = useTranslations('peopleNotes'); const { session } = useAuth(); const [note, setNote] = useState(null); const [loading, setLoading] = useState(true); const [editing, setEditing] = useState(false); const [content, setContent] = useState(''); const [saving, setSaving] = useState(false); useEffect(() => { if (!session) { setLoading(false); return; } fetch(`${API_URL}/api/notes/${encodeURIComponent(did)}`, { credentials: 'include', }) .then(async (res) => { if (res.ok) { const data = (await res.json()) as { content: string }; setNote(data.content); setContent(data.content); } }) .catch(() => {}) .finally(() => setLoading(false)); }, [did, session]); const handleSave = useCallback(async () => { setSaving(true); try { const res = await fetch(`${API_URL}/api/notes/${encodeURIComponent(did)}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ content: content.trim() }), }); if (res.ok) { toast.success(tn('noteSaved')); setNote(content.trim()); setEditing(false); } } catch { toast.error('Failed to save'); } finally { setSaving(false); } }, [content, did, tn]); const handleDelete = useCallback(async () => { try { const res = await fetch(`${API_URL}/api/notes/${encodeURIComponent(did)}`, { method: 'DELETE', credentials: 'include', }); if (res.ok) { toast.success(tn('noteDeleted')); setNote(null); setContent(''); setEditing(false); } } catch { toast.error('Failed to delete'); } }, [did, tn]); // Don't render for own profile or when not authenticated if (!session || loading || session.did === did) return null; if (editing) { return (