import{b as p}from"./index-BFM0W1o1.js";import{r}from"./index-Cjq2zQnM.js";const v=r.createContext({}),e={};function C({children:l,autoDetect:f=!1}){const n=r.useRef(),o=r.useReducer(c=>!c,!1)[1],{openDialog:I,closeDialog$:a,Users:u,subscribeEvent:g}=p(),x=r.useRef({}),t=r.useRef(),U=r.useCallback((c="card",s)=>{if(e.dialogId!==void 0)return;e.dialogId=!1;const i=[];return I({content:{className:"@internal:AuthUser",params:{by:c,choices:s}},width:"100%",height:"100%"}).then(d=>{e.dialogId=t.current=d,i.push(g(`Dialog/${d}.onClose`,()=>{t.current&&(e.dialogId===t.current&&(e.dialogId=void 0),t.current=void 0,n.current=null,o())}))}).catch(()=>{n.current=null,o()}),()=>{i.forEach(d=>d()),t.current&&(e.dialogId===t.current&&(e.dialogId=void 0),a(t.current),t.current=void 0)}},[a,o,I,g]),h=r.useCallback(()=>{t.current&&(a(t.current),e.dialogId===t.current&&(e.dialogId=void 0),t.current=void 0),u.closeAuth$()},[u,a]),m=r.useCallback(()=>{h(),n.current=void 0,o()},[h,o]);return r.useEffect(()=>{function c(s,i){if(e.dialogId){if(t.current!==e.dialogId)return}else if(e.autoDetect&&x.current!==e.autoDetect)return;if(s){if(n.current&&s.id===n.current.id)return;n.current={...s,authType:i}}else{if(n.current&&!n.current.id)return;n.current={authType:i}}o()}return g("Users.onAuthorized",c)},[]),r.useEffect(()=>{if(!(!f||e.autoDetect))return e.autoDetect=x.current,u.autoDetect$(f),()=>{u.autoDetect$(!1),e.autoDetect=void 0}},[u,f]),r.createElement(v.Provider,{value:{user:n.current,actions:{startAuth:U,resetAuth:m,closeAuth:h}}},l)}function R(){return r.useContext(v).user}function E(){return r.useContext(v).actions}export{C as U,E as a,R as u};
