import "./style.pcss";

import type {
  ReactNode, ReactElement, FC, SourceHTMLAttributes,
} from "react";
import type { IPicture, TMediaQueries } from "./config/types";
import { getMediaQuery } from "./lib/index";
import { constants } from "../../constants";
import type { IComponentBaseProps } from "../../types/components/index";
import { useCN } from "../../utils/react/useCN";

const Sources: FC<{ data: IPicture["sources"]; }> = ({
  data,
}): ReactNode => {
  switch (true) {
    case Array.isArray(data): {
      return data.map((source) => {
        const media = getMediaQuery(source.media);
        return <source key={`${source.srcSet ?? ""}_${media ?? ""}_${source.type ?? ""}`} {...source} media={media} />;
      });
    }
    case typeof data === "object" && !!data: {
      return Object.entries(data).map(([ query, source ]: [ string, SourceHTMLAttributes<HTMLSourceElement> ]) => {
        const media = !!constants.mediaQueries[query as keyof TMediaQueries] ? getMediaQuery(query) : query;
        return <source key={query} {...source} media={media} />;
      });
    }
    default: {
      return null;
    }
  }
};

/**
 * Компонент адаптивного изображения с разными источниками
 * @returns {ReactElement}
 */
const Picture: FC<IPicture & IComponentBaseProps> = ({
  baseClass = "picture",
  extraClasses = {},
  extraAttrs = {},
  children = null,
  sources = [] as IPicture["sources"],
}): ReactElement => {

  const { getCN } = useCN(baseClass);

  return (
    <picture className={getCN("", extraClasses)} {...extraAttrs}>
      <Sources data={sources} />
      {children}
    </picture>
  );

};

export type { IPicture };
export { Picture };
