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

ROOT="${1:-/home/itahukamedia/public_html/studio.itahukamedia.com/public}"
JS="$ROOT/assets/js/modules/coproducer.inline-main.js"
TS="$(date +%Y%m%d_%H%M%S)"

cp -a "$JS" "$JS.bak.$TS"
echo "Backup created: $JS.bak.$TS"

# 1) Fix TrackSubscribed using undefined p -> participant
perl -0pi -e '
s/findSlotByUid\(uid\) \|\| allocateSlotForUser\(\{ uid, name: \(p\?\.name \|\| p\?\.identity \|\| uid\) \}\)/findSlotByUid(uid) || allocateSlotForUser({ uid, name: (participant?.name || participant?.identity || uid) })/g;
' "$JS"

# 2) Repair the corrupted toggleCamPreview / toggleMicMonitor block
perl -0pi -e '
s/function toggleMicMonitor\(idx\)\{\n\s*if \(!s\.connected\) return;\n\s*s\.camPreview = !s\.camPreview;\n\s*renderUI\(\);\n\s*\}\n\s*\n\s*function toggleMicMonitor\(idx\)\{/function toggleCamPreview(idx){\n  const s = slots[idx];\n  if (!s || !s.connected) return;\n  s.camPreview = !s.camPreview;\n  renderUI();\n}\n\nfunction toggleMicMonitor(idx){/s;
' "$JS"

echo
echo "Verify repaired sections:"
grep -n "allocateSlotForUser({ uid, name: (participant?.name || participant?.identity || uid) })" "$JS" || true
grep -n "function toggleCamPreview" "$JS" || true
grep -n "function toggleMicMonitor" "$JS" || true

echo
echo "Show repaired area:"
sed -n '1476,1505p' "$JS"
echo
sed -n '2578,2605p' "$JS"
