import { useEffect, useRef, useState } from "preact/hooks";
import { StatusManager } from "./statusManager.tsx";
import { IS_BROWSER } from "$fresh/runtime.ts";
import { PlayerData } from "../util/players.ts";
import { Button } from "../components/Button.tsx";

export function ActivePlayerList() {
  const [players, setPlayers] = useState<PlayerData[]>([]);

  useEffect(() => {
    if (!IS_BROWSER) return;
    configureEventSource();
  }, []);

  const eventSource = useRef<EventSource>();

  const configureEventSource = () => {
    if (eventSource.current?.OPEN) eventSource.current.close();
    eventSource.current = new EventSource("/api/players");
    eventSource.current.addEventListener("players", (e) => {
      setPlayers(JSON.parse(e.data));
    });
  };

  const followStatusManager = (action: string) => {
    if (action === "started" || action === "restarted") {
      configureEventSource();
    }
  };

  return (
    <div>
      <StatusManager onAction={followStatusManager} />
      <div class="grid grid-cols-2 p-8">
        <h2 class="col-span-2 font-pixel text-xl">Active Players</h2>
        {players.map((p) => <PlayerCard player={p} />)}
      </div>
    </div>
  );
}

function PlayerCard({ player }: { player: PlayerData }) {
  return (
    <div class="flex gap-4">
      <img class="w-16" src={player.avatar} alt={`${player.username}'s avatar`} />
      <div>
        <h3>{player.username}</h3>
        <small class="opacity-50">UUID: {player.id}</small>
        <div>
          Did you know that bats are the only mammal that can fly?
        </div>
      </div>
    </div>
  );
}
