import{r as i,o as I,a as h,A as p,I as k}from"./tpFEFzWU.js";const P=globalThis.setInterval;function E(y={}){const{autoConnect:v=!0,reconnectDelay:W=3e3,maxReconnectAttempts:f=5}=y,u=k(),c=i(!1),S=i(null),l=i(null),r=i(0);let e=null,a=null,t=null;const m=()=>{if(u.public.wsUrl)return u.public.wsUrl;{const n=window.location.protocol==="https:"?"wss:":"ws:",o=window.location.hostname,s=u.public.wsPort||"3001";return`${n}//${o}:${s}`}},d=()=>{if(e?.readyState===WebSocket.OPEN)return;const n=m();if(n)try{e=new WebSocket(n),e.onopen=()=>{c.value=!0,r.value=0,console.log("[WS] Connected"),t=P(()=>{e?.readyState===WebSocket.OPEN&&e.send(JSON.stringify({type:"ping"}))},3e4)},e.onmessage=o=>{try{const s=JSON.parse(o.data);S.value=s,s.type==="connected"&&(l.value=s.clientId)}catch(s){console.error("[WS] Parse error:",s)}},e.onclose=()=>{c.value=!1,l.value=null,console.log("[WS] Disconnected"),t&&(clearInterval(t),t=null),g()},e.onerror=o=>{console.error("[WS] Error:",o)}}catch(o){console.error("[WS] Connection failed:",o),g()}},b=()=>{a&&(clearTimeout(a),a=null),t&&(clearInterval(t),t=null),e&&(e.close(),e=null),c.value=!1,l.value=null},g=()=>{if(r.value>=f){console.log("[WS] Max reconnect attempts reached");return}a=setTimeout(()=>{r.value++,console.log(`[WS] Reconnecting (${r.value}/${f})...`),d()},W)},w=n=>{e?.readyState===WebSocket.OPEN?e.send(JSON.stringify(n)):console.warn("[WS] Cannot send message: not connected")},N=n=>{e?.readyState===WebSocket.OPEN&&e.send(JSON.stringify({type:"subscribe",channel:n}))},O=n=>{e?.readyState===WebSocket.OPEN&&e.send(JSON.stringify({type:"unsubscribe",channel:n}))};return v&&I(()=>{d()}),h(()=>{b()}),{isConnected:p(c),lastMessage:S,clientId:p(l),connect:d,disconnect:b,send:w,subscribe:N,unsubscribe:O}}export{P as s,E as u};
