import React, { useState } from 'react'; import { useGetAddressByPhone } from '@/hooks/useAddressData'; import clsx from 'clsx'; interface GetAddressByPhoneModalProps { isOpen: boolean; onClose: () => void; onSuccess?: (data: any) => void; } export const GetAddressByPhoneModal: React.FC = ({ isOpen, onClose, onSuccess, }) => { const [phone, setPhone] = useState(''); const [errorMessage, setErrorMessage] = useState(''); const { mutate: getAddress, isPending } = useGetAddressByPhone(); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); setErrorMessage(''); // Validate phone number if (!phone || !/^0+(\d{9,10})$/.test(phone)) { setErrorMessage((window.coolviad_checkout_data?.phone_error as string) || 'Invalid phone number'); return; } // Check reCAPTCHA if element exists const recaptchaElement = document.getElementById('g-recaptcha-response') as HTMLInputElement; const recaptchaValue = recaptchaElement ? recaptchaElement.value : ''; if (recaptchaElement && !recaptchaValue) { setErrorMessage('Please complete verification.'); return; } getAddress( { phone, recaptcha: recaptchaValue }, { onSuccess: (data) => { // Fill in the address fields if (data.billing) { Object.keys(data.billing).forEach((key) => { const element = document.getElementById(key) as HTMLInputElement | HTMLSelectElement; if (element) { if (element.tagName === 'SELECT') { element.value = data.billing[key] || ''; // Trigger change event for Select2 if (typeof jQuery !== 'undefined') { jQuery(element).trigger('change'); } } else { element.value = data.billing[key] || ''; } } }); } setErrorMessage(''); onSuccess?.(data); onClose(); // Focus on first name field const firstNameField = document.getElementById('billing_first_name') || document.getElementById('billing_last_name'); if (firstNameField) { (firstNameField as HTMLInputElement).focus(); } }, onError: (error: any) => { setErrorMessage( error.message || window.coolviad_checkout_data?.loadaddress_error || 'Unable to load address' ); }, } ); }; const handleCancel = () => { setErrorMessage(''); setPhone(''); onClose(); const firstNameField = document.getElementById('billing_first_name') || document.getElementById('billing_last_name'); if (firstNameField) { (firstNameField as HTMLInputElement).focus(); } }; if (!isOpen) return null; return (

Get address from phone number

setPhone(e.target.value)} disabled={isPending} /> {/* reCAPTCHA placeholder - actual implementation in PHP */}
{errorMessage && (
{errorMessage}
)} {isPending && (
{(window.coolviad_checkout_data?.loading_text as string) || 'Loading...'}
)}
); };