'use client';

import { useState, useEffect, useCallback, Suspense } from 'react';
import { useSearchParams } from 'next/navigation';
import Image from 'next/image';
import Link from 'next/link';
import { FilterModal, FilterState, FilterField } from '@/components/profiles/FilterModal';
import { agentsService, AgentType, PublicAgentProfile, SearchAgentsParams } from '@/services/agents.service';
import { profileSectionsService, FilterableField } from '@/services/profile-sections.service';
import { uploadService } from '@/services/upload.service';
import { MobileBackButton } from '@/components/layout/MobileBackButton';

interface FilterSectionProps {
  title: string;
  options: { label: string; value: string }[];
  selectedOptions: string[];
  onToggle: (optionValue: string) => void;
  showMore?: boolean;
}

function FilterSection({ title, options, selectedOptions, onToggle, showMore }: FilterSectionProps) {
  const [expanded, setExpanded] = useState(false);
  const displayOptions = expanded ? options : options.slice(0, 6);

  return (
    <div className="pb-4 mb-4">
      <div className="mb-3">
        <h3 className="font-fractul font-semibold text-[14px] text-[#00293d]">{title}</h3>
      </div>
      <div className="space-y-2">
        {displayOptions.map((option) => (
          <label key={option.value} className="flex items-center gap-2 cursor-pointer">
            <input
              type="checkbox"
              checked={selectedOptions.includes(option.value)}
              onChange={() => onToggle(option.value)}
              className="w-4 h-4 rounded border-2 border-[#00293d]/30 appearance-none cursor-pointer checked:bg-[#e58625] checked:border-[#e58625] checked:bg-[url('data:image/svg+xml,%3Csvg%20viewBox%3D%220%200%2016%2016%22%20fill%3D%22white%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M12.207%204.793a1%201%200%20010%201.414l-5%205a1%201%200%2001-1.414%200l-2-2a1%201%200%20011.414-1.414L6.5%209.086l4.293-4.293a1%201%200%20011.414%200z%22%2F%3E%3C%2Fsvg%3E')] checked:bg-center checked:bg-no-repeat focus:ring-2 focus:ring-[#e58625]/50"
            />
            <span className="font-serif text-[13px] text-[#00293d]">{option.label}</span>
          </label>
        ))}
      </div>
      {showMore && options.length > 6 && (
        <button
          onClick={() => setExpanded(!expanded)}
          className="mt-2 font-serif text-[13px] text-[#e58625] hover:underline"
        >
          {expanded ? 'Show Less' : 'Show More'}
        </button>
      )}
    </div>
  );
}

interface ProfileCardProps {
  profile: PublicAgentProfile;
  resolvedAvatarUrl?: string | null;
}

// Profile image with shimmer loading
function ProfileImage({ src, alt, className }: { src: string | null; alt: string; className?: string }) {
  const [status, setStatus] = useState<'loading' | 'loaded' | 'error'>(src ? 'loading' : 'error');

  useEffect(() => {
    setStatus(src ? 'loading' : 'error');
  }, [src]);

  return (
    <div className={`relative overflow-hidden bg-[#e8e8e8] ${className || ''}`}>
      {status === 'loading' && (
        <div className="absolute inset-0 shimmer-loading" />
      )}
      {src && status !== 'error' ? (
        /* eslint-disable-next-line @next/next/no-img-element */
        <img
          ref={(el) => { if (el?.complete) setStatus(el.naturalWidth > 0 ? 'loaded' : 'error'); }}
          src={src}
          alt={alt}
          className={`w-full h-full object-cover object-top transition-opacity duration-300 ${status === 'loaded' ? 'opacity-100' : 'opacity-0'}`}
          onLoad={() => setStatus('loaded')}
          onError={() => setStatus('error')}
        />
      ) : status === 'error' ? (
        <div className="w-full h-full flex items-center justify-center">
          <Image
            src="/assets/icons/user-placeholder-icon.svg"
            alt={alt}
            width={64}
            height={64}
            className="opacity-40"
          />
        </div>
      ) : null}
    </div>
  );
}

function ProfileCard({ profile, resolvedAvatarUrl }: ProfileCardProps) {
  const [showFullBio, setShowFullBio] = useState(false);
  const [showAllTags, setShowAllTags] = useState(false);
  const getProfileImageUrl = (): string | null => {
    if (resolvedAvatarUrl) return resolvedAvatarUrl;
    if (profile.avatar?.startsWith('/')) return profile.avatar;
    return null;
  };

  // Format member since date
  const formatMemberSince = (dateString?: string) => {
    if (!dateString) return 'Member';
    try {
      const date = new Date(dateString);
      return date.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
    } catch {
      return 'Member';
    }
  };

  // Get location string - check dynamic field values first, then fallback to legacy columns
  const getLocation = () => {
    let cityValue: string | null = null;
    let stateValue: string | null = null;

    // Helper to format snake_case to Title Case, with uppercase for 2-letter state codes.
    // City values carry a state prefix (e.g. "ne_adams", "co_aetna_estates") — strip it.
    const formatCity = (v: string) => {
      const trimmed = v.trim();
      const stripped = trimmed.replace(/^[a-z]{2}_/i, '');
      return stripped.split('_').map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(' ');
    };
    const formatValue = (v: string) => {
      const trimmed = v.trim();
      if (/^[a-z]{2}$/i.test(trimmed)) return trimmed.toUpperCase();
      return trimmed.split('_').map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(' ');
    };

    // First, check fieldValues for state and city (dynamic profile fields)
    if (profile.fieldValues && profile.fieldValues.length > 0) {
      const stateField = profile.fieldValues.find(fv => fv.field.slug === 'state');
      const cityField = profile.fieldValues.find(fv => fv.field.slug === 'city');

      if (stateField && stateField.jsonValue) {
        const value = stateField.jsonValue;
        if (Array.isArray(value) && value.length > 0) {
          stateValue = value.map(v => formatValue(String(v))).join(', ');
        } else if (typeof value === 'string' && value.trim()) {
          stateValue = formatValue(value);
        }
      }

      if (cityField && cityField.jsonValue) {
        const value = cityField.jsonValue;
        if (Array.isArray(value) && value.length > 0) {
          // City values carry a state prefix — strip it before joining
          cityValue = value.map(v => formatCity(String(v))).join(', ');
        } else if (typeof value === 'string' && value.trim()) {
          cityValue = formatCity(value);
        }
      }
    }

    // Fallback to legacy profile columns if dynamic fields not found
    if (!cityValue && profile.city) {
      cityValue = profile.city;
    }
    if (!stateValue && profile.state) {
      stateValue = profile.state;
    }

    // Build location string (state first, then city)
    if (cityValue && stateValue) {
      return `${stateValue}, ${cityValue}`;
    }
    if (cityValue && profile.country) {
      return `${cityValue}, ${profile.country}`;
    }
    if (stateValue && profile.country) {
      return `${stateValue}, ${profile.country}`;
    }
    if (cityValue) {
      return cityValue;
    }
    if (stateValue) {
      return stateValue;
    }
    if (profile.country) {
      return profile.country;
    }
    if (profile.serviceAreas && profile.serviceAreas.length > 0) {
      return profile.serviceAreas[0];
    }
    return null;
  };

  // Extract expertise tags — ONLY from the about_me_expertise field (matches admin filter source)
  const getExpertiseTags = (): string[] => {
    const tags: string[] = [];
    if (!profile.fieldValues || profile.fieldValues.length === 0) return tags;

    const fv = profile.fieldValues.find((f) => f.field.slug === 'about_me_expertise');
    if (!fv) return tags;

    const value = fv.jsonValue;
    if (Array.isArray(value)) {
      value.forEach((v) => {
        if (typeof v === 'string' && v.trim()) {
          const displayValue = v
            .split('_')
            .map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
            .join(' ');
          if (!tags.includes(displayValue)) tags.push(displayValue);
        }
      });
    } else if (typeof value === 'string' && value.trim() && !tags.includes(value)) {
      tags.push(value);
    }

    return tags;
  };

  // Get description from fieldValues (description field) or fallback to profile.bio
  const getDescription = (): string | null => {
    if (profile.fieldValues && profile.fieldValues.length > 0) {
      const descField = profile.fieldValues.find(fv => fv.field.slug === 'description');
      if (descField && descField.textValue) {
        return descField.textValue;
      }
    }
    return profile.bio;
  };

  const location = getLocation();
  const expertiseTags = getExpertiseTags();
  const description = getDescription();
  const maxDescLength = 150;
  const truncatedDescription = description && description.length > maxDescLength
    ? description.slice(0, maxDescLength) + '...'
    : description || '';
  const INITIAL_TAG_COUNT = 5;

  return (
    <div className="bg-white rounded-[20px] p-4 sm:p-5 flex flex-col sm:flex-row gap-4 sm:gap-5 shadow-[0px_10px_20px_rgba(217,217,217,0.5)] min-h-[280px]">
      {/* Profile Image & View Profile Button */}
      <div className="flex-shrink-0 flex flex-col items-center">
        <ProfileImage
          src={getProfileImageUrl()}
          alt={`${profile.firstName} ${profile.lastName}`}
          className="w-full aspect-square sm:w-[200px] sm:h-[200px] sm:aspect-auto rounded-[15px]"
        />
        <Link href={`/user/profile/${profile.id}`} className="mt-4">
          <button className="w-[113px] py-2.5 bg-[#e58625] hover:bg-[#d47720] text-[#00293d] font-fractul font-bold text-[14px] rounded-[15px] transition-colors text-center flex items-center justify-center">
            View Profile
          </button>
        </Link>
      </div>

      {/* Profile Info */}
      <div className="flex-1 min-w-0">
        {/* Header Row - Name, Verified, Match Badge */}
        <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-2">
          <div>
            {/* Name and Verified Badge */}
            <div className="flex items-center gap-2 flex-wrap">
              <h3 className="font-fractul text-[18px] text-[#00293d]">
                <span className="font-bold">{profile.firstName}</span>{' '}
                <span className="font-normal">{profile.lastName}</span>
              </h3>
              {profile.isVerified && (
                <>
                  <Image
                    src="/assets/icons/verified-expert-badge.svg"
                    alt="Verified"
                    width={14}
                    height={15}
                  />
                  <span className="font-serif font-medium text-[14px] text-[#638559]">
                    (Verified Expert)
                  </span>
                </>
              )}
            </div>
            {/* Agent Type */}
            <p className="font-serif text-[14px] text-[#00293d] mt-1">
              {profile.agentType?.name || 'Real Estate Professional'}
            </p>
          </div>

          {/* Match Badge */}
          {profile.matchPercentage && (
            <div className={`text-white px-4 py-1.5 rounded-full font-serif text-[14px] whitespace-nowrap self-start ${
              profile.matchPercentage >= 80 ? 'bg-[#638559]' : profile.matchPercentage >= 65 ? 'bg-[#7d917d]' : 'bg-[#00293d]/60'
            }`}>
              {profile.matchPercentage}% Match
            </div>
          )}
        </div>

        {/* Location & Member Since */}
        <div className="flex flex-wrap items-center gap-3 sm:gap-4 mt-3">
          {location && (
            <div className="flex items-center gap-2">
              <Image
                src="/assets/icons/location-pin-icon.svg"
                alt="Location"
                width={16}
                height={15}
              />
              <span className="font-serif font-bold text-[14px] text-[#00293d] truncate max-w-[200px]" title={location}>
                {location}
              </span>
            </div>
          )}
          <div className="flex items-center gap-2">
            <Image
              src="/assets/icons/calendar-icon.svg"
              alt="Member Since"
              width={18}
              height={18}
            />
            <span className="font-serif font-medium text-[13px] text-[#00293d]">
              Member Since {formatMemberSince(profile.createdAt)}
            </span>
          </div>
        </div>

        {/* Description */}
        {description && (
          <div className="mt-3">
            <p className="font-serif text-[13px] text-[#00293d] leading-[20px]">
              {showFullBio ? description : truncatedDescription}
              {description.length > maxDescLength && (
                <>
                  {' '}
                  <button
                    onClick={() => setShowFullBio(!showFullBio)}
                    className="font-serif font-bold text-[13px] text-[#00293d] underline"
                  >
                    {showFullBio ? 'Show Less.' : 'Show More.'}
                  </button>
                </>
              )}
            </p>
          </div>
        )}

        {/* Expertise Tags */}
        {expertiseTags.length > 0 && (
          <div className="mt-3">
            <p className="font-fractul font-bold text-[14px] text-[#00293d] mb-2">Expertise:</p>
            <div className="flex flex-wrap gap-2 items-center">
              {(showAllTags ? expertiseTags : expertiseTags.slice(0, INITIAL_TAG_COUNT)).map((tag, index) => (
                <span
                  key={index}
                  className="border border-[#00293d] rounded-[15px] px-3 py-1 font-serif text-[14px] text-[#00293d] whitespace-nowrap flex-shrink-0"
                >
                  {tag}
                </span>
              ))}
              {expertiseTags.length > INITIAL_TAG_COUNT && (
                <button
                  onClick={() => setShowAllTags(!showAllTags)}
                  className="border border-[#e58625] rounded-[15px] px-3 py-1 font-serif text-[14px] text-[#e58625] hover:bg-[#e58625]/10 transition-colors whitespace-nowrap flex-shrink-0"
                >
                  {showAllTags ? 'Show Less' : `+${expertiseTags.length - INITIAL_TAG_COUNT} more`}
                </button>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function ProfilesPageContent() {
  const searchParams = useSearchParams();

  // Get URL params directly for use in effects
  const typeFromUrl = searchParams.get('type');
  const nameFromUrl = searchParams.get('name') || '';
  const locationFromUrl = searchParams.get('location') || '';
  const filtersFromUrl = searchParams.get('filters') || '';
  const listingFromUrl = searchParams.get('listing');

  // State for API data
  const [agents, setAgents] = useState<PublicAgentProfile[]>([]);
  const [avatarUrls, setAvatarUrls] = useState<Record<string, string>>({});
  const [agentTypes, setAgentTypes] = useState<AgentType[]>([]);
  const [filterFields, setFilterFields] = useState<FilterField[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [totalPages, setTotalPages] = useState(1);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalResults, setTotalResults] = useState(0);

  // State for search and filters - initialize from URL params
  const [searchQuery, setSearchQuery] = useState(nameFromUrl);
  const [activeTypeId, setActiveTypeId] = useState<string | null>(typeFromUrl);
  const [isFilterModalOpen, setIsFilterModalOpen] = useState(false);
  const [filters, setFilters] = useState<FilterState>(() => {
    if (filtersFromUrl) {
      try {
        return JSON.parse(filtersFromUrl) as FilterState;
      } catch {
        return {};
      }
    }
    return {};
  });

  // Sync state when URL params change (e.g., browser back/forward, client-side navigation)
  useEffect(() => {
    setActiveTypeId(typeFromUrl);
    setSearchQuery(nameFromUrl);
    if (filtersFromUrl) {
      try {
        setFilters(JSON.parse(filtersFromUrl) as FilterState);
      } catch {
        // ignore invalid JSON
      }
    }
  }, [typeFromUrl, nameFromUrl, filtersFromUrl]);

  // Fetch agent types on mount
  useEffect(() => {
    const fetchAgentTypesOnly = async () => {
      try {
        const types = await agentsService.getAgentTypes();
        setAgentTypes(types);

        // If listing param is set, auto-select the matching agent type by name (case-insensitive)
        if (listingFromUrl && !typeFromUrl) {
          const target = listingFromUrl.toLowerCase().replace(/s$/, '');
          const matchedType = types.find((t: AgentType) => t.name.toLowerCase() === target);
          if (matchedType) {
            setActiveTypeId(matchedType.id);
          }
        }
      } catch (error) {
        console.error('Failed to fetch agent types:', error);
      }
    };
    fetchAgentTypesOnly();
  }, []);

  // Re-fetch filter fields whenever the selected agent type changes so the Filters modal
  // only shows options relevant to that agent type (plus globals).
  useEffect(() => {
    const fetchFilters = async () => {
      try {
        const fields = await profileSectionsService.getFilterableFields(activeTypeId);
        const filterFieldsData: FilterField[] = fields.map((f: FilterableField) => ({
          slug: f.slug,
          name: f.name,
          fieldType: f.fieldType,
          options: f.options,
        }));
        setFilterFields(filterFieldsData);
        // Drop any selected filter keys that no longer exist in the new field list
        setFilters((prev) => {
          const validSlugs = new Set(filterFieldsData.map((f) => f.slug));
          const next: typeof prev = {};
          for (const [k, v] of Object.entries(prev)) {
            if (validSlugs.has(k)) next[k] = v;
          }
          return next;
        });
      } catch (error) {
        console.error('Failed to fetch filter fields:', error);
      }
    };
    fetchFilters();
  }, [activeTypeId]);

  // Fetch agents based on filters
  const fetchAgents = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      const params: SearchAgentsParams = {
        page: currentPage,
        limit: 10,
        sortBy: 'createdAt',
        sortOrder: 'desc',
      };

      // Add search query — also applies to location (city/state/country/service_areas)
      // so single input matches across name + location fields (backend ORs them).
      if (searchQuery) {
        params.search = searchQuery;
        if (!locationFromUrl) {
          params.location = searchQuery;
        }
      }

      // Add agent type filter
      if (activeTypeId) {
        params.agentTypeId = activeTypeId;
      }

      // Add location search (searches city, state, country, and dynamic field values)
      if (locationFromUrl) {
        params.location = locationFromUrl;
      }

      // Add dynamic profile field filters
      const activeFilters = Object.entries(filters).reduce((acc, [key, values]) => {
        if (values && values.length > 0) {
          acc[key] = values;
        }
        return acc;
      }, {} as Record<string, string[]>);

      if (Object.keys(activeFilters).length > 0) {
        params.filters = activeFilters;
      }

      const response = await agentsService.searchAgents(params);

      // Resolve all avatar URLs via presigned-download-url API
      const urlMap: Record<string, string> = {};
      const avatarPromises = response.data.map(async (agent) => {
        if (agent.avatar && !agent.avatar.startsWith('http') && !agent.avatar.startsWith('/')) {
          try {
            const presignedUrl = await uploadService.getPresignedDownloadUrl(agent.avatar);
            urlMap[agent.id] = presignedUrl;
          } catch {
            // Skip failed URLs, card will show placeholder
          }
        } else if (agent.avatar) {
          urlMap[agent.id] = agent.avatar;
        }
      });
      await Promise.all(avatarPromises);

      setAvatarUrls(urlMap);
      setAgents(response.data);
      setTotalPages(response.totalPages);
      setTotalResults(response.total);
    } catch (err) {
      console.error('Failed to fetch agents:', err);
      setError('Failed to load agents. Please try again.');
    } finally {
      setLoading(false);
    }
  }, [currentPage, searchQuery, activeTypeId, locationFromUrl, filters]);

  // Fetch agents when filters change
  useEffect(() => {
    fetchAgents();
  }, [fetchAgents]);

  const toggleFilter = (fieldSlug: string, optionValue: string) => {
    setFilters(prev => {
      const currentValues = prev[fieldSlug] || [];
      const newValues = currentValues.includes(optionValue)
        ? currentValues.filter(v => v !== optionValue)
        : [...currentValues, optionValue];
      return { ...prev, [fieldSlug]: newValues };
    });
  };

  const clearAllFilters = () => {
    setFilters({});
  };

  const applyFilters = () => {
    setIsFilterModalOpen(false);
    setCurrentPage(1); // Reset to first page when applying filters
    // Filters are applied via the fetchAgents effect
  };

  const handleSearch = () => {
    if (!searchQuery.trim()) return;
    setCurrentPage(1);
    fetchAgents();
  };

  const handleTypeChange = (typeId: string | null) => {
    setActiveTypeId(typeId);
    setCurrentPage(1);
  };

  // Get filter field by slug for sidebar
  const getFilterFieldBySlug = (slug: string): FilterField | undefined => {
    return filterFields.find(f => f.slug === slug);
  };

  // Define which fields to show in sidebar (main filter categories)
  const sidebarFilterSlugs = ['client_specialization', 'loan_type', 'property_type', 'price_point'];

  // Pluralize agent type names for sidebar display (e.g. "Agent" → "Agents", "Property Manager" → "Property Managers")
  const pluralize = (name: string): string => {
    const trimmed = name.trim();
    if (!trimmed) return trimmed;
    const lower = trimmed.toLowerCase();
    if (lower.endsWith('s')) return trimmed;
    if (lower.endsWith('y')) return `${trimmed.slice(0, -1)}ies`;
    return `${trimmed}s`;
  };

  return (
    <div className="min-h-screen bg-white">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <MobileBackButton label="Back" fallbackHref="/user/dashboard" />
        <div className="flex gap-6">
          {/* Left Sidebar - hidden on mobile */}
          <div className="hidden lg:block w-[220px] flex-shrink-0 pr-6 border-r border-[#00293d]/10">
            {/* Listing Type */}
            <div className="mb-6">
              <h2 className="font-fractul font-bold text-[14px] text-[#00293d] mb-3">Listing Type</h2>
              <div className="space-y-2">
                <button
                  onClick={() => handleTypeChange(null)}
                  className={`block font-serif text-[14px] ${activeTypeId === null ? 'text-[#00293d] font-medium' : 'text-[#00293d]/70'}`}
                >
                  All Types
                </button>
                {agentTypes.map((type) => (
                  <button
                    key={type.id}
                    onClick={() => handleTypeChange(type.id)}
                    className={`block font-serif text-[14px] ${activeTypeId === type.id ? 'text-[#00293d] font-medium' : 'text-[#00293d]/70'}`}
                  >
                    {pluralize(type.name)}
                  </button>
                ))}
              </div>
            </div>

            {/* Filters */}
            <div>
              <div className="flex items-center justify-between mb-4">
                <h2 className="font-fractul font-bold text-[14px] text-[#00293d]">Filters</h2>
                <button
                  onClick={() => setIsFilterModalOpen(true)}
                  className="text-[#00293d] hover:opacity-70"
                >
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                    <path d="M3 6H21M7 12H17M11 18H13" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                  </svg>
                </button>
              </div>

              {/* Dynamic Filter Sections */}
              {sidebarFilterSlugs.map(slug => {
                const field = getFilterFieldBySlug(slug);
                if (!field) return null;
                return (
                  <FilterSection
                    key={field.slug}
                    title={field.name}
                    options={field.options}
                    selectedOptions={filters[field.slug] || []}
                    onToggle={(optionValue) => toggleFilter(field.slug, optionValue)}
                    showMore={field.options.length > 6}
                  />
                );
              })}

              {filterFields.length === 0 && (
                <div className="py-4">
                  <p className="font-serif text-[13px] text-[#00293d]/50">Loading filters...</p>
                </div>
              )}
            </div>
          </div>

          {/* Main Content */}
          <div className="flex-1 min-w-0">
            {/* Mobile Filter Button - visible only on mobile */}
            <div className="flex lg:hidden items-center justify-between mb-4">
              <h2 className="font-fractul font-bold text-[16px] text-[#00293d]">Agent Profiles</h2>
              <button
                onClick={() => setIsFilterModalOpen(true)}
                className="flex items-center gap-2 px-4 py-2 border border-[#00293d]/20 rounded-[10px] font-serif text-[13px] text-[#00293d]"
              >
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                  <path d="M3 6H21M7 12H17M11 18H13" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                </svg>
                Filters
              </button>
            </div>

            {/* Search Bar */}
            <div className="mb-4">
              <div className="relative">
                <input
                  type="text"
                  placeholder="Search Agents"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                  className="w-full h-[52px] px-5 pr-[80px] rounded-[15px] border border-[#00293d]/20 bg-white font-fractul font-light text-[14px] text-[#00293d] placeholder:text-[#00293d]/50 focus:outline-none focus:border-[#e58625]"
                />
                <button
                  onClick={handleSearch}
                  className="absolute right-0 top-0 w-[68px] h-[52px] bg-[#e58625] rounded-[15px] flex items-center justify-center hover:bg-[#d47720] transition-colors"
                >
                  <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
                    <path d="M21 21L16.65 16.65M19 11C19 15.4183 15.4183 19 11 19C6.58172 19 3 15.4183 3 11C3 6.58172 6.58172 3 11 3C15.4183 3 19 6.58172 19 11Z" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </button>
              </div>
            </div>

            {/* Agent Type Tabs */}
            <div className="flex gap-2 mb-6 overflow-x-auto pb-2 scrollbar-hide flex-nowrap sm:flex-wrap">
              <button
                onClick={() => handleTypeChange(null)}
                className={`px-4 py-2 rounded-full font-serif text-[13px] border transition-colors whitespace-nowrap flex-shrink-0 ${activeTypeId === null
                    ? 'bg-[#00293d] text-white border-[#00293d]'
                    : 'bg-white text-[#00293d] border-[#00293d]/20 hover:border-[#00293d]/40'
                  }`}
              >
                All Types
              </button>
              {agentTypes.map((type) => (
                <button
                  key={type.id}
                  onClick={() => handleTypeChange(type.id)}
                  className={`px-4 py-2 rounded-full font-serif text-[13px] border transition-colors whitespace-nowrap flex-shrink-0 ${activeTypeId === type.id
                      ? 'bg-[#00293d] text-white border-[#00293d]'
                      : 'bg-white text-[#00293d] border-[#00293d]/20 hover:border-[#00293d]/40'
                    }`}
                >
                  {type.name}
                </button>
              ))}
            </div>

            {/* Loading State */}
            {loading && (
              <div className="flex items-center justify-center py-12">
                <div className="flex flex-col items-center gap-4">
                  <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#E58625]"></div>
                  <p className="text-[14px] font-serif text-[#00293D]/70">Loading agents...</p>
                </div>
              </div>
            )}

            {/* Error State */}
            {error && !loading && (
              <div className="bg-red-50 border border-red-200 rounded-[15px] p-6 text-center">
                <p className="text-red-600 font-serif text-[14px]">{error}</p>
                <button
                  onClick={fetchAgents}
                  className="mt-4 px-6 py-2 bg-[#E58625] rounded-full text-[14px] font-semibold font-serif text-white hover:bg-[#E58625]/90 transition-colors"
                >
                  Try Again
                </button>
              </div>
            )}

            {/* Empty State */}
            {!loading && !error && agents.length === 0 && (
              <div className="bg-gray-50 rounded-[15px] p-12 text-center">
                <div className="w-16 h-16 bg-[#E58625]/10 rounded-full flex items-center justify-center mx-auto mb-4">
                  <svg className="w-8 h-8 text-[#E58625]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                  </svg>
                </div>
                <h3 className="font-fractul font-bold text-[18px] text-[#00293d] mb-2">No agents found</h3>
                <p className="font-serif text-[14px] text-[#00293d]/70">
                  Try adjusting your search criteria or filters
                </p>
              </div>
            )}

            {/* Profile Cards */}
            {!loading && !error && agents.length > 0 && (
              <div className="space-y-4">
                {agents.map((profile) => (
                  <ProfileCard key={profile.id} profile={profile} resolvedAvatarUrl={avatarUrls[profile.id]} />
                ))}
              </div>
            )}

            {/* Pagination */}
            {!loading && !error && totalPages > 1 && (
              <div className="flex justify-center items-center gap-2 mt-8 flex-wrap">
                <button
                  onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                  disabled={currentPage === 1}
                  className="px-4 py-2 rounded-[10px] border border-[#00293d]/20 font-serif text-[13px] text-[#00293d] disabled:opacity-50 disabled:cursor-not-allowed hover:border-[#00293d]/40 transition-colors"
                >
                  Previous
                </button>
                <span className="px-4 py-2 font-serif text-[13px] text-[#00293d]">
                  Page {currentPage} of {totalPages}
                </span>
                <button
                  onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                  disabled={currentPage === totalPages}
                  className="px-4 py-2 rounded-[10px] border border-[#00293d]/20 font-serif text-[13px] text-[#00293d] disabled:opacity-50 disabled:cursor-not-allowed hover:border-[#00293d]/40 transition-colors"
                >
                  Next
                </button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Filter Modal */}
      <FilterModal
        isOpen={isFilterModalOpen}
        onClose={() => setIsFilterModalOpen(false)}
        filters={filters}
        filterFields={filterFields}
        onToggleFilter={toggleFilter}
        onClearAll={clearAllFilters}
        onApply={applyFilters}
      />
    </div>
  );
}

export default function ProfilesPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen bg-white flex items-center justify-center">
        <div className="flex flex-col items-center gap-4">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#E58625]"></div>
          <p className="text-[14px] font-serif text-[#00293D]/70">Loading...</p>
        </div>
      </div>
    }>
      <ProfilesPageContent />
    </Suspense>
  );
}
