/* One-shot: đổi emoji trong help.js + feature-guide.js sang galaxy icon.
 * - Trong template backtick (HTML body): emoji -> ${giHTML("name")} (render qua innerHTML/sanitize, SVG sống).
 * - Ngoài template: field emoji:/icon: -> tên; nhãn title/label/sub/text/= "<emoji> ..." -> bỏ emoji dẫn đầu.
 * Điểm tiêu thụ field emoji/icon (text: X.emoji) sửa TAY sau. */
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));

const MAP = {
  '🃏':'cards','🎴':'cards','💬':'chat','💡':'bulb','🎓':'cap','⚡':'bolt','🗺':'map','🧠':'brain',
  '📋':'clipboard','🤖':'robot','📚':'stack','🏆':'trophy','👉':'pointer','📦':'box','✓':'check','✅':'check',
  '🔍':'search','🚀':'rocket','📄':'file','✏':'edit','🖊':'edit','🖋':'edit','🗑':'trash','☕':'coffee',
  '📝':'card','🔗':'link','🛠':'tools','🎮':'gamepad','📥':'download','★':'star','☆':'star','❓':'target',
  '🎯':'target','🔒':'lock','⭐':'star','✕':'x','✗':'x','🌟':'star','💀':'alert','🔥':'flame','🕐':'clock','⏱':'clock',
};
const EMO = /[\u{1F000}-\u{1FAFF}\u{2600}-\u{27BF}\u{2B00}-\u{2BFF}←-⇿⭐✅✓✗✕❤]️?/gu;
const nameFor = (ch) => MAP[ch.replace(/️/g,'')] || null;

function convertTemplates(seg) {              // inside a backtick template -> ${giHTML(...)}
  return seg.replace(EMO, (m) => { const n = nameFor(m); return n ? '${giHTML("' + n + '")}' : m; });
}
function convertOutside(seg) {
  // field emoji:/icon: "X" -> "name"
  seg = seg.replace(/((?:emoji|icon)\s*:\s*)(["'])([^"']*)\2/g, (full, pre, q, val) => {
    const only = val.replace(EMO, '').trim();
    const m = val.match(EMO);
    if (m && only === '') { const n = nameFor(m[0]); if (n) return pre + q + n + q; }
    return full;
  });
  // strip leading emoji in labels: (title|label|sub|text): "<emoji> rest"  and  = "<emoji> rest"
  seg = seg.replace(/((?:title|label|sub|text)\s*:\s*["'`]|=\s*["'`])\s*([\u{1F000}-\u{1FAFF}\u{2600}-\u{27BF}⭐✅✓]️?)\s*/gu, '$1');
  // any remaining outside emoji -> drop (with count)
  return seg;
}

for (const rel of ['src/hub/help.js', 'src/hub/feature-guide.js']) {
  const p = path.join(__dirname, '..', rel);
  let t = fs.readFileSync(p, 'utf8');
  // add import once (after the ../i18n require line)
  if (!t.includes('styles/gicon')) {
    t = t.replace(/(const\s*\{[^}]*\}\s*=\s*require\(["']\.\.\/i18n["']\);\n)/,
      '$1const { giHTML } = require("../styles/gicon");\n');
  }
  // split by backtick; odd indices are INSIDE templates (assumes no nested backticks)
  const parts = t.split('`');
  const out = parts.map((seg, i) => (i % 2 === 1 ? convertTemplates(seg) : convertOutside(seg)));
  t = out.join('`');
  // report leftover outside emoji
  const leftover = (t.split('`').filter((_, i) => i % 2 === 0).join('').match(EMO) || []).length;
  fs.writeFileSync(p, t);
  console.log(rel, '-> written; outside-leftover emoji:', leftover);
}
