<script setup lang="ts">
import { computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useAdminStore } from '../stores/admin';
import { TICKET_TYPES } from '@gala/shared/constants';

const router = useRouter();
const admin = useAdminStore();

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

// Award type labels
const awardLabels: Record<string, string> = {
  creative: '最佳创意奖',
  visual: '最佳视觉奖',
  atmosphere: '最佳气氛奖',
  performance: '最佳表演奖',
  teamwork: '最佳团队奖',
  popularity: '最受欢迎奖',
  potential: '最具潜力奖',
};

// Compute award statistics grouped by award type
const awardResults = computed(() => {
  const results: Array<{
    awardType: string;
    awardName: string;
    programs: Array<{ id: string; name: string; teamName: string; votes: number; percentage: number }>;
    totalVotes: number;
  }> = [];

  // Process each award type
  TICKET_TYPES.forEach(awardType => {
    const programStats: Map<string, { name: string; teamName: string; votes: number }> = new Map();
    
    // Aggregate stamps by program for this award type
    admin.programs.forEach(program => {
      if (program.stamps && program.stamps.length > 0) {
        const count = program.stamps.filter((s: any) => s.ticketType === awardType).length;
        if (count > 0) {
          programStats.set(program.id, {
            name: program.name,
            teamName: program.teamName,
            votes: count,
          });
        }
      }
    });

    // Calculate total votes for this award
    let totalVotes = 0;
    programStats.forEach(p => totalVotes += p.votes);

    // Convert to array and sort by votes descending
    const programs = Array.from(programStats.entries())
      .map(([id, data]) => ({
        id,
        name: data.name,
        teamName: data.teamName,
        votes: data.votes,
        percentage: totalVotes > 0 ? Math.round((data.votes / totalVotes) * 100) : 0,
      }))
      .sort((a, b) => b.votes - a.votes)
      .slice(0, 5); // Top 5 per award

    results.push({
      awardType,
      awardName: awardLabels[awardType] || awardType,
      programs,
      totalVotes,
    });
  });

  return results;
});

// Connect to admin store on mount
onMounted(() => {
  admin.connect();
});
</script>

<template>
  <div class="vote-results-view">
    <!-- Header -->
    <header class="header">
      <button class="back-btn" @click="goBack">← 返回</button>
      <h1 class="title gold-text">投票结果</h1>
      <div class="status-indicator">
        <span class="dot" :class="admin.isConnected ? 'online' : 'offline'"></span>
        {{ admin.isConnected ? '已连接' : '连接中...' }}
      </div>
    </header>

    <!-- Results grid - 7 award categories -->
    <main class="results-grid">
      <div v-for="award in awardResults" :key="award.awardType" class="category-card">
        <div class="category-header">
          <h2 class="category-name">{{ award.awardName }}</h2>
          <span class="total-votes">{{ award.totalVotes }} 票</span>
        </div>
        
        <div class="results-list">
          <div v-if="award.programs.length === 0" class="no-results">
            暂无投票
          </div>
          <div
            v-else
            v-for="(result, index) in award.programs"
            :key="result.id"
            class="result-item"
            :class="{ winner: index === 0 }"
          >
            <span class="rank">{{ index + 1 }}</span>
            <div class="info">
              <span class="name">{{ result.name }}</span>
              <span class="team">{{ result.teamName }}</span>
            </div>
            <div class="bar-container">
              <div class="bar" :style="{ width: result.percentage + '%' }"></div>
            </div>
            <span class="votes">{{ result.votes }}票</span>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<style lang="scss" scoped>
@use '../assets/styles/variables.scss' as *;

.vote-results-view {
  width: 100%;
  height: 100%;
  background: $color-bg-gradient;
  display: flex;
  flex-direction: column;
  overflow: auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 40px;
  flex-shrink: 0;

  .back-btn {
    background: none;
    border: 1px solid $color-gold;
    color: $color-gold;
    padding: 8px 16px;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
    transition: all $transition-fast;

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

  .title {
    font-size: 36px;
    font-weight: bold;
  }

  .status-indicator {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    color: rgba(255, 255, 255, 0.6);

    .dot {
      width: 8px;
      height: 8px;
      border-radius: 50%;

      &.online {
        background: #22c55e;
        box-shadow: 0 0 8px rgba(34, 197, 94, 0.5);
      }

      &.offline {
        background: #666;
      }
    }
  }
}

.results-grid {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  gap: 20px;
  padding: 20px 40px 40px;
  align-content: start;
}

.category-card {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba($color-gold, 0.3);
  border-radius: 12px;
  padding: 20px;

  .category-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid rgba($color-gold, 0.2);
  }

  .category-name {
    font-size: 20px;
    color: $color-gold;
    font-weight: 600;
    margin: 0;
  }

  .total-votes {
    font-size: 14px;
    color: rgba(255, 255, 255, 0.5);
    background: rgba($color-gold, 0.1);
    padding: 4px 10px;
    border-radius: 12px;
  }

  .results-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .no-results {
    padding: 20px;
    text-align: center;
    color: rgba(255, 255, 255, 0.4);
    font-style: italic;
  }

  .result-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 10px 12px;
    background: rgba(255, 255, 255, 0.03);
    border-radius: 8px;

    &.winner {
      background: rgba($color-gold, 0.1);
      border: 1px solid $color-gold;

      .rank {
        background: $color-gold;
        color: #000;
      }

      .name {
        color: $color-gold;
      }

      .bar {
        background: linear-gradient(90deg, $color-gold-dark, $color-gold);
      }
    }

    .rank {
      width: 26px;
      height: 26px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 50%;
      font-size: 13px;
      font-weight: bold;
      flex-shrink: 0;
    }

    .info {
      display: flex;
      flex-direction: column;
      min-width: 80px;
      max-width: 100px;
    }

    .name {
      font-size: 14px;
      color: $color-text-light;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .team {
      font-size: 11px;
      color: rgba(255, 255, 255, 0.4);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .bar-container {
      flex: 1;
      height: 18px;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 9px;
      overflow: hidden;

      .bar {
        height: 100%;
        background: linear-gradient(90deg, $color-primary-dark, $color-primary);
        border-radius: 9px;
        transition: width 1s ease;
      }
    }

    .votes {
      width: 50px;
      text-align: right;
      font-size: 14px;
      color: $color-text-muted;
      flex-shrink: 0;
    }
  }
}

// Responsive
@media (max-width: 768px) {
  .header {
    padding: 16px 20px;

    .title {
      font-size: 24px;
    }
  }

  .results-grid {
    grid-template-columns: 1fr;
    padding: 16px 20px;
    gap: 16px;
  }

  .category-card {
    padding: 16px;

    .category-name {
      font-size: 18px;
    }
  }
}
</style>
