/*!
 * TimeCore — 跨时区时间计算核心库（赛博游园会 D55）
 * ------------------------------------------------------------------
 * 纯 JavaScript、零外部依赖、离线可用（使用运行时内置 Intl 的完整
 * IANA 时区数据，同时支持浏览器 <script> 全局与 Node.js CommonJS）。
 *
 * 核心要点：
 *  - 一律使用 IANA 时区名（如 America/New_York），绝不用固定偏移顶替夏令时。
 *  - 墙钟时间 -> UTC 时，会探测该时区当天所有可能偏移并回验墙钟，从而
 *    正确识别「夏令时向前跳变造成的不存在时间」与「冬令时回拨造成的重复时间」。
 *  - 歧义时间会返回全部（通常是两个）UTC 选项，绝不静默替用户挑选。
 */
(function (root, factory) {
  if (typeof module === "object" && module.exports) {
    module.exports = factory();
  } else {
    root.TimeCore = factory();
  }
})(typeof globalThis !== "undefined" ? globalThis : this, function () {
  "use strict";

  var MIN = 60000;
  var HOUR = 60 * MIN;
  var DAY = 24 * HOUR;

  function pad2(n) {
    return String(n).padStart(2, "0");
  }

  // ------------------------------------------------------------------
  // 基础工具
  // ------------------------------------------------------------------

  /** 某 UTC 时刻在某时区的 UTC 偏移（毫秒）。UTC + offset = 本地墙钟。 */
  function utcOffsetMs(zone, unixMs) {
    var dtf = new Intl.DateTimeFormat("en-US", {
      timeZone: zone,
      hour12: false,
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    });
    var map = Object.create(null);
    var arr = dtf.formatToParts(new Date(unixMs));
    for (var i = 0; i < arr.length; i++) map[arr[i].type] = arr[i].value;
    var localMs = Date.UTC(
      +map.year, +map.month - 1, +map.day, +map.hour, +map.minute, +map.second
    );
    return localMs - unixMs;
  }

  /** 偏移毫秒 -> "+08:00" 样式的标签。 */
  function labelFromMs(offMs) {
    var offMin = Math.round(offMs / MIN);
    var sign = offMin >= 0 ? "+" : "-";
    var a = Math.abs(offMin);
    return sign + pad2(Math.floor(a / 60)) + ":" + pad2(a % 60);
  }

  function offsetLabel(zone, unixMs) {
    return labelFromMs(utcOffsetMs(zone, unixMs));
  }

  /** 时区短名（如 EDT / EST / GMT），无法取得时回退为空串。 */
  function zoneAbbr(zone, unixMs) {
    try {
      var arr = new Intl.DateTimeFormat("en-US", {
        timeZone: zone,
        timeZoneName: "short",
      }).formatToParts(new Date(unixMs));
      for (var i = 0; i < arr.length; i++) {
        if (arr[i].type === "timeZoneName") return arr[i].value;
      }
      return "";
    } catch (e) {
      return "";
    }
  }

  /** UTC 时刻在某时区的本地墙钟分量（1 基月）。 */
  function parts(zone, unixMs) {
    var dtf = new Intl.DateTimeFormat("en-US", {
      timeZone: zone,
      hour12: false,
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    });
    var m = Object.create(null);
    var arr = dtf.formatToParts(new Date(unixMs));
    for (var i = 0; i < arr.length; i++) m[arr[i].type] = arr[i].value;
    return {
      year: +m.year, month: +m.month, day: +m.day,
      hour: +m.hour, minute: +m.minute, second: +m.second,
    };
  }

  /** 格式化为 "YYYY-MM-DD HH:MM"。 */
  function formatLocal(zone, unixMs) {
    var p = parts(zone, unixMs);
    return p.year + "-" + pad2(p.month) + "-" + pad2(p.day) + " " +
      pad2(p.hour) + ":" + pad2(p.minute);
  }

  /** UTC 时刻 -> "YYYY-MM-DDTHH:MM:SSZ"（用于 ICS）。 */
  function utcStamp(unixMs) {
    return new Date(unixMs).toISOString()
      .replace(/[-:]/g, "")
      .replace(/\.\d{3}/, "");
  }

  // ------------------------------------------------------------------
  // 墙钟 -> UTC（正确处理 DST 不存在 / 重复）
  // ------------------------------------------------------------------

  /**
   * 把某时区的墙钟时间转换为 UTC。
   *
   * 做法：墙钟按「天真 UTC」定位后，枚举 -12:00 … +14:00 之间所有 15 分钟
   * 粒度的候选偏移，逐一回验「该 UTC 在该时区渲染出的墙钟是否完全等于目标」。
   * 于是：
   *   - 普通时间  -> kind:"unique"     options 恰 1 项
   *   - 冬令时回拨 -> kind:"ambiguous"  options 2 项（两次出现）
   *   - 夏令时跳变 -> kind:"nonexistent" options 空
   *
   * @param {string} zone IANA 时区名
   * @param {number} year,month(1-12),day,hour,minute 墙钟时间
   * @returns {{zone,year,month,day,hour,minute,kind,options,utc}}
   */
  function wallToUtc(zone, year, month, day, hour, minute) {
    var naiveUtc = Date.UTC(year, month - 1, day, hour, minute, 0);
    var options = [];
    // 现实 IANA 偏移范围为 [-12:00, +14:00]，且均为 15 分钟的整数倍。
    for (var offMin = -12 * 60; offMin <= 14 * 60; offMin += 15) {
      var u = naiveUtc - offMin * MIN;
      var p = parts(zone, u);
      if (p.year === year && p.month === month && p.day === day &&
          p.hour === hour && p.minute === minute) {
        options.push({
          utcMs: u,
          offsetMs: utcOffsetMs(zone, u),
          offsetLabel: labelFromMs(utcOffsetMs(zone, u)),
          abbr: zoneAbbr(zone, u),
        });
      }
    }
    // 按 UTC 时刻去重（理论上同一时刻不会带两个偏移，防御性处理）。
    var seen = Object.create(null);
    var uniq = [];
    for (var i = 0; i < options.length; i++) {
      if (!seen[options[i].utcMs]) {
        seen[options[i].utcMs] = true;
        uniq.push(options[i]);
      }
    }
    uniq.sort(function (a, b) { return a.utcMs - b.utcMs; });
    var kind = uniq.length === 0 ? "nonexistent"
      : uniq.length === 1 ? "unique" : "ambiguous";
    return {
      zone: zone, year: year, month: month, day: day,
      hour: hour, minute: minute, kind: kind,
      options: uniq,
      utc: uniq.map(function (o) { return o.utcMs; }),
    };
  }

  // ------------------------------------------------------------------
  // 输入解析与校验
  // ------------------------------------------------------------------

  function parseDate(day) {
    var m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(day == null ? "" : day).trim());
    if (!m) return null;
    var y = +m[1], mo = +m[2], d = +m[3];
    var dt = new Date(Date.UTC(y, mo - 1, d));
    if (dt.getUTCFullYear() !== y || dt.getUTCMonth() !== mo - 1 || dt.getUTCDate() !== d) {
      return null; // 无效日期（如 2026-02-30）
    }
    return { year: y, month: mo, day: d };
  }

  function parseTime(hhmm) {
    var s = String(hhmm == null ? "" : hhmm).trim();
    var m = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(s);
    if (!m) return null;
    return { hour: +m[1], minute: +m[2], text: s };
  }

  function isValidZone(zone) {
    if (typeof zone !== "string" || !zone.trim()) return false;
    try {
      new Intl.DateTimeFormat("en-US", { timeZone: zone }).format(new Date(0));
      return true;
    } catch (e) {
      return false;
    }
  }

  /** 校验整个 spec，返回 { ok, errors: string[] }。 */
  function validateSpec(spec) {
    var errors = [];
    if (!spec || typeof spec !== "object") {
      return { ok: false, errors: ["输入数据为空或格式错误"] };
    }
    if (!parseDate(spec.day)) errors.push("约会日期无效（应为 YYYY-MM-DD）：" + spec.day);
    var duration = Number(spec.durationMinutes);
    if (!isFinite(duration) || duration <= 0 || Math.floor(duration) !== duration) {
      errors.push("时长必须是正整数分钟：" + spec.durationMinutes);
    }
    var list = Array.isArray(spec.participants) ? spec.participants : null;
    if (!list || list.length === 0) {
      errors.push("至少需要一位参与者");
    } else {
      list.forEach(function (p, idx) {
        var tag = "参与者#" + (idx + 1) + (p && p.name ? "（" + p.name + "）" : "");
        if (!p || !p.name || !String(p.name).trim()) errors.push(tag + " 缺少姓名");
        if (!isValidZone(p && p.zone)) errors.push(tag + " 时区无效（需 IANA 名称，如 Asia/Shanghai）：" + (p && p.zone));
        if (!parseTime(p && p.start)) errors.push(tag + " 开始时间无效（应为 HH:MM）：" + (p && p.start));
        if (!parseTime(p && p.end)) errors.push(tag + " 结束时间无效（应为 HH:MM）：" + (p && p.end));
      });
    }
    return { ok: errors.length === 0, errors: errors };
  }

  // ------------------------------------------------------------------
  // 参与者窗口 -> 交集 -> 候选
  // ------------------------------------------------------------------

  /**
   * 把单个参与者的「本地日期 + 起止墙钟」转换成 UTC 区间。
   * 边界若命中 DST 不存在/重复，会返回错误而非静默挑选。
   */
  function participantWindow(p, day) {
    var errors = [];
    var d = parseDate(day);
    var name = (p && p.name) ? String(p.name).trim() : "";
    var zone = (p && p.zone) ? String(p.zone).trim() : "";
    if (!d) return { ok: false, errors: ["日期无效（应为 YYYY-MM-DD）：" + day], name: name, zone: zone };
    if (!name) errors.push("缺少参与者姓名");
    if (!isValidZone(zone)) { if (zone) errors.push("时区无效：" + zone); else errors.push("缺少时区"); }
    var s = parseTime(p && p.start);
    var e = parseTime(p && p.end);
    if (!s) errors.push("开始时间无效（HH:MM）：" + (p && p.start));
    if (!e) errors.push("结束时间无效（HH:MM）：" + (p && p.end));
    if (errors.length) return { ok: false, errors: errors, name: name, zone: zone };

    var sr = wallToUtc(zone, d.year, d.month, d.day, s.hour, s.minute);
    var er = wallToUtc(zone, d.year, d.month, d.day, e.hour, e.minute);
    if (sr.kind === "nonexistent") {
      return { ok: false, errors: ["开始时间 " + s.text + " 在 " + zone + " 当天不存在（夏令时向前跳变）"], name: name, zone: zone };
    }
    if (sr.kind === "ambiguous") {
      return { ok: false, errors: ["开始时间 " + s.text + " 在 " + zone + " 当天出现两次（冬令时回拨），需显式选择其一"], name: name, zone: zone };
    }
    if (er.kind === "nonexistent") {
      return { ok: false, errors: ["结束时间 " + e.text + " 在 " + zone + " 当天不存在（夏令时向前跳变）"], name: name, zone: zone };
    }
    if (er.kind === "ambiguous") {
      return { ok: false, errors: ["结束时间 " + e.text + " 在 " + zone + " 当天出现两次（冬令时回拨），需显式选择其一"], name: name, zone: zone };
    }

    var startMs = sr.utc[0];
    var endMs = er.utc[0];
    var crossMidnight = false;
    if (endMs < startMs) {
      // 结束早于开始：视为跨入次日
      endMs += DAY;
      crossMidnight = true;
    } else if (endMs === startMs) {
      return { ok: false, errors: ["时间窗口为空（开始时间等于结束时间）"], name: name, zone: zone };
    }

    return {
      ok: true, name: name, zone: zone,
      start: s.text, end: e.text,
      utcStartMs: startMs, utcEndMs: endMs,
      crossMidnight: crossMidnight,
      startResult: sr, endResult: er,
    };
  }

  /** 求多个 UTC 区间的交集。 */
  function intersect(windows) {
    var valid = [];
    for (var i = 0; i < windows.length; i++) {
      if (windows[i] && windows[i].ok) valid.push(windows[i]);
    }
    if (valid.length === 0) return { ok: false, reason: "无有效参与者窗口" };
    var startMs = -Infinity, endMs = Infinity;
    for (var j = 0; j < valid.length; j++) {
      if (valid[j].utcStartMs > startMs) startMs = valid[j].utcStartMs;
      if (valid[j].utcEndMs < endMs) endMs = valid[j].utcEndMs;
    }
    if (endMs <= startMs) {
      return { ok: false, reason: "没有共同空闲时间（交集为空）", startMs: startMs, endMs: endMs };
    }
    return {
      ok: true, startMs: startMs, endMs: endMs,
      durationMin: Math.round((endMs - startMs) / MIN),
      members: valid,
    };
  }

  /** 在交集内按固定时长切分候选槽（从交集起点开始，每 durationMin 一个）。 */
  function candidates(slot, durationMin) {
    if (!slot || !slot.ok) return [];
    var dur = durationMin * MIN;
    var list = [];
    for (var t = slot.startMs; t + dur <= slot.endMs; t += dur) {
      list.push({ startMs: t, endMs: t + dur, durationMin: durationMin });
    }
    return list;
  }

  /** 某 UTC 时刻在某时区的本地信息（含日期/时间/偏移/短名）。 */
  function localInfo(zone, unixMs) {
    var p = parts(zone, unixMs);
    return {
      zone: zone,
      utcMs: unixMs,
      year: p.year, month: p.month, day: p.day, hour: p.hour, minute: p.minute,
      date: p.year + "-" + pad2(p.month) + "-" + pad2(p.day),
      time: pad2(p.hour) + ":" + pad2(p.minute),
      full: p.year + "-" + pad2(p.month) + "-" + pad2(p.day) + " " +
        pad2(p.hour) + ":" + pad2(p.minute),
      offsetLabel: offsetLabel(zone, unixMs),
      abbr: zoneAbbr(zone, unixMs),
    };
  }

  /** 求某个时刻全体参与者的本地日期时间。 */
  function localsAt(windows, unixMs) {
    var out = [];
    for (var i = 0; i < windows.length; i++) {
      var w = windows[i];
      out.push({
        name: w.name,
        zone: w.zone,
        local: localInfo(w.zone, unixMs),
      });
    }
    return out;
  }

  // ------------------------------------------------------------------
  // ICS 生成
  // ------------------------------------------------------------------

  function icsEscape(s) {
    return String(s)
      .replace(/\\/g, "\\\\")
      .replace(/\r\n/g, "\n")
      .replace(/\r/g, "\n")
      .replace(/\n/g, "\\n")
      .replace(/,/g, "\\,")
      .replace(/;/g, "\\;");
  }

  /** 按 RFC 5545 折叠长行：每行 ≤75 八位组，续行以空格开头，行尾 CRLF。 */
  function icsFold(line) {
    var MAX = 75;
    var enc = new TextEncoder();
    var segments = [];
    var cur = "";
    var curBytes = 0;
    var chars = Array.from(line); // 按码点迭代，避免拆坏多字节字符
    for (var i = 0; i < chars.length; i++) {
      var ch = chars[i];
      var b = enc.encode(ch).length;
      var limit = segments.length === 0 ? MAX : MAX - 1; // 续行含前导空格
      if (curBytes + b > limit) {
        segments.push(cur);
        cur = " " + ch;
        curBytes = 1 + b;
      } else {
        cur += ch;
        curBytes += b;
      }
    }
    if (cur) segments.push(cur);
    return segments.join("\r\n");
  }

  /**
   * 生成单个 VEVENT 的完整 ICS 文本（Publish 方法，非邀请，不写入任何日历）。
   * @param {object} ev {uid, dtstampMs, startMs, endMs, summary, description, location}
   */
  function buildIcs(ev) {
    var lines = [
      "BEGIN:VCALENDAR",
      "VERSION:2.0",
      "PRODID:-//CyberFete//TimeCore D55//CN",
      "CALSCALE:GREGORIAN",
      "METHOD:PUBLISH",
      "BEGIN:VEVENT",
      "UID:" + ev.uid,
      "DTSTAMP:" + utcStamp(ev.dtstampMs),
      "DTSTART:" + utcStamp(ev.startMs),
      "DTEND:" + utcStamp(ev.endMs),
      "SUMMARY:" + icsEscape(ev.summary == null ? "跨时区约会" : ev.summary),
    ];
    if (ev.description != null && ev.description !== "") {
      lines.push("DESCRIPTION:" + icsEscape(ev.description));
    }
    if (ev.location != null && ev.location !== "") {
      lines.push("LOCATION:" + icsEscape(ev.location));
    }
    lines.push("END:VEVENT");
    lines.push("END:VCALENDAR");
    return lines.map(icsFold).join("\r\n") + "\r\n";
  }

  function makeUid(prefix) {
    var rand = Math.floor(Math.random() * 1e9);
    return (prefix || "cyberfete-d55") + "-" + Date.now() + "-" + rand;
  }

  /**
   * 由候选槽 + 参与者窗口生成一个 ICS 文本（会为每位参与者计算本地时间并
   * 写入 DESCRIPTION，便于人工核对）。
   */
  function icsForCandidate(cand, windows, opts) {
    opts = opts || {};
    var locals = localsAt(windows, cand.startMs);
    var descParts = [];
    for (var i = 0; i < locals.length; i++) {
      var L = locals[i];
      descParts.push(L.name + " (" + L.zone + ", " + L.local.offsetLabel + "): " +
        L.local.full + " 起，30 分钟");
    }
    var names = windows.map(function (w) { return w.name; }).join("、");
    var startLocal = localInfo(windows[0].zone, cand.startMs);
    return buildIcs({
      uid: opts.uid || makeUid("meeting"),
      dtstampMs: opts.dtstampMs || Date.now(),
      startMs: cand.startMs,
      endMs: cand.endMs,
      summary: opts.summary || (names + " 的跨时区约会（" + cand.durationMin + " 分钟）"),
      description: descParts.join("\n"),
      location: opts.location || "",
    });
  }

  // ------------------------------------------------------------------
  // 便捷入口：一次性计算
  // ------------------------------------------------------------------

  function compute(spec) {
    var v = validateSpec(spec);
    if (!v.ok) return { ok: false, errors: v.errors };
    var windows = spec.participants.map(function (p) {
      return participantWindow(p, spec.day);
    });
    var bad = windows.filter(function (w) { return !w.ok; });
    if (bad.length > 0) {
      var flat = [];
      bad.forEach(function (w) { flat = flat.concat(w.errors); });
      return { ok: false, errors: flat, windows: windows };
    }
    var slot = intersect(windows);
    if (!slot.ok) return { ok: false, errors: [slot.reason], windows: windows, intersection: slot };
    var cands = candidates(slot, Number(spec.durationMinutes));
    return { ok: true, windows: windows, intersection: slot, candidates: cands };
  }

  return {
    VERSION: "1.0.0",
    MIN: MIN,
    HOUR: HOUR,
    DAY: DAY,
    // 基础
    utcOffsetMs: utcOffsetMs,
    labelFromMs: labelFromMs,
    offsetLabel: offsetLabel,
    zoneAbbr: zoneAbbr,
    parts: parts,
    formatLocal: formatLocal,
    utcStamp: utcStamp,
    // 墙钟 -> UTC
    wallToUtc: wallToUtc,
    // 解析与校验
    parseDate: parseDate,
    parseTime: parseTime,
    isValidZone: isValidZone,
    validateSpec: validateSpec,
    // 高层
    participantWindow: participantWindow,
    intersect: intersect,
    candidates: candidates,
    localInfo: localInfo,
    localsAt: localsAt,
    compute: compute,
    // ICS
    icsEscape: icsEscape,
    icsFold: icsFold,
    buildIcs: buildIcs,
    makeUid: makeUid,
    icsForCandidate: icsForCandidate,
  };
});