<script setup>
import moment from 'moment';
import { onBeforeUnmount, ref, watch } from 'vue';

const props = defineProps({
    isLoading: {
        type: Boolean,
        default: false
    },
    message: {
        type: String,
        default: ''
    }
});

const startTime = ref(null);
const timerInterval = ref(null);
const elapsedTime = ref('00:00');

const startTimer = () => {
    startTime.value = Date.now();
    timerInterval.value = setInterval(() => {
        const elapsed = moment.duration(Date.now() - startTime.value);
        elapsedTime.value = moment.utc(elapsed.asMilliseconds()).format('mm:ss');
    }, 1000);
};

const stopTimer = () => {
    if (timerInterval.value) {
        clearInterval(timerInterval.value);
        timerInterval.value = null;
    }
};

const resetTimer = () => {
    stopTimer();
    startTime.value = null;
    elapsedTime.value = '00:00';
};

// Watch for loading changes
watch(
    () => props.isLoading,
    (newValue) => {
        if (newValue) {
            startTimer();
        } else {
            stopTimer();
        }
    }
);

// Cleanup on unmount
onBeforeUnmount(() => {
    stopTimer();
});

defineExpose({
    startTimer,
    stopTimer,
    resetTimer
});
</script>

<template>
    <div v-if="isLoading" class="flex flex-col items-center">
        <div v-if="message && message.includes('/')">
            <span>{{ message }}</span>
        </div>
        <div v-else>Starting execution...</div>
        <div class="flex justify-center mt-4">
            <jellyfish-loader :loading="isLoading" scale="1" color="#A100FF" />
        </div>
        <div class="flex justify-center" style="margin-bottom: 30px">
            <p>Time elapsed:&nbsp;</p>
            <div class="timer">{{ elapsedTime }}</div>
        </div>
    </div>
</template>

<style scoped>
.timer {
    font-family: monospace;
    font-weight: bold;
}
</style>
