"use client";

import React, { createContext, useEffect, useReducer } from "react";
import { useLenis } from "lenis/react";
import LazyLoad from "vanilla-lazyload";
import getTheme from "@/utils/getTheme";

export type MenuItem = {
  ID: string;
  url: string;
  title: string;
};

export type StateType = {
  menu: Array<MenuItem>;
  theme: string;
  pageLocked: boolean;
  contactPrefillMessage: string;
  showMenu: boolean;
  currentMenuItem: null | number;
};

const initialState: StateType = {
  menu: [],
  theme: getTheme(),
  pageLocked: false,
  contactPrefillMessage: "",
  showMenu: false,
  currentMenuItem: null,
};

export const AppContext = createContext<{
  state: StateType;
  setState: Function;
}>({
  state: initialState,
  setState: () => {},
});

export const AppContextProvider = ({
  children,
  menu,
}: {
  children: React.ReactNode;
  menu: any;
}) => {
  const [state, setState] = useReducer(
    (state: StateType, newState: Partial<StateType>): StateType => ({
      ...state,
      ...newState,
    }),
    {
      ...initialState,
      menu,
    }
  );

  const lenis = useLenis();

  useEffect(() => {
    // @ts-ignore
    if (!document.lazyLoadInstance) {
      // @ts-ignore
      document.lazyLoadInstance = new LazyLoad();
    }

    // @ts-ignore
    document.lazyLoadInstance.update();
  }, []);

  useEffect(() => {
    if (state.pageLocked) {
      lenis?.stop();
      document.documentElement.style.overflow = "hidden";
      document.body.style.overflow = "hidden";
      document.body.style.height = "100%";
      return;
    }

    lenis?.start();
    document.documentElement.style.overflow = "";
    document.body.style.overflow = "";
    document.body.style.height = "";
  }, [lenis, state.pageLocked]);

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", state.theme);
  }, [state.theme]);

  return (
    <>
      <AppContext.Provider value={{ state, setState }}>
        {children}
      </AppContext.Provider>
    </>
  );
};
