<template>
    <div class="container">
      <div class="timer">
        <v-label color="primary" class="labelTime-style" >{{ formatTime }}</v-label>
    </div>

      <v-row no-gutters justify="space-around" >
        <v-btn class="buttons" color="primary" icon="mdi-play" @click="startTimer"></v-btn>
        <v-btn color="primary"  icon="mdi-pause" @click="pauseTimer"></v-btn>
        <v-btn color="primary" icon="mdi-restart" @click="resetTimer"></v-btn>
      </v-row>
    </div>
</template>
  
<script setup>
  import { ref, computed, onBeforeUnmount } from 'vue';
  
  const timerActive = ref(false);
  const startTime = ref(null);
  const currentTime = ref(null);
  const elapsedTime = ref(0);
  
  const formatTime = computed(() => {
    let seconds = Math.floor(elapsedTime.value / 1000);
    let minutes = Math.floor(seconds / 60);
    let hours = Math.floor(minutes / 60);
  
    seconds = seconds % 60;
    minutes = minutes % 60;
  
    return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
  });
  
  const pad = (number) => {
    return (number < 10 ? "0" : "") + number;
  };
  
  const startTimer = () => {
    if (!timerActive.value) {
      timerActive.value = true;
      startTime.value = Date.now() - elapsedTime.value;
      updateTimer();
    }
  };
  
  const pauseTimer = () => {
    if (timerActive.value) {
      timerActive.value = false;
      clearInterval(currentTime.value);
    }
  };
  
  const resetTimer = () => {
    elapsedTime.value = 0;
    timerActive.value = false;
    clearInterval(currentTime.value);
  };
  
  const updateTimer = () => {
    currentTime.value = setInterval(() => {
      elapsedTime.value = Date.now() - startTime.value;
    }, 1000);
  };
  
  onBeforeUnmount(() => {
    clearInterval(currentTime.value);
  });
</script>
    
<script>
    const startTimer = () => {
    if (!timerActive.value) {
        timerActive.value = true;
        startTime.value = Date.now() - elapsedTime.value;
        updateTimer();
    }
    };

    const pauseTimer = () => {
    if (timerActive.value) {
        timerActive.value = false;
        clearInterval(currentTime.value);
    }
    };

    const resetTimer = () => {
    elapsedTime.value = 0;
    timerActive.value = false;
    clearInterval(currentTime.value);
    };

    export { startTimer, pauseTimer, resetTimer };
</script>

<style>
  .container {
    text-align: center;
    margin-top: auto; /* Place le container en bas de son parent */
    margin-bottom: 1px; /* Marge en bas pour un espacement */
    position: fixed; /* Le positionne de manière fixe */
    left: 0;
    right: 0;
    bottom: 0;
    padding: 20px;
  }
  .timer {
    margin-bottom: 15px;
  }
  .labelTime-style {
    font-size: 30px !important;
    font-weight: 500;
    color: #e91e1e !important;
    opacity: 90% !important;
  }
  .buttons{
    background-color: rgb(255, 255, 255);
  }
</style>
