import { useMutation, useQuery } from '@apollo/client/react';
import { gql } from '@apollo/client';
import { DISCOVER_PROFILES_QUERY } from '../api/operations/queries';
import { DEVICE_LOCATION_UPDATE_MUTATION } from '../api/operations/mutations';
import { ProfileCard } from '../components/profile/ProfileCard';
import { ProfileDetailModal } from '../components/profile/ProfileDetailModal';
import { LoadingPage, LoadingCards } from '../components/ui/Loading';
import { useState, useEffect, useRef, useCallback } from 'react';
import { useLocation } from '../hooks/useLocation';
import { useFavorites } from '../hooks/useFavorites';
import { apolloClient } from '../api/client';
import { authManager } from '../api/auth';

// Separate query for load more to avoid cache conflicts
const LOAD_MORE_PROFILES_QUERY = gql`
  query LoadMoreProfiles($input: ProfileDiscoveryInput!) {
    discovery(input: $input) {
      nodes {
        id
        age
        imaginaryName
        gender
        sexuality
        isIncognito
        isMajestic
        verificationStatus
        connectionGoals
        desires
        bio
        interests
        distance { km mi __typename }
        photos {
          id
          pictureUrls { small medium large __typename }
          pictureType
          __typename
        }
        interactionStatus { message mine theirs __typename }
        __typename
      }
      hasNextBatch
      __typename
    }
  }
`;

const styles = {
  container: {
    paddingBottom: '48px',
  },

  // Header
  header: {
    marginBottom: '32px',
  },
  title: {
    fontFamily: "'Clash Display', sans-serif",
    fontSize: '36px',
    fontWeight: 700,
    color: '#ffffff',
    margin: 0,
    marginBottom: '8px',
    letterSpacing: '-0.02em',
  },
  subtitle: {
    fontFamily: "'Satoshi', sans-serif",
    fontSize: '15px',
    color: 'rgba(255,255,255,0.5)',
    margin: 0,
  },

  // Filter section
  filterContainer: {
    display: 'flex',
    gap: '12px',
    marginBottom: '32px',
    overflowX: 'auto' as const,
    paddingBottom: '8px',
  },
  filterButton: (isActive: boolean, variant: 'all' | 'liked' | 'passed' | 'online') => {
    const gradients = {
      all: 'linear-gradient(135deg, #be3144 0%, #c41e3a 100%)',
      liked: 'linear-gradient(135deg, #22c55e 0%, #16a34a 100%)',
      passed: 'linear-gradient(135deg, #64748b 0%, #475569 100%)',
      online: 'linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%)',
    };
    return {
      display: 'flex',
      alignItems: 'center',
      gap: '10px',
      padding: '14px 24px',
      borderRadius: '50px',
      fontSize: '14px',
      fontWeight: 600,
      fontFamily: "'Satoshi', sans-serif",
      whiteSpace: 'nowrap' as const,
      border: isActive ? 'none' : '1px solid rgba(255,255,255,0.08)',
      background: isActive ? gradients[variant] : 'rgba(255,255,255,0.03)',
      color: isActive ? '#ffffff' : 'rgba(255,255,255,0.7)',
      cursor: 'pointer',
      transition: 'all 0.2s ease',
      boxShadow: isActive ? '0 4px 20px rgba(0,0,0,0.3)' : 'none',
    };
  },
  filterBadge: (isActive: boolean, variant: 'all' | 'liked' | 'passed') => {
    const colors = {
      all: { bg: 'rgba(190,49,68,0.25)', color: '#f4a5b0' },
      liked: { bg: 'rgba(34,197,94,0.25)', color: '#86efac' },
      passed: { bg: 'rgba(100,116,139,0.25)', color: '#cbd5e1' },
    };
    return {
      padding: '4px 10px',
      borderRadius: '20px',
      fontSize: '12px',
      fontWeight: 700,
      fontFamily: "'Satoshi', sans-serif",
      background: isActive ? 'rgba(255,255,255,0.2)' : colors[variant].bg,
      color: isActive ? '#ffffff' : colors[variant].color,
    };
  },

  // Profile grid
  profileGrid: {
    display: 'grid',
    gridTemplateColumns: 'repeat(2, 1fr)',
    gap: '16px',
  },
  profileGridMd: {
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))',
    gap: '16px',
  },

  // Empty states
  emptyState: {
    display: 'flex',
    flexDirection: 'column' as const,
    alignItems: 'center',
    justifyContent: 'center',
    padding: '80px 20px',
  },
  emptyIcon: (variant: 'error' | 'empty' | 'liked' | 'passed') => {
    const colors = {
      error: { bg: 'rgba(239,68,68,0.1)', color: '#ef4444' },
      empty: { bg: 'linear-gradient(135deg, rgba(190,49,68,0.15) 0%, rgba(190,49,68,0.05) 100%)', color: '#be3144' },
      liked: { bg: 'rgba(34,197,94,0.1)', color: '#22c55e' },
      passed: { bg: 'rgba(100,116,139,0.1)', color: '#64748b' },
    };
    return {
      width: '80px',
      height: '80px',
      borderRadius: '50%',
      background: colors[variant].bg,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      marginBottom: '24px',
    };
  },
  emptyTitle: {
    fontFamily: "'Clash Display', sans-serif",
    fontSize: '22px',
    fontWeight: 600,
    color: '#ffffff',
    marginBottom: '8px',
    textAlign: 'center' as const,
  },
  emptyText: {
    fontFamily: "'Satoshi', sans-serif",
    fontSize: '15px',
    color: 'rgba(255,255,255,0.5)',
    textAlign: 'center' as const,
    maxWidth: '280px',
  },

  // Load more button
  loadMoreContainer: {
    display: 'flex',
    justifyContent: 'center',
    marginTop: '48px',
  },
  loadMoreButton: {
    display: 'flex',
    alignItems: 'center',
    gap: '10px',
    padding: '16px 32px',
    borderRadius: '50px',
    fontSize: '15px',
    fontWeight: 600,
    fontFamily: "'Satoshi', sans-serif",
    background: 'rgba(255,255,255,0.05)',
    border: '1px solid rgba(255,255,255,0.1)',
    color: '#ffffff',
    cursor: 'pointer',
    transition: 'all 0.2s ease',
  },

  // Match modal
  matchOverlay: {
    position: 'fixed' as const,
    inset: 0,
    background: 'rgba(0,0,0,0.92)',
    backdropFilter: 'blur(20px)',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    zIndex: 60,
  },
  matchContent: {
    textAlign: 'center' as const,
    padding: '40px',
  },
  matchIconContainer: {
    position: 'relative' as const,
    marginBottom: '32px',
  },
  matchIcon: {
    width: '100px',
    height: '100px',
    margin: '0 auto',
    borderRadius: '50%',
    background: 'linear-gradient(135deg, #be3144 0%, #c41e3a 100%)',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    boxShadow: '0 0 60px rgba(190,49,68,0.5), 0 0 100px rgba(190,49,68,0.3)',
  },
  matchSparkle: (position: { top?: string; bottom?: string; left?: string; right?: string }) => ({
    position: 'absolute' as const,
    width: '16px',
    height: '16px',
    color: '#fbbf24',
    ...position,
  }),
  matchTitle: {
    fontFamily: "'Clash Display', sans-serif",
    fontSize: '42px',
    fontWeight: 700,
    color: '#ffffff',
    margin: 0,
    marginBottom: '12px',
    letterSpacing: '-0.02em',
  },
  matchSubtitle: {
    fontFamily: "'Satoshi', sans-serif",
    fontSize: '18px',
    color: 'rgba(255,255,255,0.6)',
    margin: 0,
    marginBottom: '40px',
  },
  matchButtons: {
    display: 'flex',
    gap: '16px',
    justifyContent: 'center',
  },
  matchButton: (isPrimary: boolean) => ({
    padding: '16px 32px',
    borderRadius: '50px',
    fontSize: '15px',
    fontWeight: 600,
    fontFamily: "'Satoshi', sans-serif",
    border: isPrimary ? 'none' : '1px solid rgba(255,255,255,0.2)',
    background: isPrimary ? 'linear-gradient(135deg, #be3144 0%, #c41e3a 100%)' : 'rgba(255,255,255,0.05)',
    color: '#ffffff',
    cursor: 'pointer',
    transition: 'all 0.2s ease',
  }),

  // Loading grid
  loadingGrid: {
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))',
    gap: '16px',
    marginTop: '16px',
  },
};

type FilterType = 'all' | 'liked' | 'disliked';

export function DiscoverPage() {
  const [selectedProfileId, setSelectedProfileId] = useState<string | null>(null);
  const [matchAlert, setMatchAlert] = useState(false);
  const [allProfiles, setAllProfiles] = useState<any[]>([]);
  const [loadingMore, setLoadingMore] = useState(false);
  const [hasMore, setHasMore] = useState<boolean | null>(null);
  const [filter, setFilter] = useState<FilterType>(() => {
    return (localStorage.getItem('feeld_discover_filter') as FilterType) || 'all';
  });
  const [recentlyOnlineOnly, setRecentlyOnlineOnly] = useState(() => {
    return localStorage.getItem('feeld_discover_recently_online') === 'true';
  });
  const initialLoadDone = useRef(false);
  const savedLikedMeProfiles = useRef<Set<string>>(new Set());
  const { location } = useLocation();
  const { isFavorite, toggleFavorite } = useFavorites();

  // Set device location on Feeld when Discover page loads (emulates app open GPS)
  const [updateDeviceLocation] = useMutation(DEVICE_LOCATION_UPDATE_MUTATION);
  const locationSetRef = useRef(false);
  useEffect(() => {
    if (location && !locationSetRef.current) {
      locationSetRef.current = true;
      updateDeviceLocation({
        variables: { input: { latitude: location.latitude, longitude: location.longitude } },
      }).then(() => {
        console.log(`[Discover] Location set to ${location.name || `${location.latitude},${location.longitude}`}`);
      }).catch((err) => {
        console.error('[Discover] Failed to set location:', err);
      });
    }
  }, [location, updateDeviceLocation]);

  // Fetch rotation location (what the cron actually set on Feeld)
  const [rotationLocation, setRotationLocation] = useState<string | null>(null);
  useEffect(() => {
    fetch('/api/location-rotation/status')
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        if (data?.enabled && data?.lastResult?.status === 'success') {
          setRotationLocation(data.lastResult.location);
        }
      })
      .catch(() => {});
  }, []);

  // Save all discovered profiles to backend cache for Likes page enrichment
  const saveDiscoveredProfiles = useCallback(async (profiles: any[], discoveredLocation?: string) => {
    if (!profiles.length) return;

    const safeStr = (v: any) => (typeof v === 'string' ? v : '');

    // Strip photos (signed URLs expire quickly) and sanitize __typename fields
    const stripped = profiles.map(p => ({
      id: p.id,
      imaginaryName: p.imaginaryName,
      age: p.age,
      gender: safeStr(p.gender),
      sexuality: safeStr(p.sexuality),
      bio: p.bio,
      desires: p.desires,
      connectionGoals: p.connectionGoals,
      verificationStatus: p.verificationStatus,
      interactionStatus: p.interactionStatus,
      discoveredLocation: discoveredLocation ?? null,
      discoveredAt: new Date().toISOString(),
    }));

    try {
      const response = await fetch('/api/discovered-profiles/batch', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ profiles: stripped }),
      });
      if (response.ok) {
        const result = await response.json();
        console.log(`Saved ${result.added} new, ${result.updated} updated discovered profiles (${result.total} total)`);
      }
    } catch (err) {
      console.error('Failed to save discovered profiles:', err);
    }
  }, []);

  // Save profiles that liked me to the backend for matching on Likes page
  const saveWhoLikedMeProfile = useCallback(async (profile: any) => {
    if (savedLikedMeProfiles.current.has(profile.id)) {
      return; // Already saved this profile
    }

    try {
      const response = await fetch('/api/who-liked-you', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ profile }),
      });

      if (response.ok) {
        savedLikedMeProfiles.current.add(profile.id);
        console.log('Saved who-liked-me profile from Discover:', profile.imaginaryName, profile.id);
      }
    } catch (err) {
      console.error('Failed to save who-liked-me profile:', err);
    }
  }, []);

  const [locationKey, setLocationKey] = useState(0);

  const { data, loading, error, refetch } = useQuery(DISCOVER_PROFILES_QUERY, {
    variables: {
      input: {
        filters: {
          ageRange: [22, 59],
          maxDistance: 100,
          lookingFor: ['WOMAN', 'MAN_WOMAN_COUPLE', 'WOMAN_WOMAN_COUPLE'],
          recentlyOnline: recentlyOnlineOnly,
          desiringFor: [],
        },
      },
    },
    fetchPolicy: 'network-only', // Always fetch fresh data
  });

  // Persist filter changes to localStorage
  useEffect(() => {
    localStorage.setItem('feeld_discover_filter', filter);
  }, [filter]);
  useEffect(() => {
    localStorage.setItem('feeld_discover_recently_online', String(recentlyOnlineOnly));
  }, [recentlyOnlineOnly]);

  // Refetch when recentlyOnlineOnly changes
  useEffect(() => {
    if (initialLoadDone.current) {
      console.log('Recently online filter changed:', recentlyOnlineOnly);
      setAllProfiles([]);
      initialLoadDone.current = false;
      refetch();
    }
  }, [recentlyOnlineOnly]);

  // Refetch when location changes (location is set via DeviceLocationUpdate mutation)
  useEffect(() => {
    if (location && initialLoadDone.current) {
      console.log('Location changed, refetching discover profiles...', location);
      setAllProfiles([]);
      initialLoadDone.current = false;
      setLocationKey(k => k + 1);
      refetch();
    }
  }, [location?.latitude, location?.longitude]);

  // Initialize profiles only on first successful load
  useEffect(() => {
    if (!initialLoadDone.current && data?.discovery?.nodes) {
      setAllProfiles(data.discovery.nodes);
      setHasMore(data.discovery.hasNextBatch ?? false);
      initialLoadDone.current = true;
      // Cache all discovered profiles for Likes page enrichment
      saveDiscoveredProfiles(data.discovery.nodes, location?.name || rotationLocation || undefined);
    }
  }, [data, location?.name, rotationLocation]);

  // Save profiles that liked me to the backend for matching on Likes page
  useEffect(() => {
    const profilesToCheck = allProfiles.length > 0 ? allProfiles : (data?.discovery?.nodes || []);
    const likedMeProfiles = profilesToCheck.filter(
      (p: any) => p.interactionStatus?.theirs === 'LIKED'
    );

    likedMeProfiles.forEach((profile: any) => {
      saveWhoLikedMeProfile(profile);
    });
  }, [allProfiles, data?.discovery?.nodes, saveWhoLikedMeProfile]);

  const handleLoadMore = async () => {
    if (loadingMore) return; // Prevent double-click
    const currentProfiles = allProfiles.length > 0 ? allProfiles : (data?.discovery?.nodes || []);
    const alreadyShownProfileIDs = currentProfiles.map((p: any) => p.id);

    setLoadingMore(true);
    try {
      const result = await apolloClient.query({
        query: LOAD_MORE_PROFILES_QUERY,
        variables: {
          input: {
            filters: {
              ageRange: [22, 59],
              maxDistance: 100,
              lookingFor: ['WOMAN', 'MAN_WOMAN_COUPLE', 'WOMAN_WOMAN_COUPLE'],
              recentlyOnline: recentlyOnlineOnly,
              desiringFor: [],
              alreadyShownProfileIDs,
            },
          },
        },
        fetchPolicy: 'no-cache',
      });

      const newProfiles = result.data?.discovery?.nodes || [];
      setAllProfiles(prev => [...prev, ...newProfiles]);
      setHasMore(result.data?.discovery?.hasNextBatch ?? false);
      // Cache all discovered profiles for Likes page enrichment
      saveDiscoveredProfiles(newProfiles, location?.name || rotationLocation || undefined);
    } catch (err) {
      console.error('Failed to load more profiles:', err);
    } finally {
      setLoadingMore(false);
    }
  };

  if (loading) return <LoadingPage message="Finding connections..." />;

  if (error) {
    // Auto-retry on auth errors: force refresh token and refetch
    const isAuthError = error.message?.includes('Unauthorized') || error.message?.includes('UNAUTHENTICATED');
    return (
      <div style={styles.emptyState}>
        <div style={styles.emptyIcon('error')}>
          <svg viewBox="0 0 24 24" fill="none" stroke="#ef4444" strokeWidth="1.5" style={{ width: '36px', height: '36px' }}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z" />
          </svg>
        </div>
        <h2 style={styles.emptyTitle}>Connection Error</h2>
        <p style={styles.emptyText}>{error.message}</p>
        <button
          onClick={async () => {
            try { await authManager.forceRefresh(); } catch {}
            window.location.reload();
          }}
          style={{
            marginTop: '16px',
            padding: '14px 32px',
            background: 'var(--gradient-desire, linear-gradient(135deg, #7c3aed, #a855f7))',
            border: 'none',
            borderRadius: '12px',
            color: '#fff',
            fontSize: '15px',
            fontWeight: 600,
            fontFamily: "'Satoshi', sans-serif",
            cursor: 'pointer',
          }}
        >
          {isAuthError ? 'Reconnect' : 'Retry'}
        </button>
        {isAuthError && (
          <button
            onClick={async () => { try { await authManager.forceRefresh(); } catch {} window.location.reload(); }}
            style={{
              marginTop: '8px',
              padding: '10px 24px',
              background: 'transparent',
              border: '1px solid rgba(255,255,255,0.15)',
              borderRadius: '12px',
              color: 'rgba(255,255,255,0.5)',
              fontSize: '13px',
              fontWeight: 500,
              fontFamily: "'Satoshi', sans-serif",
              cursor: 'pointer',
            }}
          >
            Reset Credentials
          </button>
        )}
      </div>
    );
  }

  const rawProfiles = allProfiles.length > 0 ? allProfiles : (data?.discovery?.nodes || []);
  const hasNextBatch = hasMore ?? (data?.discovery?.hasNextBatch ?? false);

  // Filter profiles based on selection
  const profiles = rawProfiles.filter((profile: any) => {
    if (filter === 'all') return true;
    const theirs = profile.interactionStatus?.theirs;
    if (filter === 'liked') return theirs === 'LIKED';
    if (filter === 'disliked') return theirs === 'DISLIKED';
    return true;
  });

  // Count for filter badges
  const likedCount = rawProfiles.filter((p: any) => p.interactionStatus?.theirs === 'LIKED').length;
  const dislikedCount = rawProfiles.filter((p: any) => p.interactionStatus?.theirs === 'DISLIKED').length;

  if (rawProfiles.length === 0) {
    return (
      <div style={styles.emptyState}>
        <div style={styles.emptyIcon('empty')}>
          <svg viewBox="0 0 24 24" fill="none" stroke="#be3144" strokeWidth="1" style={{ width: '40px', height: '40px' }}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
          </svg>
        </div>
        <h2 style={styles.emptyTitle}>No Profiles Yet</h2>
        <p style={styles.emptyText}>Check back soon for new connections</p>
      </div>
    );
  }

  return (
    <div style={styles.container}>
      {/* Header */}
      <div style={styles.header}>
        <h1 style={styles.title}>Discover</h1>
        <p style={styles.subtitle}>
          {rawProfiles.length} {rawProfiles.length === 1 ? 'profile' : 'profiles'} waiting
          {(rotationLocation || location) && (
            <span style={{ marginLeft: '12px', color: 'rgba(255,255,255,0.4)' }}>
              • 📍 {rotationLocation || location?.name || `${location?.latitude.toFixed(2)}, ${location?.longitude.toFixed(2)}`}
              {rotationLocation && <span style={{ marginLeft: '6px', fontSize: '11px', color: 'rgba(245,158,11,0.6)' }}>(auto)</span>}
            </span>
          )}
        </p>
      </div>

      {/* Filter Buttons */}
      <div style={styles.filterContainer}>
        <button
          onClick={() => setFilter('all')}
          style={styles.filterButton(filter === 'all', 'all')}
        >
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ width: '16px', height: '16px' }}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6A2.25 2.25 0 016 3.75h2.25A2.25 2.25 0 0110.5 6v2.25a2.25 2.25 0 01-2.25 2.25H6a2.25 2.25 0 01-2.25-2.25V6zM3.75 15.75A2.25 2.25 0 016 13.5h2.25a2.25 2.25 0 012.25 2.25V18a2.25 2.25 0 01-2.25 2.25H6A2.25 2.25 0 013.75 18v-2.25zM13.5 6a2.25 2.25 0 012.25-2.25H18A2.25 2.25 0 0120.25 6v2.25A2.25 2.25 0 0118 10.5h-2.25a2.25 2.25 0 01-2.25-2.25V6zM13.5 15.75a2.25 2.25 0 012.25-2.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-2.25A2.25 2.25 0 0113.5 18v-2.25z" />
          </svg>
          All
          <span style={styles.filterBadge(filter === 'all', 'all')}>
            {rawProfiles.length}
          </span>
        </button>

        <button
          onClick={() => setFilter('liked')}
          style={styles.filterButton(filter === 'liked', 'liked')}
        >
          <svg viewBox="0 0 24 24" fill="currentColor" style={{ width: '16px', height: '16px' }}>
            <path d="M11.645 20.91l-.007-.003-.022-.012a15.247 15.247 0 01-.383-.218 25.18 25.18 0 01-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0112 5.052 5.5 5.5 0 0116.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 01-4.244 3.17 15.247 15.247 0 01-.383.219l-.022.012-.007.004-.003.001a.752.752 0 01-.704 0l-.003-.001z" />
          </svg>
          Likes You
          {likedCount > 0 && (
            <span style={styles.filterBadge(filter === 'liked', 'liked')}>
              {likedCount}
            </span>
          )}
        </button>

        <button
          onClick={() => setFilter('disliked')}
          style={styles.filterButton(filter === 'disliked', 'passed')}
        >
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ width: '16px', height: '16px' }}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
          </svg>
          Passed
          {dislikedCount > 0 && (
            <span style={styles.filterBadge(filter === 'disliked', 'passed')}>
              {dislikedCount}
            </span>
          )}
        </button>

        {/* Spacer */}
        <div style={{ flex: 1 }} />

        {/* Recently Online Toggle */}
        <button
          onClick={() => setRecentlyOnlineOnly(!recentlyOnlineOnly)}
          style={styles.filterButton(recentlyOnlineOnly, 'online')}
        >
          <svg viewBox="0 0 24 24" fill={recentlyOnlineOnly ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="2" style={{ width: '16px', height: '16px' }}>
            <circle cx="12" cy="12" r="3" />
            <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707" />
          </svg>
          Recently Online
        </button>
      </div>

      {/* Empty filter state */}
      {profiles.length === 0 ? (
        <div style={styles.emptyState}>
          <div style={styles.emptyIcon(filter === 'liked' ? 'liked' : 'passed')}>
            {filter === 'liked' ? (
              <svg viewBox="0 0 24 24" fill="#22c55e" style={{ width: '36px', height: '36px' }}>
                <path d="M11.645 20.91l-.007-.003-.022-.012a15.247 15.247 0 01-.383-.218 25.18 25.18 0 01-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0112 5.052 5.5 5.5 0 0116.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 01-4.244 3.17 15.247 15.247 0 01-.383.219l-.022.012-.007.004-.003.001a.752.752 0 01-.704 0l-.003-.001z" />
              </svg>
            ) : (
              <svg viewBox="0 0 24 24" fill="none" stroke="#64748b" strokeWidth="1.5" style={{ width: '36px', height: '36px' }}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
              </svg>
            )}
          </div>
          <h3 style={styles.emptyTitle}>
            {filter === 'liked' ? 'No likes yet' : 'No passes yet'}
          </h3>
          <p style={styles.emptyText}>
            {filter === 'liked'
              ? 'People who like you will appear here'
              : "Profiles you've passed on will appear here"
            }
          </p>
        </div>
      ) : (
        <>
          {/* Profile Grid */}
          <div style={styles.profileGridMd}>
            {profiles.map((profile: any, index: number) => (
              <ProfileCard
                key={profile.id}
                profile={profile}
                onClick={() => setSelectedProfileId(profile.id)}
                index={index}
                onToggleFavorite={toggleFavorite}
                isFavorited={isFavorite(profile.id)}
              />
            ))}
          </div>

          {/* Loading more */}
          {loadingMore && (
            <div style={styles.loadingGrid}>
              <LoadingCards count={4} />
            </div>
          )}
        </>
      )}

      {/* Load More Button */}
      {hasNextBatch && profiles.length > 0 && !loadingMore && (
        <div style={styles.loadMoreContainer}>
          <button
            onClick={handleLoadMore}
            style={styles.loadMoreButton}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = 'rgba(255,255,255,0.08)';
              e.currentTarget.style.borderColor = 'rgba(255,255,255,0.15)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = 'rgba(255,255,255,0.05)';
              e.currentTarget.style.borderColor = 'rgba(255,255,255,0.1)';
            }}
          >
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ width: '18px', height: '18px' }}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 13.5L12 21m0 0l-7.5-7.5M12 21V3" />
            </svg>
            Load More Profiles
          </button>
        </div>
      )}

      {/* Profile Detail Modal */}
      {selectedProfileId && (
        <ProfileDetailModal
          profileId={selectedProfileId}
          onClose={() => setSelectedProfileId(null)}
          onMatch={() => setMatchAlert(true)}
        />
      )}

      {/* Match Alert */}
      {matchAlert && (
        <div
          style={styles.matchOverlay}
          onClick={() => setMatchAlert(false)}
        >
          <div style={styles.matchContent} onClick={(e) => e.stopPropagation()}>
            {/* Celebration animation */}
            <div style={styles.matchIconContainer}>
              <div style={styles.matchIcon}>
                <svg viewBox="0 0 24 24" fill="#ffffff" style={{ width: '48px', height: '48px' }}>
                  <path d="M11.645 20.91l-.007-.003-.022-.012a15.247 15.247 0 01-.383-.218 25.18 25.18 0 01-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0112 5.052 5.5 5.5 0 0116.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 01-4.244 3.17 15.247 15.247 0 01-.383.219l-.022.012-.007.004-.003.001a.752.752 0 01-.704 0l-.003-.001z" />
                </svg>
              </div>
              {/* Sparkles */}
              <div style={styles.matchSparkle({ top: '-8px', left: '-8px' })}>
                <svg viewBox="0 0 24 24" fill="currentColor">
                  <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
                </svg>
              </div>
              <div style={styles.matchSparkle({ top: '-4px', right: '-12px' })}>
                <svg viewBox="0 0 24 24" fill="currentColor" style={{ width: '12px', height: '12px' }}>
                  <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
                </svg>
              </div>
              <div style={styles.matchSparkle({ bottom: '0px', right: '-4px' })}>
                <svg viewBox="0 0 24 24" fill="currentColor" style={{ width: '10px', height: '10px' }}>
                  <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
                </svg>
              </div>
            </div>

            <h2 style={styles.matchTitle}>It's a Match!</h2>
            <p style={styles.matchSubtitle}>You can now message each other</p>

            <div style={styles.matchButtons}>
              <button
                onClick={() => setMatchAlert(false)}
                style={styles.matchButton(false)}
                onMouseEnter={(e) => {
                  e.currentTarget.style.background = 'rgba(255,255,255,0.1)';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.background = 'rgba(255,255,255,0.05)';
                }}
              >
                Keep Browsing
              </button>
              <button
                onClick={() => setMatchAlert(false)}
                style={styles.matchButton(true)}
                onMouseEnter={(e) => {
                  e.currentTarget.style.transform = 'scale(1.02)';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.transform = 'scale(1)';
                }}
              >
                Send Message
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
