"use client"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useEffect, useId, useState } from "react"; import { huf } from "@/components/PackageCards"; import { api, errorText } from "@/lib/api"; import { contents } from "@/lib/packageContents"; import { christmasMorning } from "@/lib/season"; import type { Package, PayMethod } from "@/lib/types"; const MAX_MESSAGE = 300; const MAX_NAME = 60; const looksLikeEmail = (s: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim()); const same = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase(); /** `2026-12-24` on the browser's clock. */ const localDay = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; /** "dec. 24. 8:00" */ const whenText = (d: Date) => d.toLocaleString("hu-HU", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit", }); /** * The gift order: which package, whom it is for and from whom, how it gets * to the recipient (we e-mail it, the address typed twice; or the buyer * hands it over), and a message. Then Stripe's payment page, back to "My * gifts". */ export function GiftForm({ packages, initial, defaultFrom, canPay, termsConsent, }: { packages: Package[]; initial?: string; defaultFrom: string; canPay: PayMethod | null; termsConsent: boolean; }) { const router = useRouter(); const id = useId(); const start = packages.find((p) => p.id === initial) ?? packages.find((p) => p.id === "couple") ?? packages[0]; const [pkg, setPkg] = useState(start?.id ?? ""); const [name, setName] = useState(""); const [byEmail, setByEmail] = useState(true); const [email, setEmail] = useState(""); const [confirm, setConfirm] = useState(""); const [from, setFrom] = useState(defaultFrom.slice(0, MAX_NAME)); const [message, setMessage] = useState(""); const [timed, setTimed] = useState(false); const xmas = christmasMorning(); const [day, setDay] = useState(xmas ? localDay(xmas) : ""); const [clock, setClock] = useState("08:00"); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); // Back from Stripe's page (the browser may restore this page as it was). useEffect(() => { const reset = (e: PageTransitionEvent) => { if (e.persisted) setBusy(false); }; window.addEventListener("pageshow", reset); return () => window.removeEventListener("pageshow", reset); }, []); const chosen = packages.find((p) => p.id === pkg); const mismatch = byEmail && confirm.trim() !== "" && !same(email, confirm); const emailOk = !byEmail || (looksLikeEmail(email) && same(email, confirm)); const stripe = canPay === "stripe" || canPay === "stripe_test"; // The chosen moment on the buyer's own clock. const sendAt = day && clock ? new Date(`${day}T${clock}`) : null; const ahead = sendAt ? sendAt.getTime() - Date.now() : 0; const timeOk = sendAt !== null && !Number.isNaN(ahead) && ahead > 10 * 60 * 1000 && ahead < 365 * 86400 * 1000; async function submit(e: React.FormEvent) { e.preventDefault(); if (!chosen || !emailOk || !name.trim()) return; setBusy(true); setError(null); try { const r = await api<{ id: string; url: string | null }>( "/gifts/checkout", { body: { package: chosen.id, recipient_name: name.trim(), recipient_email: byEmail ? email.trim() : null, recipient_email_confirm: byEmail ? confirm.trim() : null, from_name: from.trim() || null, message: message.trim() || null, send_at: byEmail && timed && sendAt ? sendAt.toISOString() : null, }, }, ); if (r.url) { window.location.assign(r.url); return; } router.push("/ajandekaim"); } catch (err) { setError(errorText(err)); setBusy(false); } } return (
Melyik csomagot adod?
{packages.map((p) => ( ))}
setName(e.target.value)} placeholder="Például: Bea" aria-describedby={`${id}-name-hint`} required /> Az utalványon: „{name.trim() || "Bea"} részére” {byEmail ? `, a levélben: „Szia ${name.trim() || "Bea"}!”` : ""}.
setFrom(e.target.value)} placeholder="Például: Anna" />
Hogyan kapja meg?
{byEmail && (
setEmail(e.target.value)} required />
setConfirm(e.target.value)} aria-invalid={mismatch || undefined} aria-describedby={`${id}-confirm-msg`} required /> {mismatch ? "A két cím nem egyezik." : "Hogy biztosan jó címre menjen."}
)} {byEmail && (
Mikor kapja meg?
{xmas && ( )}
{timed && (
setDay(e.target.value)} />
setClock(e.target.value)} />
)} {timed ? timeOk ? "A te időd szerint. Addig az Ajándékaim oldalon letöltheted az utalványt, vagy elküldheted azonnal is." : "Válassz egy jövőbeli időpontot (legfeljebb egy évre előre)." : "Ha későbbre szánod, időzítsd, vagy válaszd az „Én adom át” lehetőséget."}
)}