import { ChangeEventHandler, useEffect, useState } from "react"
import { io } from "socket.io-client"
let socket: ReturnType<typeof io>

const Home = () => {
  const [input, setInput] = useState("")

  useEffect(() => {
    socketInitializer()
  }, [])

  const socketInitializer = async () => {
    await fetch("/api/ws")
    socket = io()

    socket.on("connect", () => {
      console.log("connected")
    })

    socket.on("update-input", (msg) => {
      setInput(msg)
    })
  }

  const onChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
    setInput(e.target.value)
    socket.emit("input-change", e.target.value)
  }

  return (
    <input
      placeholder="Type something"
      value={input}
      onChange={onChangeHandler}
    />
  )
}

export default Home
