Files
blackheart-website/src/components/ui/SignupModal.tsx
T
diana.dolgolyova a587736dd3 feat: mobile UX, admin polish, rate limiting, and media assets
- Mobile responsiveness improvements across admin and public sections
- Admin: bookings modal, open-day page, team page, layout polish
- Added rate limiting, CSRF hardening, auth-edge improvements
- Scroll reveal, floating contact, back-to-top, Yandex map fixes
- Schedule filters refactor, team profile/info component updates
- New useTrainerPhotos hook
- Added class, team, master-class, and news images
2026-04-10 18:42:54 +03:00

299 lines
12 KiB
TypeScript

"use client";
import { useState, useEffect, useCallback } from "react";
import { createPortal } from "react-dom";
import { X, CheckCircle, Send, Phone as PhoneIcon, Instagram } from "lucide-react";
import { BRAND } from "@/lib/constants";
import { useFocusTrap } from "@/hooks/useFocusTrap";
import { formatBelarusPhone } from "@/lib/formatting";
interface SignupModalProps {
open: boolean;
onClose: () => void;
title?: string;
subtitle?: string;
/** API endpoint to POST to */
endpoint: string;
/** Extra fields merged into the POST body (e.g. masterClassTitle, classId, eventId, groupInfo) */
extraBody?: Record<string, unknown>;
/** Custom success message */
successMessage?: string;
/** Custom waiting list message */
waitingMessage?: string;
/** Custom error message */
errorMessage?: string;
/** Custom Instagram hint text */
instagramHint?: string;
/** Callback with API response data on success */
onSuccess?: (data: Record<string, unknown>) => void;
}
export function SignupModal({
open,
onClose,
title = "Записаться",
subtitle,
endpoint,
extraBody,
successMessage,
waitingMessage,
errorMessage,
instagramHint,
onSuccess,
}: SignupModalProps) {
const [name, setName] = useState("");
const [phone, setPhone] = useState("+375 ");
const [instagram, setInstagram] = useState("");
const [telegram, setTelegram] = useState("");
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState("");
const [success, setSuccess] = useState(false);
const [successData, setSuccessData] = useState<Record<string, unknown> | null>(null);
const focusTrapRef = useFocusTrap<HTMLDivElement>(open);
function handlePhoneChange(raw: string) {
setPhone(formatBelarusPhone(raw));
}
useEffect(() => {
if (!open) return;
function onKey(e: KeyboardEvent) {
if (e.key === "Escape") onClose();
}
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [open, onClose]);
useEffect(() => {
if (open) document.body.style.overflow = "hidden";
else document.body.style.overflow = "";
return () => { document.body.style.overflow = ""; };
}, [open]);
const handleSubmit = useCallback(async (e: React.FormEvent) => {
e.preventDefault();
setError("");
const cleanPhone = phone.replace(/\D/g, "");
if (!/^375(25|29|33|44)\d{7}$/.test(cleanPhone)) {
setError("Введите корректный номер телефона");
return;
}
setSubmitting(true);
try {
const body: Record<string, unknown> = {
name: name.trim(),
phone: cleanPhone,
...extraBody,
};
if (instagram.trim()) body.instagram = `@${instagram.trim()}`;
if (telegram.trim()) body.telegram = `@${telegram.trim()}`;
const res = await fetch(endpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const data = await res.json();
if (!res.ok) {
setError(data.error || "Ошибка при записи");
return;
}
setSuccess(true);
setSuccessData(data);
onSuccess?.(data);
} catch {
setError("network");
} finally {
setSubmitting(false);
}
}, [name, phone, instagram, telegram, endpoint, extraBody, onSuccess]);
const handleClose = useCallback(() => {
onClose();
setTimeout(() => {
setName("");
setPhone("+375 ");
setInstagram("");
setTelegram("");
setError("");
setSuccess(false);
setSuccessData(null);
}, 300);
}, [onClose]);
function openInstagramDM() {
const text = `Здравствуйте! Меня зовут ${name}. Хочу записаться${subtitle ? ` (${subtitle})` : ""}. Мой телефон: ${phone}`;
window.open(`https://ig.me/m/blackheartdancehouse?text=${encodeURIComponent(text)}`, "_blank");
handleClose();
}
if (!open) return null;
return createPortal(
<div className="modal-overlay fixed inset-0 z-[60] flex items-center justify-center p-4" role="dialog" aria-modal="true" aria-label={title} onClick={handleClose}>
<div className="absolute inset-0 bg-black/70 backdrop-blur-sm" />
<div
ref={focusTrapRef}
className="modal-content relative w-full max-w-md rounded-2xl border border-white/[0.08] bg-neutral-950 p-6 sm:p-8 shadow-2xl"
onClick={(e) => e.stopPropagation()}
>
<button
onClick={handleClose}
aria-label="Закрыть"
className="absolute right-4 top-4 flex h-11 w-11 items-center justify-center rounded-full text-neutral-500 transition-colors hover:bg-white/[0.06] hover:text-white cursor-pointer"
>
<X size={18} />
</button>
{success ? (
<div className="py-4 text-center">
{successData?.isWaiting ? (
<>
<div className="mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-amber-500/10">
<CheckCircle size={28} className="text-amber-500" />
</div>
<h3 className="text-lg font-bold text-white">Вы в листе ожидания</h3>
<p className="mt-2 text-sm text-neutral-400 leading-relaxed whitespace-pre-line">
{waitingMessage || "Все места заняты, но мы добавили вас в лист ожидания.\nЕсли кто-то откажется — мы предложим место вам."}
</p>
<a
href={BRAND.instagram}
target="_blank"
rel="noopener noreferrer"
className="mt-3 inline-flex items-center gap-1.5 text-sm text-pink-400 hover:text-pink-300"
>
<Instagram size={14} />
{instagramHint || "По вопросам пишите в Instagram"}
</a>
</>
) : (
<>
<div className="mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-emerald-500/10">
<CheckCircle size={28} className="text-emerald-500" />
</div>
<h3 className="text-lg font-bold text-white">
{successMessage || "Вы записаны!"}
</h3>
{subtitle && <p className="mt-1 text-sm text-neutral-400">{subtitle}</p>}
<a
href={BRAND.instagram}
target="_blank"
rel="noopener noreferrer"
className="mt-3 inline-flex items-center gap-1.5 text-sm text-pink-400 hover:text-pink-300"
>
<Instagram size={14} />
{instagramHint || "По вопросам пишите в Instagram"}
</a>
</>
)}
</div>
) : error === "network" ? (
/* Network error — fallback to Instagram DM */
<div className="py-4 text-center">
<div className="mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-amber-500/10">
<Instagram size={28} className="text-amber-400" />
</div>
<h3 className="text-lg font-bold text-white">Что-то пошло не так</h3>
<p className="mt-2 text-sm text-neutral-400">
{errorMessage || "Не удалось отправить заявку. Свяжитесь с нами через Instagram — мы запишем вас!"}
</p>
<button
onClick={openInstagramDM}
className="mt-5 flex w-full items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-purple-600 to-pink-500 py-3 text-sm font-semibold text-white transition-all hover:opacity-90 cursor-pointer"
>
<Instagram size={16} />
Написать в Instagram
</button>
<button
onClick={() => setError("")}
className="mt-2 text-xs text-neutral-500 hover:text-white transition-colors cursor-pointer"
>
Попробовать снова
</button>
</div>
) : (
<>
<div className="mb-6">
<h3 className="text-xl font-bold text-white">{title}</h3>
{subtitle && <p className="mt-1 text-sm text-neutral-400">{subtitle}</p>}
</div>
<form onSubmit={handleSubmit} className="space-y-3">
<div>
<label htmlFor="signup-name" className="sr-only">Ваше имя</label>
<input
id="signup-name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Ваше имя"
required
aria-required="true"
className="w-full rounded-xl border border-white/[0.08] bg-white/[0.04] px-4 py-3 text-sm text-white placeholder-neutral-500 outline-none transition-colors focus:border-gold/40 focus:bg-white/[0.06]"
/>
</div>
<div className="relative">
<label htmlFor="signup-phone" className="sr-only">Телефон</label>
<PhoneIcon size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-neutral-500" />
<input
id="signup-phone"
type="tel"
value={phone}
onChange={(e) => handlePhoneChange(e.target.value)}
placeholder="+375 (__) ___-__-__"
required
aria-required="true"
aria-describedby={error && error !== "network" ? "error-phone" : undefined}
className="w-full rounded-xl border border-white/[0.08] bg-white/[0.04] pl-9 pr-4 py-3 text-sm text-white placeholder-neutral-500 outline-none transition-colors focus:border-gold/40 focus:bg-white/[0.06]"
/>
</div>
<div className="grid grid-cols-2 gap-2">
<div className="relative">
<label htmlFor="signup-instagram" className="sr-only">Instagram (необязательно)</label>
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-neutral-500 text-xs">@</span>
<input
id="signup-instagram"
type="text"
value={instagram}
onChange={(e) => setInstagram(e.target.value.replace(/^@/, ""))}
placeholder="Instagram"
className="w-full rounded-xl border border-white/[0.08] bg-white/[0.04] pl-7 pr-3 py-3 text-sm text-white placeholder-neutral-500 outline-none transition-colors focus:border-gold/40 focus:bg-white/[0.06]"
/>
</div>
<div className="relative">
<label htmlFor="signup-telegram" className="sr-only">Telegram (необязательно)</label>
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-neutral-500 text-xs">@</span>
<input
id="signup-telegram"
type="text"
value={telegram}
onChange={(e) => setTelegram(e.target.value.replace(/^@/, ""))}
placeholder="Telegram"
className="w-full rounded-xl border border-white/[0.08] bg-white/[0.04] pl-7 pr-3 py-3 text-sm text-white placeholder-neutral-500 outline-none transition-colors focus:border-gold/40 focus:bg-white/[0.06]"
/>
</div>
</div>
{error && error !== "network" && (
<p id="error-phone" role="alert" className="text-sm text-red-400">{error}</p>
)}
<button
type="submit"
disabled={submitting}
className="flex w-full items-center justify-center gap-2 rounded-xl bg-gold py-3 text-sm font-semibold text-black transition-all hover:bg-gold-light hover:shadow-lg hover:shadow-gold/20 cursor-pointer disabled:opacity-50"
>
<Send size={15} />
{submitting ? "Записываем..." : "Записаться"}
</button>
</form>
</>
)}
</div>
</div>,
document.body
);
}