import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{mt as t}from"./antd-NNbrPHoG.js";import{a as n,i as r,n as i,r as a}from"./api-BW0YTlHd.js";import{t as o}from"./react-vendor-nIJYBVRh.js";var s=e(t(),1),c=o(),l=(0,s.createContext)(null);function u(e){if(!e)return null;let t=e.toLowerCase();return t===`admin`||t===`operator`||t===`viewer`?t:null}function d({children:e}){let[t,o]=(0,s.useState)(!1),[d,f]=(0,s.useState)(!0),[p,m]=(0,s.useState)(!1),[h,g]=(0,s.useState)(null),_=(0,s.useCallback)(async()=>{try{r()&&await i.logout()}catch{}a(),g(null)},[]);(0,s.useEffect)(()=>{let e=!1;return(async()=>{try{let t=await i.getConsoleConfig();if(e)return;f(!!t.auth_required);let n=!!t.needs_bootstrap;if(m(n),!t.auth_required){g({username:`anonymous`,email:null,role:`admin`}),o(!0);return}if(n){a(),g(null),o(!0);return}if(!r()){o(!0);return}let s=await i.getMe();if(e)return;g(s)}catch{a(),g(null)}finally{e||o(!0)}})(),()=>{e=!0}},[]);let v=(0,s.useCallback)(async(e,t)=>{let r=await i.login(e,t);n(r.token),g({username:r.user.username,email:r.user.email??null,role:r.user.role})},[]),y=(0,s.useCallback)(async(e,t)=>{await i.bootstrap(e,t),a(),g(null),m(!1)},[]),b=u(h?.role),x=!d||b===`admin`||b===`operator`,S=!d||b===`admin`,C=(0,s.useMemo)(()=>({ready:t,authRequired:d,needsBootstrap:p,user:h,role:b,canWrite:x,isAdmin:S,login:v,bootstrap:y,logout:_}),[t,d,p,h,b,x,S,v,y,_]);return(0,c.jsx)(l.Provider,{value:C,children:e})}function f(){let e=(0,s.useContext)(l);if(!e)throw Error(`useAuth outside AuthProvider`);return e}export{f as n,d as t};