/*!
 * render.js — D44 家电保修台账视图模型（UMD）
 * 只做纯函数：输入 ledger + 基准日/筛选条件，输出可直接渲染的行模型。
 * 浏览器中依赖全局 DateCore；CommonJS 中自动 require('./date-core.js')。
 */
(function (root, factory) {
  'use strict';
  if (typeof module === 'object' && module.exports) {
    module.exports = factory(require('../date-core.js'));
  } else if (typeof define === 'function' && define.amd) {
    define(['../date-core'], factory);
  } else {
    root.D44Render = factory(root.DateCore);
  }
})(typeof globalThis !== 'undefined' ? globalThis : (typeof self !== 'undefined' ? self : this), function (DateCore) {
  'use strict';

  if (!DateCore) throw new Error('render.js 依赖 date-core.js，请先加载日期内核');

  var TONES = { active: 'ok', expiring: 'warn', expired: 'danger', invalid: 'danger' };
  var LABELS = { active: '保修中', expiring: '即将到期', expired: '已过保', invalid: '数据缺失' };
  var FILTERS = ['all', 'expiring', 'active', 'expired'];

  function trim(value) {
    return value === null || value === undefined ? '' : String(value).trim();
  }

  function escapeHtml(value) {
    return String(value === null || value === undefined ? '' : value)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;');
  }

  function toneOf(code) {
    return TONES[code] || 'danger';
  }

  function labelOf(code) {
    return LABELS[code] || '未知状态';
  }

  function formatMonthCount(months) {
    return months + ' 个月';
  }

  function validateItem(item, index) {
    var errors = [];
    var prefix = '第 ' + (index + 1) + ' 条记录';
    if (!item || typeof item !== 'object' || Array.isArray(item)) {
      return { errors: [prefix + '不是有效对象'], values: null };
    }
    var id = trim(item.id);
    var name = trim(item.name);
    if (!id) errors.push(prefix + '缺少编号（id）');
    if (!name) errors.push(prefix + '缺少家电名称（name）');

    var purchaseRaw = trim(item.purchaseDate);
    var purchaseDate = null;
    if (!purchaseRaw) {
      errors.push((id ? '【' + id + '】' : prefix) + '购买日期为空');
    } else if (!DateCore.isValidDate(purchaseRaw)) {
      errors.push('【' + id + '】购买日期无效：“' + purchaseRaw + '”，应为 YYYY-MM-DD');
    } else {
      purchaseDate = purchaseRaw;
    }

    var monthsRaw = item.warrantyMonths;
    var months = null;
    if (monthsRaw === '' || monthsRaw === null || monthsRaw === undefined) {
      errors.push((id ? '【' + id + '】' : prefix) + '保修月数为空');
    } else {
      var parsed = Number(monthsRaw);
      if (!isFinite(parsed) || Math.floor(parsed) !== parsed || parsed < 0) {
        errors.push('【' + id + '】保修月数必须是非负整数：“' + monthsRaw + '”');
      } else {
        months = parsed;
      }
    }

    var receiptPath = trim(item.receiptPath) || (trim(item.receiptFile) ? 'receipts/' + trim(item.receiptFile) : '');
    if (!receiptPath) errors.push((id ? '【' + id + '】' : prefix) + '凭证路径为空');

    var expiryDate = null;
    var reminderDate = null;
    var status = null;
    if (purchaseDate !== null && months !== null) {
      expiryDate = DateCore.warrantyEnd(purchaseDate, months);
      reminderDate = DateCore.reminderDate(expiryDate, 30);
      if (trim(item.expiryDate) && trim(item.expiryDate) !== expiryDate) {
        errors.push('【' + id + '】台账截止日 ' + trim(item.expiryDate) + ' 与规则计算值 ' + expiryDate + ' 不一致');
      }
    }

    return {
      errors: errors,
      values: {
        id: id || '（无编号）',
        name: name || '（未命名家电）',
        purchaseDate: purchaseDate,
        warrantyMonths: months,
        expiryDate: expiryDate,
        reminderDate: reminderDate,
        receiptPath: receiptPath,
        icsPath: trim(item.icsPath) || (id ? 'ics/' + id + '-warranty.ics' : ''),
        sourceStatus: item.status || null
      }
    };
  }

  function buildRow(item, index, asOf, windowDays) {
    var checked = validateItem(item, index);
    var values = checked.values;
    if (!values) {
      return {
        id: '（无编号）',
        name: '（未命名家电）',
        errors: checked.errors,
        statusCode: 'invalid',
        statusLabel: LABELS.invalid,
        tone: 'danger',
        daysText: '—',
        warnings: [],
        receiptPath: '',
        icsPath: ''
      };
    }

    var errors = checked.errors.slice();
    var statusCode = 'invalid';
    var status = null;
    var daysText = '—';
    var warnings = [];

    if (errors.length === 0) {
      status = DateCore.statusOf(values.expiryDate, asOf, windowDays);
      statusCode = status.code;
      daysText = DateCore.describeDays(values.expiryDate, asOf, windowDays);
      if (status.daysRemaining === 0) warnings.push('今日到期');
      if (values.reminderDate < values.purchaseDate) {
        warnings.push('保修期不足 30 天，提醒日早于购买日');
      }
      if (values.warrantyMonths === 0) warnings.push('0 个月保修，购买当天即截止');
    }

    return {
      index: index,
      id: values.id,
      name: values.name,
      purchaseDate: values.purchaseDate || '',
      warrantyMonths: values.warrantyMonths,
      monthsText: values.warrantyMonths === null ? '—' : formatMonthCount(values.warrantyMonths),
      expiryDate: values.expiryDate || '',
      reminderDate: values.reminderDate || '',
      receiptPath: values.receiptPath,
      icsPath: values.icsPath,
      statusCode: statusCode,
      statusLabel: LABELS[statusCode],
      tone: TONES[statusCode],
      daysRemaining: status ? status.daysRemaining : null,
      overdueDays: status ? status.overdueDays : null,
      daysText: daysText,
      warnings: warnings,
      errors: errors
    };
  }

  function matchesQuery(row, query) {
    if (!query) return true;
    var needle = query.toLowerCase();
    return String(row.id).toLowerCase().indexOf(needle) !== -1 ||
      String(row.name).toLowerCase().indexOf(needle) !== -1;
  }

  function emptyMessageFor(filter, query, total) {
    if (total === 0) return '台账中没有任何记录，请先检查数据源是否为空。';
    var filterText = { all: '全部', expiring: '即将到期', active: '保修中', expired: '已过保' }[filter] || '全部';
    if (query && filter !== 'all') {
      return '没有找到同时匹配“' + query + '”和筛选“' + filterText + '”的记录。可清空搜索或切换筛选。';
    }
    if (query) return '没有找到名称或编号包含“' + query + '”的家电。请检查关键词。';
    if (filter === 'expiring') return '当前基准日下没有 30 天内到期的家电。可调整基准日期查看其他时间点。';
    if (filter === 'active') return '当前基准日下没有仍在保修期内的家电。';
    if (filter === 'expired') return '当前基准日下没有被过保的家电。';
    return '没有可显示的记录。';
  }

  /**
   * 生成页面视图模型。
   * @param {object} ledger {meta:{asOf, windowDays}, items:[]}
   * @param {object} options {asOf, filter, q, windowDays}
   */
  function buildView(ledger, options) {
    var opts = options || {};
    if (!ledger || !Array.isArray(ledger.items)) {
      throw new TypeError('台账数据格式错误：缺少 items 数组');
    }
    var meta = ledger.meta || {};
    var windowDays = opts.windowDays === undefined ? (meta.windowDays === undefined ? 30 : meta.windowDays) : opts.windowDays;
    if (!Number.isInteger(windowDays) || windowDays < 0) {
      throw new RangeError('提醒窗口必须是大于等于 0 的整数：' + windowDays);
    }
    var asOf = opts.asOf === undefined ? meta.asOf : opts.asOf;
    if (!DateCore.isValidDate(asOf)) {
      throw new RangeError('基准日期无效：“' + asOf + '”，应为真实存在的 YYYY-MM-DD 日期');
    }
    var filter = opts.filter || 'all';
    if (FILTERS.indexOf(filter) === -1) {
      throw new RangeError('未知筛选条件：“' + filter + '”');
    }
    var query = trim(opts.q);

    var rows = ledger.items.map(function (item, index) {
      return buildRow(item, index, asOf, windowDays);
    });

    rows.sort(function (a, b) {
      if (a.errors.length && !b.errors.length) return 1;
      if (!a.errors.length && b.errors.length) return -1;
      if (a.expiryDate && b.expiryDate && a.expiryDate !== b.expiryDate) {
        return a.expiryDate < b.expiryDate ? -1 : 1;
      }
      return String(a.id).localeCompare(String(b.id), 'zh-Hans-CN');
    });

    var counts = { all: rows.length, expiring: 0, active: 0, expired: 0, invalid: 0 };
    var dataErrors = [];
    rows.forEach(function (row) {
      if (row.errors.length) {
        counts.invalid += 1;
        dataErrors.push({ id: row.id, message: row.errors.join('；') });
      } else {
        counts[row.statusCode] += 1;
      }
    });

    var visible = rows.filter(function (row) {
      if (filter !== 'all' && row.statusCode !== filter) return false;
      return matchesQuery(row, query);
    });

    return {
      asOf: asOf,
      windowDays: windowDays,
      filter: filter,
      query: query,
      rows: visible,
      allRows: rows,
      counts: counts,
      total: rows.length,
      visibleCount: visible.length,
      empty: visible.length === 0,
      emptyMessage: emptyMessageFor(filter, query, rows.length),
      dataErrors: dataErrors
    };
  }

  return {
    VERSION: '1.0.0',
    FILTERS: FILTERS,
    escapeHtml: escapeHtml,
    toneOf: toneOf,
    labelOf: labelOf,
    buildView: buildView
  };
});
