import logo from './logo.svg';
import './App.css';
import React, { useEffect, useState } from 'react';

// Timer
const Timer = ({ ms }) => {
    const [count, setCount] = useState(ms)
    const [isRunning, setIsRunning] = useState(false)

    console.log(count)

    // функция-перевод секунд в нормальный вид
    function timerFormat(time) {
        const h = Math.floor(time / 60 / 60)
        const m = Math.floor(time / 60) - (h * 60)
        const s = time % 60

        const defaultZero = (param) => (param > 9) ? param : '0' + param

        return `${defaultZero(h)} : ${defaultZero(m)} : ${defaultZero(s)}`
    }

    // таймер
    useEffect(() => {
        if (isRunning) {
            const int = setInterval(() => {
                setCount(count => {
                    if (count <= 0) {
                        setIsRunning(false)
                        return 0
                    }
                    return count - 1
                })
            }, 1000)
            return () => clearInterval(int)
        }
    }, [isRunning])

    return (
        <div>
            <h2>Timer</h2>
            {timerFormat(count)}
            <br />
            <button onClick={() => setIsRunning(!isRunning)}>{isRunning ? 'Pause' : 'Start'}</button>
        </div >
    )
}

function App() {
    return (
        <div className="App">
            <header>

                {/* Timer */}
                <Timer ms={7205} />
                <Timer ms={5} />

            </header>
        </div>
    );
}

export default App;