// Insert FM state vars + getFileIcon before initFileManager
const fs = require('fs');
const f  = 'E:/Deployment/public/js/app.js';
let src  = fs.readFileSync(f, 'utf8').replace(/\r\n/g, '\n');

// The anchor is: the FM comment line immediately followed by "  function initFileManager()"
// We replace just the "  function initFileManager() {" opening with the vars + icon fn + opening
const anchor = '\n  function initFileManager() {';
const idx = src.indexOf(anchor);
if (idx === -1) { console.error('Anchor not found!'); process.exit(1); }

const INSERT = `

  let fmItems  = [];
  let fmSort   = { col: 'name', dir: 'asc' };
  let fmCtxItem = null;

  function getFileIcon(name, isDir) {
    if (isDir) return '<i class="fa-solid fa-folder fmi-dir"></i>';
    const ext = (name.split('.').pop() || '').toLowerCase();
    const map = {
      js:'fa-brands fa-js fmi-js',       ts:'fa-solid fa-code fmi-ts',
      html:'fa-brands fa-html5 fmi-html', htm:'fa-brands fa-html5 fmi-html',
      css:'fa-brands fa-css3-alt fmi-css', scss:'fa-brands fa-css3-alt fmi-css',
      json:'fa-solid fa-code fmi-json',   xml:'fa-solid fa-code fmi-xml',
      md:'fa-solid fa-file-lines fmi-md', txt:'fa-solid fa-file-lines fmi-txt',
      log:'fa-solid fa-file-lines fmi-txt', csv:'fa-solid fa-file-lines fmi-txt',
      jpg:'fa-solid fa-file-image fmi-img', jpeg:'fa-solid fa-file-image fmi-img',
      png:'fa-solid fa-file-image fmi-img', gif:'fa-solid fa-file-image fmi-img',
      svg:'fa-solid fa-bezier-curve fmi-img', webp:'fa-solid fa-file-image fmi-img',
      ico:'fa-solid fa-file-image fmi-img',
      pdf:'fa-solid fa-file-pdf fmi-pdf',
      zip:'fa-solid fa-file-zipper fmi-zip', rar:'fa-solid fa-file-zipper fmi-zip',
      '7z':'fa-solid fa-file-zipper fmi-zip', gz:'fa-solid fa-file-zipper fmi-zip',
      sql:'fa-solid fa-database fmi-db',   db:'fa-solid fa-database fmi-db',
      cs:'fa-solid fa-code fmi-ts',        py:'fa-brands fa-python fmi-py',
      java:'fa-brands fa-java fmi-php',    php:'fa-brands fa-php fmi-php',
      dll:'fa-solid fa-microchip fmi-dll', exe:'fa-solid fa-terminal fmi-exe',
      ps1:'fa-brands fa-windows fmi-ps',   bat:'fa-solid fa-terminal fmi-bat',
      sh:'fa-solid fa-terminal fmi-sh',    config:'fa-solid fa-gear fmi-cfg',
      cfg:'fa-solid fa-gear fmi-cfg',      ini:'fa-solid fa-gear fmi-cfg',
      env:'fa-solid fa-gear fmi-cfg',      cshtml:'fa-brands fa-html5 fmi-html',
    };
    return \`<i class="\${map[ext] || 'fa-solid fa-file fmi-default'}"></i>\`;
  }`;

src = src.slice(0, idx) + INSERT + anchor + src.slice(idx + anchor.length);
fs.writeFileSync(f, src.replace(/\n/g, '\r\n'), 'utf8');
console.log('Done — state vars + getFileIcon inserted before initFileManager');
