<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="showScoreBeforeInput">{{ t('table.score') }}</th>
            <th>{{ inputLabel }}</th>
            <th>{{ t('table.verification') }}</th>
            <th v-if="showRank">{{ t('table.rank') }}</th>
            <th v-if="showSeed">{{ t('table.seed') }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, index) in filteredRows" :key="'desk-' + stage + '-' + 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">{{ row.groupCode || t('labels.unassigned') }}</td>
            <td v-if="showScoreBeforeInput" class="mono strong">{{ row.score }}</td>
            <td>
              <input
                class="score-input"
                type="number"
                inputmode="numeric"
                pattern="[0-9]*"
                min="0"
                max="9999"
                :value="scoreInputValue(stage, row.playerId)"
                @focus="onScoreFocus(stage, row.playerId)"
                @input="onScoreInput(stage, row.playerId, $event)"
                @blur="onScoreCommit(stage, row.playerId)"
                @keydown.enter.prevent="onScoreCommit(stage, row.playerId)"
              />
            </td>
            <td>
              <div class="proof-actions">
                <button class="btn btn-outline btn-xs" @click="openScoreProofUploader(stage, row.playerId)">
                  {{ hasScoreProof(stage, row.playerId) ? t('actions.replaceProof') : t('actions.uploadProof') }}
                </button>
                <!-- <button
                  v-if="hasScoreProof(stage, row.playerId)"
                  class="btn btn-ai btn-xs"
                  @click="requestScoreAdvice(stage, row.playerId)"
                >
                  {{ t('actions.aiAdvisor') }}
                </button> -->
                <button v-if="hasScoreProof(stage, row.playerId)" class="btn btn-danger btn-xs" @click="removeScoreProof(stage, row.playerId)">
                  {{ t('actions.removeProof') }}
                </button>
                <img
                  v-if="hasScoreProof(stage, row.playerId)"
                  class="proof-thumb"
                  :src="scoreProofFor(stage, row.playerId)"
                  :alt="t('table.verification')"
                  @click="openProofPreview(stage, row.playerId)"
                />
              </div>
            </td>
            <td v-if="showRank" class="mono rank">{{ row.rank }}</td>
            <td v-if="showSeed" class="mono">{{ row.seed }}</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="'mob-' + stage + '-' + 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') }}: {{ row.groupCode || t('labels.unassigned') }}</span>
          <span v-if="showScoreBeforeInput">{{ t('table.score') }}: {{ row.score }}</span>
          <span v-if="showRank">{{ t('table.rank') }}: {{ row.rank }}</span>
          <span v-if="showSeed">{{ t('table.seed') }}: {{ row.seed }}</span>
        </div>

        <label class="score-label">{{ inputLabel }}</label>
        <input
          class="score-input"
          type="number"
          inputmode="numeric"
          pattern="[0-9]*"
          min="0"
          max="9999"
          :value="scoreInputValue(stage, row.playerId)"
          @focus="onScoreFocus(stage, row.playerId)"
          @input="onScoreInput(stage, row.playerId, $event)"
          @blur="onScoreCommit(stage, row.playerId)"
          @keydown.enter.prevent="onScoreCommit(stage, row.playerId)"
        />

        <div class="proof-actions mobile-proof-actions">
          <button class="btn btn-outline btn-xs" @click="openScoreProofUploader(stage, row.playerId)">
            {{ hasScoreProof(stage, row.playerId) ? t('actions.replaceProof') : t('actions.uploadProof') }}
          </button>
          <!-- <button
            v-if="hasScoreProof(stage, row.playerId)"
            class="btn btn-ai btn-xs"
            @click="requestScoreAdvice(stage, row.playerId)"
          >
            {{ t('actions.aiAdvisor') }}
          </button> -->
          
          <button v-if="hasScoreProof(stage, row.playerId)" class="btn btn-danger btn-xs" @click="removeScoreProof(stage, row.playerId)">
            {{ t('actions.removeProof') }}
          </button>
          <img
            v-if="hasScoreProof(stage, row.playerId)"
            class="proof-thumb"
            :src="scoreProofFor(stage, row.playerId)"
            :alt="t('table.verification')"
            @click="openProofPreview(stage, row.playerId)"
          />
        </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, scoreValueStyle } from '../../utils/scoreGroupTheme'

const props = defineProps({
  t: { type: Function, required: true },
  stage: { type: String, required: true },
  rows: { type: Array, 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 },
  colorMode: { type: String, default: 'group' },
  showScoreBeforeInput: { type: Boolean, default: false },
  inputLabel: { type: String, required: true },
  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 },
  removeScoreProof: { type: Function, required: true },
  openProofPreview: { type: Function, required: true },
  requestScoreAdvice: { 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
  if (props.showGroup) count += 1
  if (props.showScoreBeforeInput) count += 1
  if (props.showRank) count += 1
  if (props.showSeed) count += 1
  return count
})

function scoreGroupStyleFor(row) {
  if (props.colorMode === 'score') {
    return scoreValueStyle(row?.score)
  }
  return scoreGroupStyle(row)
}
</script>
