export type InterestValues = {
  fullName: string;
  phone: string;
  email: string;
  consent: boolean;
};

export type InterestField = keyof InterestValues;
export type InterestErrorKey =
  | 'nameRequired'
  | 'nameShort'
  | 'phoneRequired'
  | 'phoneInvalid'
  | 'emailInvalid'
  | 'consentRequired';
export type InterestErrors = Partial<Record<InterestField, InterestErrorKey>>;

export const emptyInterest: InterestValues = { fullName: '', phone: '', email: '', consent: false };

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;

export function validateField(field: InterestField, values: InterestValues): InterestErrorKey | undefined {
  switch (field) {
    case 'fullName': {
      const name = values.fullName.trim();
      if (!name) return 'nameRequired';
      return name.length < 2 ? 'nameShort' : undefined;
    }
    case 'phone': {
      const phone = values.phone.trim();
      if (!phone) return 'phoneRequired';
      // Accept spaces, dashes and brackets as typed; count digits only.
      if (!/^\+?[\d\s\-()]+$/.test(phone)) return 'phoneInvalid';
      const digits = phone.replace(/\D/g, '').length;
      return digits < 8 || digits > 15 ? 'phoneInvalid' : undefined;
    }
    case 'email': {
      const email = values.email.trim();
      return email && !EMAIL.test(email) ? 'emailInvalid' : undefined;
    }
    case 'consent':
      return values.consent ? undefined : 'consentRequired';
  }
}

const FIELDS: InterestField[] = ['fullName', 'phone', 'email', 'consent'];

export function validateInterest(values: InterestValues): InterestErrors {
  const errors: InterestErrors = {};
  for (const field of FIELDS) {
    const error = validateField(field, values);
    if (error) errors[field] = error;
  }
  return errors;
}
