import { useState, useEffect } from 'react';
import { WorkoutSession } from '../types';

export const useSessionTimer = (activeSession: WorkoutSession | null) => {
    const [elapsedTime, setElapsedTime] = useState<string>('00:00:00');

    useEffect(() => {
        let interval: number;
        if (activeSession) {
            const updateTimer = () => {
                const diff = Math.floor((Date.now() - activeSession.startTime) / 1000);
                const h = Math.floor(diff / 3600);
                const m = Math.floor((diff % 3600) / 60);
                const s = diff % 60;
                setElapsedTime(`${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`);
            };

            updateTimer();
            interval = window.setInterval(updateTimer, 1000);
        } else {
            setElapsedTime('00:00:00');
        }
        return () => clearInterval(interval);
    }, [activeSession]);

    return elapsedTime;
};
