<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { useDisplayStore } from '../stores/display';
import { HorseRaceRenderer } from '../pixi/HorseRaceRenderer';
import type { AdminState } from '@gala/shared/types';
import { SOCKET_EVENTS } from '@gala/shared/constants';

const router = useRouter();
const displayStore = useDisplayStore();

// Canvas ref
const canvasRef = ref<HTMLCanvasElement | null>(null);
let renderer: HorseRaceRenderer | null = null;

// State
const votingOpen = ref(false);
const totalVotes = ref(0);

function goBack() {
  router.push('/');
}

// Handle state sync from admin
function handleStateSync(state: AdminState) {
  votingOpen.value = state.voting.subPhase === 'OPEN';
  totalVotes.value = state.voting.totalVotes;

  // Update renderer with programs
  if (renderer && state.voting.programs) {
    renderer.setPrograms(
      state.voting.programs.map((p) => ({
        id: p.id,
        name: p.name,
        votes: p.votes,
      }))
    );
  }
}

// Handle real-time vote updates
function handleVoteUpdate(data: { candidateId: string; totalVotes: number }) {
  if (renderer) {
    renderer.updateVotes(data.candidateId, data.totalVotes);
  }
  // Update total votes
  totalVotes.value = data.totalVotes;
}

onMounted(async () => {
  await nextTick();

  if (canvasRef.value) {
    renderer = new HorseRaceRenderer();
    await renderer.init(canvasRef.value);
  }

  const socket = displayStore.getSocket();
  if (socket) {
    socket.on(SOCKET_EVENTS.ADMIN_STATE_SYNC as any, handleStateSync);
    socket.on(SOCKET_EVENTS.VOTE_UPDATED as any, handleVoteUpdate);
    // Request initial state
    socket.emit(SOCKET_EVENTS.ADMIN_STATE_SYNC as any);
  }
});

onUnmounted(() => {
  if (renderer) {
    renderer.destroy();
    renderer = null;
  }

  const socket = displayStore.getSocket();
  if (socket) {
    socket.off(SOCKET_EVENTS.ADMIN_STATE_SYNC as any, handleStateSync);
    socket.off(SOCKET_EVENTS.VOTE_UPDATED as any, handleVoteUpdate);
  }
});
</script>

<template>
  <div class="horse-race-view">
    <!-- Canvas Background -->
    <canvas ref="canvasRef" class="race-canvas"></canvas>

    <!-- Overlay UI -->
    <div class="overlay-ui">
      <!-- Header -->
      <header class="header">
        <button class="back-btn" @click="goBack">← 返回</button>
        <h1 class="title">🏇 节目热度赛马</h1>
        <div class="header-right">
          <div class="vote-counter">
            <span class="counter-label">总票数</span>
            <span class="counter-value">{{ totalVotes.toLocaleString() }}</span>
          </div>
          <div class="status">
            <span class="status-badge" :class="{ open: votingOpen }">
              {{ votingOpen ? '投票进行中' : '投票未开始' }}
            </span>
            <span class="online-count">{{ displayStore.onlineUsers }} 人在线</span>
            <span class="connection-dot" :class="{ connected: displayStore.isConnected }"></span>
          </div>
        </div>
      </header>

      <!-- Legend -->
      <div class="legend">
        <div class="legend-item">
          <span class="legend-icon start"></span>
          <span>起点</span>
        </div>
        <div class="legend-item">
          <span class="legend-icon finish"></span>
          <span>终点</span>
        </div>
        <div class="legend-item">
          <span class="legend-icon horse"></span>
          <span>热度光球</span>
        </div>
      </div>

      <!-- Footer Hint -->
      <div class="footer-hint">
        <span>💡 每收到一票，对应节目的马匹将向前推进</span>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
$color-gold: #f0c239;
$color-red: #c21f30;
$color-text-muted: #888;

.horse-race-view {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  background: #0a0a0a;
}

.race-canvas {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
}

.overlay-ui {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  pointer-events: none;

  > * {
    pointer-events: auto;
  }
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 40px;
  background: linear-gradient(180deg, rgba(0, 0, 0, 0.8) 0%, transparent 100%);

  .back-btn {
    background: rgba(0, 0, 0, 0.5);
    border: 1px solid $color-gold;
    color: $color-gold;
    padding: 10px 20px;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.2s;
    backdrop-filter: blur(10px);

    &:hover {
      background: rgba($color-gold, 0.2);
    }
  }

  .title {
    font-size: 32px;
    font-family: 'SimSun', 'Songti SC', serif;
    font-weight: bold;
    color: $color-gold;
    text-shadow: 0 2px 10px rgba($color-gold, 0.5);
  }

  .header-right {
    display: flex;
    align-items: center;
    gap: 24px;
  }

  .vote-counter {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    background: rgba(0, 0, 0, 0.5);
    padding: 8px 16px;
    border-radius: 8px;
    border: 1px solid rgba($color-gold, 0.3);
    backdrop-filter: blur(10px);

    .counter-label {
      font-size: 12px;
      color: $color-text-muted;
    }

    .counter-value {
      font-size: 28px;
      font-weight: bold;
      color: $color-gold;
      font-family: 'Courier New', monospace;
    }
  }

  .status {
    display: flex;
    align-items: center;
    gap: 12px;

    .status-badge {
      padding: 6px 16px;
      border-radius: 4px;
      font-size: 14px;
      background: rgba(255, 255, 255, 0.1);
      color: $color-text-muted;
      border: 1px solid rgba(255, 255, 255, 0.2);

      &.open {
        background: rgba(34, 197, 94, 0.2);
        color: #4ade80;
        border-color: rgba(34, 197, 94, 0.4);
      }
    }

    .online-count {
      font-size: 14px;
      color: $color-text-muted;
    }

    .connection-dot {
      width: 10px;
      height: 10px;
      border-radius: 50%;
      background: #666;

      &.connected {
        background: #4ade80;
        box-shadow: 0 0 10px rgba(74, 222, 128, 0.5);
      }
    }
  }
}

.legend {
  position: absolute;
  bottom: 80px;
  left: 40px;
  display: flex;
  gap: 24px;
  background: rgba(0, 0, 0, 0.6);
  padding: 12px 24px;
  border-radius: 8px;
  backdrop-filter: blur(10px);

  .legend-item {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    color: $color-text-muted;
  }

  .legend-icon {
    width: 16px;
    height: 16px;
    border-radius: 50%;

    &.start {
      background: $color-gold;
      opacity: 0.5;
    }

    &.finish {
      background: linear-gradient(135deg, $color-gold 50%, transparent 50%);
      border: 2px solid $color-gold;
    }

    &.horse {
      background: radial-gradient(circle, #fff 0%, $color-gold 50%, transparent 100%);
      box-shadow: 0 0 10px $color-gold;
    }
  }
}

.footer-hint {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.6);
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 14px;
  color: $color-text-muted;
  backdrop-filter: blur(10px);
}
</style>
