<script setup lang="ts">
import { createStringMatrix } from '@/common/helpers'
import { computed } from 'vue'

const props = defineProps(['games', 'finalScore', 'winner'])

const playerNames = computed<any[]>(() =>
  (props.finalScore || []).map((score: any) => {
    const type = score.name === props.winner.name ? 'winner-name' : 'name'
    return { type, value: score.name }
  }),
)
const totals = computed<any[]>(() =>
  props.finalScore.map((score: any) => {
    const type = score.name === props.winner.name ? 'winner-final-score' : 'final-score'
    return { type, value: `${score.score}` }
  }),
)
const matrix = computed<any[][]>(() => {
  if (props.games === undefined) {
    return []
  }
  const m = props.games.map((game: any) => {
    const winner = game.winner.name
    return game.players.map((player: any) => {
      const type = player.name === winner ? 'winner-score' : 'score'
      return { type, value: `${player.score}` }
    })
  })
  m.unshift(playerNames.value)
  m.push(totals.value)
  const rows = m.length
  const cols = m[0].length
  const t: any[][] = createStringMatrix(cols, rows)
  try {
    for (let row = 0; row < m.length; row++) {
      for (let col = 0; col < m[0].length; col++) {
        t[col][row] = m[row][col]
      }
    }
  } catch (error) {
    console.error('error :>> ', error)
  }
  return t
})

function getCellClasses(value: any) {
  const { type } = value
  return {
    'has-text-weight-bold':
      type === 'name' ||
      type === 'final-score' ||
      type === 'winner-final-score' ||
      type === 'winner-name',
    'has-text-primary':
      type === 'winner-score' || type === 'winner-name' || type === 'winner-final-score',
  }
}
</script>
<template>
  <table class="table is-striped is-fullwidth is-hoverable">
    <thead>
      <th>{{ $t('player') }}</th>
      <th v-for="(game, $index) in games" :key="game">{{ $t('round-index', [$index]) }}</th>
      <th>{{ $t('final-score') }}</th>
    </thead>
    <tbody>
      <tr v-for="(row, $index) in matrix" :key="$index">
        <td :class="getCellClasses(col)" v-for="(col, $index) in row" :key="$index">
          {{ col.value }}
        </td>
      </tr>
    </tbody>
  </table>
</template>

<style scoped></style>
