'use client';

import { useEffect, useState } from 'react';
import io from 'socket.io-client';




export default function HomePage() {
  let baseUrl = "";
  if (typeof window !== "undefined") {
    baseUrl = `${window.location.protocol}//${window.location.hostname}`;
  }
  const backendUrl = `${baseUrl}:${process.env.NEXT_PUBLIC_API_BASE}`;
  const socket = io(`${backendUrl}`);

  const [time, setTime] = useState(new Date());
  
  const [currentPlayer, setCurrentPlayer] = useState<string | null>(null);

  const [gameStatus, setGameStatus] = useState<{ gameActive: boolean, players: any[] }>({
    gameActive: false,
    players: [],
  });

  useEffect(() => {
    socket.on('connect', () => {
      console.log('Connected to Socket.IO server');
    });

    socket.on('player_update', (data: { nextPlayer: string }) => {
      setCurrentPlayer(data.nextPlayer);
      fetchStatus();
    });

    return () => {
      socket.off('player_update');
    };
  }, []);
  // Idle clock stuff
  useEffect(() => {
    const interval = setInterval(() => setTime(new Date()), 1000);
    return () => clearInterval(interval);
  }, []);

  const timeString = time.toLocaleTimeString('en-US', {
    hour: 'numeric',
    minute: '2-digit',
  });

  const dateString = time.toLocaleDateString('en-US', {
    month: 'long',
    day: 'numeric',
    year: 'numeric',
  });

  const day = time.getDate();
  const suffix =
    day % 10 === 1 && day !== 11 ? 'st' :
    day % 10 === 2 && day !== 12 ? 'nd' :
    day % 10 === 3 && day !== 13 ? 'rd' : 'th';

  const formattedDate = `${time.toLocaleString('en-US', { month: 'long' })} ${day}${suffix}, ${time.getFullYear()}`;

  const advanceTurn = async () => {
    await fetch(`${baseUrl}/next`); // triggers backend to emit event
  };

  const fetchStatus = async () => {
    try {
      const res = await fetch(`${backendUrl}/status`);
      const data = await res.json();
      setGameStatus(data);
    } catch (err) {
      console.error("Failed to fetch status", err);
    }
  };

  if (gameStatus.gameActive) {
    return (
      <main className="p-6">
        <h1 className="text-2xl font-bold mb-4">Game Turn Tracker</h1>

        <div className="mb-4">
          {currentPlayer ? (
            <p className="text-lg">
              🎯 Current Player: <strong>{currentPlayer.name} ({currentPlayer.group})</strong>
            </p>
          ) : (
            <p className="text-gray-500">Waiting for turn to start…</p>
          )}
        </div>

        <button
          onClick={advanceTurn}
          className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700"
        >
          Next Player
        </button>
      </main>
    );
  } else {
      return (
        <main>
          <div className="h-screen flex flex-col items-center justify-center text-center text-4xl font-semibold">
            <div>{timeString}</div>
            <div className="text-2xl mt-2">{formattedDate}</div>
          </div>
          <div className="w-full py-4 text-center text-gray-500">
            <div className="text-xl mt-2">Go to {baseUrl} to start a game!</div>
          </div>
        </main>
    );
  }

}
