'use client';

import { BreakpointConfiguration } from '@/features/builder/config/breakpoints.config';
import { BlockConfiguration } from '@/features/builder/config/editor.config';
import { Block } from '@/features/builder/types/block';
import { Breakpoint } from '@/features/builder/types/responsive';
import { createStyle } from '@/features/builder/utils';
import { generateContentStyles, generateFontsUrl } from '@/features/builder/utils/style';
import { generateThemeStyles } from '@/features/builder/utils/theme';
import { ThemeSettings } from '@/features/theme/types';
import { useServerInsertedHTML } from 'next/navigation';
import { FC, memo } from 'react';

type Props = {
  content: Record<string, Block>;
  themeSettings: ThemeSettings;
};

const StyleManager: FC<Props> = memo(({ content, themeSettings }) => {
  let isServerStylesInjected = false;

  const breakpoints = BreakpointConfiguration.getBreakpoints();

  const style = createStyle();

  style.register({
    $global: true,
    '.hide-on-desktop': {
      [BreakpointConfiguration.getMediaQuery(Breakpoint.DESKTOP)]: {
        display: 'none',
      },
    },
    '.hide-on-tablet': {
      [BreakpointConfiguration.getMediaQuery(Breakpoint.TABLET)]: {
        display: 'none',
      },
    },
    '.hide-on-mobile': {
      [BreakpointConfiguration.getMediaQuery(Breakpoint.MOBILE)]: {
        display: 'none',
      },
    },
  });

  const defaultStyles = style.get();

  const contentStyles = generateContentStyles({
    content,
    themeSettings,
    breakpoints,
    config: BlockConfiguration.getConfig(),
  });

  const themeStyles = generateThemeStyles({ settings: themeSettings, breakpoints });

  const styles = defaultStyles + themeStyles + contentStyles;

  const fontsUrl = generateFontsUrl(styles);

  // For SSR - inject styles only once
  useServerInsertedHTML(() => {
    if (isServerStylesInjected) {
      return null;
    }
    isServerStylesInjected = true;

    return (
      <>
        <link href={fontsUrl} id="fonts" rel="stylesheet"></link>
        <style id="dynamic-styles" dangerouslySetInnerHTML={{ __html: styles }}></style>
      </>
    );
  });

  return null;
});

StyleManager.displayName = 'StyleManager';

export default StyleManager;
