import { getDictionary } from "@/dictionaries";
import { useParams } from "next/navigation";
import React from "react";

export const useDictionary = (): Dictionary => {
  const [dict, setDict] = React.useState<Dictionary>();

  const params: GlobalParams = useParams();

  React.useEffect(() => {
    const fetchDitionary = async () => {
      const dictionary = await getDictionary(params.lang);

      setDict(dictionary);
    };

    fetchDitionary();

    return () => {
      setDict(undefined);
    };
  }, [params.lang]);

  return dict;
};

export const useModals = () => {
  const [list, setList] = React.useState<GlobalModal[]>([]);

  const openModal = (modal: GlobalModal) => {
    setList((prev) => {
      const exists = prev.findIndex((e) => e.id === modal.id) > -1;
      return exists ? prev : [...prev, modal];
    });
  };

  const closeModal = (id: string, close?: boolean) => {
    setList((prev) => {
      const index = prev.findIndex((e) => e.id === id);

      if (index === -1) return prev;

      const modalToClose = prev[index];

      if (close) {
        return [...prev.slice(0, index), ...prev.slice(index + 1)];
      }

      return [
        ...prev.slice(0, index),
        {
          ...modalToClose,
          closing: true,
        },
        ...prev.slice(index + 1),
      ];
    });
  };

  return { list, openModal, closeModal };
};
