import { getValuesFromRGBString } from "@/services/color-formatter";
import { useEffect } from "react";

export const useSchemeColorByElement = (
  element: Element | null,
  searchSelectors: string,
  dependencies: ReadonlyArray<unknown> = []
) => {
  useEffect(() => {
    const pageElement = element?.querySelectorAll(searchSelectors)[0];

    const scheme = document.querySelector('meta[name="theme-color"]');
    if (scheme && !pageElement) {
      return scheme.setAttribute("content", "#ffffff");
    }
    if (!pageElement) return;
    let backgroundColor = window.getComputedStyle(pageElement)?.backgroundColor;
    const colorScheme = getValuesFromRGBString(backgroundColor);
    if (colorScheme?.a === 0) {
      backgroundColor = "#ffffff";
    }
    if (scheme && backgroundColor.length) {
      return scheme.setAttribute("content", backgroundColor);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [element, ...dependencies]);
  return null;
};
