"use client"

import { useCallback } from 'react';

import type { AuthChannel, AuthFormValidation } from '../types';

// Email regex - RFC 5322 simplified
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// Phone regex - E.164 format (+[country][number], 7-15 digits)
const PHONE_REGEX = /^\+[1-9]\d{6,14}$/;

/**
 * Hook for auth identifier validation.
 * Pure functions - no state, no side effects.
 */
export const useAuthValidation = (): AuthFormValidation => {
  /**
   * Detect channel type from identifier string.
   * Returns 'email' if contains @, 'phone' if starts with + and matches E.164.
   */
  const detectChannelFromIdentifier = useCallback((id: string): AuthChannel | null => {
    if (!id) return null;

    // Email detection - contains @
    if (id.includes('@')) {
      return 'email';
    }

    // Phone detection - starts with + and matches E.164 format
    if (id.startsWith('+') && PHONE_REGEX.test(id)) {
      return 'phone';
    }

    return null;
  }, []);

  /**
   * Validate identifier format based on channel type.
   */
  const validateIdentifier = useCallback((id: string, channelType?: AuthChannel): boolean => {
    if (!id) return false;

    const channel = channelType || detectChannelFromIdentifier(id);

    if (channel === 'email') {
      return EMAIL_REGEX.test(id);
    }

    if (channel === 'phone') {
      return PHONE_REGEX.test(id);
    }

    return false;
  }, [detectChannelFromIdentifier]);

  return {
    detectChannelFromIdentifier,
    validateIdentifier,
  };
};

// Export standalone functions for use outside React
export const detectChannelFromIdentifier = (id: string): AuthChannel | null => {
  if (!id) return null;
  if (id.includes('@')) return 'email';
  if (id.startsWith('+') && PHONE_REGEX.test(id)) return 'phone';
  return null;
};

export const validateIdentifier = (id: string, channelType?: AuthChannel): boolean => {
  if (!id) return false;
  const channel = channelType || detectChannelFromIdentifier(id);
  if (channel === 'email') return EMAIL_REGEX.test(id);
  if (channel === 'phone') return PHONE_REGEX.test(id);
  return false;
};
