import { svgPathProperties } from 'svg-path-properties';
import { text, num, choice, color, assert, svgDoc, svgResults, label, json, plain, file, canvas, png, esc } from './common.js';

const content = () => text('content', '文字', 'ABC abc 123');
const size = () => num('size', '字号(px)', 48, 8, 240);
const family = () => choice('family', '系统字体', [['sans-serif', '无衬线'], ['serif', '衬线'], ['monospace', '等宽']]);
const nameOf = (font) => font.getEnglishName('fontFamily') || 'UploadedFont';
async function readFont(files, index = 0) {
  assert(files[index], '请选择字体文件。'); assert(files[index].size <= 8 * 1024 * 1024, '字体文件上限8MB。');
  let font; try { const { default: opentype } = await import('opentype.js'); font = opentype.parse(await files[index].arrayBuffer()); } catch { throw new Error('字体无法解析,仅支持有效TTF、OTF和WOFF,不支持WOFF2或字体集合。'); }
  assert(font.numGlyphs > 0 && font.numGlyphs <= 100000 && font.unitsPerEm > 0, '字体字形数量或单位无效。'); return font;
}
function verifyText(font, value, maximum = 300) {
  assert([...value].length <= maximum && value.trim(), `文字需为1–${maximum}个字符。`);
  const missing = [...new Set([...value].filter((c) => !font.hasChar(c)))]; assert(!missing.length, `字体缺少这些字符:${missing.slice(0, 20).join(' ')}`);
  assert(!font.tables.svg && !font.tables.colr, '此操作仅支持普通轮廓字体,不支持SVG或彩色字形。');
}
function pathFor(font, value, x, y, px) {
  verifyText(font, value); const path = font.getPath(value, x, y, px, { kerning: true, hinting: false });
  assert(path.commands.length <= 100000, '文字轮廓过于复杂,请减少字符。');
  return path;
}
function pathData(path) {
  // opentype 2.0's decimal exponent rounding can emit NaN for tiny float remainders.
  const fields = { M: ['x', 'y'], L: ['x', 'y'], C: ['x1', 'y1', 'x2', 'y2', 'x', 'y'], Q: ['x1', 'y1', 'x', 'y'], Z: [] };
  return path.commands.map((command) => {
    assert(fields[command.type], '字体轮廓命令无效。');
    return command.type + fields[command.type].map((key) => {
      assert(Number.isFinite(command[key]), '字体轮廓坐标无效。');
      return Number(command[key].toFixed(3));
    }).join(' ');
  }).join('');
}
function fittedPath(font, value, px, x, y, maxWidth) {
  const advance = font.getAdvanceWidth(value, px); assert(advance <= maxWidth, '文字超出样张宽度,请缩小字号或减少文字。');
  return `<path d="${pathData(pathFor(font, value, x, y, px))}" fill="#183f32"/>`;
}
export const font_inspect = /*#__PURE__*/ (() => ({ fields: [text('characters', '检查字符', 'ABC abc 123')], async run({ files, values: v }) {
  const f = await readFont(files); assert([...v.characters].length <= 1000, '最多检查1000字符。');
  const report = { family: nameOf(f), names: f.names, glyphs: f.numGlyphs, unitsPerEm: f.unitsPerEm, ascender: f.ascender, descender: f.descender, tables: Object.keys(f.tables), embeddingFlags: f.tables.os2?.fsType || 0, characters: [...new Set(v.characters)].map((c) => ({ character: c, codePoint: c.codePointAt(0), glyph: f.charToGlyphIndex(c), supported: f.hasChar(c) })) };
  return [json(report, 'font-info.json')];
} }))();
export const font_specimen = /*#__PURE__*/ (() => ({ fields: [content(), num('base', '基础字号', 24, 8, 80)], async run({ files, values: v }) {
  const font = await readFont(files); verifyText(font, v.content); let body = label(nameOf(font), 24, 30, 'font-size="18"'), y = 60;
  for (const multiplier of [1, 1.5, 2, 3]) { const px = v.base * multiplier; y += px + 14; body += label(`${px}px`, 24, y) + fittedPath(font, v.content, px, 110, y, 1030); }
  return svgResults(svgDoc(body, 1180, Math.ceil(y + 55), '字体样张'), 'specimen');
} }))();
export const text_metrics = /*#__PURE__*/ (() => ({ fields: [content(), family(), size(), num('width', '行宽(px)', 480, 100, 1600), num('spacing', '字距(px)', 0, -4, 30, .5)], async run({ values: v }) {
  assert([...v.content].length <= 1500, '最多1500字符。'); const probe = canvas(1, 1).getContext('2d'); probe.font = `${v.size}px ${v.family}`;
  probe.letterSpacing = `${v.spacing}px`; const measure = (s) => probe.measureText(s).width;
  const lines = []; let current = ''; for (const char of v.content) { if (char === '\n' || (current && measure(current + char) > v.width)) { lines.push(current); current = char === '\n' ? '' : char; } else current += char; } lines.push(current);
  assert(lines.length <= 40 && lines.every((s) => measure(s) <= v.width), '行数超过40行或单个字符超过行宽。');
  const height = Math.ceil(lines.length * v.size * 1.5 + 60), node = canvas(v.width + 48, height, '#ffffff'), ctx = node.getContext('2d'); ctx.font = probe.font; ctx.fillStyle = '#183f32'; ctx.letterSpacing = `${v.spacing}px`;
  lines.forEach((s, i) => ctx.fillText(s, 24, 30 + v.size + i * v.size * 1.5));
  return [await png(node, 'text-layout.png'), json({ font: probe.font, spacing: v.spacing, lineWidth: v.width, lines: lines.map((text) => ({ text, width: measure(text), ...(() => { const m = probe.measureText(text); return { ascent: m.actualBoundingBoxAscent, descent: m.actualBoundingBoxDescent }; })() })) }, 'metrics.json')];
} }))();
export const type_scale = /*#__PURE__*/ (() => ({ fields: [num('base', '基础字号', 16, 8, 40), num('ratio', '字号比例', 1.25, 1.05, 2, .05), num('steps', '阶梯级数', 7, 3, 10)], async run({ values: v }) {
  const sizes = Array.from({ length: v.steps }, (_, i) => Number((v.base * v.ratio ** i).toFixed(3))); assert(sizes.at(-1) <= 240, '最大字号超过240px,请降低比例或级数。'); let y = 20;
  const body = sizes.map((px, i) => { y += px + 22; return label(`T${i} · ${px}px · Aa`, 24, y, `style="font-size:${px}px"`); }).join('');
  return [...await svgResults(svgDoc(body, 1000, Math.ceil(y + 40), '字号阶梯'), 'type-scale'), plain(`:root {\n${sizes.map((px, i) => `  --text-${i}: ${px / 16}rem; /* ${px}px at root 16px */`).join('\n')}\n}\n`, 'type-scale.css', 'text/css'), json(sizes, 'sizes.json')];
} }))();
export const fluid_type = /*#__PURE__*/ (() => ({ fields: [num('small', '最小字号(px)', 16, 8, 100), num('large', '最大字号(px)', 32, 8, 240), num('from', '起始视口(px)', 320, 200, 2000), num('to', '结束视口(px)', 1280, 300, 4000), num('root', '根字号(px)', 16, 8, 32)], async run({ values: v }) {
  assert(v.to > v.from && v.large > v.small, '结束视口及最大字号必须分别大于起始值。');
  const slope = (v.large - v.small) / (v.to - v.from), intercept = v.small - slope * v.from, css = `font-size: clamp(${v.small / v.root}rem, ${+(intercept / v.root).toFixed(8)}rem + ${+(100 * slope).toFixed(8)}vw, ${v.large / v.root}rem);`;
  const samples = Array.from({ length: 7 }, (_, i) => { const viewport = Math.round(v.from * .75 + (v.to * 1.1 - v.from * .75) * i / 6); return { viewport, size: Math.max(v.small, Math.min(v.large, intercept + slope * viewport)) }; });
  return [plain(`/* 根字号基准 ${v.root}px;用户调整根字号时,rem边界随之变化。 */\n.fluid-text { ${css} }\n`, 'fluid-type.css', 'text/css'), json({ css, slope, intercept, samples }, 'fluid-type.json'), ...await svgResults(svgDoc(samples.map((s, i) => label(`${s.viewport}px 视口 → ${s.size.toFixed(2)}px 字号`, 24, 44 + i * 52, `style="font-size:${Math.min(32, s.size)}px"`)).join(''), 1000, 420, '响应式字号'), 'fluid-type')];
} }))();
export const font_pair = /*#__PURE__*/ (() => ({ fields: [text('heading', '标题文字', 'ABC'), text('body', '正文字样', 'abc 123'), num('headingSize', '标题字号', 60, 12, 120), num('bodySize', '正文字号', 28, 8, 60)], async run({ files, values: v }) {
  assert(files.length === 2, '请按顺序选择两份字体。'); const first = await readFont(files), second = await readFont(files, 1);
  const body = [first, second].map((heading, i) => { const bodyFont = i ? first : second, top = 35 + i * 230; return label(`标题:${nameOf(heading)} / 正文:${nameOf(bodyFont)}`, 24, top) + fittedPath(heading, v.heading, v.headingSize, 24, top + 90, 950) + fittedPath(bodyFont, v.body, v.bodySize, 24, top + 155, 950); }).join('');
  return svgResults(svgDoc(body, 1000, 490, '字体搭配对照'), 'font-pair');
} }))();
export const text_path = /*#__PURE__*/ (() => ({ fields: [text('content', '文字', '沿着曲线排布文字'), text('path', '路径d(画布800×400)', 'M 40 250 C 200 20 600 20 760 250', true), num('size', '字号(px)', 32, 8, 100), num('spacing', '字距(px)', 2, 0, 30)], async run({ values: v }) {
  assert(v.path.length <= 8000 && /^[MmZzLlHhVvCcSsQqTtAa\s\d.,eE+-]+$/.test(v.path), 'SVG路径字符无效。'); let path; try { path = new svgPathProperties(v.path); } catch { throw new Error('SVG路径语法无效。'); }
  const length = path.getTotalLength(); assert(length > 0 && length <= 10000, '路径长度须在0–10000之间。'); assert([...v.content].length <= 200, '最多200字符。');
  const ctx = canvas(1, 1).getContext('2d'); ctx.font = `${v.size}px sans-serif`; const advances = [...v.content].map((c) => ctx.measureText(c).width + v.spacing); assert(advances.reduce((a, b) => a + b, 0) <= length, '文字宽度超过路径,请减少内容或字号。');
  let distance = 0; const placements = [], body = [...v.content].map((c, i) => { const advance = advances[i], center = distance + advance / 2, p = path.getPointAtLength(center), tangent = path.getTangentAtLength(center), angle = Math.atan2(tangent.y, tangent.x) * 180 / Math.PI; distance += advance; assert(Number.isFinite(p.x) && Number.isFinite(p.y) && p.x >= v.size && p.x <= 800 - v.size && p.y >= v.size && p.y <= 400 - v.size, '排字位置超出800×400画布安全边界,请调整路径。'); placements.push({ character: c, distance: center, x: p.x, y: p.y, angle }); return `<text transform="translate(${p.x} ${p.y}) rotate(${angle})" text-anchor="middle" font-family="sans-serif" font-size="${v.size}" fill="#167d68">${esc(c)}</text>`; }).join('');
  return [...await svgResults(svgDoc(`<path d="${esc(v.path)}" fill="none" stroke="#c6d8d1"/>${body}`, 800, 400, '沿路径排字'), 'text-path'), json({ length, placements }, 'placements.json')];
} }))();
export const text_outline = /*#__PURE__*/ (() => ({ fields: [content(), size(), color('fill', '填充色', '#167d68')], async run({ files, values: v }) {
  const font = await readFont(files), path = pathFor(font, v.content, 0, 0, v.size), box = path.getBoundingBox(), w = Math.ceil(box.x2 - box.x1 + 40), h = Math.ceil(box.y2 - box.y1 + 40);
  assert(w > 40 && h > 40 && w <= 4096 && h <= 4096, '轮廓为空或超过4096px,请减少文字和字号。');
  return [...await svgResults(svgDoc(`<path transform="translate(${20 - box.x1} ${20 - box.y1})" d="${pathData(path)}" fill="${v.fill}"/>`, w, h, v.content), 'text-outline'), json({ family: nameOf(font), text: v.content, size: v.size, advance: font.getAdvanceWidth(v.content, v.size), bounds: box }, 'outline-metrics.json')];
} }))();
export const font_subset = /*#__PURE__*/ (() => ({ fields: [text('content', '保留字符(最多256种)', 'ABC 123', true)], async run({ files, values: v }) {
  const { default: opentype } = await import('opentype.js');
  const font = await readFont(files), chars = [...new Set(v.content)]; verifyText(font, chars.join(''), 256);
  const flags = font.tables.os2?.fsType || 0; assert(!(flags & (0x2 | 0x100 | 0x200)), '此字体标记了嵌入或子集限制,无法导出子集。');
  const clone = (original, unicode, name) => { const path = new opentype.Path(); path.commands = original.path.commands.map((c) => ({ ...c })); return new opentype.Glyph({ name, unicode, advanceWidth: original.advanceWidth, path }); };
  const glyphs = [clone(font.glyphs.get(0), undefined, '.notdef'), ...chars.map((c) => clone(font.charToGlyph(c), c.codePointAt(0), `uni${c.codePointAt(0).toString(16).toUpperCase()}`))];
  const subset = new opentype.Font({ familyName: `${nameOf(font)} Subset`, styleName: 'Regular', unitsPerEm: font.unitsPerEm, ascender: font.ascender, descender: font.descender, glyphs });
  // Retain license/copyright records supplied by the source, while keeping new family names.
  for (const platform of ['unicode', 'windows', 'macintosh']) for (const key of ['copyright', 'license', 'licenseURL', 'trademark', 'manufacturer', 'designer']) if (font.names[platform]?.[key]) { subset.names[platform] ||= {}; subset.names[platform][key] = { ...font.names[platform][key] }; }
  return [file(new Blob([subset.toArrayBuffer()], { type: 'font/otf' }), 'subset.otf'), json({ source: nameOf(font), sourceNames: font.names, characters: chars, glyphs: glyphs.length, retained: '普通轮廓、字符映射和前进宽度', omitted: ['kerning', '高级排版', '可变轴', 'hinting', '彩色字形'], embeddingFlags: flags }, 'subset-report.json')];
} }))();
export const unicode_inspect = /*#__PURE__*/ (() => ({ fields: [text('content', '检查文字', 'A中👩‍💻 é\u200b', true)], async run({ values: v }) {
  assert([...v.content].length <= 2000, '最多2000个码点。'); const characters = [...v.content].map((character) => ({ character, codePoint: 'U+' + character.codePointAt(0).toString(16).toUpperCase().padStart(4, '0'), utf16Units: character.length, category: /\p{Cf}|\p{Cc}/u.test(character) ? '控制或格式字符' : /\p{M}/u.test(character) ? '组合标记' : /\s/u.test(character) ? '空白' : '可见字符' }));
  const segments = [...new Intl.Segmenter('zh', { granularity: 'grapheme' }).segment(v.content)].map(({ segment, index }) => ({ segment, index }));
  return [json({ utf16Length: v.content.length, codePoints: characters.length, graphemes: segments.length, nfc: v.content.normalize('NFC'), nfkc: v.content.normalize('NFKC'), characters, segments }, 'unicode.json'), plain(characters.map((c) => `${c.codePoint}\t${c.category}\t${JSON.stringify(c.character)}`).join('\n'), 'codepoints.txt')];
} }))();