"use client"; import { useState, useTransition } from "react"; import { useRouter } from "next/navigation"; import { updateAddress } from "@/lib/api/addresses"; import type { Address, AddressLabel } from "@/types/api"; const ADDRESS_LABEL_FA: Record = { home: "خانه", work: "محل کار", other: "سایر", }; /** * Doubles as both a plain address-management screen (reached from the profile menu) * and a picker (reached from checkout's "تغییر آدرس" with a `next` return path) — * the radio always reflects/sets which address is the default, "تأیید" just persists * that choice and, if there's somewhere to return to, goes back there. */ export function AddressSelector({ addresses, next }: { addresses: Address[]; next: string | null }) { const router = useRouter(); const [selectedUuid, setSelectedUuid] = useState( () => addresses.find((a) => a.is_default)?.uuid ?? addresses[0]?.uuid ?? null, ); const [error, setError] = useState(null); const [isPending, startTransition] = useTransition(); function handleConfirm() { setError(null); const currentDefaultUuid = addresses.find((a) => a.is_default)?.uuid; if (!selectedUuid || selectedUuid === currentDefaultUuid) { if (next) router.push(next); return; } startTransition(async () => { const result = await updateAddress(selectedUuid, { is_default: true }); if (result.ok) { if (next) router.push(next); else router.refresh(); } else { setError(result.message); } }); } return (
{addresses.map((address) => { const isSelected = address.uuid === selectedUuid; return ( ); })} {addresses.length === 0 && (

هنوز آدرسی ثبت نکرده‌اید.

)}
{error &&

{error}

} {addresses.length > 0 && ( )}
); }