'use client'; import { useRef, useState } from 'react'; import { Loader2, Pencil } from 'lucide-react'; import { toast } from 'sonner'; import { TimezoneCombobox } from '@/components/shared/timezone-combobox'; import { formatTimezoneLabel } from '@/lib/i18n/timezones'; import type { CountryCode } from '@/lib/i18n/countries'; import { cn } from '@/lib/utils'; interface InlineTimezoneFieldProps { value: string | null | undefined; onSave: (next: string | null) => Promise; /** Optional country to surface "Suggested" zones in the picker. */ countryHint?: CountryCode | null; emptyText?: string; disabled?: boolean; className?: string; 'data-testid'?: string; } export function InlineTimezoneField({ value, onSave, countryHint, emptyText = '—', disabled, className, 'data-testid': testId, }: InlineTimezoneFieldProps) { const [editing, setEditing] = useState(false); const [saving, setSaving] = useState(false); // Set true when the user picks a value from the dropdown, so the // popover-close handler knows commit() will exit edit mode itself. const pickedRef = useRef(false); async function commit(next: string | null) { pickedRef.current = true; if (next === (value ?? null)) { setEditing(false); return; } setSaving(true); try { await onSave(next); setEditing(false); } catch (err) { toast.error(err instanceof Error ? err.message : 'Failed to save'); } finally { setSaving(false); } } if (editing) { return (
void commit(tz)} countryHint={countryHint ?? undefined} data-testid={testId} defaultOpen onOpenChange={(open) => { // Auto-exit edit mode when the dropdown closes without a pick, // so the user isn't stuck looking at the trigger. commit() owns // the exit when a value was selected. if (!open && !pickedRef.current) { setEditing(false); } if (open) pickedRef.current = false; }} /> {saving && }
); } const display = value ? formatTimezoneLabel(value) : null; return ( ); }