<template>
  <div class="score-grid">
    <div class="score-cell cell-blue color-blue">
      <div class="score-content">
        <div class="score-info info-left">
          <div class="team-name">Bleue</div>
          <div class="sub-score-container sub-left">
            <span class="sub-label">Total</span>
            <span class="team-score sub-score">{{ scores.BlueTotalScore }}</span>
          </div>
        </div>
        <div class="score-main">
          <Transition name="score-pop" mode="out-in">
            <div :key="scores.BlueRoundScore" class="team-score main-score">{{ scores.BlueRoundScore }}</div>
          </Transition>
        </div>
      </div>
    </div>
    <div class="score-cell cell-red color-red">
      <div class="score-content">
        <div class="score-main">
          <Transition name="score-pop" mode="out-in">
            <div :key="scores.RedRoundScore" class="team-score main-score">{{ scores.RedRoundScore }}</div>
          </Transition>
        </div>
        <div class="score-info info-right">
          <div class="team-name">Rouge</div>
          <div class="sub-score-container sub-right">
            <span class="sub-label">Total</span>
            <span class="team-score sub-score">{{ scores.RedTotalScore }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="score-cell cell-green color-green">
      <div class="score-content">
        <div class="score-info info-left">
          <div class="team-name">Verte</div>
          <div class="sub-score-container sub-left">
            <span class="sub-label">Total</span>
            <span class="team-score sub-score">{{ scores.GreenTotalScore }}</span>
          </div>
        </div>
        <div class="score-main">
          <Transition name="score-pop" mode="out-in">
            <div :key="scores.GreenRoundScore" class="team-score main-score">{{ scores.GreenRoundScore }}</div>
          </Transition>
        </div>
      </div>
    </div>
    <div class="score-cell cell-yellow color-yellow">
      <div class="score-content">
        <div class="score-main">
          <Transition name="score-pop" mode="out-in">
            <div :key="scores.YellowRoundScore" class="team-score main-score">{{ scores.YellowRoundScore }}</div>
          </Transition>
        </div>
        <div class="score-info info-right">
          <div class="team-name">Jaune</div>
          <div class="sub-score-container sub-right">
            <span class="sub-label">Total</span>
            <span class="team-score sub-score">{{ scores.YellowTotalScore }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <div class="timer-container">
      <div class="timer-display">{{ timerDisplay }}</div>
    </div>
  </div>
</template>

<script setup>
  import { onMounted, onUnmounted, reactive, ref } from 'vue';
  import mqtt from 'mqtt'
  import config from '@/config.js'

  const mqttBrokerUrl = config.mqttBrokerUrl
  let client = null

  const scores = reactive({
    RedTotalScore: 0,
    BlueTotalScore: 0,
    YellowTotalScore: 0,
    GreenTotalScore: 0,
    RedRoundScore: 0,
    BlueRoundScore: 0,
    YellowRoundScore: 0,
    GreenRoundScore: 0,
  });

  const timerDisplay = ref('00:00');

  function formatTime(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
  }

  function handleMessage(topic, message) {
    let parsedMessage;
    try {
      parsedMessage = JSON.parse(message);
    } catch (e) {
      console.error("Erreur d'analyse JSON:", e);
      return;
    }

    if (topic === 'game/score' && parsedMessage.TEAM) {
       scores.RedTotalScore = parsedMessage.TEAM.Red.TotalScore
       scores.BlueTotalScore = parsedMessage.TEAM.Blue.TotalScore
       scores.YellowTotalScore = parsedMessage.TEAM.Yellow.TotalScore
       scores.GreenTotalScore = parsedMessage.TEAM.Green.TotalScore

       scores.RedRoundScore = parsedMessage.TEAM.Red.RoundScore
       scores.BlueRoundScore = parsedMessage.TEAM.Blue.RoundScore
       scores.YellowRoundScore = parsedMessage.TEAM.Yellow.RoundScore
       scores.GreenRoundScore = parsedMessage.TEAM.Green.RoundScore
    }

    if (topic === 'game/timer' && parsedMessage.time !== undefined) {
       timerDisplay.value = formatTime(parsedMessage.time);
    }
  }

  function subscribeToTopic(topic, callback) {
    if(client) {
        client.subscribe(topic)
        client.on('message', (receivedTopic, message) => { callback(receivedTopic.toString(), message.toString())
        })
    }
  }

  onMounted(() => {
    client = mqtt.connect(mqttBrokerUrl)
    subscribeToTopic('game/score', (topic, message) => {
      handleMessage(topic, message);
    });
    subscribeToTopic('game/timer', (topic, message) => {
      handleMessage(topic, message);
    });
    // Request score refresh
    client.publish('game/score/request', '{}');
  });

  onUnmounted(() => {
    if (client) {
      client.end()
    }
  })
</script>

<style scoped>
  .score-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr;
    width: 100vw;
    height: 100vh;
    padding: 40px;
    gap: 60px;
    position: relative;
    font-family: 'Bahnschrift', sans-serif;
  }

  .score-cell {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    box-shadow: 0 10px 30px rgba(0,0,0,0.5);
    transition: transform 0.2s;
    overflow: hidden;
  }
  .cell-blue {
    border-radius: 65px 225px 75px 225px !important;
  }
  .cell-red {
    border-radius: 225px 65px 225px 75px !important;
  }
  .cell-green {
    border-radius: 225px 65px 225px 75px !important;
  } 
  .cell-yellow {
    border-radius: 75px 225px 65px 225px !important;
  }

  .score-content {
    display: flex;
    flex-direction: row; /* Horizontal layout */
    align-items: center;
    justify-content: space-around; /* Spread out */
    width: 100%;
    padding: 0 40px;
  }

  .score-main {
    flex: 2; /* Takes more space */
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .score-info {
    flex: 1; /* Takes less space */
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .info-right {
    align-items: flex-end;
    text-align: right;
  }

  .info-left {
    align-items: flex-start;
    text-align: left;
  }

  .team-name {
    font-size: 2.2rem;
    font-weight: 900;
    letter-spacing: 2px;
    opacity: 0.9;
    color: rgba(255, 255, 255, 0.95);
    text-transform: uppercase;
    margin-bottom: 15px;
    text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
  }

  .team-score {
    font-weight: bold;
    color: white;
    line-height: 1;
    text-shadow: 4px 4px 8px rgba(0,0,0,0.4);
  }

  .main-score {
    font-size: 10rem; /* Even larger */
    margin: 0;
  }

  .sub-score-container {
    background-color: rgba(0, 0, 0, 0.2);
    padding: 10px 20px;
    border-radius: 20px;
    display: flex;
    flex-direction: column;
    min-width: 120px;
  }

  .sub-right {
    align-items: flex-end;
  }

  .sub-left {
    align-items: flex-start;
  }

  .sub-label {
    font-size: 1rem;
    text-transform: uppercase;
    opacity: 0.8;
    color: rgba(255, 255, 255, 0.9);
    margin-bottom: 2px;
    font-weight: 600;
  }

  .sub-score {
    font-size: 2.5rem;
  }

  .timer-container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 10;
    background-color: #1a1a1a;
    padding: 20px 40px;
    border-radius: 80px;
    border: 6px solid #333;
    box-shadow: 0 0 50px rgba(0,0,0,0.8);
  }

  .timer-display {
    font-size: 8rem;
    font-weight: bold;
    color: white;
    font-family: monospace;
    text-shadow: 0 0 20px rgba(255, 255, 255, 0.2);
  }

  .color-blue {
    background: linear-gradient(135deg, rgb(var(--v-theme-BlueBuzzer)), #1a3a5a);
  }

  .color-red {
    background: linear-gradient(135deg, rgb(var(--v-theme-RedBuzzer)), #5a1a1a);
  }

  .color-green {
    background: linear-gradient(135deg, rgb(var(--v-theme-GreenBuzzer)), #1a5a2a);
  }

  .color-yellow {
    background: linear-gradient(135deg, rgb(var(--v-theme-YellowBuzzer)), #5a5a1a);
  }

  /* Score Pop Animation */
  .score-pop-enter-active {
    animation: pop-in 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  }
  .score-pop-leave-active {
    animation: pop-out 0.2s ease-in;
  }

  @keyframes pop-in {
    0% {
      transform: scale(0.5);
      opacity: 0;
    }
    100% {
      transform: scale(1);
      opacity: 1;
    }
  }

  @keyframes pop-out {
    0% {
      transform: scale(1);
      opacity: 1;
    }
    100% {
      transform: scale(1.5);
      opacity: 0;
    }
  }
</style>
