// ===== 拍照组件 =====
const { useState: useStateCam, useRef: useRefCam, useEffect: useEffectCam } = React;

function CameraCapture({ onCapture, onCancel }) {
  const videoRef = useRefCam(null);
  const canvasRef = useRefCam(null);
  const streamRef = useRefCam(null);
  const [mode, setMode] = useStateCam('camera'); // camera | preview | error
  const [photo, setPhoto] = useStateCam(null);
  const [errorMsg, setErrorMsg] = useStateCam('');

  useEffectCam(() => {
    startCamera();
    return () => {
      if (streamRef.current) {
        streamRef.current.getTracks().forEach(t => t.stop());
      }
    };
  }, []);

  const startCamera = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({
        video: { facingMode: 'environment', width: { ideal: 1280 }, height: { ideal: 960 } },
        audio: false,
      });
      streamRef.current = stream;
      if (videoRef.current) {
        videoRef.current.srcObject = stream;
      }
      setMode('camera');
    } catch (err) {
      console.error('相机启动失败:', err);
      setErrorMsg('无法访问相机，请检查权限或使用上传照片');
      setMode('error');
    }
  };

  const takePhoto = () => {
    const video = videoRef.current;
    const canvas = canvasRef.current;
    if (!video || !canvas) return;

    const ctx = canvas.getContext('2d');
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    ctx.drawImage(video, 0, 0);

    const dataUrl = canvas.toDataURL('image/jpeg', 0.8);
    setPhoto(dataUrl);
    setMode('preview');

    if (streamRef.current) {
      streamRef.current.getTracks().forEach(t => t.stop());
    }
  };

  const retake = () => {
    setPhoto(null);
    setMode('camera');
    startCamera();
  };

  const confirmPhoto = () => {
    if (onCapture && photo) {
      onCapture(photo);
    }
  };

  const handleFileUpload = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
      setPhoto(ev.target.result);
      setMode('preview');
    };
    reader.readAsDataURL(file);
  };

  return (
    <div className="camera-capture">
      <canvas ref={canvasRef} style={{ display: 'none' }} />

      {mode === 'camera' && (
        <div className="camera-container">
          <video ref={videoRef} className="camera-video" autoPlay playsInline muted />
          <button className="camera-shutter" onClick={takePhoto}>
            <div className="camera-shutter-inner" />
          </button>
          <div style={{
            position: 'absolute',
            top: '12px',
            left: '12px',
            right: '12px',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}>
            <span style={{
              background: 'rgba(0,0,0,0.6)',
              color: 'white',
              padding: '6px 12px',
              borderRadius: '6px',
              fontSize: '13px',
              fontWeight: 600,
            }}>
              拍摄设备锁定状态
            </span>
            {onCancel && (
              <button
                onClick={onCancel}
                style={{
                  background: 'rgba(0,0,0,0.6)',
                  color: 'white',
                  border: 'none',
                  padding: '6px 14px',
                  borderRadius: '6px',
                  fontSize: '13px',
                  cursor: 'pointer',
                  fontFamily: 'inherit',
                }}
              >
                取消
              </button>
            )}
          </div>
        </div>
      )}

      {mode === 'preview' && photo && (
        <div>
          <div style={{ position: 'relative', borderRadius: '12px', overflow: 'hidden' }}>
            <img src={photo} alt="预览" style={{ width: '100%', display: 'block' }} />
            <div style={{
              position: 'absolute',
              top: '12px',
              left: '12px',
              background: 'rgba(46,125,50,0.9)',
              color: 'white',
              padding: '6px 12px',
              borderRadius: '6px',
              fontSize: '13px',
              fontWeight: 600,
            }}>
              照片已拍摄
            </div>
          </div>
          <div style={{ display: 'flex', gap: '10px', marginTop: '12px' }}>
            <button className="btn btn-ghost btn-small" onClick={retake} style={{ flex: 1 }}>
              重新拍摄
            </button>
            <button className="btn btn-success btn-small" onClick={confirmPhoto} style={{ flex: 1 }}>
              确认使用
            </button>
          </div>
        </div>
      )}

      {mode === 'error' && (
        <div style={{
          background: 'var(--card-bg)',
          border: '1px solid var(--border)',
          borderRadius: '12px',
          padding: '24px',
          textAlign: 'center',
        }}>
          <div style={{ fontSize: '40px', marginBottom: '12px' }}>📷</div>
          <p style={{ color: 'var(--danger-light)', fontSize: '14px', marginBottom: '16px' }}>
            {errorMsg}
          </p>
          <label className="btn btn-primary btn-small" style={{ cursor: 'pointer', display: 'inline-flex' }}>
            上传照片
            <input type="file" accept="image/*" onChange={handleFileUpload} style={{ display: 'none' }} />
          </label>
        </div>
      )}

      {mode === 'camera' && (
        <div style={{ marginTop: '12px', textAlign: 'center' }}>
          <label style={{
            color: 'var(--text-muted)',
            fontSize: '13px',
            cursor: 'pointer',
            textDecoration: 'underline',
          }}>
            或者从相册选择照片
            <input type="file" accept="image/*" onChange={handleFileUpload} style={{ display: 'none' }} />
          </label>
        </div>
      )}
    </div>
  );
}

window.CameraCapture = CameraCapture;
