import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
  Box,
  Container,
  Heading,
  Input,
  Text,
  VStack,
  InputGroup,
  InputLeftElement,
  Icon,
  Flex,
  Spinner,
  SimpleGrid,
  Badge,
  HStack,
  Image,
  Divider,
  Button,
  Tabs,
  TabList,
  TabPanels,
  Tab,
  TabPanel,
  Link,
  Stack,
  useColorModeValue,
} from '@chakra-ui/react';
import { FaSearch, FaCalendar, FaUsers, FaImage, FaHandshake, FaMapMarkerAlt, FaEnvelope, FaPhone } from 'react-icons/fa';
import { useSearchParams, useNavigate, Link as RouterLink } from 'react-router-dom';
import MainLayout from '../components/layout/MainLayout';
import { searchAll, SearchResults } from '../services/search';
import NewsletterCTA from '../components/common/NewsletterCTA';
import SponsorsSection from '../components/common/SponsorsSection';
import { assetUrl } from '../utils/url';

const SearchPage: React.FC = () => {
  const [params, setParams] = useSearchParams();
  const navigate = useNavigate();
  const initial = String(params.get('q') || '');
  const [q, setQ] = useState(initial);
  const [debounced, setDebounced] = useState(initial);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [results, setResults] = useState<SearchResults>({
    clubs: [],
    matches: [],
    matchesPast: [],
    articles: [],
    players: [],
    events: [],
    sponsors: [],
    teams: [],
    contacts: [],
    gallery: [],
    total: 0,
  });
  const [activeTab, setActiveTab] = useState<string>('all');

  // Display limits
  const [matchLimit, setMatchLimit] = useState<number>(10);
  const [matchPastLimit, setMatchPastLimit] = useState<number>(10);
  const [articleLimit, setArticleLimit] = useState<number>(12);
  const [playerLimit, setPlayerLimit] = useState<number>(12);
  const [eventLimit, setEventLimit] = useState<number>(10);

  const inputRef = useRef<HTMLInputElement | null>(null);
  const bgColor = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.600');

  // Debounce
  useEffect(() => {
    const id = setTimeout(() => setDebounced(q.trim()), 400);
    return () => clearTimeout(id);
  }, [q]);

  const doSearch = useCallback(async (query: string) => {
    if (!query) {
      setResults({
        clubs: [],
        matches: [],
        matchesPast: [],
        articles: [],
        players: [],
        events: [],
        sponsors: [],
        teams: [],
        contacts: [],
        gallery: [],
        total: 0,
      });
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const searchResults = await searchAll(query);
      setResults(searchResults);
    } catch (e: any) {
      setError(e?.message || 'Chyba vyhledávání');
    } finally {
      setLoading(false);
    }
  }, []);

  // Trigger on load and when debounced query changes
  useEffect(() => {
    const current = String(params.get('q') || '');
    if (debounced !== current) {
      const next = new URLSearchParams(params.toString());
      if (debounced) next.set('q', debounced); else next.delete('q');
      setParams(next, { replace: true });
    }
    setMatchLimit(10);
    setMatchPastLimit(10);
    setArticleLimit(12);
    setPlayerLimit(12);
    setEventLimit(10);
    doSearch(debounced);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [debounced]);

  const hasAny = useMemo(() => results.total > 0, [results.total]);
  
  // Filter out clubs with no names
  const validClubs = useMemo(() => 
    results.clubs.filter(c => c.title && String(c.title).trim()),
    [results.clubs]
  );

  const onSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const next = q.trim();
    setQ(next);
    setDebounced(next);
    const sp = new URLSearchParams(params.toString());
    if (next) sp.set('q', next); else sp.delete('q');
    navigate(`/hledat?${sp.toString()}`);
  };

  // Helpers: highlight query occurrences
  const highlight = (text?: string, qy?: string) => {
    const t = String(text || '');
    const q = String(qy || '').trim();
    if (!t || !q) return t;
    try {
      const esc = q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      const re = new RegExp(esc, 'gi');
      const parts = t.split(re);
      const matches = t.match(re) || [];
      const out: any[] = [];
      parts.forEach((p, idx) => {
        out.push(p);
        if (idx < matches.length) out.push(<mark key={idx} style={{ backgroundColor: '#fde68a' }}>{matches[idx]}</mark>);
      });
      return <>{out}</>;
    } catch {
      return t;
    }
  };

  return (
    <MainLayout>
      <Container maxW="7xl" py={{ base: 6, md: 10 }}>
        <VStack align="stretch" spacing={8}>
          <Box>
            <Heading as="h1" size={{ base: 'xl', md: '2xl' }} mb={2}>Vyhledávání</Heading>
            <Text color="gray.600">Prohledávejte kluby, zápasy, články, hráče, akce a další obsah</Text>
          </Box>

          <Box as="form" onSubmit={onSubmit}>
            <InputGroup size="lg">
              <InputLeftElement pointerEvents="none">
                <Icon as={FaSearch} color="gray.400" />
              </InputLeftElement>
              <Input
                placeholder="Hledat kluby, zápasy, články, hráče, akce..."
                value={q}
                onChange={(e) => { setQ(e.target.value); }}
                bg={bgColor}
                borderColor={borderColor}
                ref={inputRef}
                _focus={{ borderColor: 'brand.primary', boxShadow: '0 0 0 1px var(--chakra-colors-brand-primary)' }}
              />
            </InputGroup>
            <Button type="submit" mt={3} colorScheme="blue" size="lg">Vyhledat</Button>
          </Box>


          {loading && (
            <Flex justify="center" my={12}>
              <VStack spacing={3}>
                <Spinner size="xl" color="brand.primary" thickness="4px" />
                <Text color="gray.500">Vyhledávám...</Text>
              </VStack>
            </Flex>
          )}

          {error && (
            <Box p={4} bg="red.50" borderRadius="md" borderWidth="1px" borderColor="red.200">
              <Text color="red.700" fontWeight="medium">Chyba při vyhledávání</Text>
              <Text color="red.600" fontSize="sm">{error}</Text>
            </Box>
          )}

          {!loading && !hasAny && debounced && (
            <Box textAlign="center" py={12}>
              <Icon as={FaSearch} boxSize={16} color="gray.300" mb={4} />
              <Heading size="md" mb={2}>Žádné výsledky</Heading>
              <Text color="gray.500">Pro dotaz "{debounced}" nebyly nalezeny žádné výsledky</Text>
              <Text color="gray.500" fontSize="sm" mt={2}>Zkuste jiné klíčové slovo nebo hledejte obecnější termín</Text>
            </Box>
          )}

          {/* Tabs for filtering */}
          {hasAny && (
            <Tabs
              variant="enclosed"
              colorScheme="blue"
              index={['all', 'clubs', 'matches', 'articles', 'players', 'events', 'other'].indexOf(activeTab)}
              onChange={(i) => setActiveTab(['all', 'clubs', 'matches', 'articles', 'players', 'events', 'other'][i])}
            >
              <TabList flexWrap="wrap">
                <Tab><Icon as={FaSearch} mr={2} />Vše ({results.total})</Tab>
                <Tab>Kluby ({validClubs.length})</Tab>
                <Tab>Zápasy ({results.matches.length + results.matchesPast.length})</Tab>
                <Tab>Články ({results.articles.length})</Tab>
                <Tab><Icon as={FaUsers} mr={2} />Hráči ({results.players.length})</Tab>
                <Tab><Icon as={FaCalendar} mr={2} />Akce ({results.events.length})</Tab>
                <Tab>Ostatní ({results.teams.length + results.sponsors.length + results.contacts.length + results.gallery.length})</Tab>
              </TabList>

              <TabPanels>
                {/* All Results Tab */}
                <TabPanel px={0}>
                  <VStack align="stretch" spacing={8}>
                    {/* Clubs */}
                    {validClubs.length > 0 && (
                      <Box>
                        <HStack justify="space-between" mb={4}>
                          <Heading size="md">Kluby</Heading>
                          <Badge colorScheme="blue" fontSize="md">{validClubs.length}</Badge>
                        </HStack>
                        <SimpleGrid columns={{ base: 1, md: 2 }} spacing={4}>
                          {validClubs.slice(0, 6).map((c) => (
                            <Flex key={c.id} p={4} bg={bgColor} borderWidth="1px" borderRadius="md" align="center" gap={3}>
                              {c.logo_url && <Image src={c.logo_url} alt={c.title} boxSize="50px" objectFit="contain" />}
                              <VStack align="start" spacing={1}>
                                <Text fontWeight="bold">{highlight(c.title, q)}</Text>
                                {c.subtitle && <Text fontSize="sm" color="gray.500">{c.subtitle}</Text>}
                              </VStack>
                            </Flex>
                          ))}
                        </SimpleGrid>
                        {validClubs.length > 6 && (
                          <Button mt={3} size="sm" onClick={() => setActiveTab('clubs')}>
                            Zobrazit všech {validClubs.length} klubů
                          </Button>
                        )}
                      </Box>
                    )}

                    {/* Players */}
                    {results.players.length > 0 && (
                      <Box>
                        <HStack justify="space-between" mb={4}>
                          <Heading size="md"><Icon as={FaUsers} mr={2} />Hráči</Heading>
                          <Badge colorScheme="green" fontSize="md">{results.players.length}</Badge>
                        </HStack>
                        <SimpleGrid columns={{ base: 2, md: 4, lg: 6 }} spacing={4}>
                          {results.players.slice(0, 6).map((p) => (
                            <Stack
                              key={p.id}
                              as={RouterLink}
                              to={p.url || '#'}
                              borderWidth="1px"
                              borderRadius="lg"
                              overflow="hidden"
                              bg={bgColor}
                              _hover={{ boxShadow: 'md', transform: 'translateY(-2px)' }}
                              transition="all 0.2s"
                            >
                              <Image
                                src={assetUrl(p.image_url) || '/logo512.png'}
                                alt={p.title}
                                objectFit="cover"
                                w="100%"
                                h="140px"
                              />
                              <VStack p={2} spacing={1} align="start">
                                <Text fontWeight="bold" fontSize="xs" noOfLines={1}>{highlight(p.title, q)}</Text>
                                {p.subtitle && <Text fontSize="xs" color="gray.500" noOfLines={1}>{p.subtitle}</Text>}
                              </VStack>
                            </Stack>
                          ))}
                        </SimpleGrid>
                        {results.players.length > 6 && (
                          <Button mt={3} size="sm" onClick={() => setActiveTab('players')}>
                            Zobrazit všech {results.players.length} hráčů
                          </Button>
                        )}
                      </Box>
                    )}

                    {/* Matches */}
                    {(results.matches.length + results.matchesPast.length) > 0 && (
                      <Box>
                        <HStack justify="space-between" mb={4}>
                          <Heading size="md">Zápasy</Heading>
                          <Badge colorScheme="purple" fontSize="md">{results.matches.length + results.matchesPast.length}</Badge>
                        </HStack>
                        <VStack align="stretch" spacing={3}>
                          {results.matches.slice(0, 3).map((m) => (
                            <Flex key={m.id} p={3} bg={bgColor} borderWidth="1px" borderRadius="md" justify="space-between" flexWrap="wrap" gap={2}>
                              <HStack gap={2}>
                                {m.metadata?.home_logo_url && <Image src={m.metadata.home_logo_url} alt="" boxSize="24px" objectFit="contain" />}
                                <Text fontSize="sm" fontWeight="medium">{highlight(m.title, q)}</Text>
                                {m.metadata?.away_logo_url && <Image src={m.metadata.away_logo_url} alt="" boxSize="24px" objectFit="contain" />}
                              </HStack>
                              {m.date && <Text fontSize="xs" color="gray.500">{m.date} {m.time}</Text>}
                            </Flex>
                          ))}
                        </VStack>
                        {(results.matches.length + results.matchesPast.length) > 3 && (
                          <Button mt={3} size="sm" onClick={() => setActiveTab('matches')}>
                            Zobrazit všechny zápasy
                          </Button>
                        )}
                      </Box>
                    )}

                    {/* Articles */}
                    {results.articles.length > 0 && (
                      <Box>
                        <HStack justify="space-between" mb={4}>
                          <Heading size="md">Články</Heading>
                          <Badge colorScheme="teal" fontSize="md">{results.articles.length}</Badge>
                        </HStack>
                        <SimpleGrid columns={{ base: 1, md: 2, lg: 3 }} spacing={4}>
                          {results.articles.slice(0, 6).map((a) => (
                            <Stack
                              key={a.id}
                              as={RouterLink}
                              to={a.url || '#'}
                              borderWidth="1px"
                              borderRadius="lg"
                              overflow="hidden"
                              bg={bgColor}
                              _hover={{ boxShadow: 'lg', transform: 'translateY(-2px)' }}
                              transition="all 0.2s"
                            >
                              {a.image_url && (
                                <Image src={a.image_url} alt={a.title} objectFit="cover" w="100%" h="140px" />
                              )}
                              <VStack p={3} spacing={2} align="start">
                                <Text fontWeight="bold" fontSize="sm" noOfLines={2}>{highlight(a.title, q)}</Text>
                                {a.description && (
                                  <Text fontSize="xs" color="gray.600" noOfLines={2}>{highlight(a.description, q)}</Text>
                                )}
                              </VStack>
                            </Stack>
                          ))}
                        </SimpleGrid>
                        {results.articles.length > 6 && (
                          <Button mt={3} size="sm" onClick={() => setActiveTab('articles')}>
                            Zobrazit všech {results.articles.length} článků
                          </Button>
                        )}
                      </Box>
                    )}

                    {/* Events */}
                    {results.events.length > 0 && (
                      <Box>
                        <HStack justify="space-between" mb={4}>
                          <Heading size="md"><Icon as={FaCalendar} mr={2} />Akce</Heading>
                          <Badge colorScheme="orange" fontSize="md">{results.events.length}</Badge>
                        </HStack>
                        <SimpleGrid columns={{ base: 1, md: 2 }} spacing={4}>
                          {results.events.slice(0, 4).map((e) => (
                            <Flex key={e.id} p={3} bg={bgColor} borderWidth="1px" borderRadius="md" gap={2}>
                              <Icon as={FaCalendar} boxSize={5} color="orange.400" mt={1} />
                              <VStack align="start" spacing={1} flex={1}>
                                <Text fontWeight="bold" fontSize="sm">{highlight(e.title, q)}</Text>
                                {e.description && (
                                  <Text fontSize="xs" color="gray.600" noOfLines={2}>{highlight(e.description, q)}</Text>
                                )}
                                {e.date && <Text fontSize="xs" color="gray.500">{e.date} {e.time}</Text>}
                              </VStack>
                            </Flex>
                          ))}
                        </SimpleGrid>
                        {results.events.length > 4 && (
                          <Button mt={3} size="sm" onClick={() => setActiveTab('events')}>
                            Zobrazit všechny akce
                          </Button>
                        )}
                      </Box>
                    )}
                  </VStack>
                </TabPanel>

                {/* Clubs Tab */}
                <TabPanel px={0}>
                  {validClubs.length > 0 ? (
                    <SimpleGrid columns={{ base: 1, md: 2 }} spacing={4}>
                      {validClubs.map((c) => (
                        <Flex key={c.id} p={4} bg={bgColor} borderWidth="1px" borderRadius="md" align="center" gap={3}>
                          {c.logo_url && <Image src={c.logo_url} alt={c.title} boxSize="60px" objectFit="contain" />}
                          <VStack align="start" spacing={1}>
                            <Text fontWeight="bold">{highlight(c.title, q)}</Text>
                            {c.subtitle && <Text fontSize="sm" color="gray.500">{c.subtitle}</Text>}
                          </VStack>
                        </Flex>
                      ))}
                    </SimpleGrid>
                  ) : (
                    <Text color="gray.500">Žádné kluby nenalezeny</Text>
                  )}
                </TabPanel>

                {/* Matches Tab */}
                <TabPanel px={0}>
                  <VStack align="stretch" spacing={6}>
                    {results.matches.length > 0 && (
                      <Box>
                        <Heading size="sm" mb={3}>Nadcházející zápasy</Heading>
                        <VStack align="stretch" spacing={3}>
                          {results.matches.map((m) => (
                            <Flex key={m.id} p={4} bg={bgColor} borderWidth="1px" borderRadius="md" justify="space-between" flexWrap="wrap" gap={3}>
                              <HStack gap={2}>
                                {m.metadata?.home_logo_url && <Image src={m.metadata.home_logo_url} alt="" boxSize="32px" objectFit="contain" />}
                                <Text fontWeight="medium">{highlight(m.title, q)}</Text>
                                {m.metadata?.away_logo_url && <Image src={m.metadata.away_logo_url} alt="" boxSize="32px" objectFit="contain" />}
                              </HStack>
                              <HStack gap={2}>
                                {m.date && <Text fontSize="sm" color="gray.500">{m.date} {m.time}</Text>}
                                {m.subtitle && <Badge>{highlight(m.subtitle, q)}</Badge>}
                              </HStack>
                            </Flex>
                          ))}
                        </VStack>
                      </Box>
                    )}
                    {results.matchesPast.length > 0 && (
                      <Box>
                        <Heading size="sm" mb={3}>Minulé zápasy</Heading>
                        <VStack align="stretch" spacing={3}>
                          {results.matchesPast.map((m) => (
                            <Flex key={m.id} p={4} bg={bgColor} borderWidth="1px" borderRadius="md" justify="space-between" flexWrap="wrap" gap={3}>
                              <HStack gap={2}>
                                {m.metadata?.home_logo_url && <Image src={m.metadata.home_logo_url} alt="" boxSize="32px" objectFit="contain" />}
                                <Text fontWeight="medium">{highlight(m.title, q)}</Text>
                                {m.metadata?.away_logo_url && <Image src={m.metadata.away_logo_url} alt="" boxSize="32px" objectFit="contain" />}
                              </HStack>
                              <HStack gap={2}>
                                {m.date && <Text fontSize="sm" color="gray.500">{m.date} {m.time}</Text>}
                                {m.subtitle && <Badge>{highlight(m.subtitle, q)}</Badge>}
                              </HStack>
                            </Flex>
                          ))}
                        </VStack>
                      </Box>
                    )}
                    {results.matches.length === 0 && results.matchesPast.length === 0 && (
                      <Text color="gray.500">Žádné zápasy nenalezeny</Text>
                    )}
                  </VStack>
                </TabPanel>

                {/* Articles Tab */}
                <TabPanel px={0}>
                  {results.articles.length > 0 ? (
                    <SimpleGrid columns={{ base: 1, md: 2, lg: 3 }} spacing={4}>
                      {results.articles.map((a) => (
                        <Stack
                          key={a.id}
                          as={RouterLink}
                          to={a.url || '#'}
                          borderWidth="1px"
                          borderRadius="lg"
                          overflow="hidden"
                          bg={bgColor}
                          _hover={{ boxShadow: 'lg', transform: 'translateY(-2px)' }}
                          transition="all 0.2s"
                        >
                          {a.image_url && (
                            <Image src={a.image_url} alt={a.title} objectFit="cover" w="100%" h="160px" />
                          )}
                          <VStack p={4} spacing={2} align="start">
                            <Text fontWeight="bold" noOfLines={2}>{highlight(a.title, q)}</Text>
                            {a.description && (
                              <Text fontSize="sm" color="gray.600" noOfLines={3}>{highlight(a.description, q)}</Text>
                            )}
                          </VStack>
                        </Stack>
                      ))}
                    </SimpleGrid>
                  ) : (
                    <Text color="gray.500">Žádné články nenalezeny</Text>
                  )}
                </TabPanel>

                {/* Players Tab */}
                <TabPanel px={0}>
                  {results.players.length > 0 ? (
                    <SimpleGrid columns={{ base: 2, md: 3, lg: 4 }} spacing={4}>
                      {results.players.map((p) => (
                        <Stack
                          key={p.id}
                          as={RouterLink}
                          to={p.url || '#'}
                          borderWidth="1px"
                          borderRadius="lg"
                          overflow="hidden"
                          bg={bgColor}
                          _hover={{ boxShadow: 'md', transform: 'translateY(-2px)' }}
                          transition="all 0.2s"
                        >
                          <Image
                            src={assetUrl(p.image_url) || '/logo512.png'}
                            alt={p.title}
                            objectFit="cover"
                            w="100%"
                            h="200px"
                          />
                          <VStack p={3} spacing={1} align="start">
                            <Text fontWeight="bold" fontSize="sm">{highlight(p.title, q)}</Text>
                            {p.subtitle && <Text fontSize="xs" color="gray.500">{p.subtitle}</Text>}
                            {p.metadata?.jersey_number && (
                              <Badge colorScheme="blue">#{p.metadata.jersey_number}</Badge>
                            )}
                          </VStack>
                        </Stack>
                      ))}
                    </SimpleGrid>
                  ) : (
                    <Text color="gray.500">Žádní hráči nenalezeni</Text>
                  )}
                </TabPanel>

                {/* Events Tab */}
                <TabPanel px={0}>
                  {results.events.length > 0 ? (
                    <SimpleGrid columns={{ base: 1, md: 2 }} spacing={4}>
                      {results.events.map((e) => (
                        <Flex key={e.id} p={4} bg={bgColor} borderWidth="1px" borderRadius="md" gap={3}>
                          <Icon as={FaCalendar} boxSize={8} color="orange.400" />
                          <VStack align="start" spacing={1} flex={1}>
                            <Text fontWeight="bold">{highlight(e.title, q)}</Text>
                            {e.description && (
                              <Text fontSize="sm" color="gray.600" noOfLines={2}>{highlight(e.description, q)}</Text>
                            )}
                            <HStack fontSize="sm" color="gray.500" spacing={3}>
                              {e.date && <Text>{e.date} {e.time}</Text>}
                              {e.metadata?.location && (
                                <HStack spacing={1}>
                                  <Icon as={FaMapMarkerAlt} />
                                  <Text>{e.metadata.location}</Text>
                                </HStack>
                              )}
                            </HStack>
                          </VStack>
                        </Flex>
                      ))}
                    </SimpleGrid>
                  ) : (
                    <Text color="gray.500">Žádné akce nenalezeny</Text>
                  )}
                </TabPanel>

                {/* Other Tab - Teams, Sponsors, Contacts, Gallery */}
                <TabPanel px={0}>
                  <VStack align="stretch" spacing={8}>
                    {results.teams.length > 0 && (
                      <Box>
                        <Heading size="sm" mb={3}>Týmy</Heading>
                        <SimpleGrid columns={{ base: 1, md: 2 }} spacing={4}>
                          {results.teams.map((t) => (
                            <Flex key={t.id} p={4} bg={bgColor} borderWidth="1px" borderRadius="md" gap={3}>
                              {t.logo_url && <Image src={t.logo_url} alt={t.title} boxSize="48px" objectFit="contain" />}
                              <VStack align="start" spacing={1}>
                                <Text fontWeight="bold">{highlight(t.title, q)}</Text>
                                {t.subtitle && <Text fontSize="sm" color="gray.500">{t.subtitle}</Text>}
                              </VStack>
                            </Flex>
                          ))}
                        </SimpleGrid>
                      </Box>
                    )}

                    {results.sponsors.length > 0 && (
                      <Box>
                        <Heading size="sm" mb={3}><Icon as={FaHandshake} mr={2} />Sponzoři</Heading>
                        <SimpleGrid columns={{ base: 2, md: 4 }} spacing={4}>
                          {results.sponsors.map((s) => (
                            <Flex
                              key={s.id}
                              as={s.url ? Link : undefined}
                              href={s.url}
                              isExternal={!!s.url}
                              p={4}
                              bg={bgColor}
                              borderWidth="1px"
                              borderRadius="md"
                              align="center"
                              justify="center"
                            >
                              {s.logo_url ? (
                                <Image src={s.logo_url} alt={s.title} maxH="60px" maxW="100%" objectFit="contain" />
                              ) : (
                                <Text fontWeight="medium">{highlight(s.title, q)}</Text>
                              )}
                            </Flex>
                          ))}
                        </SimpleGrid>
                      </Box>
                    )}

                    {results.contacts.length > 0 && (
                      <Box>
                        <Heading size="sm" mb={3}><Icon as={FaEnvelope} mr={2} />Kontakty</Heading>
                        <SimpleGrid columns={{ base: 1, md: 2 }} spacing={4}>
                          {results.contacts.map((c) => (
                            <Flex key={c.id} p={4} bg={bgColor} borderWidth="1px" borderRadius="md" gap={3}>
                              {c.image_url ? (
                                <Image src={c.image_url} alt={c.title} boxSize="50px" borderRadius="full" objectFit="cover" />
                              ) : (
                                <Icon as={FaUsers} boxSize={10} color="gray.400" />
                              )}
                              <VStack align="start" spacing={1} flex={1}>
                                <Text fontWeight="bold">{highlight(c.title, q)}</Text>
                                {c.subtitle && <Text fontSize="sm" color="gray.600">{c.subtitle}</Text>}
                                {c.metadata?.email && (
                                  <HStack fontSize="xs" color="gray.500">
                                    <Icon as={FaEnvelope} />
                                    <Text>{c.metadata.email}</Text>
                                  </HStack>
                                )}
                                {c.metadata?.phone && (
                                  <HStack fontSize="xs" color="gray.500">
                                    <Icon as={FaPhone} />
                                    <Text>{c.metadata.phone}</Text>
                                  </HStack>
                                )}
                              </VStack>
                            </Flex>
                          ))}
                        </SimpleGrid>
                      </Box>
                    )}

                    {results.gallery.length > 0 && (
                      <Box>
                        <Heading size="sm" mb={3}><Icon as={FaImage} mr={2} />Galerie</Heading>
                        <SimpleGrid columns={{ base: 2, md: 3, lg: 4 }} spacing={4}>
                          {results.gallery.map((g) => (
                            <Stack
                              key={g.id}
                              as={RouterLink}
                              to={g.url || '#'}
                              borderWidth="1px"
                              borderRadius="lg"
                              overflow="hidden"
                              bg={bgColor}
                              _hover={{ boxShadow: 'md', transform: 'translateY(-2px)' }}
                              transition="all 0.2s"
                            >
                              {g.image_url && (
                                <Image src={g.image_url} alt={g.title} objectFit="cover" w="100%" h="120px" />
                              )}
                              <VStack p={3} spacing={1} align="start">
                                <Text fontWeight="bold" fontSize="sm" noOfLines={1}>{highlight(g.title, q)}</Text>
                                {g.metadata?.photo_count && (
                                  <Text fontSize="xs" color="gray.500">{g.metadata.photo_count} fotek</Text>
                                )}
                              </VStack>
                            </Stack>
                          ))}
                        </SimpleGrid>
                      </Box>
                    )}

                    {results.teams.length === 0 && results.sponsors.length === 0 && results.contacts.length === 0 && results.gallery.length === 0 && (
                      <Text color="gray.500">Žádné další výsledky</Text>
                    )}
                  </VStack>
                </TabPanel>
              </TabPanels>
            </Tabs>
          )}
        </VStack>

        {/* Newsletter CTA */}
        <NewsletterCTA />
        
        {/* Sponsors Section */}
        <SponsorsSection />
      </Container>
    </MainLayout>
  );
};

export default SearchPage;
