import { ref, onUnmounted } from 'vue';


export function useWebSocket(url) {
  const ws = ref(null);
  const data = ref(null);
  const isConnected = ref(false);
  const error = ref(null);
  let reconnectTimer = null;

  const connect = () => {
    if (ws.value && ws.value.readyState === WebSocket.OPEN) {
      console.log('[WS] Already connected.');
      return;
    }
    
    error.value = null;
    console.log(`[WS] Attempting to connect to: ${url}`);
    
    ws.value = new WebSocket(url);

    ws.value.onopen = () => {
      isConnected.value = true;
      console.log('✅ [WS] Connection established.');
      clearTimeout(reconnectTimer);
    };

    ws.value.onmessage = (event) => {
      console.log('🔔 [WS] Message received. Parsing data...'); 
      try {
        const parsedData = JSON.parse(event.data);
        data.value = parsedData; 
      } catch (e) {
        error.value = new Error('Gagal memproses pesan WebSocket.');
        console.error('❌ [WS] Data parsing error:', e);
        data.value = null; 
      }
    };

    ws.value.onerror = (e) => {
      console.error('❌ [WS] WebSocket error:', e);
      error.value = e;
    };

    ws.value.onclose = (event) => {
      isConnected.value = false;
      if (event.code !== 1000) {
          console.log('🛑 [WS] Connection closed unexpectedly. Reconnecting in 5s...');
          reconnectTimer = setTimeout(connect, 5000); // Reconnect setelah 5 detik
      } else {
          console.log('🛑 [WS] Connection closed normally.');
      }
    };
  };
  
  const disconnect = () => {
    if (ws.value) {
        ws.value.close(1000, "Component unmounted");
        ws.value = null;
    }
    clearTimeout(reconnectTimer);
  };
  
  onUnmounted(() => {
    disconnect();
  });

  return {
    wsData: data,
    isConnected,
    error,
    connect,
    disconnect,
  };
}