import fs from 'fs';

const roomPath = 'C:/X/workspace/jumpa.id/vc/components/xcuRoom.tsx';
let roomContent = fs.readFileSync(roomPath, 'utf-8');

// 1. Fix the TypeError (Crash)
roomContent = roomContent.replace(
    /\$\{autoPilotMetrics\.bw\.toFixed\(1\)\}/g,
    `\${Number(autoPilotMetrics.bw || 0).toFixed(1)}`
);

// 2. Fix the Handlers to support cycling to 'auto'
const oldHandlers = `    const handleToggleAudioEngine = () => {
      const newMode = audioEngineMode === 'xcu-neural' ? 'pcm' : 'xcu-neural';
      setAudioEngineMode(newMode);
      if (matrixRef.current) {
          matrixRef.current.hotSwapAudioEngine(newMode);
          alert(newMode === 'xcu-neural' ? '🔊 XCU Neural Audio AKTIF! (VAD & Zero Bandwidth).' : '⚠️ Raw PCM Audio Aktif. Peringatan: Konsumsi Bandwidth Tinggi.');
      }
  };
  const handleToggleEngine = () => {
      const newMode = videoEngineMode === 'webcodecs' ? 'canvas' : 'webcodecs';
      setVideoEngineMode(newMode);
      if (matrixRef.current) {
          matrixRef.current.hotSwapVideoEngine(newMode);
          alert(newMode === 'webcodecs' ? '🚀 XCU Quantum WebCodecs (Hardware GPU Acceleration) AKTIF! Latensi dinolkan.' : '⚠️ Mode Kompatibilitas Canvas Aktif. Peringatan: Latensi 1-2 detik.');
      }
  };`;

const newHandlers = `    const handleToggleAudioEngine = () => {
      const newMode = audioEngineMode === 'auto' ? 'xcu-neural' : (audioEngineMode === 'xcu-neural' ? 'pcm' : 'auto');
      setAudioEngineMode(newMode);
      if (matrixRef.current) {
          matrixRef.current.hotSwapAudioEngine(newMode);
      }
  };
  const handleToggleEngine = () => {
      const newMode = videoEngineMode === 'auto' ? 'webcodecs' : (videoEngineMode === 'webcodecs' ? 'canvas' : 'auto');
      setVideoEngineMode(newMode);
      if (matrixRef.current) {
          matrixRef.current.hotSwapVideoEngine(newMode);
      }
  };`;

// Safe replace
roomContent = roomContent.replace(oldHandlers, newHandlers);

fs.writeFileSync(roomPath, roomContent, 'utf-8');
console.log("Crash resolved and handlers fixed.");
