import { Ionicons } from '@expo/vector-icons';
import * as Haptics from 'expo-haptics';
import { LinearGradient } from 'expo-linear-gradient';
import { router } from 'expo-router';
import React, { useCallback, useMemo, useRef, useState } from 'react';
import {
  Animated,
  FlatList,
  Platform,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useColors } from '@/hooks/useColors';
import { CATEGORIES, COURSES, CREATORS, VIDEOS, formatCount, formatPrice } from '@/data/mockData';

type ResultTab = 'all' | 'courses' | 'creators' | 'videos';
type SortBy = 'popular' | 'newest' | 'price_low' | 'price_high';
type Level = 'all' | 'Beginner' | 'Intermediate' | 'Advanced';

const TRENDING = [
  'Nail art business', 'Epoxy table', 'Jollof rice', 'Afrobeats mixing',
  'Interior decor', 'Furniture making', 'Tufted headboard',
];

const SORT_OPTIONS: { key: SortBy; label: string }[] = [
  { key: 'popular', label: 'Most Popular' },
  { key: 'newest', label: 'Newest' },
  { key: 'price_low', label: 'Price: Low' },
  { key: 'price_high', label: 'Price: High' },
];

const LEVEL_OPTIONS: Level[] = ['all', 'Beginner', 'Intermediate', 'Advanced'];

const CAT_ICONS: Record<string, string> = {
  all: 'star', beauty: 'sparkles', diy: 'hammer-outline',
  decor: 'home-outline', cooking: 'restaurant-outline', music: 'musical-notes-outline',
  art: 'color-palette-outline', business: 'briefcase-outline', tech: 'laptop-outline',
  furniture: 'cube-outline',
};

function highlight(text: string, query: string, primaryColor: string, baseColor: string) {
  if (!query.trim()) return <Text style={{ color: baseColor }}>{text}</Text>;
  const lower = text.toLowerCase();
  const idx = lower.indexOf(query.toLowerCase());
  if (idx === -1) return <Text style={{ color: baseColor }}>{text}</Text>;
  return (
    <Text>
      <Text style={{ color: baseColor }}>{text.slice(0, idx)}</Text>
      <Text style={{ color: primaryColor, fontFamily: 'Poppins_700Bold' }}>{text.slice(idx, idx + query.length)}</Text>
      <Text style={{ color: baseColor }}>{text.slice(idx + query.length)}</Text>
    </Text>
  );
}

export default function ExploreScreen() {
  const colors = useColors();
  const insets = useSafeAreaInsets();
  const inputRef = useRef<TextInput>(null);
  const [query, setQuery] = useState('');
  const [focused, setFocused] = useState(false);
  const [tab, setTab] = useState<ResultTab>('all');
  const [catFilter, setCatFilter] = useState('all');
  const [sortBy, setSortBy] = useState<SortBy>('popular');
  const [level, setLevel] = useState<Level>('all');
  const [showFilters, setShowFilters] = useState(false);
  const [history, setHistory] = useState<string[]>([
    'Epoxy art', 'Nail business', 'West African food',
  ]);
  const filterAnim = useRef(new Animated.Value(0)).current;

  const topPad = Platform.OS === 'web' ? 67 : insets.top;
  const isSearching = query.trim().length > 0 || focused;

  const toggleFilters = useCallback(() => {
    const next = !showFilters;
    setShowFilters(next);
    Animated.spring(filterAnim, {
      toValue: next ? 1 : 0,
      useNativeDriver: false,
      speed: 20,
      bounciness: 4,
    }).start();
  }, [showFilters, filterAnim]);

  const filterHeight = filterAnim.interpolate({ inputRange: [0, 1], outputRange: [0, 138] });

  const commitSearch = useCallback((q: string) => {
    if (!q.trim()) return;
    setHistory((prev) => [q, ...prev.filter((h) => h !== q)].slice(0, 8));
  }, []);

  const clearHistory = useCallback(() => setHistory([]), []);

  const sortedCourses = useMemo(() => {
    let cs = [...COURSES];
    if (catFilter !== 'all') cs = cs.filter((c) => c.categoryId === catFilter);
    if (level !== 'all') cs = cs.filter((c) => c.level === level);
    if (query.trim()) {
      const q = query.toLowerCase();
      cs = cs.filter((c) =>
        c.title.toLowerCase().includes(q) ||
        c.description.toLowerCase().includes(q) ||
        CREATORS.find((cr) => cr.id === c.creatorId)?.name.toLowerCase().includes(q)
      );
    }
    if (sortBy === 'popular') cs.sort((a, b) => b.enrolledCount - a.enrolledCount);
    else if (sortBy === 'price_low') cs.sort((a, b) => a.price - b.price);
    else if (sortBy === 'price_high') cs.sort((a, b) => b.price - a.price);
    return cs;
  }, [query, catFilter, level, sortBy]);

  const filteredCreators = useMemo(() => {
    if (!query.trim()) return CREATORS;
    const q = query.toLowerCase();
    return CREATORS.filter((c) =>
      c.name.toLowerCase().includes(q) ||
      c.specialty.toLowerCase().includes(q) ||
      c.username.toLowerCase().includes(q)
    );
  }, [query]);

  const filteredVideos = useMemo(() => {
    if (!query.trim()) return [];
    const q = query.toLowerCase();
    return VIDEOS.filter((v) =>
      v.title.toLowerCase().includes(q) ||
      v.description.toLowerCase().includes(q) ||
      CREATORS.find((c) => c.id === v.creatorId)?.name.toLowerCase().includes(q)
    );
  }, [query]);

  const totalResults = sortedCourses.length + filteredCreators.length + filteredVideos.length;

  const tabCounts = {
    all: totalResults,
    courses: sortedCourses.length,
    creators: filteredCreators.length,
    videos: filteredVideos.length,
  };

  const activeFilters = (catFilter !== 'all' ? 1 : 0) + (level !== 'all' ? 1 : 0) + (sortBy !== 'popular' ? 1 : 0);

  return (
    <View style={[s.screen, { backgroundColor: colors.background }]}>
      {/* Fixed top bar */}
      <View style={[s.topBar, { paddingTop: topPad + 10, backgroundColor: colors.background, borderBottomColor: colors.border }]}>
        <View style={[s.searchRow, { backgroundColor: colors.card, borderColor: focused ? colors.primary : colors.border }]}>
          <Ionicons name="search-outline" size={18} color={focused ? colors.primary : colors.mutedForeground} />
          <TextInput
            ref={inputRef}
            style={[s.searchInput, { color: colors.foreground }]}
            placeholder="Search skills, creators, courses..."
            placeholderTextColor={colors.mutedForeground}
            value={query}
            onChangeText={setQuery}
            onFocus={() => setFocused(true)}
            onBlur={() => setFocused(false)}
            onSubmitEditing={() => commitSearch(query)}
            returnKeyType="search"
          />
          {query.length > 0 && (
            <TouchableOpacity onPress={() => { setQuery(''); setTab('all'); }}>
              <Ionicons name="close-circle" size={18} color={colors.mutedForeground} />
            </TouchableOpacity>
          )}
        </View>

        {isSearching && (
          <TouchableOpacity
            onPress={() => { setQuery(''); setFocused(false); inputRef.current?.blur(); setTab('all'); }}
            style={s.cancelBtn}
          >
            <Text style={[s.cancelText, { color: colors.primary }]}>Cancel</Text>
          </TouchableOpacity>
        )}
      </View>

      {!isSearching ? (
        /* ── DISCOVERY MODE ── */
        <ScrollView contentContainerStyle={[s.scroll, { paddingBottom: Platform.OS === 'web' ? 100 : 80 }]} showsVerticalScrollIndicator={false}>
          {/* Trending */}
          <Text style={[s.sectionTitle, { color: colors.foreground }]}>Trending Searches</Text>
          <View style={s.trendingGrid}>
            {TRENDING.map((t) => (
              <TouchableOpacity
                key={t}
                onPress={() => { setQuery(t); setFocused(false); commitSearch(t); }}
                style={[s.trendingChip, { backgroundColor: colors.card, borderColor: colors.border }]}
              >
                <Ionicons name="trending-up-outline" size={13} color={colors.primary} />
                <Text style={[s.trendingText, { color: colors.foreground }]}>{t}</Text>
              </TouchableOpacity>
            ))}
          </View>

          {/* Categories */}
          <Text style={[s.sectionTitle, { color: colors.foreground }]}>Browse by Skill</Text>
          <View style={s.catGrid}>
            {CATEGORIES.slice(1).map((cat) => (
              <TouchableOpacity
                key={cat.id}
                onPress={() => { setCatFilter(cat.id); setQuery(' '); setFocused(false); }}
                activeOpacity={0.8}
                style={s.catItem}
              >
                <LinearGradient colors={cat.gradientColors} style={s.catIcon} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }}>
                  <Ionicons name={CAT_ICONS[cat.id] as any ?? 'star-outline'} size={26} color="#fff" />
                </LinearGradient>
                <Text style={[s.catLabel, { color: colors.foreground }]} numberOfLines={1}>{cat.name}</Text>
              </TouchableOpacity>
            ))}
          </View>

          {/* Top Creators */}
          <Text style={[s.sectionTitle, { color: colors.foreground }]}>Top Creators</Text>
          <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={s.creatorsRow}>
            {CREATORS.map((creator) => (
              <TouchableOpacity
                key={creator.id}
                onPress={() => router.push(`/creator/${creator.id}` as any)}
                style={[s.creatorCard, { backgroundColor: colors.card, borderColor: colors.border }]}
                activeOpacity={0.85}
              >
                <View style={[s.creatorAvatar, { backgroundColor: creator.avatarColor }]}>
                  <Text style={s.creatorAvatarText}>{creator.avatarInitials}</Text>
                </View>
                {creator.isVerified && (
                  <View style={[s.verifiedBadge, { backgroundColor: colors.primary }]}>
                    <Ionicons name="checkmark" size={9} color="#fff" />
                  </View>
                )}
                <Text style={[s.creatorName, { color: colors.foreground }]} numberOfLines={1}>{creator.name}</Text>
                <Text style={[s.creatorSpec, { color: colors.mutedForeground }]} numberOfLines={1}>{creator.specialty}</Text>
                <Text style={[s.creatorFollowers, { color: colors.primary }]}>{formatCount(creator.followers)} followers</Text>
              </TouchableOpacity>
            ))}
          </ScrollView>

          {/* Featured Courses */}
          <Text style={[s.sectionTitle, { color: colors.foreground }]}>Featured Courses</Text>
          {COURSES.slice(0, 3).map((course) => {
            const creator = CREATORS.find((c) => c.id === course.creatorId);
            return (
              <TouchableOpacity
                key={course.id}
                onPress={() => router.push(`/course/${course.id}` as any)}
                style={[s.featuredCard, { backgroundColor: colors.card, borderColor: colors.border }]}
                activeOpacity={0.85}
              >
                <LinearGradient colors={course.gradientColors} style={s.featuredThumb} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }}>
                  <Ionicons name="play-circle" size={28} color="rgba(255,255,255,0.85)" />
                  <View style={[s.levelBadge, { backgroundColor: 'rgba(0,0,0,0.4)' }]}>
                    <Text style={s.levelBadgeText}>{course.level}</Text>
                  </View>
                </LinearGradient>
                <View style={s.featuredInfo}>
                  <Text style={[s.featuredTitle, { color: colors.foreground }]} numberOfLines={2}>{course.title}</Text>
                  <Text style={[s.featuredCreator, { color: colors.mutedForeground }]}>{creator?.name}</Text>
                  <View style={s.featuredMeta}>
                    <View style={s.ratingRow}>
                      <Ionicons name="star" size={12} color="#F59E0B" />
                      <Text style={[s.ratingText, { color: colors.foreground }]}>{course.rating}</Text>
                      <Text style={[s.ratingCount, { color: colors.mutedForeground }]}>({formatCount(course.ratingCount)})</Text>
                    </View>
                    <Text style={[s.price, { color: colors.primary }]}>{formatPrice(course.price)}</Text>
                  </View>
                </View>
              </TouchableOpacity>
            );
          })}
        </ScrollView>
      ) : (
        /* ── SEARCH RESULTS MODE ── */
        <View style={{ flex: 1 }}>
          {/* Filters bar */}
          <View style={[s.filtersBar, { borderBottomColor: colors.border }]}>
            <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={s.filtersScroll}>
              <TouchableOpacity
                onPress={toggleFilters}
                style={[
                  s.filterToggleBtn,
                  { backgroundColor: activeFilters > 0 ? colors.primary : colors.card, borderColor: activeFilters > 0 ? colors.primary : colors.border },
                ]}
              >
                <Ionicons name="options-outline" size={14} color={activeFilters > 0 ? '#fff' : colors.foreground} />
                <Text style={[s.filterToggleText, { color: activeFilters > 0 ? '#fff' : colors.foreground }]}>
                  Filters{activeFilters > 0 ? ` (${activeFilters})` : ''}
                </Text>
              </TouchableOpacity>

              {SORT_OPTIONS.map((opt) => (
                <TouchableOpacity
                  key={opt.key}
                  onPress={() => { setSortBy(opt.key); Haptics.selectionAsync(); }}
                  style={[
                    s.filterChip,
                    { backgroundColor: sortBy === opt.key ? colors.primary + '22' : colors.card, borderColor: sortBy === opt.key ? colors.primary : colors.border },
                  ]}
                >
                  <Text style={[s.filterChipText, { color: sortBy === opt.key ? colors.primary : colors.foreground }]}>{opt.label}</Text>
                </TouchableOpacity>
              ))}
            </ScrollView>

            {/* Expandable advanced filters */}
            <Animated.View style={[s.advFilters, { height: filterHeight, borderTopColor: colors.border, overflow: 'hidden' }]}>
              <View style={s.advFiltersInner}>
                <Text style={[s.advFilterLabel, { color: colors.mutedForeground }]}>CATEGORY</Text>
                <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={s.advFilterRow}>
                  {CATEGORIES.map((cat) => (
                    <TouchableOpacity
                      key={cat.id}
                      onPress={() => setCatFilter(cat.id)}
                      style={[s.advChip, { backgroundColor: catFilter === cat.id ? colors.primary : colors.secondary, borderColor: catFilter === cat.id ? colors.primary : colors.border }]}
                    >
                      <Text style={[s.advChipText, { color: catFilter === cat.id ? '#fff' : colors.foreground }]}>{cat.name}</Text>
                    </TouchableOpacity>
                  ))}
                </ScrollView>
                <Text style={[s.advFilterLabel, { color: colors.mutedForeground, marginTop: 8 }]}>LEVEL</Text>
                <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={s.advFilterRow}>
                  {LEVEL_OPTIONS.map((l) => (
                    <TouchableOpacity
                      key={l}
                      onPress={() => setLevel(l)}
                      style={[s.advChip, { backgroundColor: level === l ? colors.primary : colors.secondary, borderColor: level === l ? colors.primary : colors.border }]}
                    >
                      <Text style={[s.advChipText, { color: level === l ? '#fff' : colors.foreground }]}>{l === 'all' ? 'All Levels' : l}</Text>
                    </TouchableOpacity>
                  ))}
                </ScrollView>
              </View>
            </Animated.View>
          </View>

          {/* Result tabs */}
          {query.trim().length > 0 && (
            <View style={[s.tabBar, { borderBottomColor: colors.border }]}>
              {(['all', 'courses', 'creators', 'videos'] as ResultTab[]).map((t) => (
                <TouchableOpacity
                  key={t}
                  onPress={() => setTab(t)}
                  style={[s.tabBtn, tab === t && { borderBottomColor: colors.primary, borderBottomWidth: 2.5 }]}
                >
                  <Text style={[s.tabText, { color: tab === t ? colors.primary : colors.mutedForeground }]}>
                    {t.charAt(0).toUpperCase() + t.slice(1)}
                  </Text>
                  {tabCounts[t] > 0 && (
                    <View style={[s.tabCount, { backgroundColor: tab === t ? colors.primary : colors.secondary }]}>
                      <Text style={[s.tabCountText, { color: tab === t ? '#fff' : colors.mutedForeground }]}>{tabCounts[t]}</Text>
                    </View>
                  )}
                </TouchableOpacity>
              ))}
            </View>
          )}

          <ScrollView
            contentContainerStyle={[s.scroll, { paddingBottom: Platform.OS === 'web' ? 100 : 80 }]}
            showsVerticalScrollIndicator={false}
            keyboardShouldPersistTaps="handled"
          >
            {/* History (before typing) */}
            {query.trim() === '' && history.length > 0 && (
              <>
                <View style={s.historyHeader}>
                  <Text style={[s.sectionTitle, { color: colors.foreground, marginBottom: 0 }]}>Recent</Text>
                  <TouchableOpacity onPress={clearHistory}>
                    <Text style={[s.clearText, { color: colors.mutedForeground }]}>Clear all</Text>
                  </TouchableOpacity>
                </View>
                {history.map((h) => (
                  <TouchableOpacity
                    key={h}
                    onPress={() => { setQuery(h); commitSearch(h); }}
                    style={[s.historyRow, { borderBottomColor: colors.border }]}
                  >
                    <Ionicons name="time-outline" size={16} color={colors.mutedForeground} />
                    <Text style={[s.historyText, { color: colors.foreground }]}>{h}</Text>
                    <Ionicons name="arrow-up-back-outline" size={14} color={colors.mutedForeground} style={{ transform: [{ rotate: '45deg' }] }} />
                  </TouchableOpacity>
                ))}

                <Text style={[s.sectionTitle, { color: colors.foreground, marginTop: 20 }]}>Trending Searches</Text>
                <View style={s.trendingGrid}>
                  {TRENDING.map((t) => (
                    <TouchableOpacity
                      key={t}
                      onPress={() => { setQuery(t); commitSearch(t); }}
                      style={[s.trendingChip, { backgroundColor: colors.card, borderColor: colors.border }]}
                    >
                      <Ionicons name="trending-up-outline" size={13} color={colors.primary} />
                      <Text style={[s.trendingText, { color: colors.foreground }]}>{t}</Text>
                    </TouchableOpacity>
                  ))}
                </View>
              </>
            )}

            {query.trim().length > 0 && totalResults === 0 && (
              <View style={s.emptyState}>
                <Ionicons name="search-outline" size={52} color={colors.mutedForeground} />
                <Text style={[s.emptyTitle, { color: colors.foreground }]}>No results for "{query}"</Text>
                <Text style={[s.emptyHint, { color: colors.mutedForeground }]}>Try a different keyword or browse by category</Text>
              </View>
            )}

            {/* Courses */}
            {(tab === 'all' || tab === 'courses') && sortedCourses.length > 0 && (
              <>
                {tab === 'all' && <Text style={[s.sectionTitle, { color: colors.foreground }]}>Courses ({sortedCourses.length})</Text>}
                {sortedCourses.map((course) => {
                  const creator = CREATORS.find((c) => c.id === course.creatorId);
                  return (
                    <TouchableOpacity
                      key={course.id}
                      onPress={() => router.push(`/course/${course.id}` as any)}
                      style={[s.resultCard, { backgroundColor: colors.card, borderColor: colors.border }]}
                      activeOpacity={0.85}
                    >
                      <LinearGradient colors={course.gradientColors} style={s.resultThumb} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }}>
                        <Ionicons name="book-outline" size={22} color="rgba(255,255,255,0.85)" />
                      </LinearGradient>
                      <View style={s.resultInfo}>
                        <View style={s.resultTagRow}>
                          <View style={[s.typeTag, { backgroundColor: colors.primary + '18' }]}>
                            <Text style={[s.typeTagText, { color: colors.primary }]}>Course</Text>
                          </View>
                          <View style={[s.typeTag, { backgroundColor: colors.secondary }]}>
                            <Text style={[s.typeTagText, { color: colors.mutedForeground }]}>{course.level}</Text>
                          </View>
                        </View>
                        <Text style={[s.resultTitle, { color: colors.foreground }]} numberOfLines={2}>
                          {highlight(course.title, query, colors.primary, colors.foreground)}
                        </Text>
                        <Text style={[s.resultSub, { color: colors.mutedForeground }]}>{creator?.name} · {course.totalDuration}</Text>
                        <View style={s.resultMeta}>
                          <View style={s.ratingRow}>
                            <Ionicons name="star" size={11} color="#F59E0B" />
                            <Text style={[s.ratingText, { color: colors.foreground }]}>{course.rating}</Text>
                            <Text style={[s.ratingCount, { color: colors.mutedForeground }]}>({formatCount(course.ratingCount)})</Text>
                          </View>
                          <Text style={[s.resultPrice, { color: colors.primary }]}>{formatPrice(course.price)}</Text>
                        </View>
                      </View>
                    </TouchableOpacity>
                  );
                })}
              </>
            )}

            {/* Creators */}
            {(tab === 'all' || tab === 'creators') && filteredCreators.length > 0 && (
              <>
                {tab === 'all' && <Text style={[s.sectionTitle, { color: colors.foreground }]}>Creators ({filteredCreators.length})</Text>}
                {filteredCreators.map((creator) => (
                  <TouchableOpacity
                    key={creator.id}
                    onPress={() => router.push(`/creator/${creator.id}` as any)}
                    style={[s.resultCard, { backgroundColor: colors.card, borderColor: colors.border }]}
                    activeOpacity={0.85}
                  >
                    <View style={[s.creatorThumb, { backgroundColor: creator.avatarColor }]}>
                      <Text style={s.creatorThumbText}>{creator.avatarInitials}</Text>
                      {creator.isVerified && (
                        <View style={[s.verifiedSmall, { backgroundColor: colors.primary }]}>
                          <Ionicons name="checkmark" size={8} color="#fff" />
                        </View>
                      )}
                    </View>
                    <View style={s.resultInfo}>
                      <View style={[s.typeTag, { backgroundColor: '#FF3CAC18', alignSelf: 'flex-start', marginBottom: 4 }]}>
                        <Text style={[s.typeTagText, { color: '#FF3CAC' }]}>Creator</Text>
                      </View>
                      <Text style={[s.resultTitle, { color: colors.foreground }]} numberOfLines={1}>
                        {highlight(creator.name, query, colors.primary, colors.foreground)}
                      </Text>
                      <Text style={[s.resultSub, { color: colors.mutedForeground }]}>
                        {highlight(creator.specialty, query, colors.primary, colors.mutedForeground)}
                      </Text>
                      <Text style={[s.creatorFollowerCount, { color: colors.primary }]}>
                        {formatCount(creator.followers)} followers · {creator.coursesCount} courses
                      </Text>
                    </View>
                  </TouchableOpacity>
                ))}
              </>
            )}

            {/* Videos */}
            {(tab === 'all' || tab === 'videos') && filteredVideos.length > 0 && (
              <>
                {tab === 'all' && <Text style={[s.sectionTitle, { color: colors.foreground }]}>Videos ({filteredVideos.length})</Text>}
                {filteredVideos.map((video) => {
                  const creator = CREATORS.find((c) => c.id === video.creatorId);
                  return (
                    <TouchableOpacity
                      key={video.id}
                      style={[s.resultCard, { backgroundColor: colors.card, borderColor: colors.border }]}
                      activeOpacity={0.85}
                    >
                      <LinearGradient colors={video.gradientColors as [string, string, string]} style={s.resultThumb} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }}>
                        <Ionicons name="play-circle-outline" size={22} color="rgba(255,255,255,0.85)" />
                        <View style={[s.durationBadge, { backgroundColor: 'rgba(0,0,0,0.5)' }]}>
                          <Text style={s.durationText}>{video.duration}</Text>
                        </View>
                      </LinearGradient>
                      <View style={s.resultInfo}>
                        <View style={[s.typeTag, { backgroundColor: '#7928CA18', alignSelf: 'flex-start', marginBottom: 4 }]}>
                          <Text style={[s.typeTagText, { color: '#7928CA' }]}>Short</Text>
                        </View>
                        <Text style={[s.resultTitle, { color: colors.foreground }]} numberOfLines={2}>
                          {highlight(video.title, query, colors.primary, colors.foreground)}
                        </Text>
                        <Text style={[s.resultSub, { color: colors.mutedForeground }]}>@{creator?.username}</Text>
                        <View style={s.ratingRow}>
                          <Ionicons name="heart-outline" size={11} color={colors.mutedForeground} />
                          <Text style={[s.ratingCount, { color: colors.mutedForeground }]}>{formatCount(video.likes)}</Text>
                          <Ionicons name="chatbubble-outline" size={11} color={colors.mutedForeground} style={{ marginLeft: 8 }} />
                          <Text style={[s.ratingCount, { color: colors.mutedForeground }]}>{formatCount(video.comments)}</Text>
                        </View>
                      </View>
                    </TouchableOpacity>
                  );
                })}
              </>
            )}
          </ScrollView>
        </View>
      )}
    </View>
  );
}

const s = StyleSheet.create({
  screen: { flex: 1 },
  topBar: {
    flexDirection: 'row', alignItems: 'center', gap: 10,
    paddingHorizontal: 16, paddingBottom: 12, borderBottomWidth: 1,
  },
  searchRow: {
    flex: 1, flexDirection: 'row', alignItems: 'center', gap: 10,
    borderWidth: 1.5, borderRadius: 14, paddingHorizontal: 13, paddingVertical: 11,
  },
  searchInput: { flex: 1, fontSize: 14, fontFamily: 'Poppins_400Regular' },
  cancelBtn: { paddingVertical: 4 },
  cancelText: { fontSize: 14, fontFamily: 'Poppins_600SemiBold' },

  scroll: { paddingHorizontal: 16, paddingTop: 16 },
  sectionTitle: { fontSize: 17, fontFamily: 'Poppins_700Bold', marginBottom: 14 },

  trendingGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: 8, marginBottom: 24 },
  trendingChip: {
    flexDirection: 'row', alignItems: 'center', gap: 5,
    paddingHorizontal: 12, paddingVertical: 8, borderRadius: 20, borderWidth: 1,
  },
  trendingText: { fontSize: 13, fontFamily: 'Poppins_500Medium' },

  catGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: 12, marginBottom: 28 },
  catItem: { width: '28%', alignItems: 'center', gap: 7 },
  catIcon: { width: 68, height: 68, borderRadius: 20, alignItems: 'center', justifyContent: 'center' },
  catLabel: { fontSize: 12, fontFamily: 'Poppins_500Medium', textAlign: 'center' },

  creatorsRow: { gap: 10, paddingRight: 4, paddingBottom: 4, marginBottom: 8 },
  creatorCard: {
    width: 118, padding: 13, borderRadius: 16, borderWidth: 1,
    alignItems: 'center', gap: 5,
  },
  creatorAvatar: { width: 52, height: 52, borderRadius: 26, alignItems: 'center', justifyContent: 'center' },
  creatorAvatarText: { color: '#fff', fontSize: 16, fontFamily: 'Poppins_700Bold' },
  verifiedBadge: {
    position: 'absolute', top: 24, right: 25,
    width: 16, height: 16, borderRadius: 8,
    alignItems: 'center', justifyContent: 'center', borderWidth: 1.5, borderColor: '#fff',
  },
  creatorName: { fontSize: 12, fontFamily: 'Poppins_700Bold', textAlign: 'center' },
  creatorSpec: { fontSize: 10, fontFamily: 'Poppins_400Regular', textAlign: 'center' },
  creatorFollowers: { fontSize: 11, fontFamily: 'Poppins_600SemiBold' },

  featuredCard: {
    flexDirection: 'row', gap: 12, borderRadius: 14, borderWidth: 1,
    overflow: 'hidden', marginBottom: 12,
  },
  featuredThumb: {
    width: 90, alignSelf: 'stretch', minHeight: 90,
    alignItems: 'center', justifyContent: 'center', gap: 6,
  },
  levelBadge: { paddingHorizontal: 5, paddingVertical: 2, borderRadius: 4 },
  levelBadgeText: { color: '#fff', fontSize: 9, fontFamily: 'Poppins_600SemiBold' },
  featuredInfo: { flex: 1, padding: 12, gap: 3 },
  featuredTitle: { fontSize: 14, fontFamily: 'Poppins_700Bold', lineHeight: 20 },
  featuredCreator: { fontSize: 12, fontFamily: 'Poppins_400Regular' },
  featuredMeta: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginTop: 4 },
  ratingRow: { flexDirection: 'row', alignItems: 'center', gap: 3 },
  ratingText: { fontSize: 12, fontFamily: 'Poppins_700Bold' },
  ratingCount: { fontSize: 11, fontFamily: 'Poppins_400Regular' },
  price: { fontSize: 13, fontFamily: 'Poppins_700Bold' },

  filtersBar: { borderBottomWidth: 1 },
  filtersScroll: { gap: 8, paddingHorizontal: 16, paddingVertical: 10 },
  filterToggleBtn: {
    flexDirection: 'row', alignItems: 'center', gap: 5,
    paddingHorizontal: 12, paddingVertical: 7, borderRadius: 20, borderWidth: 1,
  },
  filterToggleText: { fontSize: 12, fontFamily: 'Poppins_600SemiBold' },
  filterChip: {
    paddingHorizontal: 12, paddingVertical: 7, borderRadius: 20, borderWidth: 1,
  },
  filterChipText: { fontSize: 12, fontFamily: 'Poppins_500Medium' },
  advFilters: { borderTopWidth: 1 },
  advFiltersInner: { paddingHorizontal: 16, paddingVertical: 10, gap: 6 },
  advFilterLabel: { fontSize: 10, fontFamily: 'Poppins_700Bold', letterSpacing: 1 },
  advFilterRow: { gap: 8, paddingBottom: 2 },
  advChip: { paddingHorizontal: 12, paddingVertical: 6, borderRadius: 16, borderWidth: 1 },
  advChipText: { fontSize: 12, fontFamily: 'Poppins_500Medium' },

  tabBar: {
    flexDirection: 'row', borderBottomWidth: 1,
    paddingHorizontal: 16,
  },
  tabBtn: {
    flexDirection: 'row', alignItems: 'center', gap: 5,
    paddingVertical: 11, marginRight: 20, borderBottomWidth: 2.5, borderBottomColor: 'transparent',
  },
  tabText: { fontSize: 13, fontFamily: 'Poppins_600SemiBold' },
  tabCount: { paddingHorizontal: 6, paddingVertical: 2, borderRadius: 8 },
  tabCountText: { fontSize: 10, fontFamily: 'Poppins_700Bold' },

  historyHeader: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 },
  clearText: { fontSize: 13, fontFamily: 'Poppins_500Medium' },
  historyRow: {
    flexDirection: 'row', alignItems: 'center', gap: 12,
    paddingVertical: 13, borderBottomWidth: 1,
  },
  historyText: { flex: 1, fontSize: 14, fontFamily: 'Poppins_400Regular' },

  emptyState: { alignItems: 'center', paddingVertical: 56, gap: 10 },
  emptyTitle: { fontSize: 17, fontFamily: 'Poppins_700Bold', textAlign: 'center' },
  emptyHint: { fontSize: 13, fontFamily: 'Poppins_400Regular', textAlign: 'center' },

  resultCard: {
    flexDirection: 'row', gap: 12, borderRadius: 14, borderWidth: 1,
    overflow: 'hidden', marginBottom: 10,
  },
  resultThumb: {
    width: 80, minHeight: 80, alignSelf: 'stretch',
    alignItems: 'center', justifyContent: 'center',
  },
  creatorThumb: {
    width: 80, alignSelf: 'stretch',
    alignItems: 'center', justifyContent: 'center',
  },
  creatorThumbText: { color: '#fff', fontSize: 22, fontFamily: 'Poppins_700Bold' },
  verifiedSmall: {
    position: 'absolute', bottom: 8, right: 8,
    width: 16, height: 16, borderRadius: 8,
    alignItems: 'center', justifyContent: 'center',
  },
  resultInfo: { flex: 1, paddingVertical: 11, paddingRight: 12, gap: 3 },
  resultTagRow: { flexDirection: 'row', gap: 6, marginBottom: 2 },
  typeTag: { paddingHorizontal: 7, paddingVertical: 2, borderRadius: 5 },
  typeTagText: { fontSize: 10, fontFamily: 'Poppins_600SemiBold' },
  resultTitle: { fontSize: 14, fontFamily: 'Poppins_600SemiBold', lineHeight: 20 },
  resultSub: { fontSize: 12, fontFamily: 'Poppins_400Regular' },
  resultMeta: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginTop: 3 },
  resultPrice: { fontSize: 13, fontFamily: 'Poppins_700Bold' },
  creatorFollowerCount: { fontSize: 11, fontFamily: 'Poppins_600SemiBold', marginTop: 2 },
  durationBadge: { position: 'absolute', bottom: 6, right: 6, paddingHorizontal: 5, paddingVertical: 2, borderRadius: 4 },
  durationText: { color: '#fff', fontSize: 9, fontFamily: 'Poppins_600SemiBold' },
});
