import { useEffect, useRef, useState, useCallback } from "react";

export default function useMqttWebSocket({ enabled = true, onMessage } = {}) {
  const wsRef = useRef(null);
  const [connected, setConnected] = useState(false);
  const reconnectTimer = useRef(null);
  const onMessageRef = useRef(onMessage);
  onMessageRef.current = onMessage;

  const connect = useCallback(() => {
    const token = localStorage.getItem("access_token");
    if (!token) return;

    const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
    const ws = new WebSocket(
      `${protocol}//${window.location.host}/api/mqtt/ws?token=${token}`
    );

    ws.onopen = () => setConnected(true);
    ws.onclose = () => {
      setConnected(false);
      if (enabled) {
        reconnectTimer.current = setTimeout(connect, 5000);
      }
    };
    ws.onerror = () => {};
    ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        onMessageRef.current?.(data);
      } catch {
        // ignore invalid JSON
      }
    };
    wsRef.current = ws;
  }, [enabled]);

  useEffect(() => {
    if (enabled) connect();
    return () => {
      clearTimeout(reconnectTimer.current);
      wsRef.current?.close();
    };
  }, [enabled, connect]);

  return { connected };
}
