import type { PondView } from '@dorfteich/shared'; import { useQuery, useQueryClient } from '@tanstack/react-query'; import { useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { Link, useNavigate } from 'react-router-dom'; import { useAuth } from '../auth/auth-context'; import { FormError } from '../components/forms'; import { apiGet, apiPost } from '../lib/api'; import { useDismissable } from '../lib/use-dismissable'; import { useCurrentPondRoute } from './use-pond-route'; /** * Top-bar dropdown to switch between the signed-in user's ponds (issue #26) * — and to create a new shared pond right from the menu. Creation is * quota-gated server-side (`additional shared ponds per user`); a rejected * attempt surfaces the translated error instead of hiding the option. */ export function PondSwitcher(): React.JSX.Element | null { const { t } = useTranslation(); const { user } = useAuth(); const { pondSlug } = useCurrentPondRoute(); const navigate = useNavigate(); const queryClient = useQueryClient(); const [open, setOpen] = useState(false); const [creating, setCreating] = useState(false); const [name, setName] = useState(''); const [description, setDescription] = useState(''); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); const menuRef = useRef(null); const close = (): void => { setOpen(false); setCreating(false); setError(null); }; useDismissable(menuRef, open, close); const ponds = useQuery({ queryKey: ['ponds'], queryFn: () => apiGet('/ponds'), enabled: Boolean(user), }); if (!ponds.data || ponds.data.length === 0) return null; const current = ponds.data.find((pond) => pond.slug === pondSlug); const create = async (event: React.FormEvent): Promise => { event.preventDefault(); setError(null); setBusy(true); try { const pond = await apiPost('/ponds', { name: name.trim(), description: description.trim(), }); await queryClient.invalidateQueries({ queryKey: ['ponds'] }); close(); setName(''); setDescription(''); navigate(`/p/${pond.slug}`); } catch (err) { setError(err); } finally { setBusy(false); } }; return (
{open && !creating && (
{ponds.data.map((pond) => ( {pond.name} ))}
)} {open && creating && (
void create(e)}>

{t('pond.create.title')}

{t('pond.create.quotaHint')}

)}
); }