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cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bbb872
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2eba0cc
 
 
8bbb872
 
 
 
 
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
import React, { useState, useEffect, useRef } from 'react';
import CalibrationOverlay from './CalibrationOverlay';

function FocusPageLocal({ videoManager, sessionResult, setSessionResult, isActive }) {
  const [currentFrame, setCurrentFrame] = useState(15);
  const [timelineEvents, setTimelineEvents] = useState([]);
  const [stats, setStats] = useState(null);
  const [availableModels, setAvailableModels] = useState([]);
  const [currentModel, setCurrentModel] = useState('mlp');
  const [calibration, setCalibration] = useState(null);
  const [l2csBoost, setL2csBoost] = useState(false);
  const [l2csBoostAvailable, setL2csBoostAvailable] = useState(false);

  const localVideoRef = useRef(null);
  const displayCanvasRef = useRef(null);
  const pipVideoRef = useRef(null); // 用于 PiP 的隐藏 video 元素
  const pipStreamRef = useRef(null);

  // 辅助函数:格式化时间
  const formatDuration = (seconds) => {
    if (seconds === 0) return "0s";
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}m ${secs}s`;
  };

  useEffect(() => {
    if (!videoManager) return;

    const originalOnStatusUpdate = videoManager.callbacks.onStatusUpdate;
    videoManager.callbacks.onStatusUpdate = (isFocused) => {
      setTimelineEvents(prev => {
        const newEvents = [...prev, { isFocused, timestamp: Date.now() }];
        if (newEvents.length > 60) newEvents.shift();
        return newEvents;
      });
      if (originalOnStatusUpdate) originalOnStatusUpdate(isFocused);
    };

    videoManager.callbacks.onCalibrationUpdate = (cal) => {
      setCalibration(cal && cal.active ? { ...cal } : null);
    };

    const statsInterval = setInterval(() => {
      if (videoManager && videoManager.getStats) {
        setStats(videoManager.getStats());
      }
    }, 1000);

    return () => {
      if (videoManager) {
        videoManager.callbacks.onStatusUpdate = originalOnStatusUpdate;
        videoManager.callbacks.onCalibrationUpdate = null;
      }
      clearInterval(statsInterval);
    };
  }, [videoManager]);

  // Fetch available models on mount
  useEffect(() => {
    fetch('/api/models')
      .then(res => res.json())
      .then(data => {
        if (data.available) setAvailableModels(data.available);
        if (data.current) setCurrentModel(data.current);
        if (data.l2cs_boost !== undefined) setL2csBoost(data.l2cs_boost);
        if (data.l2cs_boost_available !== undefined) setL2csBoostAvailable(data.l2cs_boost_available);
      })
      .catch(err => console.error('Failed to fetch models:', err));
  }, []);

  const handleModelChange = async (modelName) => {
    try {
      const res = await fetch('/api/settings', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ model_name: modelName })
      });
      const result = await res.json();
      if (result.updated) {
        setCurrentModel(modelName);
        setL2csBoostAvailable(modelName !== 'l2cs' && availableModels.includes('l2cs'));
        if (modelName === 'l2cs') setL2csBoost(false);
      }
    } catch (err) {
      console.error('Failed to switch model:', err);
    }
  };

  const handleBoostToggle = async () => {
    const next = !l2csBoost;
    try {
      const res = await fetch('/api/settings', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ l2cs_boost: next })
      });
      if (res.ok) setL2csBoost(next);
    } catch (err) {
      console.error('Failed to toggle L2CS boost:', err);
    }
  };

  const handleStart = async () => {
    try {
      if (videoManager) {
        setSessionResult(null);
        setTimelineEvents([]);

        console.log('Initializing local camera...');
        await videoManager.initCamera(localVideoRef.current, displayCanvasRef.current);
        console.log('Camera initialized');

        console.log('Starting local streaming...');
        await videoManager.startStreaming();
        console.log('Streaming started successfully');
      }
    } catch (err) {
      console.error('Start error:', err);
      let errorMessage = "Failed to start: ";

      if (err.name === 'NotAllowedError') {
        errorMessage += "Camera permission denied. Please allow camera access.";
      } else if (err.name === 'NotFoundError') {
        errorMessage += "No camera found. Please connect a camera.";
      } else if (err.name === 'NotReadableError') {
        errorMessage += "Camera is already in use by another application.";
      } else {
        errorMessage += err.message || "Unknown error occurred.";
      }

      alert(errorMessage + "\n\nCheck browser console for details.");
    }
  };

  const handleStop = async () => {
    if (videoManager) {
      videoManager.stopStreaming();
    }
    try {
      if (document.pictureInPictureElement === pipVideoRef.current) {
        await document.exitPictureInPicture();
      }
    } catch (_) {}
    if (pipVideoRef.current) {
      pipVideoRef.current.pause();
      pipVideoRef.current.srcObject = null;
    }
    if (pipStreamRef.current) {
      pipStreamRef.current.getTracks().forEach(t => t.stop());
      pipStreamRef.current = null;
    }
  };

  const handlePiP = async () => {
    try {
      // 检查是否有视频管理器和是否在运行
      if (!videoManager || !videoManager.isStreaming) {
        alert('Please start the video first.');
        return;
      }

      if (!displayCanvasRef.current) {
        alert('Video not ready.');
        return;
      }

      // 如果已经在 PiP 模式,且是本视频,退出
      if (document.pictureInPictureElement === pipVideoRef.current) {
        await document.exitPictureInPicture();
        console.log('PiP exited');
        return;
      }

      // 检查浏览器支持
      if (!document.pictureInPictureEnabled) {
        alert('Picture-in-Picture is not supported in this browser.');
        return;
      }

      // 创建或获取 PiP video 元素
      const pipVideo = pipVideoRef.current;
      if (!pipVideo) {
        alert('PiP video element not ready.');
        return;
      }

      const isSafariPiP = typeof pipVideo.webkitSetPresentationMode === 'function';

      // 优先用画布流(带检测框),失败再回退到摄像头流
      let stream = pipStreamRef.current;
      if (!stream) {
        const capture = displayCanvasRef.current.captureStream;
        if (typeof capture === 'function') {
          stream = capture.call(displayCanvasRef.current, 30);
        }
        if (!stream || stream.getTracks().length === 0) {
          const cameraStream = localVideoRef.current?.srcObject;
          if (!cameraStream) {
            alert('Camera stream not ready.');
            return;
          }
          stream = cameraStream;
        }
        pipStreamRef.current = stream;
      }

      // 确保流有轨道
      if (!stream || stream.getTracks().length === 0) {
        alert('Failed to capture video stream from canvas.');
        return;
      }

      pipVideo.srcObject = stream;

      // 播放视频(Safari 可能不会触发 onloadedmetadata)
      if (pipVideo.readyState < 2) {
        await new Promise((resolve) => {
          const onReady = () => {
            pipVideo.removeEventListener('loadeddata', onReady);
            pipVideo.removeEventListener('canplay', onReady);
            resolve();
          };
          pipVideo.addEventListener('loadeddata', onReady);
          pipVideo.addEventListener('canplay', onReady);
          // 兜底:短延迟后继续尝试
          setTimeout(resolve, 600);
        });
      }

      try {
        await pipVideo.play();
      } catch (_) {
        // Safari 可能拒绝自动播放,但仍可进入 PiP
      }

      // Safari 支持(优先)
      if (isSafariPiP) {
        try {
          pipVideo.webkitSetPresentationMode('picture-in-picture');
          console.log('PiP activated (Safari)');
          return;
        } catch (e) {
          // 如果画布流失败,回退到摄像头流再试一次
          const cameraStream = localVideoRef.current?.srcObject;
          if (cameraStream && cameraStream !== pipVideo.srcObject) {
            pipVideo.srcObject = cameraStream;
            try {
              await pipVideo.play();
            } catch (_) {}
            pipVideo.webkitSetPresentationMode('picture-in-picture');
            console.log('PiP activated (Safari fallback)');
            return;
          }
          throw e;
        }
      }

      // 标准 API
      if (typeof pipVideo.requestPictureInPicture === 'function') {
        await pipVideo.requestPictureInPicture();
        console.log('PiP activated');
      } else {
        alert('Picture-in-Picture is not supported in this browser.');
      }

    } catch (err) {
      console.error('PiP error:', err);
      alert('Failed to enter Picture-in-Picture: ' + err.message);
    }
  };

  const handleFloatingWindow = () => {
    handlePiP();
  };

  const handleFrameChange = (val) => {
    const rate = parseInt(val);
    setCurrentFrame(rate);
    if (videoManager) {
      videoManager.setFrameRate(rate);
    }
  };

  const handlePreview = () => {
    if (!videoManager || !videoManager.isStreaming) {
      alert('Please start a session first.');
      return;
    }

    // 获取当前统计数据
    const currentStats = videoManager.getStats();

    if (!currentStats.sessionId) {
      alert('No active session.');
      return;
    }

    // 计算当前持续时间(从 session 开始到现在)
    const sessionDuration = Math.floor((Date.now() - (videoManager.sessionStartTime || Date.now())) / 1000);

    // 计算当前专注分数
    const focusScore = currentStats.framesProcessed > 0
      ? (currentStats.framesProcessed * (currentStats.currentStatus ? 1 : 0)) / currentStats.framesProcessed
      : 0;

    // 显示当前实时数据
    setSessionResult({
      duration_seconds: sessionDuration,
      focus_score: focusScore,
      total_frames: currentStats.framesProcessed,
      focused_frames: Math.floor(currentStats.framesProcessed * focusScore)
    });
  };

  const handleCloseOverlay = () => {
    setSessionResult(null);
  };

  const pageStyle = isActive
    ? undefined
    : {
        position: 'absolute',
        width: '1px',
        height: '1px',
        overflow: 'hidden',
        opacity: 0,
        pointerEvents: 'none'
      };

  useEffect(() => {
    return () => {
      if (pipVideoRef.current) {
        pipVideoRef.current.pause();
        pipVideoRef.current.srcObject = null;
      }
      if (pipStreamRef.current) {
        pipStreamRef.current.getTracks().forEach(t => t.stop());
        pipStreamRef.current = null;
      }
    };
  }, []);

  return (
    <main id="page-b" className="page" style={pageStyle}>
      {/* 1. Camera / Display Area */}
      <section id="display-area" style={{ position: 'relative', overflow: 'hidden' }}>
        {/* 用于 PiP 的隐藏 video 元素(保持在 DOM 以提高兼容性) */}
        <video
          ref={pipVideoRef}
          muted
          playsInline
          autoPlay
          style={{
            position: 'absolute',
            width: '1px',
            height: '1px',
            opacity: 0,
            pointerEvents: 'none'
          }}
        />
        {/* 本地视频流(隐藏,仅用于截图) */}
        <video
          ref={localVideoRef}
          muted
          playsInline
          autoPlay
          style={{ display: 'none' }}
        />

        {/* 显示处理后的视频(使用 Canvas) */}
        <canvas
          ref={displayCanvasRef}
          width={640}
          height={480}
          style={{
            width: '100%',
            height: '100%',
            objectFit: 'contain',
            backgroundColor: '#000'
          }}
        />

        {/* 结果覆盖层 */}
        {sessionResult && (
          <div className="session-result-overlay">
            <h3>Session Complete!</h3>
            <div className="result-item">
              <span className="label">Duration:</span>
              <span className="value">{formatDuration(sessionResult.duration_seconds)}</span>
            </div>
            <div className="result-item">
              <span className="label">Focus Score:</span>
              <span className="value">{(sessionResult.focus_score * 100).toFixed(1)}%</span>
            </div>

            <button
              onClick={handleCloseOverlay}
              style={{
                marginTop: '20px',
                padding: '8px 20px',
                background: 'transparent',
                border: '1px solid white',
                color: 'white',
                borderRadius: '20px',
                cursor: 'pointer'
              }}
            >
              Close
            </button>
          </div>
        )}

        {/* 性能统计显示(开发模式) */}
        {stats && stats.isStreaming && (
          <div style={{
            position: 'absolute',
            top: '10px',
            right: '10px',
            background: 'rgba(0,0,0,0.7)',
            color: 'white',
            padding: '10px',
            borderRadius: '5px',
            fontSize: '12px',
            fontFamily: 'monospace'
          }}>
            <div>Session: {stats.sessionId}</div>
            <div>Sent: {stats.framesSent}</div>
            <div>Processed: {stats.framesProcessed}</div>
            <div>Latency: {stats.avgLatency.toFixed(0)}ms</div>
            <div>Status: {stats.currentStatus ? 'Focused' : 'Not Focused'}</div>
            <div>Confidence: {(stats.lastConfidence * 100).toFixed(1)}%</div>
          </div>
        )}
      </section>

      {/* 2. Model Selector */}
      {availableModels.length > 0 && (
        <section style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          gap: '8px',
          padding: '8px 16px',
          background: '#1a1a2e',
          borderRadius: '8px',
          margin: '8px auto',
          maxWidth: '600px'
        }}>
          <span style={{ color: '#aaa', fontSize: '13px', marginRight: '4px' }}>Model:</span>
          {availableModels.map(name => (
            <button
              key={name}
              onClick={() => handleModelChange(name)}
              style={{
                padding: '5px 14px',
                borderRadius: '16px',
                border: currentModel === name ? '2px solid #007BFF' : '1px solid #555',
                background: currentModel === name ? '#007BFF' : 'transparent',
                color: currentModel === name ? '#fff' : '#ccc',
                fontSize: '12px',
                fontWeight: currentModel === name ? 'bold' : 'normal',
                cursor: 'pointer',
                textTransform: 'uppercase',
                transition: 'all 0.2s'
              }}
            >
              {name}
            </button>
          ))}
          {l2csBoostAvailable && currentModel !== 'l2cs' && (
            <button
              onClick={handleBoostToggle}
              style={{
                padding: '5px 14px',
                borderRadius: '16px',
                border: l2csBoost ? '2px solid #f59e0b' : '1px solid #555',
                background: l2csBoost ? 'rgba(245, 158, 11, 0.15)' : 'transparent',
                color: l2csBoost ? '#f59e0b' : '#888',
                fontSize: '11px',
                fontWeight: l2csBoost ? 'bold' : 'normal',
                cursor: 'pointer',
                transition: 'all 0.2s',
                marginLeft: '4px',
              }}
            >
              {l2csBoost ? 'GAZE ON' : 'GAZE'}
            </button>
          )}
          {(currentModel === 'l2cs' || l2csBoost) && stats && stats.isStreaming && (
            <button
              onClick={() => videoManager && videoManager.startCalibration()}
              style={{
                padding: '5px 14px',
                borderRadius: '16px',
                border: '1px solid #4ade80',
                background: 'transparent',
                color: '#4ade80',
                fontSize: '12px',
                fontWeight: 'bold',
                cursor: 'pointer',
                transition: 'all 0.2s',
                marginLeft: '4px',
              }}
            >
              Calibrate
            </button>
          )}
        </section>
      )}

      {/* 3. Timeline Area */}
      <section id="timeline-area">
        <div className="timeline-label">Timeline</div>
        <div id="timeline-visuals">
          {timelineEvents.map((event, index) => (
            <div
              key={index}
              className="timeline-block"
              style={{
                backgroundColor: event.isFocused ? '#00FF00' : '#FF0000',
                width: '10px',
                height: '20px',
                display: 'inline-block',
                marginRight: '2px',
                borderRadius: '2px'
              }}
              title={event.isFocused ? 'Focused' : 'Distracted'}
            />
          ))}
        </div>
        <div id="timeline-line"></div>
      </section>

      {/* 4. Control Buttons */}
      <section id="control-panel">
        <button id="btn-cam-start" className="action-btn green" onClick={handleStart}>
          Start
        </button>

        <button id="btn-floating" className="action-btn yellow" onClick={handleFloatingWindow}>
          Floating Window
        </button>

        <button
          id="btn-preview"
          className="action-btn"
          style={{ backgroundColor: '#6c5ce7' }}
          onClick={handlePreview}
        >
          Preview Result
        </button>

        <button id="btn-cam-stop" className="action-btn red" onClick={handleStop}>
          Stop
        </button>
      </section>

      {/* 5. Frame Control */}
      <section id="frame-control">
        <label htmlFor="frame-slider">Frame Rate (FPS)</label>
        <input
          type="range"
          id="frame-slider"
          min="10"
          max="30"
          value={currentFrame}
          onChange={(e) => handleFrameChange(e.target.value)}
        />
        <input
          type="number"
          id="frame-input"
          min="10"
          max="30"
          value={currentFrame}
          onChange={(e) => handleFrameChange(e.target.value)}
        />
      </section>

      {/* Calibration overlay (fixed fullscreen, must be outside overflow:hidden containers) */}
      <CalibrationOverlay calibration={calibration} videoManager={videoManager} />
    </main>
  );
}

export default FocusPageLocal;