<template>
  <section class="panel">
    <div class="panel-heading">
      <h2>{{ t('sections.playersTitle') }}</h2>
      <p>{{ t('sections.playersSubtitle') }}</p>
    </div>

    <div class="pm-config-card">
      <div class="pm-config-top">
        <div class="pm-config-input">
          <input
            :value="groupSetupInput"
            class="name-input en"
            dir="ltr"
            :placeholder="t('sections.groupsConfigPlaceholder')"
            @input="$emit('update:group-setup-input', $event.target.value)"
          />
          <button class="btn btn-outline" @click="$emit('save-group-setup')">{{ t('actions.updateGroups') }}</button>
        </div>
        <button class="btn btn-primary" @click="$emit('auto-group-even')">{{ t('actions.randomEvenGroups') }}</button>
      </div>

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

    <div class="pm-composer-card">
      <div class="pm-composer-grid">
        <input
          :value="newPlayer.nameAr"
          class="name-input ar"
          :placeholder="t('table.arabicName')"
          @input="$emit('update:new-player', { key: 'nameAr', value: $event.target.value })"
        />
        <input
          :value="newPlayer.nameEn"
          class="name-input en"
          dir="ltr"
          :placeholder="t('table.englishName')"
          @input="$emit('update:new-player', { key: 'nameEn', value: $event.target.value })"
        />
        <select
          :value="newPlayer.groupCode"
          class="name-input"
          @change="$emit('update:new-player', { key: 'groupCode', value: $event.target.value })"
        >
          <option value="">{{ groupOptionLabel('') }}</option>
          <option v-for="group in assignableGroups" :key="'new-group-' + group" :value="group">{{ groupOptionLabel(group) }}</option>
        </select>
        <button class="btn btn-primary" @click="$emit('create-player')">{{ t('actions.addPlayer') }}</button>
      </div>

      <div class="pm-composer-actions">
        <button class="btn btn-outline" @click="$emit('convert-new-name', 'ar_to_en')">{{ t('actions.convertArToEn') }}</button>
        <button class="btn btn-outline" @click="$emit('convert-new-name', 'en_to_ar')">{{ t('actions.convertEnToAr') }}</button>
      </div>
    </div>

    <div class="players-tools players-tools-elevated">
      <input
        class="name-input"
        :value="playerFilter"
        :placeholder="t('actions.searchPlayer')"
        @input="$emit('update:player-filter', $event.target.value)"
      />
      <div class="players-sort-box">
        <label class="control-label">{{ t('labels.sortBy') }}</label>
        <select class="name-input" :value="playerSort" @change="$emit('update:player-sort', $event.target.value)">
          <option value="id">{{ t('actions.sortById') }}</option>
          <option value="nameAr">{{ t('actions.sortByArabic') }}</option>
          <option value="nameEn">{{ t('actions.sortByEnglish') }}</option>
          <option value="group">{{ t('actions.sortByGroup') }}</option>
        </select>
      </div>
    </div>

    <div class="group-cards-grid">
      <article v-for="group in groupedCards" :key="'group-card-' + group.code" class="group-player-card" :class="'group-' + group.key">
        <header class="group-player-card-head">
          <h3>{{ group.label }}</h3>
          <span class="pm-count-badge mono">{{ group.players.length }}</span>
        </header>

        <div class="group-player-list" v-if="group.players.length > 0">
          <div class="group-player-row" v-for="player in group.players" :key="'card-player-' + player.id">
            <div class="group-player-top">
              <div class="competitor-cell">
                <img :src="playerImage(player)" :alt="player.nameAr" class="competitor-image clickable" @click="$emit('open-image-uploader', player.id)" />
                <div class="name-edit-grid vertical">
                  <input
                    class="name-input ar"
                    :value="player.nameAr"
                    :placeholder="t('table.arabicName')"
                    @blur="$emit('update-player-field', { player, field: 'nameAr', event: $event })"
                  />
                  <input
                    class="name-input en"
                    dir="ltr"
                    :value="player.nameEn"
                    :placeholder="t('table.englishName')"
                    @blur="$emit('update-player-field', { player, field: 'nameEn', event: $event })"
                  />
                </div>
              </div>
            </div>

            <div class="panel-actions compact name-convert-row">
              <button class="btn btn-outline btn-xs" @click="$emit('convert-row-name', { player, direction: 'ar_to_en' })">{{ t('actions.convertArToEn') }}</button>
              <button class="btn btn-outline btn-xs" @click="$emit('convert-row-name', { player, direction: 'en_to_ar' })">{{ t('actions.convertEnToAr') }}</button>
            </div>

            <div class="group-player-actions">
              <select
                class="name-input"
                :value="normalizedGroupCode(player.groupCode)"
                @change="$emit('update-player-group', { player, event: $event })"
              >
                <option value="">{{ groupOptionLabel('') }}</option>
                <option v-for="item in assignableGroups" :key="'player-group-' + player.id + '-' + item" :value="item">
                  {{ groupOptionLabel(item) }}
                </option>
              </select>
              <button class="btn btn-outline" @click="$emit('remove-player-image', player.id)">{{ t('actions.removeImage') }}</button>
              <button class="btn btn-danger" @click="$emit('delete-player', player.id)">{{ t('actions.delete') }}</button>
            </div>
          </div>
        </div>

        <div v-else class="empty-state">{{ t('labels.noPlayers') }}</div>
      </article>
    </div>
  </section>
</template>

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

const props = defineProps({
  t: { type: Function, required: true },
  groupSetupInput: { type: String, default: '' },
  adminGroupCards: { type: Array, required: true },
  newPlayer: { type: Object, required: true },
  assignableGroups: { type: Array, required: true },
  playersSorted: { type: Array, required: true },
  playerFilter: { type: String, default: '' },
  playerSort: { type: String, default: 'id' },
  playerImage: { type: Function, required: true },
  groupOptionLabel: { type: Function, required: true },
  normalizedGroupCode: { type: Function, required: true },
})

defineEmits([
  'update:group-setup-input',
  'save-group-setup',
  'auto-group-even',
  'update:new-player',
  'create-player',
  'convert-new-name',
  'update:player-filter',
  'update:player-sort',
  'open-image-uploader',
  'update-player-field',
  'update-player-group',
  'convert-row-name',
  'remove-player-image',
  'delete-player',
])

const filteredPlayers = computed(() => {
  const query = String(props.playerFilter || '').trim().toLowerCase()
  if (!query) return props.playersSorted
  return props.playersSorted.filter((player) => {
    const ar = String(player.nameAr || '')
    const en = String(player.nameEn || '').toLowerCase()
    return ar.includes(query) || en.includes(query)
  })
})

const sortedPlayers = computed(() => {
  const items = [...filteredPlayers.value]
  items.sort((a, b) => comparePlayers(a, b, props.playerSort))
  return items
})

const groupedCards = computed(() => {
  const groups = []
  const groupMap = new Map()

  for (const raw of props.assignableGroups || []) {
    const code = props.normalizedGroupCode(raw)
    if (!code || groupMap.has(code)) continue
    groupMap.set(code, [])
    groups.push(code)
  }

  for (const player of sortedPlayers.value) {
    const code = props.normalizedGroupCode(player.groupCode)
    if (!code) continue
    if (!groupMap.has(code)) {
      groupMap.set(code, [])
      groups.push(code)
    }
    groupMap.get(code).push(player)
  }

  const unassigned = sortedPlayers.value.filter((player) => !props.normalizedGroupCode(player.groupCode))

  const cards = groups.map((code) => ({
    code,
    key: groupVisualKey(code),
    label: `${props.t('labels.group')} ${code}`,
    players: groupMap.get(code) || [],
  }))

  cards.push({
    code: '',
    key: 'u',
    label: props.t('labels.unassigned'),
    players: unassigned,
  })

  return cards
})

function comparePlayers(a, b, sort) {
  if (sort === 'nameAr') {
    return String(a.nameAr || '').localeCompare(String(b.nameAr || ''), 'ar') || a.id - b.id
  }
  if (sort === 'nameEn') {
    return String(a.nameEn || '').localeCompare(String(b.nameEn || ''), 'en') || a.id - b.id
  }
  if (sort === 'group') {
    const ga = props.normalizedGroupCode(a.groupCode)
    const gb = props.normalizedGroupCode(b.groupCode)
    if (ga !== gb) {
      if (!ga) return 1
      if (!gb) return -1
      return ga.localeCompare(gb)
    }
    return a.id - b.id
  }
  return a.id - b.id
}

function groupVisualKey(code) {
  const normalized = props.normalizedGroupCode(code)
  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'
}
</script>
