<template>
  <div>
    <nav class="tab-bar">
      <button v-for="tab in viewTabs" :key="tab.id" class="tab-btn" :class="{ active: viewTab === tab.id }" @click="$emit('change-tab', tab.id)">
        {{ tab.label }}
      </button>
    </nav>

    <section v-show="viewTab === 'groups'" class="panel">
      <div class="panel-heading">
        <h2>{{ t('sections.groupsTitle') }}</h2>
        <p>{{ t('sections.groupsSubtitle') }}</p>
      </div>

      <div class="summary-grid">
        <article v-for="group in groupSummaries" :key="group.code" class="summary-card" :class="'group-' + group.key">
          <h3>{{ t('labels.group') }} {{ group.code }}</h3>
          <p class="summary-value">{{ group.count }}</p>
          <p class="summary-status ok">{{ t('labels.players') }}</p>
        </article>
      </div>

      <div v-if="groupedPlayers.length > 0" class="view-group-grid">
        <article v-for="group in groupedPlayers" :key="'view-group-' + group.code" class="view-group-card" :class="'group-' + group.key">
          <div class="view-group-card-head">
            <h3>{{ groupLabel(group.code) }}</h3>
            <span class="pm-count-badge">{{ group.players.length }}</span>
          </div>
          <div class="table-wrap">
            <table class="score-table">
              <thead>
                <tr>
                  <th>#</th>
                  <th>{{ t('table.competitor') }}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="player in group.players" :key="'v-g-' + group.code + '-' + player.id" :class="rowClass(player.groupCode)">
                  <td class="mono">{{ player.id }}</td>
                  <td>
                    <div class="competitor-cell compact">
                      <img :src="playerImage(player)" :alt="player.nameAr" class="competitor-image" />
                      <div>
                        <p class="name-main">{{ displayName(player) }}</p>
                        <p class="name-sub">{{ secondaryName(player) }}</p>
                      </div>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </article>
      </div>
      <div v-else class="table-wrap">
        <table class="score-table">
          <tbody>
            <tr><td class="muted center">{{ t('labels.noPlayers') }}</td></tr>
          </tbody>
        </table>
      </div>
    </section>

    <section v-show="viewTab === 'live'" class="panel live-panel">
      <div class="live-corner">
        <div class="live-top-controls">
          <button class="btn btn-outline light" :class="{ active: liveMode === 'rotate' }" @click="$emit('change-live-mode', 'rotate')">
            {{ t('actions.liveRotate') }}
          </button>
          <button class="btn btn-outline light" :class="{ active: liveMode === 'fixed' }" @click="$emit('change-live-mode', 'fixed')">
            {{ t('actions.liveFixed') }}
          </button>
          <select
            v-if="liveMode === 'fixed'"
            class="group-select"
            :value="selectedLiveGroup"
            @change="$emit('change-live-group', $event.target.value)"
          >
            <option v-for="group in liveSelectableGroups" :key="'live-group-' + group" :value="group">{{ group }}</option>
          </select>
        </div>
      </div>
      <div class="live-title">{{ t('sections.liveTitle') }} · {{ liveGroupCode || t('labels.unassigned') }}</div>
      <p class="live-subtitle">{{ t('sections.liveSubtitle') }}</p>

      <div class="live-grid" v-if="liveMembers.length > 0">
        <article class="live-card" v-for="member in liveMembers" :key="'live-' + member.id">
          <img class="live-image" :src="playerImage(member)" :alt="member.nameAr" />
          <div>
            <p class="live-number">#{{ member.id }}</p>
            <p class="live-name-primary">{{ displayName(member) }}</p>
            <p class="live-name-secondary">{{ secondaryName(member) }}</p>
          </div>
        </article>
      </div>
      <div class="empty-state" v-else>{{ t('labels.emptyLive') }}</div>

      <div class="live-progress" :key="'tick-' + liveTick" />
    </section>

    <section v-show="viewTab === 'overall'" class="panel">
      <div class="panel-heading">
        <h2>{{ t('sections.overallTitle') }}</h2>
        <p>{{ t('sections.overallSubtitle') }}</p>
      </div>

      <div class="two-column">
        <div>
          <h3 class="sub-heading">{{ t('labels.allPlayers') }}</h3>
          <div class="table-wrap">
            <table class="score-table">
              <thead>
                <tr>
                  <th>{{ t('table.rank') }}</th>
                  <th>#</th>
                  <th>{{ t('table.competitor') }}</th>
                  <th>{{ t('table.group') }}</th>
                  <th>{{ t('table.score') }}</th>
                  <th>{{ t('table.tieScore') }}</th>
                  <th>{{ t('table.status') }}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="row in preliminaryRows" :key="'v-pr-' + row.playerId" :class="{ 'qualified-row': isFinalist(row.playerId) }">
                  <td class="mono rank">{{ row.rank }}</td>
                  <td class="mono">{{ row.playerId }}</td>
                  <td>
                    <div class="competitor-cell compact">
                      <img :src="playerImage(row)" :alt="row.nameAr" class="competitor-image" />
                      <div>
                        <p class="name-main">{{ displayName(row) }}</p>
                        <p class="name-sub">{{ secondaryName(row) }}</p>
                      </div>
                    </div>
                  </td>
                  <td class="mono">{{ row.groupCode || t('labels.unassigned') }}</td>
                  <td class="mono strong">
                    <span>{{ row.score }}</span>
                    <button
                      v-if="canViewProofs && preliminaryProofStage(row.playerId)"
                      class="proof-mini"
                      @click="$emit('open-proof', { stage: preliminaryProofStage(row.playerId), playerId: row.playerId })"
                    >
                      <img :src="scoreProofFor(preliminaryProofStage(row.playerId), row.playerId)" :alt="t('table.verification')" />
                    </button>
                  </td>
                  <td class="mono">
                    <span>{{ row.tieBreak }}</span>
                    <button
                      v-if="canViewProofs && hasScoreProof('prelim_tiebreak', row.playerId)"
                      class="proof-mini"
                      @click="$emit('open-proof', { stage: 'prelim_tiebreak', playerId: row.playerId })"
                    >
                      <img :src="scoreProofFor('prelim_tiebreak', row.playerId)" :alt="t('table.verification')" />
                    </button>
                  </td>
                  <td>
                    <span v-if="isFinalist(row.playerId)" class="badge success">{{ t('labels.finalist') }}</span>
                    <span v-else class="muted">{{ t('labels.notFinalist') }}</span>
                  </td>
                </tr>
                <tr v-if="preliminaryRows.length === 0"><td colspan="7" class="muted center">{{ t('labels.noPlayers') }}</td></tr>
              </tbody>
            </table>
          </div>
        </div>

        <div>
          <h3 class="sub-heading">{{ t('labels.top12') }}</h3>
          <div class="table-wrap">
            <table class="score-table">
              <thead>
                <tr>
                  <th>{{ t('table.seed') }}</th>
                  <th>{{ t('table.competitor') }}</th>
                  <th>{{ t('table.group') }}</th>
                  <th>{{ t('table.score') }}</th>
                  <th>{{ t('table.tieScore') }}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="row in finalists" :key="'v-top-' + row.playerId" class="qualified-row">
                  <td class="mono rank">{{ row.seed }}</td>
                  <td>
                    <div class="competitor-cell compact">
                      <img :src="playerImage(row)" :alt="row.nameAr" class="competitor-image" />
                      <div>
                        <p class="name-main">{{ displayName(row) }}</p>
                        <p class="name-sub">{{ secondaryName(row) }}</p>
                      </div>
                    </div>
                  </td>
                  <td class="mono">{{ row.groupCode || t('labels.unassigned') }}</td>
                  <td class="mono strong">{{ row.score }}</td>
                  <td class="mono">{{ row.tieBreak }}</td>
                </tr>
                <tr v-if="finalists.length === 0"><td colspan="5" class="muted center">{{ t('labels.noFinalists') }}</td></tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <div class="hint-box danger" v-if="prelimTie.required && !prelimTie.resolved">
        {{ t('messages.prelimTieUnresolved') }}
      </div>
    </section>

    <section v-show="viewTab === 'final'" class="panel">
      <div class="panel-heading">
        <h2>{{ t('sections.finalTitle') }}</h2>
        <p>{{ t('sections.finalSubtitle') }}</p>
      </div>

      <div class="two-column">
        <div>
          <h3 class="sub-heading">{{ t('labels.finalGroup1') }}</h3>
          <div class="table-wrap">
            <table class="score-table">
              <thead>
                <tr>
                  <th>{{ t('table.seed') }}</th>
                  <th>{{ t('table.competitor') }}</th>
                  <th>{{ t('table.score') }}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="row in finalGroup1" :key="'v-f1-' + row.playerId">
                  <td class="mono">{{ row.seed }}</td>
                  <td>
                    <div class="competitor-cell compact">
                      <img :src="playerImage(row)" :alt="row.nameAr" class="competitor-image" />
                      <div>
                        <p class="name-main">{{ displayName(row) }}</p>
                        <p class="name-sub">{{ secondaryName(row) }}</p>
                      </div>
                    </div>
                  </td>
                  <td class="mono strong">
                    <span>{{ finalTotalScore(row.playerId) }}</span>
                    <button
                      v-if="canViewProofs && finalProofStage(row.playerId)"
                      class="proof-mini"
                      @click="$emit('open-proof', { stage: finalProofStage(row.playerId), playerId: row.playerId })"
                    >
                      <img :src="scoreProofFor(finalProofStage(row.playerId), row.playerId)" :alt="t('table.verification')" />
                    </button>
                  </td>
                </tr>
                <tr v-if="finalGroup1.length === 0"><td colspan="3" class="muted center">{{ t('labels.noFinalists') }}</td></tr>
              </tbody>
            </table>
          </div>
        </div>

        <div>
          <h3 class="sub-heading">{{ t('labels.finalGroup2') }}</h3>
          <div class="table-wrap">
            <table class="score-table">
              <thead>
                <tr>
                  <th>{{ t('table.seed') }}</th>
                  <th>{{ t('table.competitor') }}</th>
                  <th>{{ t('table.score') }}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="row in finalGroup2" :key="'v-f2-' + row.playerId">
                  <td class="mono">{{ row.seed }}</td>
                  <td>
                    <div class="competitor-cell compact">
                      <img :src="playerImage(row)" :alt="row.nameAr" class="competitor-image" />
                      <div>
                        <p class="name-main">{{ displayName(row) }}</p>
                        <p class="name-sub">{{ secondaryName(row) }}</p>
                      </div>
                    </div>
                  </td>
                  <td class="mono strong">
                    <span>{{ row.score }}</span>
                    <button
                      v-if="canViewProofs && finalProofStage(row.playerId)"
                      class="proof-mini"
                      @click="$emit('open-proof', { stage: finalProofStage(row.playerId), playerId: row.playerId })"
                    >
                      <img :src="scoreProofFor(finalProofStage(row.playerId), row.playerId)" :alt="t('table.verification')" />
                    </button>
                  </td>
                </tr>
                <tr v-if="finalGroup2.length === 0"><td colspan="3" class="muted center">{{ t('labels.noFinalists') }}</td></tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <h3 class="sub-heading mt-32">{{ t('sections.finalRanking') }}</h3>
      <div class="table-wrap">
        <table class="score-table">
          <thead>
            <tr>
              <th>{{ t('table.rank') }}</th>
              <th>{{ t('table.competitor') }}</th>
              <th>{{ t('table.score') }}</th>
              <th>{{ t('table.tieScore') }}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="row in finalRows" :key="'v-fr-' + row.playerId" :class="{ 'podium-row': row.rank <= 3 }">
              <td class="mono rank">{{ row.rank }}</td>
              <td>
                <div class="competitor-cell compact">
                  <img :src="playerImage(row)" :alt="row.nameAr" class="competitor-image" />
                  <div>
                    <p class="name-main">{{ displayName(row) }}</p>
                    <p class="name-sub">{{ secondaryName(row) }}</p>
                  </div>
                </div>
              </td>
              <td class="mono strong">
                <span>{{ row.score }}</span>
                <button
                  v-if="canViewProofs && finalProofStage(row.playerId)"
                  class="proof-mini"
                  @click="$emit('open-proof', { stage: finalProofStage(row.playerId), playerId: row.playerId })"
                >
                  <img :src="scoreProofFor(finalProofStage(row.playerId), row.playerId)" :alt="t('table.verification')" />
                </button>
              </td>
              <td class="mono">
                <span>{{ row.tieBreak }}</span>
                <button
                  v-if="canViewProofs && hasScoreProof('final_tiebreak', row.playerId)"
                  class="proof-mini"
                  @click="$emit('open-proof', { stage: 'final_tiebreak', playerId: row.playerId })"
                >
                  <img :src="scoreProofFor('final_tiebreak', row.playerId)" :alt="t('table.verification')" />
                </button>
              </td>
            </tr>
            <tr v-if="finalRows.length === 0"><td colspan="4" class="muted center">{{ t('labels.noFinalists') }}</td></tr>
          </tbody>
        </table>
      </div>

      <div class="hint-box danger" v-if="finalTie.required && !finalTie.resolved">
        {{ t('messages.finalTieUnresolved') }}
      </div>
    </section>

    <section v-show="viewTab === 'podium'" class="panel podium-panel">
      <div class="panel-heading">
        <h2>{{ t('sections.podiumTitle') }}</h2>
        <p>{{ t('sections.podiumSubtitle') }}</p>
      </div>

      <div class="podium-wrapper">
        <article class="podium-col pos-2">
          <div class="podium-avatar-wrap">
            <img class="podium-img" :src="podiumImage(podiumOrdered[0])" :alt="podiumName(podiumOrdered[0])" />
          </div>
          <div class="podium-medal-icon">🥈</div>
          <h3 class="podium-name" :class="{ empty: !podiumHasResult(podiumOrdered[0]) }">{{ podiumName(podiumOrdered[0]) }}</h3>
          <div class="podium-score-wrap">
            <p class="podium-score">{{ podiumScoreMain(podiumOrdered[0]) }}</p>
            <p v-if="podiumTieSubtitle(podiumOrdered[0])" class="podium-score-sub">{{ podiumTieSubtitle(podiumOrdered[0]) }}</p>
          </div>
        </article>

        <article class="podium-col pos-1">
          <div class="podium-avatar-wrap">
            <img class="podium-img" :src="podiumImage(podiumOrdered[1])" :alt="podiumName(podiumOrdered[1])" />
          </div>
          <div class="podium-medal-icon">🥇</div>
          <h3 class="podium-name" :class="{ empty: !podiumHasResult(podiumOrdered[1]) }">{{ podiumName(podiumOrdered[1]) }}</h3>
          <div class="podium-score-wrap">
            <p class="podium-score">{{ podiumScoreMain(podiumOrdered[1]) }}</p>
            <p v-if="podiumTieSubtitle(podiumOrdered[1])" class="podium-score-sub">{{ podiumTieSubtitle(podiumOrdered[1]) }}</p>
          </div>
        </article>

        <article class="podium-col pos-3">
          <div class="podium-avatar-wrap">
            <img class="podium-img" :src="podiumImage(podiumOrdered[2])" :alt="podiumName(podiumOrdered[2])" />
          </div>
          <div class="podium-medal-icon">🥉</div>
          <h3 class="podium-name" :class="{ empty: !podiumHasResult(podiumOrdered[2]) }">{{ podiumName(podiumOrdered[2]) }}</h3>
          <div class="podium-score-wrap">
            <p class="podium-score">{{ podiumScoreMain(podiumOrdered[2]) }}</p>
            <p v-if="podiumTieSubtitle(podiumOrdered[2])" class="podium-score-sub">{{ podiumTieSubtitle(podiumOrdered[2]) }}</p>
          </div>
        </article>
      </div>
    </section>
  </div>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  t: { type: Function, required: true },
  viewTabs: { type: Array, required: true },
  viewTab: { type: String, required: true },
  groupSummaries: { type: Array, required: true },
  playersSorted: { type: Array, required: true },
  rowClass: { type: Function, required: true },
  playerImage: { type: Function, required: true },
  displayName: { type: Function, required: true },
  secondaryName: { type: Function, required: true },
  liveMode: { type: String, required: true },
  selectedLiveGroup: { type: String, default: '' },
  liveSelectableGroups: { type: Array, required: true },
  liveGroupCode: { type: String, default: '' },
  liveMembers: { type: Array, required: true },
  liveTick: { type: Number, required: true },
  preliminaryRows: { type: Array, required: true },
  finalists: { type: Array, required: true },
  isFinalist: { type: Function, required: true },
  prelimTie: { type: Object, required: true },
  finalGroup1: { type: Array, required: true },
  finalGroup2: { type: Array, required: true },
  finalRows: { type: Array, required: true },
  finalTie: { type: Object, required: true },
  finalTotalScore: { type: Function, required: true },
  preliminaryProofStage: { type: Function, required: true },
  finalProofStage: { type: Function, required: true },
  podiumOrdered: { type: Array, required: true },
  podiumImage: { type: Function, required: true },
  podiumName: { type: Function, required: true },
  podiumHasResult: { type: Function, required: true },
  podiumScoreMain: { type: Function, required: true },
  podiumTieSubtitle: { type: Function, required: true },
  canViewProofs: { type: Boolean, default: false },
  hasScoreProof: { type: Function, required: true },
  scoreProofFor: { type: Function, required: true },
})

const groupedPlayers = computed(() => {
  const map = new Map()
  const unassigned = props.t('labels.unassigned')
  for (const player of props.playersSorted) {
    const code = (player.groupCode || '').trim() || unassigned
    if (!map.has(code)) map.set(code, [])
    map.get(code).push(player)
  }
  return [...map.entries()]
    .sort((a, b) => {
      if (a[0] === unassigned) return 1
      if (b[0] === unassigned) return -1
      return String(a[0]).localeCompare(String(b[0]), undefined, { numeric: true, sensitivity: 'base' })
    })
    .map(([code, players]) => ({
      code,
      key: resolveGroupKey(code, unassigned),
      players: [...players].sort((p1, p2) => p1.id - p2.id),
    }))
})

function resolveGroupKey(code, unassigned) {
  if (code === unassigned) return 'u'
  const normalized = String(code || '').trim().toUpperCase()
  if (normalized.startsWith('A')) return 'a'
  if (normalized.startsWith('B')) return 'b'
  if (normalized.startsWith('C')) return 'c'
  if (normalized.startsWith('D')) return 'd'
  return 'u'
}

function groupLabel(code) {
  const unassigned = props.t('labels.unassigned')
  if (code === unassigned) return unassigned
  return `${props.t('labels.group')} ${code}`
}

defineEmits(['change-tab', 'change-live-mode', 'change-live-group', 'open-proof'])
</script>
