import React from 'react';

const timerMinutes = 15;
const initialTimeLeft = timerMinutes * 60 * 1000;
const startTimeKey = 'palmistry.startTime';

const addLeadingZero = (value: number) => (value < 10 ? `0${value}` : value);

const buildTimeCaption = (time: number) => {
  const minutes = Math.floor(time / 60000);
  const seconds = Math.floor((time % 60000) / 1000);
  return `${addLeadingZero(minutes)}:${addLeadingZero(seconds)}`;
};

export default function useTimer() {
  const [timeLeft, setTimeLeft] = React.useState<number | null>(null);

  const calculateTimeLeft = React.useCallback(() => {
    const startTime = localStorage.getItem(startTimeKey);
    if (!startTime) return initialTimeLeft;

    const elapsedTime = Date.now() - parseInt(startTime);
    return Math.max(0, initialTimeLeft - elapsedTime);
  }, []);

  const time = React.useMemo(() => {
    if (timeLeft == null) return buildTimeCaption(initialTimeLeft);
    return buildTimeCaption(timeLeft);
  }, [timeLeft]);

  React.useEffect(() => {
    const startTime = localStorage.getItem(startTimeKey);
    if (!startTime) {
      // Первый запуск таймера
      localStorage.setItem(startTimeKey, Date.now().toString());
    }
    setTimeLeft(calculateTimeLeft());
  }, [calculateTimeLeft]);

  React.useEffect(() => {
    if (timeLeft === null) return;

    if (timeLeft <= 0) {
      // localStorage.removeItem(startTimeKey);
      return;
    }

    const interval = setInterval(() => {
      const newTimeLeft = calculateTimeLeft();
      setTimeLeft(newTimeLeft);
    }, 1000);

    return () => clearInterval(interval);
  }, [timeLeft, calculateTimeLeft]);

  return time;
}
