/* eslint-disable no-restricted-globals */
self.onmessage = (e: MessageEvent) => {
    const { command, payload } = e.data;

    if (command === 'START') {
        const { durationSeconds } = payload;
        let remaining = durationSeconds;

        // Clear any existing interval
        if ((self as any).timerInterval) {
            clearInterval((self as any).timerInterval);
        }

        (self as any).timerInterval = setInterval(() => {
            remaining--;
            self.postMessage({ type: 'TICK', remaining });

            if (remaining <= 0) {
                clearInterval((self as any).timerInterval);
                self.postMessage({ type: 'COMPLETE' });
            }
        }, 1000);
    } else if (command === 'STOP') {
        if ((self as any).timerInterval) {
            clearInterval((self as any).timerInterval);
        }
    }
};

export { };
