"use client"; import { useEffect, useId, useMemo, useRef, useState } from "react"; import { ApiError, api, errorText } from "@/lib/api"; import { countryName } from "@/lib/astro"; import { BIRTH_DRAFT_KEY, type BirthDraft, MONTHS, composeDate, composeTime, daysIn } from "@/lib/birth"; 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 }; /** The birth data the form sends (as `POST /v1/charts` takes it). */ export type BirthInput = { date: string; time?: string; country: string; geonames_id: number; ambiguous_time?: Ambiguity; }; export function BirthForm({ initial, person, save, children, onCancel, onSaved, }: { initial: Initial; /** Not given: the user's own birth data. */ person?: PersonTarget; /** * Saves somewhere else than the user's charts (e.g. a famous person); gets * the birth data only when it changed. Its errors show in the form. */ save?: (name: string, birth: BirthInput | null) => Promise<{ id: string }>; /** More fields, after the name. */ children?: React.ReactNode; onCancel?: () => void; onSaved: (chartId: string) => void; }) { const [name, setName] = useState(person?.name ?? ""); // Our own fields, not the browser's date and time inputs: those follow the // operating system's or the browser's region (US order, AM/PM in Safari). const [year, setYear] = useState(initial?.date?.slice(0, 4) ?? ""); const [month, setMonth] = useState(initial?.date ? String(Number(initial.date.slice(5, 7))) : ""); const [day, setDay] = useState(initial?.date ? String(Number(initial.date.slice(8, 10))) : ""); const [hour, setHour] = useState(initial?.time?.slice(0, 2) ?? ""); const [minute, setMinute] = useState(initial?.time?.slice(3, 5) ?? ""); const minuteRef = useRef(null); const date = composeDate(year, month, day) ?? ""; const time = composeTime(hour, minute) ?? ""; 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), []); const [fromDraft, setFromDraft] = useState(false); // The own birth data, not given yet: offer what the visitor typed into the // public birth chart page before signing up. useEffect(() => { if (initial || person) return; let draft: BirthDraft | null = null; try { draft = JSON.parse(sessionStorage.getItem(BIRTH_DRAFT_KEY) ?? "null"); } catch { return; } if (!draft || !/^\d{4}-\d{2}-\d{2}$/.test(draft.date) || !draft.geonames_id) return; setYear(draft.date.slice(0, 4)); setMonth(String(Number(draft.date.slice(5, 7)))); setDay(String(Number(draft.date.slice(8, 10)))); if (draft.time) { setHour(draft.time.slice(0, 2)); setMinute(draft.time.slice(3, 5)); } setTimeUnknown(!draft.time); setCountry(draft.country); setPlace({ geonames_id: draft.geonames_id, name: draft.placeName, region: draft.region, population: null, country_code: draft.country, }); setFromDraft(true); }, [initial, person]); async function submit(e: React.FormEvent) { e.preventDefault(); setError(null); if (person && !name.trim()) return setError("Add meg a nevét."); if (!year && !month && !day) return setError("Add meg a születési dátumot."); if (!date) return setError("Ellenőrizd a dátumot: az év négy számjegy, és a nap legyen az adott hónapban."); if (date > today) return setError("A születési dátum nem lehet a jövőben."); if (!timeUnknown && !hour && !minute) return setError("Add meg a születési időt, vagy jelöld, hogy nem tudod."); if (!timeUnknown && !time) return setError("Ellenőrizd az időt: óra 0–23, perc 0–59."); if (!place) return setError("Válaszd ki a születési helyet a listából."); setBusy(true); try { const birth: BirthInput = { 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 = save ? await save(name.trim(), birthChanged ? birth : null) : 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 }, }); try { sessionStorage.removeItem(BIRTH_DRAFT_KEY); } catch { // storage blocked } 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 (
{fromDraft && (

Áthoztuk az adatokat, amelyeket a születési horoszkópnál megadtál. Ellenőrizd, és mentsd el.

)} {person && (
setName(e.target.value)} required />
)} {children}
Születési dátum
setYear(e.target.value.replace(/\D/g, ""))} />
Születési idő (helyi idő)
{ const v = e.target.value.replace(/\D/g, ""); setHour(v); setAmbiguous(false); // Two digits (or one that cannot start a valid hour): on to the minutes. if (v.length === 2 || (v.length === 1 && Number(v) > 2)) minuteRef.current?.focus(); }} /> { setMinute(e.target.value.replace(/\D/g, "")); setAmbiguous(false); }} />
{ setCountry(c); setPlace(null); }} />
{ambiguous && (
{person ? "Melyik időpontban született?" : "Melyik időpontban születtél?"}
)} {error && (

{error}

)}
{onCancel && ( )}
); } /** Where the country list and the place search come from: logged-in users, or the public calculator. */ export type GeoBase = "/api/geo" | "/api/v1/public/geo"; export function CountrySelect({ value, onChange, geoBase = "/api/geo", }: { value: string; onChange: (iso2: string) => void; geoBase?: GeoBase; }) { const [countries, setCountries] = useState([]); useEffect(() => { fetch(`${geoBase}/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([])); }, [geoBase]); return (
); } export function PlaceSearch({ country, value, onChange, geoBase = "/api/geo", }: { country: string; value: Place | null; onChange: (p: Place | null) => void; geoBase?: GeoBase; }) { 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]); // A place set from outside (e.g. brought over from the public chart page) shows its name. useEffect(() => { if (value) setQuery((q) => (q === value.name ? q : value.name)); }, [value]); 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(`${geoBase}/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, geoBase]); 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."}
); }