import React from "react"
import ReactDOM from "react-dom/client"

import axios from "axios"

import "./index.css"

const API_ENDPOINT = import.meta.env.PROD
	? "/api"
	: `http://${window.location.hostname}:3000/api`

const App = () => {
	const [loading, setLoading] = React.useState(true)
	const [randomWord, setRandomWord] = React.useState(null)

	async function loadRandom({ random = true } = {}) {
		setLoading(true)

		let { data } = await axios({
			url: API_ENDPOINT,
			method: "GET",
			params: {
				random,
			},
		})

		setLoading(false)

		setRandomWord(data)
	}

	async function playbackCurrentWord() {
		if (!randomWord || !randomWord.tts_file) return

		const audio = new Audio()

		audio.src = randomWord.tts_file
		audio.volume = 0.5

		audio.play()
	}

	React.useEffect(() => {
		loadRandom()
	}, [])

	return (
		<div className="app">
			<div className="result">
				{loading ? <p>Loading...</p> : <h1>{randomWord.phrase}</h1>}

				<div className="playback_audio" onClick={playbackCurrentWord}>
					<svg
						stroke="currentColor"
						fill="none"
						strokeWidth="2"
						viewBox="0 0 24 24"
						strokeLinecap="round"
						strokeLinejoin="round"
						height="1em"
						width="1em"
						xmlns="http://www.w3.org/2000/svg"
					>
						<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon>
						<path d="M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"></path>
					</svg>
				</div>
			</div>

			<footer>
				<a href="https://git.ragestudio.net/srgooglo/monstercanker">
					GitHub
				</a>
				<a href={API_ENDPOINT}>API</a>
			</footer>
		</div>
	)
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />)
