import { TypographyValues } from '../types/typography';

export type Font = {
  family: string;
  variants: string[];
  category: string;
  kind: string;
  menu: string;
  files: Record<string, string>;
};

export function loadGoogleFont(fontFamily: string): Promise<void> {
  return new Promise((resolve, reject) => {
    if (typeof window === 'undefined') {
      resolve();
      return;
    }

    import('webfontloader')
      .then((WebFont) => {
        WebFont.load({
          google: {
            families: [`${fontFamily}:100,200,300,400,500,600,700,800,900`],
          },
          active: () => resolve(),
          inactive: () => reject(new Error('Failed to load font')),
          timeout: 1500,
        });
      })
      .catch(reject);
  });
}

export const setGlobalTypography = (values?: TypographyValues): Promise<void> => {
  const root = document.documentElement;

  const promises: Promise<void>[] = [];

  if (values?.headingFontFamily) {
    promises.push(loadGoogleFont(values.headingFontFamily));
  }

  if (values?.textFontFamily) {
    promises.push(loadGoogleFont(values.textFontFamily));
  }

  root.style.setProperty('--heading-font-family', values?.headingFontFamily ?? 'Inter');
  root.style.setProperty('--heading-font-size-base', `${values?.headingFontSize ?? 40}px`);
  root.style.setProperty('--text-font-family', values?.textFontFamily ?? 'Inter');

  return Promise.all(promises).then(() => {});
};

export const getInitialValues = (): TypographyValues => {
  const computedStyle = getComputedStyle(document.documentElement);
  return {
    headingFontFamily: computedStyle.getPropertyValue('--heading-font-family').replace(/['"]/g, '') ?? 'Inter',
    headingFontSize: parseInt(computedStyle.getPropertyValue('--heading-font-size-base')) ?? 32,
    textFontFamily: computedStyle.getPropertyValue('--text-font-family').replace(/['"]/g, '') ?? 'Inter',
  };
};
