import { useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; import { MAIL_REQUEST_FROM } from "@/mailFrom"; import { mailApi } from "@/landing/lib/api"; import { productOptionsFromT } from "@/landing/lib/productLabels"; import type { Product } from "@/landing/types"; import { Button } from "@/landing/ui/Button"; import { CheckboxesGroup } from "@/landing/ui/CheckboxesGroup"; import { ruPhoneDigits } from "@/landing/lib/phoneRu"; import { INTL_PHONE_MAX_DIGITS } from "@/landing/lib/phoneIntl"; import { PhoneInputIntl } from "@/landing/ui/PhoneInputIntl"; import { PhoneInputRu } from "@/landing/ui/PhoneInputRu"; import { useRefererStore } from "@/landing/stores/useRefererStore"; import { Controller, FormProvider, useForm, type SubmitHandler, } from "react-hook-form"; import type { LeadFormValues } from "./types"; export type { LeadFormValues } from "./types"; export function LeadForm({ defaultProducts, idPrefix = "", onSuccess, phonePlaceholder, formClassName = "lg:space-y-[1.944vw] md:max-lg:space-y-7 space-y-3", }: { defaultProducts: Product[]; /** Префикс для id полей (например `modal-`), чтобы избежать дублей в DOM */ idPrefix?: string; onSuccess: (id: string) => void; phonePlaceholder?: string; formClassName?: string; }) { const { t, i18n } = useTranslation(); const isRuLocale = i18n.language.startsWith("ru"); const { referer } = useRefererStore(); const [submitError, setSubmitError] = useState(null); const projectOptions = useMemo(() => productOptionsFromT(t), [t]); const form = useForm({ defaultValues: { fullname: "", email: "", phone: "", products: defaultProducts, }, }); const { register, handleSubmit, formState: { errors, isSubmitting }, control, } = form; const nameId = idPrefix ? `${idPrefix}name` : "name"; const emailId = idPrefix ? `${idPrefix}email` : "email"; const phoneId = idPrefix ? `${idPrefix}tel` : "tel"; const onSubmit: SubmitHandler = async (data) => { setSubmitError(null); try { const { id } = await mailApi .post("mail", { json: { ...data, referer, from: MAIL_REQUEST_FROM }, }) .json<{ id: string }>(); onSuccess(id); } catch { setSubmitError(t("leadForm.submitError")); } }; return (
{submitError ? (

{submitError}

) : null}

{t("leadForm.needTitle")}

name="products" options={projectOptions} />
{ if (!value?.trim()) return t("leadForm.phoneRequired"); if (isRuLocale) { return ( ruPhoneDigits(value).length === 11 || t("leadForm.phoneInvalid") ); } const digits = value.replace(/\D/g, ""); return ( (digits.length >= 8 && digits.length <= INTL_PHONE_MAX_DIGITS) || t("leadForm.phoneInvalid") ); }, }} render={({ field }) => isRuLocale ? ( ) : ( ) } />
{errors.phone?.message ? (

{String(errors.phone.message)}

) : null}
{t("leadForm.consentBefore")} {" "} {t("leadForm.consentLinkData")} {" "} {t("leadForm.consentMiddle")}{" "} {t("leadForm.consentLinkPolicy")}
); }