<script setup>
import { ref, computed } from 'vue';
import {
  store, connectSignaling, disconnectSignaling, refreshDevices,
  connectToDevice, disconnectDevice, bindByPairingCode,
} from '../store/controllerStore';

const selected = ref('');
const authType = ref('NONE');
const authValue = ref('');

// 配对绑定
const pairCode = ref('');
const pairAlias = ref('');
const pairBusy = ref(false);
const pairMsg = ref('');
const pairErr = ref('');

const selectedDevice = computed(() =>
  store.controlledDevices.find((d) => d.deviceUid === selected.value) || null
);

function onConnectDevice() {
  if (!selected.value) {
    store.error = '请选择要连接的设备';
    return;
  }
  if (selectedDevice.value && !selectedDevice.value.online) {
    store.error = '该设备当前不在线，请先启动被控端';
    return;
  }
  if (authType.value !== 'NONE' && !authValue.value.trim()) {
    store.error = '请输入验证码或密码';
    return;
  }
  connectToDevice(selected.value, authType.value, authType.value === 'NONE' ? '' : authValue.value.trim());
}

async function onBind() {
  pairMsg.value = '';
  pairErr.value = '';
  const code = pairCode.value.trim();
  if (!code) { pairErr.value = '请输入被控端显示的配对码'; return; }
  pairBusy.value = true;
  try {
    await bindByPairingCode(code, pairAlias.value.trim());
    pairMsg.value = '绑定成功';
    pairCode.value = '';
    pairAlias.value = '';
  } catch (e) {
    pairErr.value = e.message || '绑定失败';
  } finally {
    pairBusy.value = false;
  }
}
</script>

<template>
  <div class="conn-panel">
    <div class="field">
      <label>信令服务器地址 (WebSocket)</label>
      <input class="input" v-model="store.serverUrl" placeholder="ws://host:port/ws/signal" />
    </div>

    <div class="field">
      <label>本机设备 ID（服务端下发）</label>
      <input class="input" :value="store.deviceId || '—'" disabled />
    </div>

    <button class="btn danger" v-if="store.signalingConnected" @click="disconnectSignaling">断开信令服务器</button>
    <button class="btn" v-else :disabled="store.signalingConnecting" @click="connectSignaling">
      {{ store.signalingConnecting ? '正在连接...' : '连接信令服务器' }}
    </button>

    <div class="section-title">已绑定设备 (CONTROLLED)</div>
    <button class="btn secondary" style="margin-bottom:12px" @click="refreshDevices" :disabled="store.devicesLoading">
      {{ store.devicesLoading ? '加载中…' : '刷新设备列表' }}
    </button>

    <div v-if="store.devicesError" class="error">{{ store.devicesError }}</div>

    <div v-if="!store.devicesLoading && store.controlledDevices.length === 0" class="hint">
      尚无已绑定设备。请在被控端获取配对码，并在下方「绑定新设备」中输入完成绑定。
    </div>

    <div
      v-for="d in store.controlledDevices"
      :key="d.deviceUid"
      class="device-item"
      :class="{ active: selected === d.deviceUid, offline: !d.online }"
      @click="selected = d.deviceUid"
    >
      <span class="dev-name">
        {{ d.alias || d.deviceUid }}
        <small v-if="d.alias" class="dev-uid">{{ d.deviceUid }}</small>
      </span>
      <span :style="{ color: d.online ? 'var(--accent-2)' : '#94a3b8' }">
        {{ d.online ? '在线' : '离线' }}
      </span>
    </div>

    <div class="field" style="margin-top:14px">
      <select class="select" v-model="selected">
        <option value="">选择目标设备…</option>
        <option v-for="d in store.controlledDevices" :key="d.deviceUid" :value="d.deviceUid">
          {{ (d.alias || d.deviceUid) + (d.online ? '（在线）' : '（离线）') }}
        </option>
      </select>
    </div>

    <div class="section-title" style="margin-top:14px">绑定新设备</div>
    <div class="field">
      <input class="input" v-model="pairCode" placeholder="被控端显示的配对码" />
    </div>
    <div class="field">
      <input class="input" v-model="pairAlias" placeholder="备注名（可选）" />
    </div>
    <button class="btn secondary" @click="onBind" :disabled="pairBusy">
      {{ pairBusy ? '绑定中…' : '绑定设备' }}
    </button>
    <div v-if="pairMsg" class="hint" style="color:var(--accent-2)">{{ pairMsg }}</div>
    <div v-if="pairErr" class="error">{{ pairErr }}</div>

    <div class="section-title" style="margin-top:14px">连接鉴权</div>
    <div class="auth-row">
      <label class="auth-radio"><input type="radio" value="NONE" v-model="authType" /> 免密连接</label>
      <label class="auth-radio"><input type="radio" value="CODE" v-model="authType" /> 动态验证码</label>
      <label class="auth-radio"><input type="radio" value="PASSWORD" v-model="authType" /> 固定密码</label>
    </div>
    <div v-if="authType === 'NONE'" class="hint">
      免密连接：被控端将弹出手动确认对话框，无需输入验证码或密码。
    </div>
    <div class="field" v-else>
      <input class="input" v-model="authValue" :placeholder="authType === 'PASSWORD' ? '请输入固定密码' : '请输入动态验证码'" />
    </div>

    <button
      class="btn"
      @click="onConnectDevice"
      :disabled="!selected || store.rtcConnected || !store.signalingConnected || (selectedDevice && !selectedDevice.online)"
    >发起远程控制</button>
    <button class="btn danger" style="margin-top:12px" v-if="store.rtcConnected" @click="disconnectDevice">结束控制</button>

    <div v-if="store.error" class="error">{{ store.error }}</div>

    <div class="section-title">说明</div>
    <div class="hint">
      • 本页面作为 <b>控制端 (CONTROLLER)</b>，对应原 Android / Flutter 控制端。<br />
      • 连接后可在右侧屏幕区域触摸/滑动来操控被控设备。<br />
      • 控制指令以 protobuf 经 DataChannel 发送，与原 Android 被控端完全兼容。
    </div>
  </div>
</template>

<style scoped>
.auth-row { display: flex; gap: 16px; margin-bottom: 8px; align-items: center; }
.auth-radio { display: inline-flex; align-items: center; gap: 4px; }
.device-item.offline { opacity: .6; }
.dev-name { display: flex; flex-direction: column; gap: 2px; }
.dev-uid { color: #94a3b8; font-size: 11px; }
</style>
