// PumpingStation editor — oneditsave handler. Validates, saves shared
// menu sections (logger/position), then persists pumpingStation-specific
// fields onto the node. Throws if validation fails to keep the editor open.

(function () {
  const ns = window.PSEditor = window.PSEditor || {};

  const parseNum = (id) => parseFloat(document.getElementById(id)?.value);

  ns.oneditsave = function () {
    const node = this;

    // Block save if EITHER validator surfaced any issues. basin-diagram
    // owns hierarchy issues (start ≤ inlet ≤ max ≤ overflow ≤ basinHeight,
    // dryRun < start). mode-preview owns shift-specific issues.
    const basinIssues = window._psBasinValidationIssues || [];
    const modeIssues  = window._psModeValidationIssues  || [];
    const issues = [...basinIssues, ...modeIssues];
    if (issues.length) {
      if (typeof RED !== 'undefined' && RED.notify) {
        RED.notify('PumpingStation config invalid:<br>• ' + issues.join('<br>• '),
          { type: 'error', timeout: 6000 });
      }
      throw new Error('PumpingStation: invalid config — ' + issues.join('; '));
    }

    window.EVOLV?.nodes?.pumpingStation?.loggerMenu?.saveEditor?.(node);
    window.EVOLV?.nodes?.pumpingStation?.positionMenu?.saveEditor?.(node);

    node.refHeight = document.getElementById('node-input-refHeight').value || 'NAP';
    node.simulator = document.getElementById('node-input-simulator').checked;

    [
      'basinVolume', 'basinHeight', 'inflowLevel', 'outflowLevel', 'overflowLevel',
      'basinBottomRef',
      'dryRunThresholdPercent', 'highVolumeSafetyThresholdPercent',
    ].forEach((field) => {
      const el = document.getElementById(`node-input-${field}`);
      if (el) node[field] = parseFloat(el.value) || 0;
    });

    node.enableDryRunProtection = document.getElementById('node-input-enableDryRunProtection').checked;
    node.enableHighVolumeSafety = document.getElementById('node-input-enableHighVolumeSafety').checked;
    // Deprecated aliases kept for existing runtime/schema compatibility.
    node.enableOverfillProtection = node.enableHighVolumeSafety;
    node.overfillThresholdPercent = node.highVolumeSafetyThresholdPercent;

    node.controlMode = document.getElementById('node-input-controlMode').value || 'levelbased';
    node.levelCurveType = document.getElementById('node-input-levelCurveType')?.value || 'linear';
    node.logCurveFactor = parseNum('node-input-logCurveFactor');
    node.startLevel = parseNum('node-input-startLevel');
    node.maxLevel = parseNum('node-input-maxLevel');
    // Persist as numbers — Node-RED's auto-form-binding would store these as
    // strings, and oneditprepare's setNumberField rejects non-Number values,
    // so the input would blank out on reopen.
    const stopLevelVal = parseNum('node-input-stopLevel');
    node.stopLevel = Number.isFinite(stopLevelVal) ? stopLevelVal : null;
    const holdLevelVal = parseNum('node-input-holdLevel');
    if (Number.isFinite(holdLevelVal)) node.holdLevel = holdLevelVal;
    const deadZoneVal = parseNum('node-input-deadZoneKeepAlivePercent');
    if (Number.isFinite(deadZoneVal)) node.deadZoneKeepAlivePercent = deadZoneVal;
    // minLevel is no longer a user input — it's the derived dryRunLevel
    // (outflowLevel × (1 + dryRunThresholdPercent/100)). The runtime still
    // uses node.minLevel as the unconditional STOP threshold; we set it
    // here so that semantic survives the UI change.
    const _dryRun = ns.deriveDryRunLevel?.();
    if (Number.isFinite(_dryRun)) node.minLevel = _dryRun;
    node.enableShiftedRamp = !!document.getElementById('node-input-enableShiftedRamp')?.checked;
    const shiftLevelVal = parseNum('node-input-shiftLevel');
    node.shiftLevel = Number.isFinite(shiftLevelVal) ? shiftLevelVal : 0;
    const armPctVal = parseNum('node-input-shiftArmPercent');
    node.shiftArmPercent = Number.isFinite(armPctVal) ? armPctVal : 95;
    const flowSetpoint = parseNum('node-input-flowSetpoint');
    const flowDeadband = parseNum('node-input-flowDeadband');
    if (Number.isFinite(flowSetpoint)) node.flowSetpoint = flowSetpoint;
    if (Number.isFinite(flowDeadband)) node.flowDeadband = flowDeadband;
  };
})();
