<template>
    <div class="container">
      <div class="timer">{{ formatTime }}</div>
      <div class="buttons">
        <button @click="startTimer" :disabled="timerActive">Start</button>
        <button @click="pauseTimer" :disabled="!timerActive">Pause</button>
        <button @click="resetTimer">Reset</button>
      </div>
    </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>
  
  <style>
  .container {
    text-align: center;
    margin-top: 20px;
  }
  
  .timer {
    font-size: 2em;
    margin-bottom: 20px;
  }
  
  .buttons button {
    margin: 0 10px;
    padding: 10px 20px;
    font-size: 1em;
  }
  </style>
  
  <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>
  