import { Box, HStack, Image, Link, Spinner, Text, useColorModeValue } from '@chakra-ui/react';
import { useQuery } from '@tanstack/react-query';
import api from '../services/api';
import { assetUrl } from '../utils/url';

type Sponsor = { id: number; name: string; logo_url?: string; website_url?: string };

type SponsorsResponse = Sponsor[] | { data: Sponsor[] };

const fetchSponsors = async (): Promise<Sponsor[]> => {
  const res = await api.get<SponsorsResponse>('/sponsors');
  const data = Array.isArray(res.data) ? res.data : res.data.data;
  return data || [];
};

const SponsorsStrip: React.FC = () => {
  const { data, isLoading, isError } = useQuery({ queryKey: ['sponsors'], queryFn: fetchSponsors });

  return (
    <Box bg={useColorModeValue('white', 'gray.800')} borderTopWidth="1px" borderColor={useColorModeValue('gray.200', 'gray.700')} mt={8} py={4}>
      <HStack spacing={6} overflowX="auto" px={4}>
        {isLoading && <Spinner />}
        {isError && <Text color="red.500">Chyba při načítání sponzorů</Text>}
        {data?.map((s) => (
          <Link key={s.id} href={s.website_url || '#'} isExternal>
            <Image src={assetUrl(s.logo_url) || '/logo192.png'} alt={s.name} height="50px" objectFit="contain" />
          </Link>
        ))}
      </HStack>
    </Box>
  );
};

export default SponsorsStrip;
