class LoggerMenu {
  constructor() {
    // no external data files for logger – all static
  }

  // 1) Server‐side: return the static menuData
  getAllMenuData() {
    return {
      logLevels: [
        { value: 'error', label: 'Error', description: 'Only error messages' },
        { value: 'warn',  label: 'Warn',  description: 'Warning and error messages' },
        { value: 'info',  label: 'Info',  description: 'Info, warning and error messages' },
        { value: 'debug', label: 'Debug', description: 'All messages including debug' }
      ]
    };
  }

  // 2) Client‐side: inject the dropdown options
  getDataInjectionCode(nodeName) {
    return `
      // Logger data loader for ${nodeName}
      window.EVOLV.nodes.${nodeName}.loggerMenu.loadData = function(node) {
        const data = window.EVOLV.nodes.${nodeName}.menuData.logger;
        const sel  = document.getElementById('node-input-logLevel');
        if (!sel) return;
        sel.innerHTML = '';
        data.logLevels.forEach(l => {
          const opt = document.createElement('option');
          opt.value = l.value;
          opt.textContent = l.label;
          opt.title = l.description;
          sel.appendChild(opt);
        });
        sel.value = node.logLevel || 'info';
      };
    `;
  }

getHtmlInjectionCode(nodeName) {
  const tpl = `
  <h3>Internal logging</h3>
    <div class="form-row">
      <label for="node-input-enableLog"><i class="fa fa-bug"></i>Logging</label>
      <input type="checkbox" id="node-input-enableLog"/>
    </div>
    <div class="form-row" id="row-logLevel">
      <label for="node-input-logLevel"><i class="fa fa-list"></i> Log Level</label>
      <select id="node-input-logLevel" style="width:60%;"></select>
    </div>
  `.replace(/`/g,'\\`').replace(/\$/g,'\\$');

  return `
    // Logger HTML injection for ${nodeName}
    window.EVOLV.nodes.${nodeName}.loggerMenu.injectHtml = function() {
      const ph = document.getElementById('logger-fields-placeholder');
      if (ph && !ph.hasChildNodes()) {
        ph.innerHTML = \`${tpl}\`;
      }
    };
  `;
}

  // 3) Client‐side: wire up the enable‐toggle behavior
  getEventInjectionCode(nodeName) {
    return `
      // Logger event wiring for ${nodeName}
      window.EVOLV.nodes.${nodeName}.loggerMenu.wireEvents = function(node) {
        const chk = document.getElementById('node-input-enableLog');
        const row = document.getElementById('row-logLevel');
        if (!chk || !row) return;
        const toggle = () => {
          row.style.display = chk.checked ? 'block' : 'none';
        };
        chk.checked = node.enableLog || false;
        toggle();
        chk.addEventListener('change', toggle);
      };
    `;
  }

  // 4) Client‐side: save logic
  getSaveInjectionCode(nodeName) {
    return `
      // Logger Save injection for ${nodeName}
      window.EVOLV.nodes.${nodeName}.loggerMenu.saveEditor = function(node) {
        console.log('Saving logger properties for ${nodeName}…');
        const chk = document.getElementById('node-input-enableLog');
        const sel = document.getElementById('node-input-logLevel');
        node.enableLog = chk ? chk.checked : false;
        node.logLevel  = sel ? sel.value : 'info';
        const errors = [];
        if (node.enableLog && !node.logLevel) {
          errors.push('Log level must be selected when logging is enabled.');
        }
        errors.forEach(e => RED.notify(e,'error'));
        // --- DEBUG: what was saved ---
        console.log('→ loggerMenu.saveEditor result:', {
          enableLog: node.enableLog,
          logLevel: node.logLevel
        });
        return errors.length === 0;
      };
    `;
  }

  // 5) Client-side: upgrade native controls to icon cards.
  //
  // Runs after wireEvents (which has already hooked the checkbox + select).
  // Adds a small toggle card next to the native checkbox and a 4-icon
  // picker row next to the native select; the natives are then hidden.
  getVisualInjectionCode(nodeName) {
    return `
      // Logger visual upgrade for ${nodeName}
      window.EVOLV.nodes.${nodeName}.loggerMenu.initVisuals = function(node) {
        const helpers = window.EVOLV && window.EVOLV.iconHelpers;
        if (!helpers) return;

        // --- Log toggle (replaces native checkbox + label) ----------
        const checkbox = document.getElementById('node-input-enableLog');
        if (checkbox) {
          const row = checkbox.closest('.form-row');
          if (row && !document.getElementById('evolv-log-toggle-' + node.id)) {
            row.classList.add('evolv-native-row-compact');
            const holder = document.createElement('div');
            holder.id = 'evolv-log-toggle-' + node.id;
            holder.className = 'evolv-icon-option evolv-log-toggle';
            holder.setAttribute('role', 'switch');
            holder.setAttribute('tabindex', '0');
            holder.setAttribute('aria-label', 'Logging');
            holder.setAttribute('aria-checked', 'false');
            holder.setAttribute('title', 'Logging');
            row.appendChild(holder);
            helpers.renderToggle(checkbox, holder, helpers.SVG.logToggle, { on: 'Log', off: 'Off' });
          }
        }

        // --- Log-level picker (replaces native select) --------------
        const select = document.getElementById('node-input-logLevel');
        if (select) {
          const row = document.getElementById('row-logLevel');
          if (row && !document.getElementById('evolv-log-level-picker-' + node.id)) {
            row.classList.add('evolv-native-row-compact');
            const holder = document.createElement('div');
            holder.id = 'evolv-log-level-picker-' + node.id;
            holder.className = 'evolv-icon-picker';
            holder.setAttribute('role', 'radiogroup');
            holder.setAttribute('aria-label', 'Log level');
            row.appendChild(holder);
            helpers.renderSelectPicker(
              select,
              holder,
              { error: helpers.SVG.error, warn: helpers.SVG.warn, info: helpers.SVG.info, debug: helpers.SVG.debug },
              { error: 'Error', warn: 'Warn', info: 'Info', debug: 'Debug' }
            );
          }
        }
      };
    `;
  }

  // 6) Compose everything into one client‐side payload
  getClientInitCode(nodeName) {
    const dataCode    = this.getDataInjectionCode(nodeName);
    const eventCode   = this.getEventInjectionCode(nodeName);
    const saveCode    = this.getSaveInjectionCode(nodeName);
    const htmlCode    = this.getHtmlInjectionCode(nodeName);
    const visualCode  = this.getVisualInjectionCode(nodeName);

    return `
      // --- LoggerMenu for ${nodeName} ---
      window.EVOLV.nodes.${nodeName}.loggerMenu =
        window.EVOLV.nodes.${nodeName}.loggerMenu || {};

      ${htmlCode}
      ${dataCode}
      ${eventCode}
      ${saveCode}
      ${visualCode}

      // oneditprepare calls this. Visual upgrade runs last so the natives
      // are already populated + wired.
      window.EVOLV.nodes.${nodeName}.loggerMenu.initEditor = function(node) {
      // ------------------  BELOW sequence is important! -------------------------------
        this.injectHtml();
        this.loadData(node);
        this.wireEvents(node);
        if (this.initVisuals) this.initVisuals(node);
      };
    `;
  }
}

module.exports = LoggerMenu;