import { useSettings } from '@wordpress/block-editor';
import { useMemo } from '@wordpress/element';

export const useFontFamilies = () => {
  const [fontFamiliesRaw] = useSettings('typography.fontFamilies');

  const fontFamiliesData = useMemo(() => {
    const data = {};

    if (fontFamiliesRaw) {
      let fontFamilies = [];
      if (Array.isArray(fontFamiliesRaw)) {
        fontFamilies = fontFamiliesRaw;
      } else if (typeof fontFamiliesRaw === 'object') {
        fontFamilies = Object.values(fontFamiliesRaw).flat().filter(Boolean);
      }

      fontFamilies.forEach((font) => {
        if (font.slug && font.name) {
          let availableWeights = [];

          if (font.fontFace && Array.isArray(font.fontFace)) {
            availableWeights = font.fontFace
              .map((face) => {
                const weight = face.fontWeight;
                if (!weight) return null;
                if (typeof weight === 'string' && weight.includes(' ')) {
                  const [min, max] = weight.split(' ').map(Number);
                  const weights = [];
                  for (let w = min; w <= max; w += 100) {
                    weights.push(String(w));
                  }
                  return weights;
                }
                return String(weight);
              })
              .flat()
              .filter(Boolean);

            availableWeights = [...new Set(availableWeights)];
          }

          data[font.slug] = {
            name: font.name,
            fontFamily: font.fontFamily,
            availableWeights: availableWeights.length > 0 ? availableWeights : null,
          };
        }
      });
    }

    return data;
  }, [fontFamiliesRaw]);

  return fontFamiliesData;
};

export const getAvailableWeightsForFont = (fontFamiliesData, fontFamilySlug) => {
  if (!fontFamilySlug || fontFamilySlug === '' || fontFamilySlug === 'system') {
    return null;
  }

  const fontData = fontFamiliesData[fontFamilySlug];
  if (!fontData) {
    return null;
  }

  return fontData.availableWeights;
};

export default useFontFamilies;
