'use client';
import { InfiniteScrollList } from '@/components/ui/infinite-scroll-list';
import AIStandardCard from '@/components/features/ai-standard-card';
import useSmartInfiniteQuery from '../../useSmartInfiniteQuery';
import { fetchCharacters } from '@/services/editor';
import { useHomeStore } from '../../store';
import { useEffect } from 'react';

const Character = () => {
  const characterParams = useHomeStore((state) => state.characterParams);

  const { dataSource, isFirstLoading, isLoadingMore, noMoreData, onLoadMore, onSearch } =
    useSmartInfiniteQuery<any, any>(fetchCharacters, {
      queryKey: 'characters',
      defaultQuery: characterParams,
    });

  useEffect(() => {
    onSearch(characterParams);
  }, [characterParams]);

  return (
    <div className="mt-4 sm:mt-8">
      <InfiniteScrollList<any>
        items={dataSource}
        enableLazyRender
        lazyRenderMargin="500px"
        columns={(width) => {
          const cardWidth = width > 1200 ? 256 : width > 588 ? 200 : width > 375 ? 170 : 150;
          return Math.floor(width / cardWidth);
        }}
        renderItem={(character) => <AIStandardCard character={character} />}
        getItemKey={(character, index) => character.id + index}
        hasNextPage={!noMoreData}
        isLoading={isFirstLoading || isLoadingMore}
        fetchNextPage={onLoadMore}
      />
    </div>
  );
};

export default Character;
