import { useEffect, useRef } from 'react';
import { useClient } from 'hooks/useClient';

export const useImageLoader = (baseUrl: string = '/api') => {
  const listContainer = useRef<HTMLDivElement>(null);
  const filesClient = useClient(baseUrl);

  const loadImages = async (imageElems: HTMLImageElement[]) => {
    imageElems.forEach(async (img) => {
      const url = img.getAttribute('data-src');
      if (url) {
        const blob = await filesClient.getBlob(url);
        const objectUrl = URL.createObjectURL(blob);
        img.src = objectUrl;
      }
    });
  };

  useEffect(() => {
    const observer = new MutationObserver((mutations) => {
      const imageElems: HTMLImageElement[] = [];
      for (const mutation of mutations) {
        if (mutation.type === 'childList') {
          const addedNodes = Array.from(mutation.addedNodes);
          for (const node of addedNodes) {
            if (node instanceof HTMLElement) {
              const parent = node.parentElement;
              if (parent) {
                const images = Array.from(parent.querySelectorAll<HTMLImageElement>('img[data-src]'));
                imageElems.push(...images);
              }
            }
          }
        }
      }
      loadImages(imageElems);
    });

    if (listContainer.current) {
      const imageElems = Array.from(listContainer.current.querySelectorAll<HTMLImageElement>('img[data-src]'));
      loadImages(imageElems);
      observer.observe(listContainer.current, {
        childList: true,
        subtree: true,
      });
    }

    return () => {
      observer.disconnect();
    };
  }, [listContainer.current]);

  return { listContainer };
};
