import { useEffect, useState } from 'react';
import { Link, Navigate } from 'react-router-dom';
import { api } from '../api';
import { useAuth } from '../AuthContext';
import BattleLiveCard from '../components/BattleLiveCard';
import { getSocket } from '../socket';

export default function BattleHub() {
  const { user, loading } = useAuth();
  const [battles, setBattles] = useState([]);
  const [spinById, setSpinById] = useState({});

  useEffect(() => {
    if (!user || user.role === 'admin') return undefined;
    let cancelled = false;

    (async () => {
      try {
        const data = await api.jackpot();
        if (!cancelled) setBattles(data.battles || []);
      } catch {
        /* hub still usable */
      }
    })();

    const socket = getSocket();
    const onList = (payload) => {
      setBattles(payload.battles || []);
    };
    const onSpin = (state) => {
      if (!state?.id) return;
      setSpinById((prev) => ({ ...prev, [state.id]: state }));
      setBattles((prev) => {
        const idx = prev.findIndex((b) => b.id === state.id);
        if (idx < 0) return [...prev, state];
        const next = [...prev];
        next[idx] = state;
        return next;
      });
    };
    const onResult = (state) => {
      const id = state?.previousRoundId || state?.id;
      if (!id) return;
      setSpinById((prev) => {
        const next = { ...prev };
        delete next[id];
        return next;
      });
    };

    socket.emit('jackpots:subscribe');
    socket.on('jackpots:list', onList);
    socket.on('jackpot:spin', onSpin);
    socket.on('jackpot:result', onResult);
    socket.on('connect', () => socket.emit('jackpots:subscribe'));

    return () => {
      cancelled = true;
      socket.emit('jackpots:unsubscribe');
      socket.off('jackpots:list', onList);
      socket.off('jackpot:spin', onSpin);
      socket.off('jackpot:result', onResult);
    };
  }, [user]);

  if (loading) return <p className="muted">Loading…</p>;
  if (!user) return <Navigate to="/login" replace />;
  if (user.role === 'admin') return <Navigate to="/admin" replace />;

  return (
    <section className="section">
      <div className="section-head">
        <div>
          <h1>Battle</h1>
        </div>
      </div>
      <div className="mode-grid">
        <Link to="/battle/create" className="mode-card mode-card-wide">
          <div className="mode-card-top">
            <h2>Create a Battle</h2>
          </div>
          <p className="muted mode-blurb">
            Bet items to open a new pot. Others can join — chance scales with value. Timer starts at
            2 players.
          </p>
        </Link>

        {battles.map((b) => (
          <BattleLiveCard key={b.id} battle={b} spinEvent={spinById[b.id]} />
        ))}

        {battles.length === 0 && (
          <p className="muted mode-pot-empty" style={{ gridColumn: '1 / -1' }}>
            No open battles — create one to get started.
          </p>
        )}
      </div>
    </section>
  );
}
