import { useEffect, useState } from "react";

export function useRuntimeState() {
  const [appState, setAppState] = useState(null);

  useEffect(() => {
    let mounted = true;
    let socket;
    let retryTimer;

    const connectWebSocket = () => {
      const protocol = window.location.protocol === "https:" ? "wss" : "ws";
      socket = new WebSocket(`${protocol}://${window.location.host}/ws`);
      socket.onmessage = (event) => {
        try {
          const nextState = JSON.parse(event.data);
          if (mounted) {
            setAppState(nextState);
          }
        } catch (error) {
          console.error("Failed to parse state update", error);
        }
      };
      socket.onclose = () => {
        if (mounted) {
          retryTimer = window.setTimeout(connectWebSocket, 1000);
        }
      };
    };

    fetch("/api/state")
      .then((response) => response.json())
      .then((state) => {
        if (mounted) {
          setAppState(state);
          connectWebSocket();
        }
      })
      .catch((error) => {
        console.error("Failed to load initial state", error);
      });

    return () => {
      mounted = false;
      if (retryTimer) {
        window.clearTimeout(retryTimer);
      }
      if (socket) {
        socket.close();
      }
    };
  }, []);

  return [appState, setAppState];
}
