import React,{useContext,useEffect}from"react";import{useNotify}from"../../../../js/hooks/useNotify.js";import Encryption from"../../../../js/helpers/encryption.js";import{useGlobalState}from"../../../../js/hooks/useGlobalState.js";import{debounce,once,isEmpty}from"lodash-es";import{jsx as _jsx}from"react/jsx-runtime";const FavouritesContext=React.createContext(),formatFavourites=e=>[...e.gamesMulti?Object.values(e.gamesMulti).map(e=>({...e,isMulti:!0})):[],...e.games?Object.values(e.games):[]].map(e=>({path:`/user/favorite-games/${e.isMulti?"m":"s"}${e.id}`,isMulti:e.isMulti,code:e.code,name:e.name,logo:e.logo,color:e.mainRgbColor,results:e.gameResult[0],jackpot:e.gameJackpot,gameData:{timezone:e.drawTimeZone,state:e?.state,draw_type:e.drawType,isPickXType:e.isPickXType,isPartOfJackpotsPool:e.isPartOfJackpotsPool,isDaily:e.isDaily,isGeneratable:e.isGeneratable,position:e.position,extraData:e.gameExtraData,game_bonus_balls:e.bonusBall,unknownPrizeLabel:e.unknownPrizeLabel,prizeLabel:e.prizeLabel,prizeSubLabel:e.prizeSubLabel,multiple_draw_labels:e.multipleDrawsMainDrawLabel?[e.multipleDrawsMainDrawLabel,e.multipleDrawsSecondDrawLabel,e.multipleDrawsThirdDrawLabel]:null},lucky_numbers:e.luckyNumbers})).reduce((e,t)=>(t.isMulti?(e[0].push(t),e[0].sort((e,t)=>e.gameData.position===t.gameData.position?0:e.gameData.position>t.gameData.position?1:-1)):(e[1].push(t),e[1].sort((e,t)=>e.gameData.state.stateFullName===t.gameData.state.stateFullName?e.gameData.position===t.gameData.position?0:e.gameData.position>t.gameData.position?1:-1:e.gameData.state.stateFullName>t.gameData.state.stateFullName?1:-1)),e),[[],[]]).flat();export const FavouritesProvider=({children:e,apis:t,code:n,showDoublePlay:s,maxFavouriteGames:o,fetchFavouritesFromUser:i})=>{const r=useNotify(),[a,l]=useGlobalState("favourites",null),[c,d]=useGlobalState("gamesList",null),[u,h]=useGlobalState("fetchedFavourites",!1),m=debounce(async e=>{const n=await fetch(`${t.show_double_play}${e}`,{credentials:"same-origin",cache:"reload"});n.status!==201&&r({type:"error",message:"Couldn't save Double Play preference"})},5e3);useEffect(()=>{if(c&&a){const e=[...c],t=[...e.filter(e=>e.isMulti).sort((e,t)=>e.position===t.position?0:e.position>t.position?1:-1),...e.filter(e=>!e.isMulti).sort((e,t)=>e.stateFullName===t.stateFullName?e.position===t.position?0:e.position>t.position?1:-1:e.stateFullName>t.stateFullName?1:-1)],n=t.filter(e=>a.map(e=>e.code).includes(e.code)),s=t.filter(e=>!a.map(e=>e.code).includes(e.code)),o=[...n,...s];d(o)}},[a]);const f=async()=>{if(!c){const i=await fetch(t.get_list,{credentials:"same-origin",cache:"reload"}),a=await i.text(),e=JSON.parse((new Encryption).decrypt(a,n)),s=[...e.gamesMulti.map(e=>({...e,isMulti:!0})).sort((e,t)=>e.position===t.position?0:e.position>t.position?1:-1),...e.games.sort((e,t)=>e.stateFullName===t.stateFullName?e.position===t.position?0:e.position>t.position?1:-1:e.stateFullName>t.stateFullName?1:-1)],r=s.filter(e=>e.isFavourite),c=s.filter(e=>!e.isFavourite),o=[...r,...c];return d(o),o}},p=once(async()=>{if(h(!0),!a&&!u){const e=()=>{fetch(t.user_api_path,{cache:"no-cache"}).then(e=>e.text()).then(e=>{console.log(e);const t=JSON.parse(e);!isEmpty(t)&&typeof t.favouriteGames!="undefined"&&l(t.favouriteGames.reduce((e,t)=>(e[t]={code:t},e),{}))})};e(),window.addEventListener("pageshow",t=>{t.persisted&&e()})}}),g=once(async()=>{if(h(!0),!a&&!u){const o=await fetch(t.get_favourites,{credentials:"same-origin",cache:"reload"}),i=await o.text(),e=JSON.parse((new Encryption).decrypt(i,n));console.log(e);const s=formatFavourites(e);return l(s),s}}),v=async({gamesToAdd:e=[],gamesToRemove:s=[]})=>{try{console.log("updating",e,s);const i=await fetch(`${t.update}/${e.length>0?e.join("|"):"0"}/${s.length>0?s.join("|"):"0"}`,{credentials:"same-origin",cache:"reload"});if(i.status===200){const e=await i.text(),t=JSON.parse((new Encryption).decrypt(e,n)),s=formatFavourites(t);r({type:"success",message:"Favorite games updated"}),l(s)}else{let e;return a&&(e=Object.values(a).length),r(e>=o?{type:"error",message:"You've reached the maximum number of favorite games",requires_action:!0,action_name:"Manage games",onAction:()=>{window.location.href="/user/favorite-games"}}:{type:"error",message:"Couldn't update favorite games"}),1}}catch{let e;return a&&(e=Object.values(a).length),r({type:"error",message:e>=o?"You've reached the maximum number of favorite games":"Couldn't update favorite games"}),1}};return useEffect(()=>{i?p():g()},[]),_jsx(FavouritesContext.Provider,{value:{update:v,getGamesList:f,gamesList:c,updateDoublePlayPreference:m,showDoublePlay:s,maxFavouriteGames:o,favourites:a},children:_jsx(FavouritesContext.Consumer,{children:e})})};const useFavourites=()=>{const e=useContext(FavouritesContext);return e};export default useFavourites