(function () {
  function cleanTeacherFields(input) {
    const source = input || {};
    const trimmed = {
      name: typeof source.name === 'string' ? source.name.trim() : '',
      phone: typeof source.phone === 'string' ? source.phone.trim() : '',
      email: typeof source.email === 'string' ? source.email.trim() : '',
      specialty: typeof source.specialty === 'string' ? source.specialty.trim() : ''
    };
    // Optional fields: keep as empty string (not null) to match existing payload style.
    return trimmed;
  }

  function validateRequiredName(name) {
    return typeof name === 'string' && name.trim().length > 0;
  }

  // Allow digits, spaces, +, -, parentheses. Require at least 7 digits overall.
  function isValidPhone(phone) {
    if (typeof phone !== 'string') return false;
    if (!/^[\d\s+()\-]+$/.test(phone)) return false;
    const digits = phone.replace(/\D/g, '');
    return digits.length >= 7 && digits.length <= 20;
  }

  function isValidEmail(email) {
    if (typeof email !== 'string') return false;
    if (email.length > 254) return false;
    // Pragmatic email pattern: local-part@domain.tld with at least one dot in domain.
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  }

  function validateTeacher(input) {
    const errors = {};
    const { name, phone, email } = input || {};
    if (!validateRequiredName(name)) {
      errors.name = '姓名为必填项';
    }
    if (phone && phone.length > 0 && !isValidPhone(phone)) {
      errors.phone = '电话格式不正确';
    }
    if (email && email.length > 0 && !isValidEmail(email)) {
      errors.email = '邮箱格式不正确';
    }
    return errors;
  }

  function summarizeReferences(counts) {
    const classesTotal = (counts && counts.classes && counts.classes.total) || 0;
    const schedulesTotal = (counts && counts.schedules && counts.schedules.total) || 0;
    const totalCount = classesTotal + schedulesTotal;
    const parts = [];
    if (classesTotal > 0) parts.push(`班级 ${classesTotal} 个`);
    if (schedulesTotal > 0) parts.push(`排期 ${schedulesTotal} 个`);
    return {
      hasReferences: totalCount > 0,
      totalCount,
      classesTotal,
      schedulesTotal,
      message: parts.join('、')
    };
  }

  const exports_ = { cleanTeacherFields, validateTeacher, summarizeReferences };

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = exports_;
  }

  if (typeof window !== 'undefined') {
    window.teachers = exports_;
  }
})();