"use client"; import { useEffect, useId, useMemo, useRef, useState } from "react"; import { ApiError, api, errorText } from "@/lib/api"; import { countryName } from "@/lib/astro"; import type { BirthData, Country, Place } from "@/lib/types"; type Initial = (BirthData & { placeName: string | null; region: string | null }) | null; type Ambiguity = "earlier" | "later"; const ERRORS: Record = { place_not_found: "Nem találjuk ezt a települést. Válassz a listából.", nonexistent_local_time: "Ez az időpont az óraátállítás miatt nem létezett ezen a napon (az órát előreállították). Ellenőrizd a születési időt.", invalid_date: "Érvénytelen dátum.", }; /** Someone else's chart: added with a name, or (with `chartId`) corrected. */ export type PersonTarget = { chartId?: string; name?: string }; export function BirthForm({ initial, person, onCancel, onSaved, }: { initial: Initial; /** Not given: the user's own birth data. */ person?: PersonTarget; onCancel?: () => void; onSaved: (chartId: string) => void; }) { const [name, setName] = useState(person?.name ?? ""); const [date, setDate] = useState(initial?.date ?? ""); const [time, setTime] = useState(initial?.time?.slice(0, 5) ?? ""); const [timeUnknown, setTimeUnknown] = useState(initial ? !initial.time : false); const [country, setCountry] = useState(initial?.country ?? "HU"); const [place, setPlace] = useState( initial?.geonames_id && initial.placeName ? { geonames_id: initial.geonames_id, name: initial.placeName, region: initial.region, population: null, country_code: initial.country ?? "HU", } : null, ); const [ambiguous, setAmbiguous] = useState(false); const [ambiguity, setAmbiguity] = useState("earlier"); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); const today = useMemo(() => new Date().toISOString().slice(0, 10), []); async function submit(e: React.FormEvent) { e.preventDefault(); setError(null); if (person && !name.trim()) return setError("Add meg a nevét."); if (!date) return setError("Add meg a születési dátumot."); if (!timeUnknown && !time) return setError("Add meg a születési időt, vagy jelöld, hogy nem tudod."); if (!place) return setError("Válaszd ki a születési helyet a listából."); setBusy(true); try { const birth = { date, ...(timeUnknown ? {} : { time }), country, geonames_id: place.geonames_id, ...(ambiguous ? { ambiguous_time: ambiguity } : {}), }; // Correcting a person: the birth data only when it changed, so a new // name alone does not recalculate the chart or drop its analyses. const birthChanged = !initial || ambiguous || date !== initial.date || (timeUnknown ? null : time) !== (initial.time?.slice(0, 5) ?? null) || country !== (initial.country ?? "HU") || place.geonames_id !== initial.geonames_id; const saved = person?.chartId ? await api<{ id: string }>(`/charts/${person.chartId}`, { method: "PATCH", body: birthChanged ? { label: name.trim(), birth } : { label: name.trim() }, }) : await api<{ id: string }>("/charts", { body: person ? { label: name.trim(), is_primary: false, birth } : { label: "Saját képlet", is_primary: true, birth }, }); onSaved(saved.id); } catch (err) { if (err instanceof ApiError && err.code === "ambiguous_local_time") { setAmbiguous(true); setError( "Ez az időpont az óraátállítás miatt kétszer is előfordult ezen a napon. Válaszd ki, melyikben születtél, és mentsd újra.", ); } else { setError(err instanceof ApiError ? (ERRORS[err.code] ?? errorText(err)) : errorText(err)); } } finally { setBusy(false); } } return (
{person && (
setName(e.target.value)} required />
)}
setDate(e.target.value)} required />
{ setTime(e.target.value); setAmbiguous(false); }} />
{ setCountry(c); setPlace(null); }} />
{ambiguous && (
{person ? "Melyik időpontban született?" : "Melyik időpontban születtél?"}
)} {error && (

{error}

)}
{onCancel && ( )}
); } function CountrySelect({ value, onChange }: { value: string; onChange: (iso2: string) => void }) { const [countries, setCountries] = useState([]); useEffect(() => { fetch("/api/geo/countries") .then((r) => (r.ok ? r.json() : { countries: [] })) .then((d: { countries: Country[] }) => { const named = d.countries.map((c) => ({ iso2: c.iso2, name: countryName(c.iso2, c.name) })); named.sort((a, b) => a.name.localeCompare(b.name, "hu")); setCountries(named); }) .catch(() => setCountries([])); }, []); return (
); } function PlaceSearch({ country, value, onChange, }: { country: string; value: Place | null; onChange: (p: Place | null) => void; }) { const listId = useId(); const [query, setQuery] = useState(value?.name ?? ""); const [results, setResults] = useState([]); const [open, setOpen] = useState(false); const [active, setActive] = useState(0); const [loading, setLoading] = useState(false); const seq = useRef(0); // A new country starts a new search. const firstCountry = useRef(country); useEffect(() => { if (country === firstCountry.current) return; firstCountry.current = country; setQuery(""); setResults([]); }, [country]); useEffect(() => { const q = query.trim(); if (q.length < 2 || (value && value.name === query)) { setResults([]); return; } const id = ++seq.current; setLoading(true); const timer = setTimeout(async () => { try { const res = await fetch(`/api/geo/places?country=${country}&q=${encodeURIComponent(q)}&limit=8`); const data = res.ok ? ((await res.json()) as { places: Place[] }) : { places: [] }; if (id === seq.current) { setResults(data.places); setActive(0); setOpen(true); } } catch { if (id === seq.current) setResults([]); } finally { if (id === seq.current) setLoading(false); } }, 250); return () => clearTimeout(timer); }, [query, country, value]); function choose(p: Place) { onChange(p); setQuery(p.name); setOpen(false); } function onKey(e: React.KeyboardEvent) { if (!open || results.length === 0) return; if (e.key === "ArrowDown") { e.preventDefault(); setActive((a) => (a + 1) % results.length); } else if (e.key === "ArrowUp") { e.preventDefault(); setActive((a) => (a - 1 + results.length) % results.length); } else if (e.key === "Enter") { e.preventDefault(); choose(results[active]); } else if (e.key === "Escape") { setOpen(false); } } const showList = open && results.length > 0; return (
{ setQuery(e.target.value); if (value) onChange(null); }} onKeyDown={onKey} onFocus={() => results.length > 0 && setOpen(true)} onBlur={() => setTimeout(() => setOpen(false), 150)} /> {showList && (
    {results.map((p, i) => (
  • ))}
)}
{value ? `Kiválasztva: ${value.name}${value.region ? `, ${value.region}` : ""}` : loading ? "Keresés…" : query.trim().length >= 2 && results.length === 0 ? "Nincs találat ebben az országban." : "Válassz a listából."}
); }