import { Server } from "socket.io";

const io = new Server(3001, {
  cors: {
    origin: ["http://localhost:3000", "https://yourdomain.com"], // Update in production
    methods: ["GET", "POST"],
  },
});

// Game phases
const PHASES = {
  PROGRESS: "progress",   // 10 seconds - players join + progress bar
  SPIN: "playx",
  BREAK: "break",         // 5 seconds - show result + effects
};

// Broadcast full phase state to all connected clients
function broadcastPhase() {
  const payload = {
    phase: currentPhase,
    phaseEndAt,
    roundId: currentRoundId,
    result: currentPhase === PHASES.BREAK ? currentResult : null, // Reveal only during break
    serverNow: Date.now(),
  };

  io.emit("phaseUpdate", payload);
}

// Frequent timer updates for smooth progress bar (every 500ms)
setInterval(() => {
  const now = Date.now();
  const remainingMs = Math.max(0, phaseEndAt - now);
  const durationMs = PHASE_DURATION[currentPhase];

  io.emit("timerUpdate", {
    phase: currentPhase,
    remainingSec: Math.ceil(remainingMs / 1000),
    durationSec: durationMs / 1000,
    serverNow: Date.now(),
  });
}, 1000);

// Phase advancement check (every second)
setInterval(() => {
  if (Date.now() >= phaseEndAt) {
    advancePhase();
  }
}, 1000);

// Initial broadcast to start the cycle properly
broadcastPhase();

// Socket connection handling
io.on("connection", (socket) => {
  console.log("Player connected:", socket.id);

  // Immediately send current game state to the newly connected client
  socket.emit("phaseUpdate", {
    phase: currentPhase,
    phaseEndAt,
    roundId: currentRoundId,
    result: currentPhase === PHASES.BREAK ? currentResult : null,
    serverNow: Date.now(),
  });

  // Optional: Allow clients to request current state (useful on reconnect)
  // socket.on("requestRoundState", () => {
  //   socket.emit("phaseUpdate", {
  //     phase: currentPhase,
  //     phaseEndAt,
  //     roundId: currentRoundId,
  //     result: currentPhase === PHASES.BREAK ? currentResult : null,
  //     serverNow: Date.now(),
  //   });
  // });

  socket.on("phaseUpdate", (data) => {
    setServerOffsetMs(data.serverNow - Date.now());
    setRoundEndAt(data.phaseEndAt);
    setCurrentRoundId(data.roundId);

    if (data.phase === "progress") {
      setStripPhase("idle");
      setStripSpinning(false);
      setShowWinnerEffects(false);
      setWinner(false);
    } 
    else if (data.phase === "spin") {
      setStripPhase("spinning");        // ← Triggers animation above
      setStripSpinning(true);
      setShowWinnerEffects(false);
      setWinner(false);
    } 
    else if (data.phase === "break" && data.result) {
      const targetIndex = getTargetIndex(data.roundId, data.result);
      stopSpinToIndex(targetIndex);     // ← Smooth stop + reveal
    }
  });

  socket.on("disconnect", () => {
    console.log("Player disconnected:", socket.id);
  });
});



console.log("Roll Game Server running on port 3001");
console.log("Cycle: 10s Progress → 15s Spin → 5s Break");
