import { createContext, useEffect, useReducer } from "react"
import {useLocation} from 'react-router-dom'

const data ={
    device:'',
    currentPage:'',
    pageIndex:0,
    theme:'light'
}
export const AppContext = createContext<{data:typeof data,dispatch:any}>({
    data:data,
    dispatch:()=>null
})

interface Actions {
    type: string
    payload: any
}
const AppReducer = (state:typeof data,action:Actions)=>{
    const {type,payload} = action
     switch(type){
        case 'slideOnChange':
            state.pageIndex = payload.pageIndex
            if(state.currentPage==='/chain33'&&state.pageIndex===1){
                state.theme = 'dark'
            }else{
                state.theme = 'light'
            }    

        break;
        case 'routerOnChange':
            state.currentPage = payload.currentPage
        break;
    }
    console.log(state);
    
    
    return state
}

export const AppProvider = (props: any)=>{
    const [state,dispatch] = useReducer(AppReducer,data)
    const location = useLocation()
    useEffect(()=>{
        dispatch({type:'routerOnChange',payload:{currentPage:location.pathname}})
    },[location])
    return(
        <AppContext.Provider value={{data:state,dispatch}}>
            {props.children}
        </AppContext.Provider>
    )
}