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

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

// 节目列表
const programs = ref<VotingProgram[]>([]);
const votingOpen = ref(false);
const totalVotes = ref(0);

// Grid ref for stamp animation targeting
const gridRef = ref<InstanceType<typeof PostcardGrid> | null>(null);

// 格式化投票总数
const formattedVotes = computed(() => {
  return totalVotes.value.toLocaleString();
});

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

// 处理状态同步
function handleStateSync(state: AdminState) {
  programs.value = state.voting.programs;
  votingOpen.value = state.voting.subPhase === 'OPEN';
  totalVotes.value = state.voting.totalVotes;
}

// 监听投票更新事件
function handleVoteUpdate(data: { candidateId: string; totalVotes: number; stamp?: any }) {
  const program = programs.value.find(p => p.id === data.candidateId);
  if (program) {
    program.votes = data.totalVotes;
    // 如果有印章信息，添加到列表触发动画
    if (data.stamp) {
      if (!program.stamps) program.stamps = [];
      program.stamps.push(data.stamp);
    }
    // 更新总票数
    totalVotes.value = programs.value.reduce((sum, p) => sum + p.votes, 0);
  }
}

onMounted(() => {
  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);
    // 请求初始状态
    socket.emit(SOCKET_EVENTS.ADMIN_STATE_SYNC as any);
  }
});

onUnmounted(() => {
  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="live-voting-view">
    <!-- 头部信息栏 -->
    <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">{{ formattedVotes }}</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>

    <!-- 明信片网格 -->
    <main class="grid-container">
      <PostcardGrid
        ref="gridRef"
        :programs="programs"
        :columns="4"
        :rows="2"
      />
    </main>
  </div>
</template>


<style lang="scss" scoped>
// Philatelic postcard theme colors
$color-paper: #FDFBF7;
$color-ink: #2c2c2c;
$color-red: #c41e3a;
$color-gold: #d4af37;
$color-text-muted: #666;

.live-voting-view {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
  background: $color-paper;
  color: $color-ink;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 40px;
  position: relative;
  z-index: 100;
  background: rgba(255, 255, 255, 0.9);
  border-bottom: 1px solid #ddd;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  flex-wrap: wrap;
  gap: 12px;

  .back-btn {
    background: white;
    border: 1px solid $color-ink;
    color: $color-ink;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.2s;

    &:hover {
      background: $color-ink;
      color: white;
    }
  }

  .title {
    font-size: 32px;
    font-family: 'SimSun', 'Songti SC', serif;
    font-weight: bold;
    color: $color-red;
    letter-spacing: 8px;
  }

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

  .vote-counter {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    background: white;
    padding: 8px 16px;
    border-radius: 8px;
    border: 1px solid #ddd;

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

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

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

    .status-badge {
      padding: 6px 16px;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 500;
      background: #f5f5f5;
      color: $color-text-muted;
      border: 1px solid #ddd;

      &.open {
        background: rgba(34, 197, 94, 0.1);
        color: #16a34a;
        border-color: rgba(34, 197, 94, 0.3);
      }
    }

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

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

      &.connected {
        background: #22c55e;
      }
    }
  }

  // Responsive adjustments
  @media (max-width: 900px) {
    padding: 16px 20px;
    
    .title {
      font-size: 24px;
      letter-spacing: 4px;
    }
    
    .vote-counter .counter-value {
      font-size: 22px;
    }
  }

  @media (max-width: 600px) {
    padding: 12px 16px;
    justify-content: center;
    
    .title {
      font-size: 20px;
      letter-spacing: 2px;
      width: 100%;
      text-align: center;
      order: -1;
    }
    
    .back-btn {
      padding: 6px 12px;
      font-size: 12px;
    }
    
    .header-right {
      gap: 12px;
    }
    
    .vote-counter {
      padding: 6px 12px;
      
      .counter-value {
        font-size: 18px;
      }
    }
    
    .status {
      .online-count {
        display: none;
      }
    }
  }
}

.grid-container {
  flex: 1;
  overflow: hidden;
}
</style>
