import React, {
  CSSProperties,
  ReactNode,
  useEffect,
  useState,
} from 'react';

import { useAppConfig } from '@/contexts/AppConfigContext';

// Типы для размеров колонок (1–24 или undefined)
type ColSize = number | undefined;

interface ColProps {
  col?: ColSize;
  children?: ReactNode;
  style?: CSSProperties;
  className?: string;
  inline?: boolean;
}

const ColCSS: React.FC<ColProps> = ({ col, className, children, style, inline = false }) => {

  const { isMobile } = useAppConfig();

  const [screenSize, setScreenSize] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => setScreenSize(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  const colSize = isMobile ? 24 : col ?? 24;
  const colStyle: CSSProperties = {
    flexGrow: 0,
    flexShrink: 0,
    flexBasis: `${(colSize / 24) * 100}%`, // Рассчитываем ширину колонки
    maxWidth: `${(colSize / 24) * 100}%`,
    ...style,
  };

  if (inline) {
    return <div>{children}</div>
  }

  return <div className={className} style={colStyle}>{children}</div>;
};

interface RowProps {
  children: ReactNode;
  style?: CSSProperties;
  gap?: number;
  align?: 'top' | 'middle' | 'bottom';
  justify?: 'start' | 'end' | 'center' | 'space-around' | 'space-between';
  className?: string;
  inline?: boolean;
}

const RowCSS: React.FC<RowProps> = ({ children, style, gap, justify, className, inline = false }) => {


  const rowStyle: CSSProperties = {
    display: 'flex',
    flexWrap: 'wrap',
    ...style,
    //Учитываем gap на основе gutter
    //  margin:  `-${gutter?.[1] / 2}px -${gutter?.[0] / 2}px`,
  };

  if (gap) {
    rowStyle.gap = `${gap}px`;
  }

  if (inline) {
    return <div>{children}</div>
  }

  return <div style={rowStyle} className={className}>{children}</div>;
};

export { ColCSS, RowCSS };
