"use client";

import React, { createContext, useCallback, useContext, useState } from "react";

import { useUserStore } from "../stores/userStore";

const HomeProductsWrapperContext = createContext<any>({});

export type HomeProductsWrapperProps = {
  children: React.ReactNode;
  isOfferBannerClosed: boolean;
  closeBanner: () => Promise<void>;
};

export function HomeProductsWrapper({
  isOfferBannerClosed,
  closeBanner,
  children,
}: HomeProductsWrapperProps) {
  //
  const { user } = useUserStore();

  const [isBannerClosed, setIsBannerClosed] =
    useState<boolean>(isOfferBannerClosed);

  const proceedCloseBanner = useCallback(() => {
    setIsBannerClosed(true);
    closeBanner();
  }, [closeBanner, setIsBannerClosed]);

  const MainData: HomeProductsWrapperContextDto = {
    proceedCloseBanner,
    isBannerClosed,
    isSubscriptionActive: user?.activeMembership === true,
  };

  return (
    <HomeProductsWrapperContext.Provider value={MainData}>
      {children}
    </HomeProductsWrapperContext.Provider>
  );
}

export const useHomeProductsContext = (): HomeProductsWrapperContextDto =>
  useContext(HomeProductsWrapperContext);

export type HomeProductsWrapperContextDto = {
  proceedCloseBanner: () => void;
  isBannerClosed: boolean;
  isSubscriptionActive: boolean;
};
