#!/usr/bin/env bash
set -euo pipefail

FILE="assets/js/modules/coproducer.inline-main.js"
BACKUP="${FILE}.bak_master_cleanup_$(date +%Y%m%d_%H%M%S)"

cp -p "$FILE" "$BACKUP"

# Remove old master runtime patches V1 and V2 completely, keep V3 only
perl -0pi -e 's@/\* __masterMixerRuntimePatchV1.*?\n\)\(\);\n@@sg' "$FILE"
perl -0pi -e 's@/\* __masterMixerRuntimePatchV2.*?\n\)\(\);\n@@sg' "$FILE"

# Add duplicate cleanup + row alignment helper once
if ! grep -q '__masterMixerCleanupAndAlignV1' "$FILE"; then
cat >> "$FILE" <<'JS'

/* __masterMixerCleanupAndAlignV1
   - remove any non-strip/custom duplicate MASTER widgets
   - keep only the real strip in #stripRow
   - squeeze/alignment for all strips on one row
*/
(function(){
  if (window.__masterMixerCleanupAndAlignV1) return;
  window.__masterMixerCleanupAndAlignV1 = true;

  function ensureAlignCss(){
    if (document.getElementById('__masterMixerAlignCssV1')) return;
    var st = document.createElement('style');
    st.id = '__masterMixerAlignCssV1';
    st.textContent = [
      '.mixerWrap{overflow-x:auto; overflow-y:hidden;}',
      '#stripRow{display:flex !important; flex-wrap:nowrap !important; align-items:stretch !important; gap:8px !important;}',
      '#stripRow > .strip{flex:1 1 0 !important; min-width:0 !important; width:auto !important;}',
      '#stripRow > .strip[data-master-strip="1"]{flex:1 1 0 !important; min-width:0 !important;}'
    ].join('\n');
    document.head.appendChild(st);
  }

  function removeCustomMasterDuplicates(){
    // remove older custom master widgets that are NOT real .strip children of #stripRow
    document.querySelectorAll('[data-ch="master"], .mixerStrip--master, .ch[data-ch="master"]').forEach(function(el){
      if (el.closest && el.closest('#stripRow') && el.classList.contains('strip')) return;
      try { el.remove(); } catch(_){}
    });

    // if more than one master strip exists in stripRow, keep the last one
    var row = document.getElementById('stripRow');
    if (!row) return;

    var masters = row.querySelectorAll('.strip[data-master-strip="1"], .strip#st-master');
    if (masters.length <= 1) return;

    for (var i = 0; i < masters.length - 1; i++) {
      try { masters[i].remove(); } catch(_){}
    }
  }

  function run(){
    ensureAlignCss();
    removeCustomMasterDuplicates();
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', run, { once:true });
  } else {
    run();
  }

  var tries = 0;
  var t = setInterval(function(){
    run();
    tries++;
    if (tries > 120) clearInterval(t);
  }, 500);
})();
JS
fi

echo "Backup: $BACKUP"
echo
echo "Verification:"
grep -n '__masterMixerRuntimePatchV3\|__masterMixerCleanupAndAlignV1\|__masterMixerRuntimePatchV1\|__masterMixerRuntimePatchV2' "$FILE" || true
