File size: 20,483 Bytes
35ee466
 
 
 
7f2a14a
1476e59
7f2a14a
 
62cb269
1476e59
35ee466
1476e59
 
35ee466
1476e59
848947d
7da7877
62cb269
7da7877
35ee466
 
 
 
 
 
848947d
7f2a14a
 
7da7877
35ee466
7da7877
35ee466
 
 
 
 
7f2a14a
a28e1ed
35ee466
62cb269
 
35ee466
1476e59
7da7877
 
35ee466
 
 
 
1476e59
a28e1ed
35ee466
a28e1ed
35ee466
 
a28e1ed
35ee466
7da7877
35ee466
a28e1ed
7da7877
1476e59
 
35ee466
1476e59
7da7877
1476e59
35ee466
 
a28e1ed
1476e59
 
 
 
a28e1ed
 
7da7877
1476e59
35ee466
7da7877
35ee466
1476e59
35ee466
 
 
62cb269
7da7877
35ee466
 
 
 
 
 
62cb269
1476e59
 
 
35ee466
62cb269
35ee466
 
1476e59
35ee466
 
1476e59
 
35ee466
62cb269
35ee466
 
 
7da7877
35ee466
 
a28e1ed
35ee466
 
a28e1ed
35ee466
a28e1ed
 
 
 
 
 
 
 
1476e59
35ee466
a28e1ed
 
35ee466
 
 
 
a28e1ed
35ee466
 
a28e1ed
35ee466
a28e1ed
 
35ee466
a28e1ed
35ee466
 
7da7877
a28e1ed
35ee466
1476e59
848947d
35ee466
a28e1ed
1476e59
35ee466
62cb269
35ee466
a28e1ed
62cb269
35ee466
 
 
 
a28e1ed
35ee466
7da7877
35ee466
a28e1ed
 
 
 
 
62cb269
35ee466
 
a28e1ed
 
35ee466
 
 
a28e1ed
35ee466
 
a28e1ed
35ee466
 
62cb269
35ee466
a28e1ed
35ee466
62cb269
35ee466
a28e1ed
 
35ee466
 
62cb269
35ee466
a28e1ed
35ee466
a28e1ed
35ee466
 
 
 
 
 
 
 
 
 
 
 
 
 
7da7877
35ee466
 
a28e1ed
35ee466
 
 
 
a28e1ed
35ee466
a28e1ed
35ee466
a28e1ed
 
35ee466
 
 
62cb269
a28e1ed
35ee466
 
 
a28e1ed
35ee466
a28e1ed
35ee466
 
a28e1ed
35ee466
7da7877
1476e59
7da7877
1476e59
a28e1ed
 
 
 
 
35ee466
1476e59
35ee466
a28e1ed
35ee466
 
62cb269
35ee466
 
1476e59
a28e1ed
35ee466
 
 
 
a28e1ed
35ee466
 
 
 
 
 
 
1476e59
35ee466
a28e1ed
1476e59
35ee466
62cb269
35ee466
 
a28e1ed
35ee466
 
 
 
 
 
1476e59
35ee466
 
 
1476e59
 
7da7877
a28e1ed
7da7877
1476e59
7da7877
35ee466
 
a28e1ed
35ee466
 
 
 
62cb269
35ee466
a28e1ed
35ee466
62cb269
35ee466
7da7877
62cb269
7da7877
 
 
35ee466
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7da7877
35ee466
 
 
 
 
7da7877
35ee466
7da7877
 
35ee466
1476e59
35ee466
 
 
 
 
 
 
 
 
 
62cb269
35ee466
 
 
 
 
 
 
 
 
 
 
 
1476e59
35ee466
 
 
7da7877
7f2a14a
1476e59
688a2e9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/**
Copyright 2024 Google LLC
... (Ω„Ψ§ΫŒΨ³Ω†Ψ³ و ΨͺوآیحاΨͺ دیگر Ω…Ψ«Ω„ Ω‚Ψ¨Ω„) ...
*/
import cn from "classnames";
import React, { memo, ReactNode, RefObject, useEffect, useRef, useState } from "react";
import { useLiveAPIContext } from "../../contexts/LiveAPIContext";
import { AudioRecorder } from "../../lib/audio-recorder";
// SVG Icons for Controls (Ω‡Ω…Ψ§Ω†Ψ·ΩˆΨ± Ϊ©Ω‡ Ω‚Ψ¨Ω„Ψ§ Ψͺعریف Ψ΄Ψ―)
const SvgPauseIcon = () => <svg width="37" height="37" viewBox="0 0 37 37" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M15.9872 29.6198V8.28342C15.9872 6.25781 15.132 5.44757 12.9713 5.44757H7.52469C5.36404 5.44757 4.50879 6.25781 4.50879 8.28342V29.6198C4.50879 31.6454 5.36404 32.4556 7.52469 32.4556H12.9713C15.132 32.4556 15.9872 31.6454 15.9872 29.6198Z" fill="#BE123C"/><path opacity="0.4" d="M31.5175 29.6198V8.28342C31.5175 6.25781 30.6622 5.44757 28.5016 5.44757H23.055C20.9093 5.44757 20.0391 6.25781 20.0391 8.28342V29.6198C20.0391 31.6454 20.8943 32.4556 23.055 32.4556H28.5016C30.6622 32.4556 31.5175 31.6454 31.5175 29.6198Z" fill="#BE123C"/></svg>;
const SvgMicrophoneIcon = () => <svg width="38" height="38" viewBox="0 0 69 68" fill="none" xmlns="http://www.w3.org/2000/svg" transform="scale(0.55)"><path opacity="0.4" d="M49.9479 27.1824C49.0803 27.1824 48.3907 27.872 48.3907 28.7396V32.2544C48.3907 40.1293 41.984 46.5361 34.109 46.5361C26.234 46.5361 19.8273 40.1293 19.8273 32.2544V28.7173C19.8273 27.8497 19.1377 27.1601 18.2701 27.1601C17.4025 27.1601 16.7129 27.8497 16.7129 28.7173V32.2321C16.7129 41.2861 23.6758 48.7384 32.5518 49.5393V54.2776C32.5518 55.1452 33.2414 55.8348 34.109 55.8348C34.9766 55.8348 35.6662 55.1452 35.6662 54.2776V49.5393C44.52 48.7607 51.5051 41.2861 51.5051 32.2321V28.7173C51.4829 27.872 50.7933 27.1824 49.9479 27.1824Z" fill="#BE123C"/><path d="M34.1099 11.3434C28.682 11.3434 24.2773 15.7481 24.2773 21.176V32.5658C24.2773 37.9938 28.682 42.3984 34.1099 42.3984C39.5379 42.3984 43.9425 37.9938 43.9425 32.5658V21.176C43.9425 15.7481 39.5379 11.3434 34.1099 11.3434ZM37.0241 26.8042C36.8684 27.3826 36.3567 27.7608 35.7784 27.7608C35.6671 27.7608 35.5559 27.7385 35.4447 27.7163C34.5771 27.4716 33.665 27.4716 32.7974 27.7163C32.0856 27.9165 31.396 27.4938 31.218 26.8042C31.0178 26.1146 31.4404 25.4027 32.1301 25.2247C33.4426 24.8688 34.8218 24.8688 36.1343 25.2247C36.8017 25.4027 37.2021 26.1146 37.0241 26.8042ZM38.2031 22.4885C38.0029 23.0224 37.5135 23.3339 36.9796 23.3339C36.8239 23.3339 36.6904 23.3116 36.5347 23.2671C34.9775 22.6887 33.2423 22.6887 31.6852 23.2671C31.0178 23.5118 30.2614 23.1559 30.0167 22.4885C29.772 21.8212 30.128 21.0648 30.7953 20.8423C32.9309 20.0637 35.289 20.0637 37.4245 20.8423C38.0919 21.087 38.4478 21.8212 38.2031 22.4885Z" fill="#BE123C"/></svg>;
const SvgCameraIcon = () => <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg"><path opacity="0.4" d="M21.8118 5.52235H11.9265C6.29183 5.52235 4.10059 7.7136 4.10059 13.3482V26.5286C4.10059 30.318 6.16002 34.3545 11.9265 34.3545H21.8118C27.4464 34.3545 29.6376 32.1633 29.6376 26.5286V13.3482C29.6376 7.7136 27.4464 5.52235 21.8118 5.52235Z" fill="#2252A0"/><path d="M19.3406 18.9169C21.0512 18.9169 22.438 17.5302 22.438 15.8195C22.438 14.1089 21.0512 12.7222 19.3406 12.7222C17.6299 12.7222 16.2432 14.1089 16.2432 15.8195C16.2432 17.5302 17.6299 18.9169 19.3406 18.9169Z" fill="#2252A0"/><path d="M36.0629 10.3332C35.3874 9.98721 33.9705 9.5918 32.0429 10.9428L29.6045 12.6562C29.621 12.8869 29.6374 13.1011 29.6374 13.3482V26.5286C29.6374 26.7758 29.6045 26.9899 29.6045 27.2206L32.0429 28.934C33.0643 29.659 33.954 29.8896 34.6625 29.8896C35.2721 29.8896 35.7499 29.7249 36.0629 29.5601C36.7384 29.2141 37.8752 28.275 37.8752 25.919V13.9743C37.8752 11.6183 36.7384 10.6792 36.0629 10.3332Z" fill="#2252A0"/></svg>;
const SvgStopCamIcon = () => <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg"><path opacity="0.4" d="M29.0785 10.8076L6.91966 32.9665C4.61316 31.5002 3.70703 28.8807 3.70703 26.36V13.18C3.70703 7.54555 5.89821 5.35437 11.5327 5.35437H21.4177C26.1789 5.35437 28.4854 6.9195 29.0785 10.8076Z" fill="#2252A0"/><path opacity="0.4" d="M29.2427 15.2394V26.36C29.2427 26.4918 29.2262 26.5907 29.2262 26.706C29.2262 26.8213 29.2097 26.9366 29.2097 27.052H29.2262C29.045 32.1757 26.8208 34.1856 21.417 34.1856H11.532C11.1202 34.1856 10.7412 34.1692 10.3623 34.1197L29.2427 15.2394Z" fill="#2252A0"/><path opacity="0.4" d="M29.21 27.052C29.21 26.9366 29.2264 26.8213 29.2264 26.706C29.2429 26.8213 29.2429 26.9366 29.2264 27.052H29.21Z" fill="#2252A0"/><path opacity="0.4" d="M29.2264 12.4716C29.2429 12.5869 29.2429 12.7187 29.2264 12.834C29.2264 12.7187 29.21 12.6034 29.21 12.488L29.2264 12.4716Z" fill="#2252A0"/><path d="M37.4804 13.8061V25.734C37.4804 28.0899 36.3436 29.029 35.6682 29.3749C35.3551 29.5397 34.8774 29.7209 34.2678 29.7209C33.5594 29.7209 32.6697 29.4903 31.6483 28.7654L29.2264 27.052H29.21C29.21 26.9366 29.2264 26.8213 29.2264 26.706C29.2264 26.5907 29.2429 26.4918 29.2429 26.36V15.2394L34.6302 9.85205C35.0751 9.885 35.421 10.0168 35.6682 10.1651C36.3436 10.5111 37.4804 11.4501 37.4804 13.8061Z" fill="#2252A0"/><path d="M35.8666 3.67393C35.3723 3.17968 34.565 3.17968 34.0708 3.67393L3.6744 34.0868C3.18015 34.581 3.18015 35.3883 3.6744 35.8826C3.92152 36.1132 4.23455 36.245 4.56405 36.245C4.89355 36.245 5.20657 36.1132 5.4537 35.8661L35.8666 5.45323C36.3773 4.95898 36.3773 4.16818 35.8666 3.67393Z" fill="#2252A0"/></svg>;
const SvgSwitchCameraIcon = () => <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 19H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h5"/><path d="M13 5h7a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-5"/><path d="m17 12-3-3 3-3"/><path d="m7 12 3 3-3 3"/></svg>;

export type ControlTrayProps = {
  videoRef: RefObject<HTMLVideoElement>;
  children?: ReactNode;
  supportsVideo: boolean;
  onVideoStreamChange: (stream: MediaStream | null) => void;
  isAppMicActive: boolean;
  onAppMicToggle: (active: boolean) => void;
  isAppCamActive: boolean;
  onAppCamToggle: (active: boolean) => void;
  createLogoFunction: (isMini: boolean, isActive: boolean, type?: 'human' | 'ai') => ReactNode;
};

function ControlTray({
  videoRef,
  onVideoStreamChange,
  supportsVideo,
  isAppMicActive,
  onAppMicToggle,
  isAppCamActive,
  onAppCamToggle,
  createLogoFunction,
}: ControlTrayProps) {
  const { client, connected, connect, disconnect } = useLiveAPIContext();
  const [audioRecorder] = useState(() => new AudioRecorder());
  const [muted, setMuted] = useState(true);
  const [inVolume, setInVolume] = useState(0);
  const [activeLocalVideoStream, setActiveLocalVideoStream] = useState<MediaStream | null>(null);
  const [currentFacingMode, setCurrentFacingMode] = useState<'user' | 'environment'>('user');
  const [isSwitchingCamera, setIsSwitchingCamera] = useState(false);

  useEffect(() => {
    setMuted(!isAppMicActive);
  }, [isAppMicActive]);

  useEffect(() => {
    console.log(`isAppCamActive effect: ${isAppCamActive}, current activeLocalVideoStream: ${activeLocalVideoStream ? 'Exists' : 'Null'}`);
    if (isAppCamActive && !activeLocalVideoStream) {
      console.log("isAppCamActive TRUE and no stream, calling startWebcam()");
      startWebcam();
    } else if (!isAppCamActive && activeLocalVideoStream) {
      console.log("isAppCamActive FALSE and stream exists, calling stopWebcam()");
      stopWebcam();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isAppCamActive]); // activeLocalVideoStream removed to prevent re-triggering startWebcam if it fails and sets stream to null

  useEffect(() => {
    const onData = (base64: string) => {
      if (client && connected) {
        client.sendRealtimeInput([{ mimeType: "audio/pcm;rate=16000", data: base64 }]);
      }
    };
    if (connected && !muted && audioRecorder) {
      audioRecorder.on("data", onData).on("volume", setInVolume).start();
    } else if (audioRecorder && audioRecorder.recording) { // Check if it's recording before stopping
      audioRecorder.stop();
    }
    return () => {
      if (audioRecorder) {
        audioRecorder.off("data", onData).off("volume", setInVolume);
        if (audioRecorder.recording) audioRecorder.stop();
      }
    };
  }, [connected, client, muted, audioRecorder]);

  const renderCanvasRef = useRef<HTMLCanvasElement>(null);
  useEffect(() => {
    let timeoutId = -1;
    function sendVideoFrame() {
      if (connected && activeLocalVideoStream) {
        timeoutId = window.setTimeout(sendVideoFrame, 1000 / 0.5); 
      }
      const video = videoRef.current;
      const canvas = renderCanvasRef.current;
      if (!video || !canvas || video.readyState < video.HAVE_METADATA || video.paused || video.ended || !client) return;
      try {
        const ctx = canvas.getContext("2d");
        if (!ctx) return;
        const scale = 0.25; 
        canvas.width = video.videoWidth * scale;
        canvas.height = video.videoHeight * scale;
        if (canvas.width > 0 && canvas.height > 0) {
          ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
          const base64 = canvas.toDataURL("image/jpeg", 0.7); 
          const data = base64.slice(base64.indexOf(",") + 1);
          client.sendRealtimeInput([{ mimeType: "image/jpeg", data }]);
        }
      } catch (error) {
        console.error("❌ Error processing video frame:", error);
      }
    }
    if (connected && activeLocalVideoStream && videoRef.current) {
      setTimeout(sendVideoFrame, 200); 
    }
    return () => { clearTimeout(timeoutId); };
  }, [connected, activeLocalVideoStream, client, videoRef]);

  useEffect(() => {
    if (videoRef.current) {
      console.log("VideoRef Effect: Current srcObject:", videoRef.current.srcObject ? 'Exists' : 'Null', "New activeLocalVideoStream:", activeLocalVideoStream ? 'Exists' : 'Null');
      if (videoRef.current.srcObject !== activeLocalVideoStream) {
        videoRef.current.srcObject = activeLocalVideoStream;
        console.log("VideoRef Effect: Assigned new stream to srcObject.");
        if (activeLocalVideoStream) {
          console.log("VideoRef Effect: Attempting to play video.");
          videoRef.current.play().then(() => {
            console.log("VideoRef Effect: Video playback started successfully.");
          }).catch(e => {
            console.warn("VideoRef Effect: Video play failed:", e);
          });
        } else {
          console.log("VideoRef Effect: activeLocalVideoStream is null, video srcObject set to null.");
        }
      }
    } else {
      console.warn("VideoRef Effect: videoRef.current is null.");
    }
  }, [activeLocalVideoStream, videoRef]);

  const ensureConnected = async () => {
    console.log("ensureConnected called. Current connected state:", connected);
    if (!connected) {
      try {
        console.log("ensureConnected: Attempting to connect...");
        await connect();
        console.log("ensureConnected: Connection successful.");
        return true;
      } catch (err) {
        console.error('❌ ensureConnected: Connection error:', err);
        return false;
      }
    }
    console.log("ensureConnected: Already connected.");
    return true;
  };

  const handleMicToggle = async () => {
    console.log("handleMicToggle called. isSwitchingCamera:", isSwitchingCamera, "Current isAppMicActive:", isAppMicActive);
    if (isSwitchingCamera) return;
    const newMicState = !isAppMicActive;
    if (newMicState) { 
      if(!await ensureConnected()) {
        console.log("handleMicToggle: ensureConnected failed while trying to turn mic ON.");
        onAppMicToggle(false); 
        return;
      }
    }
    onAppMicToggle(newMicState);
    console.log("handleMicToggle: Mic state toggled to", newMicState);
  };

  const startWebcam = async (facingModeToTry: 'user' | 'environment' = currentFacingMode) => {
    console.log("Attempting to start webcam. Current facingMode:", facingModeToTry, "isSwitchingCamera:", isSwitchingCamera);
    if (isSwitchingCamera) {
      console.log("startWebcam: Already switching camera, aborting.");
      return;
    }
    setIsSwitchingCamera(true); 

    if(!await ensureConnected()) {
        console.error("startWebcam: ensureConnected failed. Aborting webcam start.");
        onAppCamToggle(false);
        setIsSwitchingCamera(false);
        return;
    }
    console.log("startWebcam: ensureConnected succeeded.");

    try {
      console.log(`πŸš€ Getting user media with facingMode: ${facingModeToTry}`);
      const mediaStream = await navigator.mediaDevices.getUserMedia({
        video: { facingMode: facingModeToTry },
        audio: false, 
      });
      console.log("startWebcam: getUserMedia successful. Stream ID:", mediaStream.id);
      setActiveLocalVideoStream(mediaStream);
      onVideoStreamChange(mediaStream); 
      setCurrentFacingMode(facingModeToTry);
      onAppCamToggle(true);
      console.log("startWebcam: Webcam started and states updated.");
    } catch (error) {
      console.error(`❌ Error starting webcam with ${facingModeToTry}:`, error);
      if (facingModeToTry === 'user' && (error as Error).name !== 'NotFoundError') { 
         try {
            console.log("startWebcam: Attempting fallback to 'environment' facingMode.");
            const fallbackStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' }, audio: false });
            console.log("startWebcam: Fallback getUserMedia successful. Stream ID:", fallbackStream.id);
            setActiveLocalVideoStream(fallbackStream);
            onVideoStreamChange(fallbackStream);
            setCurrentFacingMode('environment');
            onAppCamToggle(true);
         } catch (fallbackError) {
            console.error('❌ Error starting webcam fallback:', fallbackError);
            setActiveLocalVideoStream(null);
            onVideoStreamChange(null);
            onAppCamToggle(false);
         }
      } else {
        setActiveLocalVideoStream(null);
        onVideoStreamChange(null);
        onAppCamToggle(false);
      }
    } finally {
      setIsSwitchingCamera(false);
      console.log("startWebcam: Finished attempt, isSwitchingCamera set to false.");
    }
  };

  const stopWebcam = () => {
    console.log("stopWebcam called.");
    if (activeLocalVideoStream) {
      console.log("stopWebcam: Stopping tracks for stream ID:", activeLocalVideoStream.id);
      activeLocalVideoStream.getTracks().forEach(track => track.stop());
    } else {
      console.log("stopWebcam: No activeLocalVideoStream to stop.");
    }
    setActiveLocalVideoStream(null);
    onVideoStreamChange(null);
    onAppCamToggle(false); 
    console.log("stopWebcam: Webcam stopped and states updated.");
  };

  const handleCamToggle = () => {
    console.log("handleCamToggle called. Current isAppCamActive:", isAppCamActive);
    if (isAppCamActive) {
      console.log("handleCamToggle: Current cam is active, calling stopWebcam.");
      stopWebcam();
    } else {
      console.log("handleCamToggle: Current cam is inactive, calling startWebcam.");
      startWebcam();
    }
  };

  const handleSwitchCamera = async () => {
    console.log("handleSwitchCamera called. isAppCamActive:", isAppCamActive, "Stream exists:", !!activeLocalVideoStream, "isSwitchingCamera:", isSwitchingCamera);
    if (!isAppCamActive || !activeLocalVideoStream || isSwitchingCamera) {
        console.log("handleSwitchCamera: Pre-conditions not met, aborting.");
        return;
    }
    
    setIsSwitchingCamera(true);
    const targetFacingMode = currentFacingMode === 'user' ? 'environment' : 'user';
    console.log(`handleSwitchCamera: Stopping current stream tracks (Stream ID: ${activeLocalVideoStream.id}). Target facingMode: ${targetFacingMode}`);
    
    activeLocalVideoStream.getTracks().forEach(track => track.stop());
    setActiveLocalVideoStream(null); 
    onVideoStreamChange(null);

    try {
      console.log(`πŸ”„ Attempting to switch camera to: ${targetFacingMode}`);
      const newStream = await navigator.mediaDevices.getUserMedia({
        video: { facingMode: { exact: targetFacingMode } },
        audio: false,
      });
      console.log("handleSwitchCamera: Switched camera successfully. New Stream ID:", newStream.id);
      setActiveLocalVideoStream(newStream);
      onVideoStreamChange(newStream);
      setCurrentFacingMode(targetFacingMode);
      if (videoRef.current) {
        videoRef.current.srcObject = newStream;
        videoRef.current.play().catch(e => console.warn("Play failed on switch:", e));
      }
    } catch (error) {
      console.error(`❌ Error switching camera to ${targetFacingMode}:`, error);
      console.log(`handleSwitchCamera: Attempting to restore camera to previous mode: ${currentFacingMode}`);
      try {
        const restoredStream = await navigator.mediaDevices.getUserMedia({
            video: { facingMode: currentFacingMode }, 
            audio: false,
        });
        console.log("handleSwitchCamera: Restored camera successfully. Stream ID:", restoredStream.id);
        setActiveLocalVideoStream(restoredStream);
        onVideoStreamChange(restoredStream);
         if (videoRef.current) {
            videoRef.current.srcObject = restoredStream;
            videoRef.current.play().catch(e => console.warn("Play failed on restore:", e));
        }
      } catch (restoreError) {
          console.error('❌ Error restoring camera:', restoreError);
          stopWebcam(); 
          onAppCamToggle(false);
      }
    } finally {
      setIsSwitchingCamera(false);
      console.log("handleSwitchCamera: Finished attempt, isSwitchingCamera set to false.");
    }
  };

   useEffect(() => {
    if (!connected) {
      console.log("Not connected: Stopping video and audio if active.");
      if (activeLocalVideoStream) {
        activeLocalVideoStream.getTracks().forEach(track => track.stop());
        setActiveLocalVideoStream(null);
        onVideoStreamChange(null);
        onAppCamToggle(false); 
      }
      if (audioRecorder.recording) {
         audioRecorder.stop();
         onAppMicToggle(false); 
      }
    }
  }, [connected, audioRecorder, activeLocalVideoStream, onAppCamToggle, onAppMicToggle, onVideoStreamChange]);


  return (
    <footer id="footer-controls" className={cn("footer-controls", {
        'layout-default': !isAppCamActive,
        'layout-with-small-logo': isAppCamActive
    })}>
      <canvas style={{ display: "none" }} ref={renderCanvasRef} />
      <div id="cam-button-wrapper" className="relative flex justify-center">
        <button
          id="cam-button"
          className="control-button cam-button-color"
          onClick={handleCamToggle}
          disabled={isSwitchingCamera || !supportsVideo}
          title={isAppCamActive ? "Stop Camera" : "Start Camera"}
        >
          {isAppCamActive ? <SvgStopCamIcon /> : <SvgCameraIcon />}
        </button>
        <div id="switch-camera-button-container" className={cn("switch-camera-button-container", { 'visible': isAppCamActive })}>
          <button
            id="switch-camera-button"
            aria-label="Switch Camera"
            className="switch-camera-button-content"
            onClick={handleSwitchCamera}
            disabled={!isAppCamActive || isSwitchingCamera}
          >
            <SvgSwitchCameraIcon/>
          </button>
        </div>
      </div>

      {isAppCamActive && (
        <div id="small-logo-container" className="flex items-center justify-center">
            {createLogoFunction(true, isAppCamActive, 'human')}
        </div>
      )}

      <button
        id="mic-button"
        className="control-button mic-button-color"
        onClick={handleMicToggle}
        disabled={isSwitchingCamera} 
        title={isAppMicActive ? "Mute Microphone" : "Unmute Microphone"}
      >
        {isAppMicActive ? <SvgPauseIcon /> : <SvgMicrophoneIcon />}
      </button>

       <button
          style={{ display: 'none'}}
          onClick={async () => {
            if (connected) await disconnect();
            else await connect();
          }}
          title={connected ? "Disconnect Stream" : "Connect Stream"}
        >
          {connected ? "Connected (Internal)" : "Disconnected (Internal)"}
       </button>
    </footer>
  );
}

export default memo(ControlTray);