import React, {useEffect, useRef, useState} from 'react';
import './App.css';
import logo from "./via-logo.svg"
import {Row} from "antd"
import socket from "./util/socket";
import NextShot from "./components/NextShot";
import ShotsTaken from "./components/ShotsTaken";
import Feed from "./components/Feed";
import Lobby from "./components/Lobby";
import {Tick} from "./types/types";

const App = () => {
    const [started, setStarted] = useState(false);
    const player = useRef(new Audio("centurion.m4a"));

    useEffect(() => {
        socket.on('started', async () => {
            setStarted(true);

            await player.current.play();
            // player.current.volume = 0;
        });

        socket.on('seek', async (sec: number) => {
            if (player.current.paused) {
                await player.current.play();
            }

            socket.once("tick_event", (tick: Tick) => {
                // Wait till the next tick to actually start so we more closely match the leader's sound
                setStarted(true);
                player.current.currentTime = tick.current
            });
        });



        return () => {
            socket.off("started");
            socket.off("seek");
        }
    });

    const feedContent = (
        <Row>
            <NextShot/>
            <Feed/>
            <ShotsTaken/>
        </Row>
    );

    const lobbyContent = (
        <Lobby/>
    );

    const content = started ? feedContent : lobbyContent;

    return (
        <>
            <section className="content">
                {content}
            </section>
            <footer>
                <img src={logo} className="via-logo" alt="logo"/>
            </footer>
        </>
    );
};

export default App;
