// Weapon Swap Indicator - D2RMM smart patch
// Faithfully implements the verified clean data mod without replacing vanilla hudpanelhd.json or sounds.txt wholesale.

var PANEL_NAME = 'weaponswapindicator';
var TIMER_NAME = 'WeaponSwapIndicator_Open';

function toByteText(value, fallback, label) {
  var raw = value;
  if (raw === undefined || raw === null || String(raw).trim() === '') {
    console.log(label + ' is empty. Using default ' + fallback + '.');
    return String(fallback);
  }

  var num = Number(String(raw).trim());
  if (!isFinite(num)) {
    console.log(label + ' is not a number: ' + raw + '. Using default ' + fallback + '.');
    return String(fallback);
  }

  num = Math.round(num);
  if (num < 0) {
    console.log(label + ' is below 0. Clamped to 0.');
    num = 0;
  }
  if (num > 255) {
    console.log(label + ' is above 255. Clamped to 255.');
    num = 255;
  }
  return String(num);
}

// 1) Add non-vanilla assets/layouts by copying them from this mod folder.
// Do not readJson() the new layout file; it does not exist in vanilla and reading it would cause a file-not-found warning.
D2RMM.copyFile('global\\ui\\layouts\\weaponswapindicatorhd.json', 'global\\ui\\layouts\\weaponswapindicatorhd.json', true);

var frontPanelSpriteType = config.frontPanelSpriteType === 'armband' ? 'armband' : 'full';
var frontPanelSpritePrefix = 'hd\\global\\ui\\panel\\hud_02\\front_panel_' + frontPanelSpriteType + '_';
var frontPanelSpriteDestPrefix = 'hd\\global\\ui\\panel\\hud_02\\front_panel_';

D2RMM.copyFile(frontPanelSpritePrefix + 'left.sprite', frontPanelSpriteDestPrefix + 'left.sprite', true);
D2RMM.copyFile(frontPanelSpritePrefix + 'left.lowend.sprite', frontPanelSpriteDestPrefix + 'left.lowend.sprite', true);
D2RMM.copyFile(frontPanelSpritePrefix + 'right.sprite', frontPanelSpriteDestPrefix + 'right.sprite', true);
D2RMM.copyFile(frontPanelSpritePrefix + 'right.lowend.sprite', frontPanelSpriteDestPrefix + 'right.lowend.sprite', true);

// 2) Smart-patch vanilla hudpanelhd.json.
var hudPath = 'global\\ui\\layouts\\hudpanelhd.json';
var hud = D2RMM.readJson(hudPath);

if (!hud.fields) {
  hud.fields = {};
}

// Match the verified clean data mod so the overlay panel is drawn over the front HUD panel.
hud.fields.priority = -2;

if (!hud.children) {
  hud.children = [];
}

// Prevent duplicate timers on re-install.
var cleanedChildren = [];
for (var i = 0; i < hud.children.length; i++) {
  var child = hud.children[i];
  var msg = child && child.fields ? child.fields.message : '';
  var name = child ? child.name : '';

  if (name === TIMER_NAME) {
    continue;
  }
  if (msg === 'PanelManager:OpenPanel:' + PANEL_NAME) {
    continue;
  }

  cleanedChildren.push(child);
}
hud.children = cleanedChildren;

hud.children.push({
  type: 'TimerWidget',
  name: TIMER_NAME,
  fields: {
    time: 0,
    message: 'PanelManager:OpenPanel:' + PANEL_NAME
  }
});

D2RMM.writeJson(hudPath, hud);

// 3) Optional smart-patch for weapon swap sound.
// OFF means: do not copy the replacement FLAC and do not modify sounds.txt, so vanilla behavior is preserved.
if (config.enableSwapSound) {
  D2RMM.copyFile('hd\\global\\sfx\\cursor\\cursor_swap_weapon_hd.flac', 'hd\\global\\sfx\\cursor\\cursor_swap_weapon_hd.flac', true);

  var volumeMin = toByteText(config.swapSoundVolumeMin, 100, '무기스왑음 최소볼륨');
  var volumeMax = toByteText(config.swapSoundVolumeMax, 100, '무기스왑음 최대볼륨');
  var priority = toByteText(config.swapSoundPriority, 255, '무기스왑음 우선순위');

  var soundsPath = 'global\\excel\\sounds.txt';
  var sounds = D2RMM.readTsv(soundsPath, { removeCarriageReturns: true });
  var foundSwapSound = false;

  for (var r = 0; r < sounds.rows.length; r++) {
    var row = sounds.rows[r];
    if (row.Sound === 'cursor_swap_weapon_hd') {
      row.FileName = 'cursor\\cursor_swap_weapon_hd.flac';
      row['Volume Min'] = volumeMin;
      row['Volume Max'] = volumeMax;
      row['Fade In'] = '0';
      row['Fade Out'] = '0';
      row.Priority = priority;
      foundSwapSound = true;
      break;
    }
  }

  if (!foundSwapSound) {
    throw new Error('cursor_swap_weapon_hd row was not found in global\\excel\\sounds.txt');
  }

  D2RMM.writeTsv(soundsPath, sounds, { addCarriageReturns: true });
}
