import { useEffect, useMemo, useState, type FormEvent } from 'react'; import './behaviorJournal.css'; type BehaviorType = { id: string; name: string; description: string | null }; type Occurrence = { id: string; birdId: string; behaviorTypeId: string; behaviorName: string; occurredAt: string; durationSeconds: number | null; severity: number | null; notes: string | null; createdAt: string; updatedAt: string; }; type Props = { bird: { id: string; name: string }; birds: { id: string; name: string }[]; onSelectBird: (id: string) => void; token: string; writable: boolean; apiFetch: (path: string, token?: string, init?: RequestInit) => Promise; }; const localDate = (date: Date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`; const localTime = (date: Date) => `${localDate(date)}T${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`; const emptyForm = () => ({ behaviorTypeId: '', occurredAt: localTime(new Date()), duration: '', severity: '', notes: '' }); export function BehaviorJournal({ bird, birds, onSelectBird, token, writable, apiFetch }: Props) { const [month, setMonth] = useState(() => new Date(new Date().getFullYear(), new Date().getMonth(), 1)); const [day, setDay] = useState(() => localDate(new Date())); const [filter, setFilter] = useState(''); const [types, setTypes] = useState([]); const [entries, setEntries] = useState([]); const [form, setForm] = useState(emptyForm); const [editing, setEditing] = useState(null); const [showForm, setShowForm] = useState(false); const [customName, setCustomName] = useState(''); const [customDescription, setCustomDescription] = useState(''); const [loading, setLoading] = useState(true); const [saving, setSaving] = useState(false); const [error, setError] = useState(''); const [notice, setNotice] = useState(''); const [revision, setRevision] = useState(0); const base = `/birds/${bird.id}`; async function request(path: string, init?: RequestInit) { const response = await apiFetch(path, token, { ...init, headers: { 'Content-Type': 'application/json', ...init?.headers } }); if (response.status === 204) return null; const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Unable to update the journal.'); return data; } useEffect(() => { let active = true; setLoading(true); setError(''); setEntries([]); const query = new URLSearchParams({ from: month.toISOString(), to: new Date(month.getFullYear(), month.getMonth() + 1, 1).toISOString() }); if (filter) query.set('behaviorTypeId', filter); Promise.all([request(`${base}/behavior-types`), request(`${base}/behaviors?${query}`)]) .then(([typeData, occurrenceData]) => { if (active) { setTypes(typeData.behaviorTypes); setEntries(occurrenceData.occurrences); } }) .catch((e) => { if (active) setError(e instanceof Error ? e.message : 'Unable to load journal.'); }) .finally(() => { if (active) setLoading(false); }); return () => { active = false; }; }, [bird.id, token, month, filter, revision]); const byDay = useMemo(() => { const result = new Map(); entries.forEach((entry) => { const key = localDate(new Date(entry.occurredAt)); result.set(key, [...(result.get(key) || []), entry]); }); return result; }, [entries]); function navigate(offset: number) { const next = new Date(month.getFullYear(), month.getMonth() + offset, 1); setMonth(next); setDay(localDate(next)); } function edit(entry: Occurrence) { setEditing(entry); setShowForm(true); setError(''); setNotice(''); setForm({ behaviorTypeId: entry.behaviorTypeId, occurredAt: localTime(new Date(entry.occurredAt)), duration: entry.durationSeconds === null ? '' : String(entry.durationSeconds), severity: entry.severity === null ? '' : String(entry.severity), notes: entry.notes || '' }); } async function save(event: FormEvent) { event.preventDefault(); setSaving(true); setError(''); setNotice(''); try { let typeId = form.behaviorTypeId; if (typeId === 'custom') { const data = await request(`${base}/behavior-types`, { method: 'POST', body: JSON.stringify({ name: customName, description: customDescription }) }); typeId = data.behaviorType.id; setTypes((previous) => [...previous.filter((type) => type.id !== typeId), data.behaviorType]); setForm((previous) => ({ ...previous, behaviorTypeId: typeId })); } // Preserve sub-second precision if the timestamp was not edited. const occurredAt = editing && form.occurredAt === localTime(new Date(editing.occurredAt)) ? editing.occurredAt : new Date(form.occurredAt).toISOString(); await request(`${base}/behaviors${editing ? `/${editing.id}` : ''}`, { method: editing ? 'PUT' : 'POST', body: JSON.stringify({ behaviorTypeId: typeId, occurredAt, durationSeconds: form.duration === '' ? null : Number(form.duration), severity: form.severity === '' ? null : Number(form.severity), notes: form.notes || null }) }); const savedDate = new Date(occurredAt); setMonth(new Date(savedDate.getFullYear(), savedDate.getMonth(), 1)); setDay(localDate(savedDate)); setFilter(''); setShowForm(false); setEditing(null); setRevision((value) => value + 1); setNotice('Occurrence saved.'); } catch (e) { setError(e instanceof Error ? e.message : 'Unable to save occurrence.'); } finally { setSaving(false); } } async function remove(entry: Occurrence) { if (!window.confirm(`Delete this ${entry.behaviorName} occurrence?`)) return; setSaving(true); setError(''); setNotice(''); try { await request(`${base}/behaviors/${entry.id}`, { method: 'DELETE' }); if (editing?.id === entry.id) { setShowForm(false); setEditing(null); } setRevision((value) => value + 1); setNotice('Occurrence deleted.'); } catch (e) { setError(e instanceof Error ? e.message : 'Unable to delete occurrence.'); } finally { setSaving(false); } } const days = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate(); return

{bird.name}

Behavior Journal

{writable && }

Record what you observed and review when it happened. Dates and times use your device’s local time zone.

{error &&

{error}

} {notice &&

{notice}

} {showForm && writable &&

{editing ? 'Edit occurrence' : 'Record occurrence'}

{form.behaviorTypeId === 'custom' && <>}