<script setup>
import { ref, computed, watch } from 'vue';
import { store, sendTouch, sendSwipe, sendLongPress, sendMotionEvent } from '../store/controllerStore';

const videoRef = ref(null);
const overlayRef = ref(null);
const hasStream = ref(false);

const active = computed(() => store.dataChannelOpen);

watch(
  () => store.remoteStream,
  (stream) => {
    if (videoRef.value && stream) {
      videoRef.value.srcObject = stream;
      // 部分浏览器在 srcObject 设置后不会自动播放（尤其是无用户手势时），需显式 play() 兜底
      videoRef.value.play().catch(() => {});
      hasStream.value = true;
    } else {
      hasStream.value = false;
    }
  }
);

// 将指针坐标映射到视频内容区相对坐标 (0~1)，兼容 object-fit: contain 的黑边。
function mapRelative(clientX, clientY) {
  const v = videoRef.value;
  const rect = v.getBoundingClientRect();
  const vw = v.videoWidth || rect.width;
  const vh = v.videoHeight || rect.height;
  const scale = Math.min(rect.width / vw, rect.height / vh) || 1;
  const dispW = vw * scale;
  const dispH = vh * scale;
  const offX = (rect.width - dispW) / 2;
  const offY = (rect.height - dispH) / 2;
  let x = (clientX - rect.left - offX) / dispW;
  let y = (clientY - rect.top - offY) / dispH;
  x = Math.max(0, Math.min(1, x));
  y = Math.max(0, Math.min(1, y));
  return { x, y };
}

const LONG_PRESS_MS = 400;
const TOUCH_SLOP = 0.02;
const SAMPLE_MS = 16;

let startX = 0, startY = 0, startTime = 0, isLongPressed = false, longTimer = null, lastMoveTs = 0;

function clearLong() {
  if (longTimer) { clearTimeout(longTimer); longTimer = null; }
}

function onDown(e) {
  if (!active.value) return;
  overlayRef.value.setPointerCapture && overlayRef.value.setPointerCapture(e.pointerId);
  isLongPressed = false;
  const p = mapRelative(e.clientX, e.clientY);
  startX = p.x; startY = p.y; startTime = Date.now(); lastMoveTs = 0;
  sendMotionEvent(0, p.x, p.y); // ACTION_DOWN
  clearLong();
  longTimer = setTimeout(() => {
    isLongPressed = true;
    sendLongPress(p.x, p.y);
  }, LONG_PRESS_MS);
}

function onMove(e) {
  if (!active.value) return;
  const p = mapRelative(e.clientX, e.clientY);
  if (Math.abs(p.x - startX) > TOUCH_SLOP || Math.abs(p.y - startY) > TOUCH_SLOP) clearLong();
  const now = Date.now();
  if (now - lastMoveTs >= SAMPLE_MS) {
    lastMoveTs = now;
    sendMotionEvent(2, p.x, p.y); // ACTION_MOVE
  }
}

function onUp(e) {
  if (!active.value) return;
  clearLong();
  const p = mapRelative(e.clientX, e.clientY);
  sendMotionEvent(1, p.x, p.y); // ACTION_UP
  if (!isLongPressed) {
    const dx = Math.abs(p.x - startX);
    const dy = Math.abs(p.y - startY);
    const dur = Date.now() - startTime;
    if (dur < 200 && dx < TOUCH_SLOP && dy < TOUCH_SLOP) sendTouch(startX, startY);
    else sendSwipe(startX, startY, p.x, p.y, Math.max(dur, 1));
  }
}
</script>

<template>
  <div class="screen-wrap">
    <video ref="videoRef" class="remote-video" autoplay playsinline muted></video>

    <div
      ref="overlayRef"
      class="touch-overlay"
      :class="{ active }"
      @pointerdown="onDown"
      @pointermove="onMove"
      @pointerup="onUp"
      @pointercancel="clearLong"
    ></div>

    <div v-if="!hasStream" class="placeholder">
      <div class="big">📱</div>
      <div v-if="!store.signalingConnected">请先在左侧连接信令服务器</div>
      <div v-else-if="!store.targetDeviceId">请选择并连接一个被控端设备</div>
      <div v-else>正在等待被控端画面…</div>
    </div>
  </div>
</template>
