<script setup>
import { onMounted } from 'vue';
import { store, initProto, logout, restoreSession } from './store/controllerStore';
import LoginPanel from './components/LoginPanel.vue';
import ConnectionPanel from './components/ConnectionPanel.vue';
import RemoteScreen from './components/RemoteScreen.vue';
import ControlBar from './components/ControlBar.vue';
import StatsBar from './components/StatsBar.vue';

onMounted(async () => {
  await initProto();
  // 页面刷新后若 sessionStorage 中仍有有效令牌，直接恢复会话并连上信令。
  await restoreSession();
});

async function onLogout() {
  await logout();
}
</script>

<template>
  <div class="app">
    <div v-if="store.restoring" class="restoring">正在恢复登录状态…</div>

    <LoginPanel v-else-if="!store.loggedIn" />

    <template v-else>
      <header class="topbar">
        <div class="brand">WebRTC 网页远程控制</div>

        <div class="status" :class="{ ok: store.rtcConnected }">{{ store.statusText }}</div>
        <div class="badges">
          <span class="badge" :class="{ on: store.signalingConnected }">信令</span>
          <span class="badge" :class="{ on: store.registered }">注册</span>
          <span class="badge" :class="{ on: store.rtcConnected }">P2P</span>
          <span class="badge" :class="{ on: store.dataChannelOpen }">通道</span>
        </div>
        <div class="user">
          <span class="user-name" :title="store.username || '已登录'">
            {{ store.username || '已登录' }}
          </span>
          <button class="btn ghost" type="button" @click="onLogout">退出</button>
        </div>
      </header>

      <main class="layout">
        <aside class="sidebar">
          <ConnectionPanel />
        </aside>
        <section class="stage">
          <RemoteScreen />
          <ControlBar />
        </section>
      </main>

      <footer class="footer">
        <StatsBar />
      </footer>
    </template>
  </div>
</template>

<style scoped>
.restoring {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  color: #94a3b8;
  font-size: 14px;
}
</style>
