<template>
  <div>
    <div class="stage-filter-bar" v-if="showFilter">
      <input
        class="name-input"
        :value="filterText"
        :placeholder="t('actions.searchPlayer')"
        @input="$emit('update:filter', $event.target.value)"
      />
    </div>

    <div class="table-wrap desktop-score-table">
      <table class="score-table">
        <thead>
          <tr>
            <th>#</th>
            <th>{{ t('table.competitor') }}</th>
            <th v-if="showGroup">{{ t('table.group') }}</th>
            <th v-if="showRank">{{ t('table.rank') }}</th>
            <th v-if="showSeed">{{ t('table.seed') }}</th>
            <th v-for="round in roundStages" :key="'head-' + round.stage">{{ round.label }}</th>
            <th>{{ t('table.total') }}</th>
            <th>{{ t('table.verification') }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, index) in filteredRows" :key="'multi-row-' + row.playerId" class="score-group-row" :style="scoreGroupStyleFor(row)">
            <td class="mono">{{ index + 1 }}</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 v-if="showGroup" class="mono">{{ groupCell(row) }}</td>
            <td v-if="showRank" class="mono rank">{{ row.rank }}</td>
            <td v-if="showSeed" class="mono">{{ row.seed }}</td>
            <td v-for="round in roundStages" :key="'cell-' + round.stage + '-' + row.playerId" class="multi-round-cell">
              <input
                class="score-input score-input-compact"
                type="number"
                inputmode="numeric"
                pattern="[0-9]*"
                min="0"
                max="9999"
                :value="scoreInputValue(round.stage, row.playerId)"
                @focus="onScoreFocus(round.stage, row.playerId)"
                @input="onScoreInput(round.stage, row.playerId, $event)"
                @blur="onScoreCommit(round.stage, row.playerId)"
                @keydown.enter.prevent="onScoreCommit(round.stage, row.playerId)"
              />
            </td>
            <td class="mono strong">{{ totalScore(row.playerId) }}</td>
            <td class="verify-round-cell">
              <div class="verify-round-list">
                <div v-for="round in roundStages" :key="'verify-' + round.stage + '-' + row.playerId" class="verify-round-item">
                  <span class="verify-round-label">{{ round.label }}</span>
                  <button class="btn btn-outline btn-xs" @click="openScoreProofUploader(round.stage, row.playerId)">
                    {{ hasScoreProof(round.stage, row.playerId) ? t('actions.replaceProof') : t('actions.uploadProof') }}
                  </button>
                  <img
                    v-if="hasScoreProof(round.stage, row.playerId)"
                    class="proof-thumb"
                    :src="scoreProofFor(round.stage, row.playerId)"
                    :alt="t('table.verification')"
                    @click="openProofPreview(round.stage, row.playerId)"
                  />
                </div>
              </div>
            </td>
          </tr>
          <tr v-if="filteredRows.length === 0">
            <td :colspan="columnCount" class="muted center">{{ t('labels.noPlayers') }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="mobile-score-cards">
      <article v-for="(row, index) in filteredRows" :key="'multi-mobile-' + row.playerId" class="score-card score-group-card" :style="scoreGroupStyleFor(row)">
        <div class="score-card-head">
          <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>
          <div class="mono">#{{ index + 1 }}</div>
        </div>

        <div class="score-card-meta">
          <span v-if="showGroup">{{ t('table.group') }}: {{ groupCell(row) }}</span>
          <span v-if="showRank">{{ t('table.rank') }}: {{ row.rank }}</span>
          <span v-if="showSeed">{{ t('table.seed') }}: {{ row.seed }}</span>
        </div>

        <div class="mobile-round-grid">
          <label v-for="round in roundStages" :key="'mobile-round-' + round.stage + '-' + row.playerId" class="mobile-round-item">
            <span class="score-label">{{ round.label }}</span>
            <input
              class="score-input"
              type="number"
              inputmode="numeric"
              pattern="[0-9]*"
              min="0"
              max="9999"
              :value="scoreInputValue(round.stage, row.playerId)"
              @focus="onScoreFocus(round.stage, row.playerId)"
              @input="onScoreInput(round.stage, row.playerId, $event)"
              @blur="onScoreCommit(round.stage, row.playerId)"
              @keydown.enter.prevent="onScoreCommit(round.stage, row.playerId)"
            />
          </label>
        </div>

        <div class="mobile-total-line">
          <span class="muted">{{ t('table.total') }}</span>
          <strong class="mono">{{ totalScore(row.playerId) }}</strong>
        </div>

        <div class="mobile-verify-block">
          <p class="mobile-verify-title">{{ t('table.verification') }}</p>
          <div class="verify-round-list mobile">
            <div v-for="round in roundStages" :key="'mobile-verify-' + round.stage + '-' + row.playerId" class="verify-round-item">
              <span class="verify-round-label">{{ round.label }}</span>
              <button class="btn btn-outline btn-xs" @click="openScoreProofUploader(round.stage, row.playerId)">
                {{ hasScoreProof(round.stage, row.playerId) ? t('actions.replaceProof') : t('actions.uploadProof') }}
              </button>
              <img
                v-if="hasScoreProof(round.stage, row.playerId)"
                class="proof-thumb"
                :src="scoreProofFor(round.stage, row.playerId)"
                :alt="t('table.verification')"
                @click="openProofPreview(round.stage, row.playerId)"
              />
            </div>
          </div>
        </div>
      </article>
      <div v-if="filteredRows.length === 0" class="empty-state">{{ t('labels.noPlayers') }}</div>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { scoreGroupStyle } from '../../utils/scoreGroupTheme'

const props = defineProps({
  t: { type: Function, required: true },
  rows: { type: Array, required: true },
  roundStages: { type: Array, required: true },
  totalScore: { type: Function, required: true },
  showFilter: { type: Boolean, default: true },
  filterText: { type: String, default: '' },
  showGroup: { type: Boolean, default: false },
  showRank: { type: Boolean, default: false },
  showSeed: { type: Boolean, default: false },
  playerImage: { type: Function, required: true },
  displayName: { type: Function, required: true },
  secondaryName: { type: Function, required: true },
  scoreInputValue: { type: Function, required: true },
  onScoreFocus: { type: Function, required: true },
  onScoreInput: { type: Function, required: true },
  onScoreCommit: { type: Function, required: true },
  hasScoreProof: { type: Function, required: true },
  scoreProofFor: { type: Function, required: true },
  openScoreProofUploader: { type: Function, required: true },
  openProofPreview: { type: Function, required: true },
})

defineEmits(['update:filter'])

const filteredRows = computed(() => {
  const query = String(props.filterText || '').trim().toLowerCase()
  if (!query) return props.rows
  return props.rows.filter((row) => {
    const ar = String(row.nameAr || '')
    const en = String(row.nameEn || '').toLowerCase()
    return ar.includes(query) || en.includes(query)
  })
})

const columnCount = computed(() => {
  let count = 4 + props.roundStages.length
  if (props.showGroup) count += 1
  if (props.showRank) count += 1
  if (props.showSeed) count += 1
  return count
})

function groupCell(row) {
  if (row.finalGroup === 1 || row.finalGroup === 2) {
    return row.finalGroup
  }
  return row.groupCode || props.t('labels.unassigned')
}

function scoreGroupStyleFor(row) {
  return scoreGroupStyle(row)
}
</script>
