(function () {
  function cleanClassroomFields(input) {
    const source = input || {};
    const trimmed = {
      name: typeof source.name === 'string' ? source.name.trim() : '',
      location: typeof source.location === 'string' ? source.location.trim() : ''
    };
    const numericCapacity = Number(source.capacity);
    trimmed.capacity = Number.isFinite(numericCapacity) ? Math.trunc(numericCapacity) : 0;
    return trimmed;
  }

  function isValidCapacity(value) {
    if (value === undefined || value === null || value === '') return true;
    if (typeof value === 'string') {
      const trimmed = value.trim();
      if (trimmed === '') return true;
      const num = Number(trimmed);
      return Number.isInteger(num) && num >= 1;
    }
    if (typeof value === 'number') {
      if (value === 0) return true; // not entered (post-clean normalised)
      return Number.isInteger(value) && value >= 1;
    }
    return false;
  }

  function validateClassroom(input) {
    const errors = {};
    const value = input || {};
    const name = typeof value.name === 'string' ? value.name.trim() : '';
    if (!name) {
      errors.name = '名称为必填项';
    }
    if (!isValidCapacity(value.capacity)) {
      errors.capacity = '容量需为大于等于 1 的整数';
    }
    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_ = { cleanClassroomFields, validateClassroom, summarizeReferences };

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

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