import React, { useState } from "react"; import emailjs from "@emailjs/browser"; import { ToastContainer, toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import { useTranslation } from "react-i18next"; import { motion, useReducedMotion } from "framer-motion"; import PhoneCodeSelect from "./PhoneCodeSelect"; const PHONE_PATTERNS: Record = { "+351": "### ### ###", "+34": "### ### ###", "+33": "# ## ## ## ##", "+44": "#### ######", "+1": "(###) ###-####", "+55": "(##) #####-####", }; const digitsOnly = (value: string) => value.replace(/\D/g, ""); const maxDigitsFor = (pattern: string) => pattern.split("").filter((c) => c === "#").length; const formatPhoneNumber = (digits: string, pattern: string) => { let result = ""; let digitIndex = 0; for (let i = 0; i < pattern.length && digitIndex < digits.length; i++) { const ch = pattern[i]; if (ch === "#") { result += digits[digitIndex]; digitIndex++; } else { result += ch; } } return result; }; const ContactForm = () => { const { t } = useTranslation(); const prefersReducedMotion = useReducedMotion(); const [countryCode, setCountryCode] = useState("+351"); const [phoneDigits, setPhoneDigits] = useState(""); const activePattern = PHONE_PATTERNS[countryCode]; const formattedPhone = formatPhoneNumber(phoneDigits, activePattern); const handleCountryChange = (code: string) => { setCountryCode(code); setPhoneDigits((prev) => prev.slice(0, maxDigitsFor(PHONE_PATTERNS[code])) ); }; const handlePhoneChange = (raw: string) => { const digits = digitsOnly(raw).slice(0, maxDigitsFor(activePattern)); setPhoneDigits(digits); }; const notify = () => { toast.success(t("contact.toasts.success")); }; const errorToast = () => { toast.error(t("contact.toasts.error")); }; const emptyForm = () => { toast.warning(t("contact.toasts.empty")); }; const sendEmail = (e: React.FormEvent) => { e.preventDefault(); const isEmpty = Array.from(e.currentTarget.elements).some((el) => { if (el.tagName !== "INPUT" && el.tagName !== "TEXTAREA") return false; const field = el as HTMLInputElement | HTMLTextAreaElement; if (field.type === "hidden") return false; return field.value.trim() === ""; }); if (isEmpty) { emptyForm(); return; } emailjs .sendForm("service_o7kxotj", "template_f30zlog", e.currentTarget, { publicKey: "vcSOwPedqkRH3nmr9", }) .then( (result) => { console.log(result.text); notify(); }, (error) => { console.log(error.text); errorToast(); } ); e.currentTarget.reset(); setPhoneDigits(""); setCountryCode("+351"); }; return (
{t("contact.form.button")}
); }; export default ContactForm;