import {__} from "@wordpress/i18n";

/**
 * PhoneInput Component
 * Validates phone number format
 *
 * @param {Object} props Component props
 * @param {React.Ref} props.textareaRef Textarea ref
 * @param {string} props.text Current text value
 * @param {Function} props.onTextChange Text change handler
 * @param {Function} props.onKeyDown Key down handler
 * @param {boolean} props.isValid Is input valid
 * @param {string} props.placeholder Custom placeholder
 */
export default function PhoneInput({
                                       textareaRef,
                                       text,
                                       onTextChange,
                                       onKeyDown,
                                       isValid,
                                       placeholder
                                   }) {
    const hasError = !isValid && text.trim().length > 0;
    const placeholderText = placeholder || __('Enter phone number...', 'limb-chatbot');

    return (
        <input
            ref={textareaRef}
            type="tel"
            className={`lbaic-textarea${hasError ? ' lbaic-textarea-invalid' : ''}`}
            placeholder={placeholderText}
            value={text}
            onChange={onTextChange}
            onKeyDown={onKeyDown}
            autoComplete="off"
        />
    );
}

/**
 * Validate phone input
 * Accepts any reasonable phone format as long as it has 10-15 digits
 *
 * @param {string} value Input value
 * @returns {boolean} Is valid phone number
 */
export const validatePhoneInput = (value) => {
    if (value.trim().length === 0) {
        return true; // Empty input is "valid" (just can't send)
    }

    const trimmedValue = value.trim();

    // Extract all digits
    const digitsOnly = trimmedValue.replace(/\D/g, '');

    // Must have 10-15 digits
    if (digitsOnly.length < 10 || digitsOnly.length > 15) {
        return false;
    }

    // Only allow digits, spaces, dashes, parentheses, dots, and optional leading +
    const allowedCharsPattern = /^[\+\d\s\-\(\)\.]+$/;

    return allowedCharsPattern.test(trimmedValue);
};
