'use client';

import { Metadata } from 'next';
import Link from 'next/link';
import Image from 'next/image';
import { useEffect, useState, useCallback, useRef } from 'react';
import { useSearchParams, useRouter, usePathname } from 'next/navigation';
import { useSession } from 'next-auth/react';
import Footer from '@/components/Footer';
import PostProjectSection from '@/components/sections/PostProjectSection';
import './find-project.css'
import { getCountryDataByDomain } from '@/lib/countries';

interface Project {
  id: string;
  title: string;
  description: string;
  budget: number;
  duration: number;
  skills: string[];
  status: string;
  publishedAt: string;
  category: {
    id: string;
    name: string;
    slug: string;
    icon?: string;
  };
  country: {
    id: string;
    name: string;
    currency: string;
    currencySymbol: string;
  };
  client: {
    id: string;
    name: string;
    profileImage: string;
    rating: number;
    reviewCount: number;
  };
  bidCount: number;
  createdAt: string;
  updatedAt: string;
}

interface Category {
  id: string;
  name: string;
  slug: string;
  icon?: string;
  isActive: boolean;
  _count: {
    projects: number;
    profiles: number;
  };
}

interface Filters {
  search: string;
  categoryId: string;
  minBudget: string;
  maxBudget: string;
  countryId: string;
  sortBy: string;
}

interface ProjectsPageProps {
  params: Promise<{
    locale: string;
  }>;
}

export default function ProjectsPage({ params }: ProjectsPageProps) {
  const datacounter = getCountryDataByDomain();
  const { data: session, status } = useSession();
  const [locale, setLocale] = useState<string>('en');
  const [projects, setProjects] = useState<Project[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showBidModal, setShowBidModal] = useState(false);
  const [modalCategoryName, setModalCategoryName] = useState('');
  const [modalCategorySlug, setModalCategorySlug] = useState('');


  const [membershipStatus, setMembershipStatus] = useState<{
    hasActiveSubscription: boolean;
    subscribedCategories: string[];
  } | null>(null);
  const [pagination, setPagination] = useState({
    currentPage: 1,
    totalPages: 1,
    totalItems: 0,
    itemsPerPage: 12,
    hasNextPage: false,
    hasPrevPage: false
  });
  const [showMoreCategories, setShowMoreCategories] = useState(false);
  const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
  const [activeFilters, setActiveFilters] = useState<string[]>([]);

  const searchParams = useSearchParams();
  const router = useRouter();
  const pathname = usePathname();
  
  // Get user role to determine UI visibility
  const userRole = (session?.user as any)?.role;
  const isClient = userRole === 'CLIENT';
  
  // Check membership status for freelancers
  useEffect(() => {
    const checkMembershipStatus = async () => {
      if (status === 'authenticated' && session?.user && userRole === 'FREELANCER') {
        try {
          const response = await fetch('/api/freelancer/membership/status');
          if (response.ok) {
            const data = await response.json();
            setMembershipStatus({
              hasActiveSubscription: data.data?.hasActiveMembership || false,
              subscribedCategories: data.data?.subscriptions?.map((sub: any) => sub.categorySlug) || []
            });
          }
        } catch (error) {
          console.error('Failed to fetch membership status:', error);
          setMembershipStatus({
            hasActiveSubscription: false,
            subscribedCategories: []
          });
        }
      }
    };

    checkMembershipStatus();
  }, [session, status, userRole]);

  // Handle bid button click with membership validation
  const handleBidClick = (project: Project) => {
    // If not logged in, redirect to login
    if (status !== 'authenticated' || !session?.user) {
      router.push(`/${locale}/login?returnUrl=${encodeURIComponent(pathname)}`);
      return;
    }

    // If user is a client, they cannot bid
    if (userRole === 'CLIENT') {
      return;
    }

    // If user is freelancer but no membership info loaded yet, wait
    if (userRole === 'FREELANCER' && membershipStatus === null) {
      return;
    }

    const arr = membershipStatus?.subscribedCategories;
    if (!arr?.includes(project.category.slug)) {
          setShowBidModal(true);
          const categoryParam = project.category.slug ? `?category-buy=${encodeURIComponent(project.category.id)}` : '';
          setModalCategoryName(project.category.name);
          setModalCategorySlug(categoryParam);
          return;
    }
    // If freelancer has active membership, allow bid
    if (membershipStatus?.hasActiveSubscription) {
      // Navigate to bid page or open bid modal
      // router.push(`/${locale}/projects/${project.id}/bid`);
      router.push(`/${locale}/freelancer/projects/${project.id}?create-bid=add`);
      return;
    }

    // If freelancer doesn't have membership, redirect to membership page with auto-selected category
    if (userRole === 'FREELANCER' && !membershipStatus?.hasActiveSubscription) {
      const categoryParam = project.category.slug ? `?category=${encodeURIComponent(project.category.slug)}` : '';
      router.push(`/${locale}/freelancer/buy-membership${categoryParam}`);
      return;
    }
  };

  // Get bid button text based on user state
  const getBidButtonText = () => {
    if (status !== 'authenticated' || !session?.user) {
      return 'Login to Bid';
    }
    if (userRole === 'CLIENT') {
      return 'View Project';
    }
    if (userRole === 'FREELANCER' && membershipStatus === null) {
      return 'Loading...';
    }
    if (userRole === 'FREELANCER' && !membershipStatus?.hasActiveSubscription) {
      return 'Get Membership';
    }
    return 'Bid';
  };

  // Check if bid button should be shown
  const shouldShowBidButton = () => {
    // Always show for unauthenticated users (shows login prompt)
    if (status !== 'authenticated' || !session?.user) {
      return true;
    }
    // Don't show for clients
    if (userRole === 'CLIENT') {
      return false;
    }
    // Show for freelancers (with different text based on membership)
    return userRole === 'FREELANCER';
  };

  // Get locale from params
  useEffect(() => {
    params.then(({ locale }) => setLocale(locale));
  }, [params]);

  // Initialize and sync selectedCategories with URL parameters
  useEffect(() => {
    const categoryIdParam = searchParams.get('categoryId');
    if (categoryIdParam) {
      const categoriesFromUrl = categoryIdParam.split(',').filter(Boolean);
      setSelectedCategories(categoriesFromUrl);
    } else {
      setSelectedCategories([]);
    }
  }, [searchParams]);

  // Update active filters for display
  const updateActiveFilters = useCallback((currentFilters: any) => {
    const active: string[] = [];
    if (currentFilters.search) {
      active.push(`Search: "${currentFilters.search}"`);
    }
    if (currentFilters.minBudget || currentFilters.maxBudget) {
      const min = currentFilters.minBudget || '0';
      const max = currentFilters.maxBudget || '∞';
      active.push(`${datacounter?.currencySymbol} ${min} – ${datacounter?.currencySymbol} ${max}`);
    }
    if (currentFilters.categoryId) {
      const category = categories.find(c => c.id === currentFilters.categoryId);
      if (category) {
        active.push(category.name);
      }
    }

    setActiveFilters(active);
  }, [categories]);

  // Sync all filters with URL parameters when searchParams change
  useEffect(() => {
    const newFilters = {
      search: searchParams.get('search') || '',
      categoryId: searchParams.get('categoryId') || '',
      minBudget: searchParams.get('minBudget') || '',
      maxBudget: searchParams.get('maxBudget') || '',
      countryId: searchParams.get('countryId') || '',
      sortBy: searchParams.get('sortBy') || 'newest'
    };
    setFilters(newFilters);
    setCurrentPage(parseInt(searchParams.get('page') || '1'));
    
    // Update active filters display when URL parameters change
    if (categories.length > 0) {
      updateActiveFilters(newFilters);
    }
  }, [searchParams, categories, updateActiveFilters]);

  // Initialize filters from URL params
  const [filters, setFilters] = useState<Filters>({
    search: searchParams.get('search') || '',
    categoryId: searchParams.get('categoryId') || '',
    minBudget: searchParams.get('minBudget') || '',
    maxBudget: searchParams.get('maxBudget') || '',
    countryId: searchParams.get('countryId') || '',
    sortBy: searchParams.get('sortBy') || 'newest'
  });

  const [currentPage, setCurrentPage] = useState(1);

  // Update URL with current filters
  const updateURL = useCallback((newFilters: Partial<Filters>, newPage?: number) => {
    const params = new URLSearchParams();

    const updatedFilters = { ...filters, ...newFilters };
    const page = newPage || currentPage;

    if (updatedFilters.search) params.set('search', updatedFilters.search);
    if (updatedFilters.categoryId) params.set('categoryId', updatedFilters.categoryId);
    if (updatedFilters.minBudget) params.set('minBudget', updatedFilters.minBudget);
    if (updatedFilters.maxBudget) params.set('maxBudget', updatedFilters.maxBudget);
    if (updatedFilters.countryId) params.set('countryId', updatedFilters.countryId);
    if (updatedFilters.sortBy && updatedFilters.sortBy !== 'newest') params.set('sortBy', updatedFilters.sortBy);
    if (page > 1) params.set('page', page.toString());

    const newURL = `${pathname}?${params.toString()}`;
    router.push(newURL, { scroll: false });
  }, [filters, currentPage, pathname, router]);

  // Fetch categories
  const fetchCategories = async () => {

    const params = new URLSearchParams({});
        if(!datacounter?.id){
              setError('Country is missing');
              return false;
          }
          params.set('countryId', datacounter?.id);
          params.set('active', 'true');
    try {
      // const response = await fetch('/api/categories?active=true');
      const response = await fetch(`/api/categories?${params.toString()}`);
      if (response.ok) {
        const categoriesData = await response.json();
        setCategories(categoriesData);
      }
    } catch (error) {
      console.error('Failed to fetch categories:', error);
    }
  };

  // Fetch projects
  const fetchProjects = useCallback(async (isLoadMore = false) => {
    try {
      setLoading(true);
      setError(null);

      const params = new URLSearchParams();
      if (filters.search) params.set('search', filters.search);
      if (filters.categoryId) params.set('categoryId', filters.categoryId);
      if (filters.minBudget) params.set('minBudget', filters.minBudget);
      if (filters.maxBudget) params.set('maxBudget', filters.maxBudget);
      if (filters.countryId) params.set('countryId', filters.countryId);
      if (filters.sortBy) params.set('sortBy', filters.sortBy);
      params.set('page', currentPage.toString());
      params.set('limit', '12');

      if(!datacounter?.id){
          setError('Country is missing');
          return false;
      }
      params.set('countryId', datacounter?.id);

      const response = await fetch(`/api/projects?${params.toString()}`);
      const data = await response.json();

      if (data.success) {
        if (isLoadMore) {
          // Append new projects to existing ones
          setProjects(prevProjects => [...prevProjects, ...data.data.projects]);
        } else {
          // Replace projects (initial load or filter change)
          setProjects(data.data.projects);
        }
        setPagination(data.data.pagination);
        updateActiveFilters(data.data.filters);
      } else {
        setError(data.message || 'Failed to fetch projects');
      }
    } catch (error) {
      setError('Network error occurred');
      console.error('Failed to fetch projects:', error);
    } finally {
      setLoading(false);
    }
  }, [filters, currentPage, updateActiveFilters]);

  // Handle filter changes
  const handleSearchChange = (value: string) => {
    const newFilters = { ...filters, search: value };
    setFilters(newFilters);
    setCurrentPage(1);
    setIsFilterChange(true);
    updateURL(newFilters, 1);
  };

  const handlePriceRangeChange = (min: string, max: string) => {
    const newFilters = { ...filters, minBudget: min, maxBudget: max };
    setFilters(newFilters);
    setCurrentPage(1);
    setIsFilterChange(true);
    updateURL(newFilters, 1);
  };

  const handleCategoryChange = (categoryId: string, checked: boolean) => {
    let newSelectedCategories: string[];

    if (categoryId === 'all') {
      newSelectedCategories = checked ? categories.map(c => c.id) : [];
    } else {
      newSelectedCategories = checked
        ? [...selectedCategories, categoryId]
        : selectedCategories.filter(id => id !== categoryId);
    }

    setSelectedCategories(newSelectedCategories);
    const newFilters = { ...filters, categoryId: newSelectedCategories.join(',') };
    setFilters(newFilters);
    setCurrentPage(1);
    setIsFilterChange(true);
    updateURL(newFilters, 1);
  };

  const handleCategoryFilter = (categoryId: string) => {
    const newFilters = { ...filters, categoryId };
    setFilters(newFilters);
    setCurrentPage(1);
    setIsFilterChange(true);
    updateURL(newFilters, 1);
  };

  const handleSortChange = (sortBy: string) => {
    const newFilters = { ...filters, sortBy };
    setFilters(newFilters);
    setCurrentPage(1);
    setIsFilterChange(true);
    updateURL(newFilters, 1);
  };

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    updateURL({}, page);
  };

  const handleLoadMore = () => {
    const nextPage = currentPage + 1;
    setCurrentPage(nextPage);
    updateURL({}, nextPage);
  };

  const clearFilter = (filterType: string) => {
    let newFilters = { ...filters };

    switch (filterType) {
      case 'search':
        newFilters.search = '';
        break;
      case 'price':
        newFilters.minBudget = '';
        newFilters.maxBudget = '';
        break;
      case 'category':
        newFilters.categoryId = '';
        setSelectedCategories([]);
        break;
    }

    setFilters(newFilters);
    setCurrentPage(1);
    setIsFilterChange(true);
    updateURL(newFilters, 1);
  };

  const clearAllFilters = () => {
    const newFilters: Filters = {
      search: '',
      categoryId: '',
      minBudget: '',
      maxBudget: '',
      countryId: '',
      sortBy: 'newest'
    };
    setFilters(newFilters);
    setSelectedCategories([]);
    setCurrentPage(1);
    setIsFilterChange(true);
    updateURL(newFilters, 1);
  };

  // Initial data fetch
  useEffect(() => {
    fetchCategories();
  }, []);

  // Track when filters change to reset projects
  const [isFilterChange, setIsFilterChange] = useState(false);

  useEffect(() => {
    if (categories.length > 0) {
      const isLoadMore = currentPage > 1 && !isFilterChange;
      fetchProjects(isLoadMore);
      if (isFilterChange) {
        setIsFilterChange(false);
      }
    }
  }, [categories, fetchProjects, currentPage, isFilterChange]);

  // Format duration
  const formatDuration = (days: number) => {
    if (days === 1) return '1 day';
    if (days < 30) return `${days} days`;
    const months = Math.floor(days / 30);
    const remainingDays = days % 30;
    if (remainingDays === 0) return `${months} month${months > 1 ? 's' : ''}`;
    return `${months} month${months > 1 ? 's' : ''} ${remainingDays} day${remainingDays > 1 ? 's' : ''}`;
  };

  // Format budget
  const formatBudget = (amount: number, currency: string) => {
    return new Intl.NumberFormat('en-EU', {
      style: 'currency',
      currency: currency || 'EUR',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0
    }).format(amount);
  };

  // Format time ago
  const formatTimeAgo = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffInHours = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60));

    if (diffInHours < 1) return 'Just now';
    if (diffInHours < 24) return `${diffInHours} hour${diffInHours > 1 ? 's' : ''} ago`;

    const diffInDays = Math.floor(diffInHours / 24);
    if (diffInDays < 7) return `${diffInDays} day${diffInDays > 1 ? 's' : ''} ago`;

    const diffInWeeks = Math.floor(diffInDays / 7);
    if (diffInWeeks < 4) return `${diffInWeeks} week${diffInWeeks > 1 ? 's' : ''} ago`;

    const diffInMonths = Math.floor(diffInDays / 30);
    return `${diffInMonths} month${diffInMonths > 1 ? 's' : ''} ago`;
  };

  // Handle project sharing
  const handleShareProject = (project: Project) => {
    const projectUrl = `${window.location.origin}/${locale}/projects/${project.id}`;
    const shareText = `Check out this project: ${project.title}`;

    if (navigator.share) {
      // Use native share API if available (mobile devices)
      navigator.share({
        title: project.title,
        text: shareText,
        url: projectUrl,
      }).catch(console.error);
    } else {
      // Fallback to clipboard copy
      navigator.clipboard.writeText(projectUrl).then(() => {
        alert('Project link copied to clipboard!');
      }).catch(() => {
        // Ultimate fallback - show the URL
        prompt('Copy this link:', projectUrl);
      });
    }
  };

  const handleCloseCancelModal = () => {
    setShowBidModal(false);
    setModalCategoryName('');
    setModalCategorySlug('');
  };

  return (
    <>
      {/* Hero Section */}
      <section className="inner-hero-wrapper">
        <div className="container">
          <div className="row">
            <div className="col-12 col-md-7 col-lg-8 align-self-center">
              <div className="hero-content">
                <h1>Find Projects</h1>
                <p>Browse project listings tailored to your skills and area of expertise</p>
              </div>
            </div>
            <div className="col-12 col-md-5 col-lg-4 align-self-end">
              <div className="inner-hero-img text-center pt-3">
                <img src="/assets/image/projectbanner-img.svg" alt="service-banner-img" />
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Find Projects Section */}
      <section className="find-project-wrapper">
        <div className="container">
          <div className="row">
            <div className="col-12 col-md-4 col-xl-3">
              <div className="filter-sidebar">
                {/* Search Filter */}
                <div className="filter-group">
                  <div className="label-icon">
                    <span className="icon">
                      <svg width="15" height="17" viewBox="0 0 15 17" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path fillRule="evenodd" clipRule="evenodd" d="M6.87495 0.5C5.85839 0.500087 4.85659 0.743273 3.95314 1.20927C3.04968 1.67527 2.27077 2.35056 1.68137 3.17882C1.09198 4.00707 0.709203 4.96426 0.564977 5.97053C0.420751 6.97681 0.519258 8.00298 0.85228 8.96344C1.1853 9.9239 1.74318 10.7908 2.47937 11.4918C3.21557 12.1928 4.10872 12.7076 5.08433 12.9932C6.05994 13.2788 7.0897 13.327 8.08771 13.1337C9.08572 12.9404 10.023 12.5112 10.8214 11.882L13.5604 14.621C13.7019 14.7576 13.8913 14.8332 14.088 14.8315C14.2846 14.8298 14.4728 14.7509 14.6118 14.6119C14.7509 14.4728 14.8297 14.2847 14.8315 14.0881C14.8332 13.8914 14.7576 13.702 14.6209 13.5605L11.8819 10.8215C12.6229 9.88146 13.0843 8.7518 13.2133 7.56179C13.3422 6.37179 13.1335 5.16952 12.6111 4.09257C12.0887 3.01562 11.2736 2.10752 10.2592 1.47217C9.24473 0.83683 8.07192 0.49992 6.87495 0.5ZM1.99995 6.875C1.99995 5.58207 2.51356 4.34209 3.4278 3.42785C4.34204 2.51361 5.58202 2 6.87495 2C8.16788 2 9.40785 2.51361 10.3221 3.42785C11.2363 4.34209 11.7499 5.58207 11.7499 6.875C11.7499 8.16793 11.2363 9.40791 10.3221 10.3221C9.40785 11.2364 8.16788 11.75 6.87495 11.75C5.58202 11.75 4.34204 11.2364 3.4278 10.3221C2.51356 9.40791 1.99995 8.16793 1.99995 6.875Z" fill="#EF7310" />
                      </svg>
                    </span>
                    <input
                      type="text"
                      className="search-input"
                      placeholder="Search project by name"
                      value={filters.search}
                      onChange={(e) => handleSearchChange(e.target.value)}
                    />
                  </div>
                </div>

                {/* Price Range Filter */}
                <div className="filter-group">
                  <div className="label-icon">
                    <span className="icon">
                      <svg width="15" height="16" viewBox="0 0 15 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M5.64088 1.03867V14.9613M1 5.64088L5.64088 1M9.50829 1.07735V15L14.1492 10.3591" stroke="#EF7310" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                      </svg>
                    </span>
                    Price Range
                  </div>
                  <div className="price-range">
                    <input
                      type="number"
                      placeholder="Min"
                      value={filters.minBudget}
                      onChange={(e) => handlePriceRangeChange(e.target.value, filters.maxBudget)}
                    />
                    <span>to</span>
                    <input
                      type="number"
                      placeholder="Max"
                      value={filters.maxBudget}
                      onChange={(e) => handlePriceRangeChange(filters.minBudget, e.target.value)}
                    />
                  </div>
                </div>

                {/* Categories Filter */}
                <div className="filter-group">
                  <div className="label-icon">
                    <span className="icon">
                      <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <g clip-path="url(#clip0_3047_3797)">
                          <path fill-rule="evenodd" clip-rule="evenodd" d="M8.83362 4C8.83362 3.72386 9.05748 3.5 9.33362 3.5H14.667C14.9431 3.5 15.167 3.72386 15.167 4C15.167 4.27614 14.9431 4.5 14.667 4.5H9.33362C9.05748 4.5 8.83362 4.27614 8.83362 4Z" fill="#EF7310"></path>
                          <path fill-rule="evenodd" clip-rule="evenodd" d="M3.97934 0.833985H4.02123C4.47015 0.833978 4.83729 0.833971 5.13567 0.858351C5.44451 0.883585 5.72344 0.937411 5.98393 1.07014C6.39162 1.27786 6.72308 1.60932 6.93082 2.017C7.06355 2.2775 7.11735 2.55643 7.14255 2.86527C7.16695 3.16364 7.16695 3.53078 7.16695 3.97969V4.02161C7.16695 4.47052 7.16695 4.83766 7.14255 5.13603C7.11735 5.44487 7.06355 5.7238 6.93082 5.9843C6.72308 6.39198 6.39162 6.72345 5.98393 6.93118C5.72344 7.06392 5.44451 7.11772 5.13567 7.14292C4.83729 7.16732 4.47016 7.16732 4.02125 7.16732H3.97933C3.53041 7.16732 3.16328 7.16732 2.8649 7.14292C2.55606 7.11772 2.27713 7.06392 2.01664 6.93118C1.60895 6.72345 1.2775 6.39198 1.06977 5.9843C0.937045 5.7238 0.883218 5.44487 0.857985 5.13603C0.833605 4.83766 0.833612 4.47052 0.833618 4.0216V3.9797C0.833612 3.53078 0.833605 3.16365 0.857985 2.86527C0.883218 2.55643 0.937045 2.2775 1.06977 2.017C1.2775 1.60932 1.60895 1.27786 2.01664 1.07014C2.27713 0.937411 2.55606 0.883585 2.8649 0.858351C3.16329 0.833971 3.53042 0.833978 3.97934 0.833985ZM2.94634 1.85503C2.69934 1.87521 2.56666 1.91222 2.47063 1.96114C2.2511 2.073 2.07263 2.25147 1.96078 2.471C1.91185 2.56702 1.87485 2.6997 1.85467 2.9467C1.83401 3.19954 1.83362 3.52569 1.83362 4.00065C1.83362 4.47561 1.83401 4.80176 1.85467 5.0546C1.87485 5.3016 1.91185 5.43429 1.96078 5.5303C2.07263 5.74983 2.2511 5.92831 2.47063 6.04016C2.56666 6.08909 2.69934 6.12609 2.94634 6.14627C3.19917 6.16693 3.52533 6.16732 4.00029 6.16732C4.47525 6.16732 4.8014 6.16693 5.05423 6.14627C5.30123 6.12609 5.43391 6.08909 5.52994 6.04016C5.74947 5.92831 5.92794 5.74983 6.03979 5.5303C6.08872 5.43428 6.12572 5.3016 6.14591 5.0546C6.16656 4.80176 6.16695 4.47561 6.16695 4.00065C6.16695 3.52569 6.16656 3.19954 6.14591 2.9467C6.12572 2.6997 6.08872 2.56702 6.03979 2.471C5.92794 2.25147 5.74947 2.073 5.52994 1.96114C5.43392 1.91222 5.30123 1.87521 5.05423 1.85503C4.8014 1.83437 4.47525 1.83398 4.00029 1.83398C3.52533 1.83398 3.19917 1.83437 2.94634 1.85503Z" fill="#EF7310"></path>
                          <path fill-rule="evenodd" clip-rule="evenodd" d="M3.97934 8.83398H4.02123C4.47015 8.83398 4.83729 8.83398 5.13567 8.85838C5.44451 8.88358 5.72344 8.93738 5.98393 9.07012C6.39162 9.27785 6.72308 9.60932 6.93082 10.017C7.06355 10.2775 7.11735 10.5565 7.14255 10.8653C7.16695 11.1637 7.16695 11.5308 7.16695 11.9797V12.0216C7.16695 12.4705 7.16695 12.8377 7.14255 13.1361C7.11735 13.4449 7.06355 13.7238 6.93082 13.9843C6.72308 14.392 6.39162 14.7235 5.98393 14.9312C5.72344 15.0639 5.44451 15.1177 5.13567 15.1429C4.83729 15.1673 4.47016 15.1673 4.02125 15.1673H3.97933C3.53041 15.1673 3.16328 15.1673 2.8649 15.1429C2.55606 15.1177 2.27713 15.0639 2.01664 14.9312C1.60895 14.7235 1.2775 14.392 1.06977 13.9843C0.937045 13.7238 0.883218 13.4449 0.857985 13.1361C0.833605 12.8377 0.833612 12.4705 0.833618 12.0216V11.9797C0.833612 11.5308 0.833605 11.1637 0.857985 10.8653C0.883218 10.5565 0.937045 10.2775 1.06977 10.017C1.2775 9.60932 1.60895 9.27785 2.01664 9.07012C2.27713 8.93738 2.55606 8.88358 2.8649 8.85838C3.16329 8.83398 3.53042 8.83398 3.97934 8.83398ZM2.94634 9.85505C2.69934 9.87518 2.56666 9.91218 2.47063 9.96112C2.2511 10.073 2.07263 10.2515 1.96078 10.471C1.91185 10.5671 1.87485 10.6997 1.85467 10.9467C1.83401 11.1995 1.83362 11.5257 1.83362 12.0007C1.83362 12.4756 1.83401 12.8018 1.85467 13.0546C1.87485 13.3016 1.91185 13.4343 1.96078 13.5303C2.07263 13.7499 2.2511 13.9283 2.47063 14.0402C2.56666 14.0891 2.69934 14.1261 2.94634 14.1463C3.19917 14.1669 3.52533 14.1673 4.00029 14.1673C4.47525 14.1673 4.8014 14.1669 5.05423 14.1463C5.30123 14.1261 5.43391 14.0891 5.52994 14.0402C5.74947 13.9283 5.92794 13.7499 6.03979 13.5303C6.08872 13.4343 6.12572 13.3016 6.14591 13.0546C6.16656 12.8018 6.16695 12.4756 6.16695 12.0007C6.16695 11.5257 6.16656 11.1995 6.14591 10.9467C6.12572 10.6997 6.08872 10.5671 6.03979 10.471C5.92794 10.2515 5.74947 10.073 5.52994 9.96112C5.43392 9.91218 5.30123 9.87518 5.05423 9.85505C4.8014 9.83438 4.47525 9.83398 4.00029 9.83398C3.52533 9.83398 3.19917 9.83438 2.94634 9.85505Z" fill="#EF7310"></path>
                          <path fill-rule="evenodd" clip-rule="evenodd" d="M11.9794 8.83398H12.0212C12.4702 8.83398 12.8373 8.83398 13.1357 8.85838C13.4445 8.88358 13.7234 8.93738 13.984 9.07012C14.3916 9.27785 14.7231 9.60932 14.9308 10.017C15.0636 10.2775 15.1174 10.5565 15.1426 10.8653C15.167 11.1637 15.167 11.5308 15.167 11.9797V12.0216C15.167 12.4705 15.167 12.8377 15.1426 13.1361C15.1174 13.4449 15.0636 13.7238 14.9308 13.9843C14.7231 14.392 14.3916 14.7235 13.984 14.9312C13.7234 15.0639 13.4445 15.1177 13.1357 15.1429C12.8373 15.1673 12.4702 15.1673 12.0212 15.1673H11.9794C11.5304 15.1673 11.1633 15.1673 10.8649 15.1429C10.5561 15.1177 10.2772 15.0639 10.0166 14.9312C9.60895 14.7235 9.27749 14.392 9.06975 13.9843C8.93702 13.7238 8.88322 13.4449 8.85802 13.1361C8.83362 12.8377 8.83362 12.4705 8.83362 12.0216V11.9797C8.83362 11.5308 8.83362 11.1637 8.85802 10.8653C8.88322 10.5565 8.93702 10.2775 9.06975 10.017C9.27749 9.60932 9.60895 9.27785 10.0166 9.07012C10.2772 8.93738 10.5561 8.88358 10.8649 8.85838C11.1633 8.83398 11.5304 8.83398 11.9794 8.83398ZM10.9464 9.85505C10.6994 9.87518 10.5667 9.91218 10.4706 9.96112C10.2511 10.073 10.0726 10.2515 9.96075 10.471C9.91182 10.5671 9.87482 10.6997 9.85468 10.9467C9.83402 11.1995 9.83362 11.5257 9.83362 12.0007C9.83362 12.4756 9.83402 12.8018 9.85468 13.0546C9.87482 13.3016 9.91182 13.4343 9.96075 13.5303C10.0726 13.7499 10.2511 13.9283 10.4706 14.0402C10.5667 14.0891 10.6994 14.1261 10.9464 14.1463C11.1992 14.1669 11.5254 14.1673 12.0003 14.1673C12.4752 14.1673 12.8014 14.1669 13.0542 14.1463C13.3012 14.1261 13.4339 14.0891 13.53 14.0402C13.7495 13.9283 13.928 13.7499 14.0398 13.5303C14.0888 13.4343 14.1258 13.3016 14.1459 13.0546C14.1666 12.8018 14.167 12.4756 14.167 12.0007C14.167 11.5257 14.1666 11.1995 14.1459 10.9467C14.1258 10.6997 14.0888 10.5671 14.0398 10.471C13.928 10.2515 13.7495 10.073 13.53 9.96112C13.4339 9.91218 13.3012 9.87518 13.0542 9.85505C12.8014 9.83438 12.4752 9.83398 12.0003 9.83398C11.5254 9.83398 11.1992 9.83438 10.9464 9.85505Z" fill="#EF7310"></path>
                        </g>
                        <defs>
                          <clipPath id="clip0_3047_3797">
                            <rect width="16" height="16" fill="white"></rect>
                          </clipPath>
                        </defs>
                      </svg>
                    </span>
                    Categories
                  </div>
                  <div className="categoryList-outer">
                    <div className="checkbox-group" id="categoryList">
                      <ul>
                        <li>
                          <input
                            type="checkbox"
                            id="allCategories"
                            checked={selectedCategories.length === categories.length}
                            onChange={(e) => handleCategoryChange('all', e.target.checked)}
                          />
                          <label htmlFor="allCategories">All Categories</label>
                        </li>
                        {categories.slice(0, showMoreCategories ? categories.length : 4).map((category) => (
                          <li key={category.id} className={!showMoreCategories && categories.indexOf(category) >= 4 ? 'more-category' : ''}>
                            <input
                              type="checkbox"
                              id={`cat-${category.id}`}
                              className="category"
                              checked={selectedCategories.includes(category.id)}
                              onChange={(e) => handleCategoryChange(category.id, e.target.checked)}
                            />
                            <label htmlFor={`cat-${category.id}`}>
                              {category.name} ({category._count.projects})
                            </label>
                          </li>
                        ))}
                      </ul>
                    </div>
                    {categories.length > 4 && (
                      <div className="show-more" onClick={() => setShowMoreCategories(!showMoreCategories)}>
                        {showMoreCategories ? 'Show less' : 'Show more'}
                        <span>
                          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ transform: showMoreCategories ? 'rotate(180deg)' : 'none' }}>
                            <path d="M13.28 5.9668L8.9333 10.3135C8.41997 10.8268 7.57997 10.8268 7.06664 10.3135L2.71997 5.9668" stroke="#EF7310" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round" />
                          </svg>
                        </span>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>

            <div className="col-12 col-md-8 col-xl-9">
              {/* Filter Bar */}
              <div className="filter-bar">
                <div className="filter-info">
                  <div className="result-text">
                    {loading ? 'Loading...' : `${pagination.totalItems} results found`}
                  </div>

                  {/* Active Filters */}
                  {activeFilters.map((filter, index) => (
                    <div key={index} className="tag">
                      {filter}
                      <button
                        onClick={() => {
                          if (filter.includes('Search:')) clearFilter('search');
                          else if (filter.includes(`${datacounter?.currencySymbol}`)) clearFilter('price');
                          else clearFilter('category');
                        }}
                      >
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path d="M12.6668 4.27398L11.7268 3.33398L8.00016 7.06065L4.2735 3.33398L3.3335 4.27398L7.06016 8.00065L3.3335 11.7273L4.2735 12.6673L8.00016 8.94065L11.7268 12.6673L12.6668 11.7273L8.94016 8.00065L12.6668 4.27398Z" fill="#787676" />
                        </svg>
                      </button>
                    </div>
                  ))}

                  {activeFilters.length > 0 && (
                    <div className="clear-all" onClick={clearAllFilters}>Clear All</div>
                  )}
                </div>

                <div className="sort-by">
                  <select
                    id="sortSelect"
                    value={filters.sortBy}
                    onChange={(e) => handleSortChange(e.target.value)}
                  >
                    <option value="newest">Newest</option>
                    <option value="oldest">Oldest</option>
                    <option value="price_low_high">Price: Low to High</option>
                    <option value="price_high_low">Price: High to Low</option>
                  </select>
                </div>
              </div>

              {/* Project Cards */}
              
                {loading ? (
                  <div className="text-center p-4 mt-5">
                    <div className="spinner-border mt-5" role="status">
                      <span className="sr-only">Loading...</span>
                    </div>
                  </div>
                ) : error ? (
                  <div className="text-center p-4 mt-2">
                    <div className="alert alert-danger">{error}</div>
                  </div>
                ) : projects.length === 0 ? (
                  <div className="text-center p-4 mt-5">
                    <h5>No projects found</h5>
                    <p>Try adjusting your filters to see more results.</p>
                  </div>
                ) : (
                  <div className="project-card-outer">{
                    projects.map((project) => (
                      <div key={project.id} className="project-card">
                        <div>
                          <div className="work-outer">
                            <div className="work-profile">
                              <Image
                                src={project.category.icon ? `/assets/image/category/${project.category.icon}` : `/assets/image/category/cabinetmaking.svg`}
                                alt={project.category.name}
                                width={18}
                                height={18}
                              />
                              <span>{project.category.name}</span>
                            </div>
                            <div className="work-time">
                              <img src="/assets/image/timer.svg" alt="timer" />
                              <span>Work duration - {formatDuration(project.duration)}</span>
                            </div>
                          </div>
                          <div className="project-info">
                            <div className="project-title">
                              {project.title.length > 100
                                ? `${project.title.substring(0, 100)}...`
                                : project.title
                              }
                            </div>

                            <div className="project-user">
                              <div className="pu-profile d-flex align-items-center">
                                <div className="pu-img">
                                  <img src={project.client.profileImage} alt="Profile" />
                                </div>
                                <div className="pu-content">
                                  <h5>{project.client.name}</h5>
                                  <div className="d-flex align-items-center gap-1">
                                    <span className="star-icon">
                                      <svg width="13" height="12" viewBox="0 0 13 12" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M10.2062 12L6.5 9.96162L2.79241 12L3.50213 7.67959L0.5 4.62053L4.64478 3.99059L6.5 0L8.35522 3.99059L12.5 4.62053L9.49787 7.68107L10.2062 12Z" fill="#FB6107"></path>
                                      </svg>
                                    </span>
                                    {project.client.rating > 0
                                      ? `${project.client.rating} (${project.client.reviewCount}+ Reviews)`
                                      : 'No reviews yet'
                                    }
                                  </div>
                                </div>
                              </div>
                              <div className="pu-share">
                                <div className="view-bid">
                                  <img src="/assets/image/noto_fire.svg" alt="noto_fire" />
                                  {project.bidCount} Bids
                                </div>
                                <button 
                                  onClick={() => handleShareProject(project)}
                                  className="share-profile"
                                  title="Share this project"
                                >
                                  <svg width="21" height="21" viewBox="0 0 21 21" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M15.5 13.8993C14.8667 13.8993 14.3 14.1494 13.8667 14.541L7.925 11.0827C7.96667 10.891 8 10.6993 8 10.4993C8 10.2993 7.96667 10.1077 7.925 9.91602L13.8 6.49102C14.25 6.90768 14.8417 7.16602 15.5 7.16602C16.8833 7.16602 18 6.04935 18 4.66602C18 3.28268 16.8833 2.16602 15.5 2.16602C14.1167 2.16602 13 3.28268 13 4.66602C13 4.86602 13.0333 5.05768 13.075 5.24935L7.2 8.67435C6.75 8.25768 6.15833 7.99935 5.5 7.99935C4.11667 7.99935 3 9.11602 3 10.4993C3 11.8827 4.11667 12.9993 5.5 12.9993C6.15833 12.9993 6.75 12.741 7.2 12.3243L13.1333 15.791C13.0917 15.966 13.0667 16.1493 13.0667 16.3327C13.0667 17.6743 14.1583 18.766 15.5 18.766C16.8417 18.766 17.9333 17.6743 17.9333 16.3327C17.9333 14.991 16.8417 13.8993 15.5 13.8993Z" fill="#EF7310" />
                                  </svg>
                                </button>
                              </div>
                            </div>
                            <div className="project-dis" dangerouslySetInnerHTML={{
                              __html: project.description.length > 150
                                ? `${project.description.substring(0, 150)}...`
                                : project.description
                            }} />
                          </div>
                        </div>

                          <div className="project-bid-oter">
                          <div className="project-price">
                            <img src="/assets/image/wallet.svg" alt="wallet" />
                            {formatBudget(project.budget, project.country.currency)}
                          </div>
                          <div className="project-bid">
                            {shouldShowBidButton() && (
                              <button 
                                onClick={() => handleBidClick(project)}
                                className="custom-btn primary-outline"
                               // disabled={userRole === 'FREELANCER' && membershipStatus === null}
                                 //style={{ cursor: "not-allowed"}}
                              >
                                <svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                  <path d="M8.5 12H16.5" stroke="#EF7310" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                  <path d="M12.5 16V8" stroke="#EF7310" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                  <path d="M9.5 22H15.5C20.5 22 22.5 20 22.5 15V9C22.5 4 20.5 2 15.5 2H9.5C4.5 2 2.5 4 2.5 9V15C2.5 20 4.5 22 9.5 22Z" stroke="#EF7310" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                </svg>
                                {getBidButtonText()}
                              </button>
                            )}
                            <Link href={`/${locale}/projects/${project.id}`} className="custom-btn secondary-outline">
                              <svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M14.5249 6.94141L19.5832 11.9997L14.5249 17.0581" stroke="#0E9493" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round" />
                                <path d="M5.4165 12H19.4415" stroke="#0E9493" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round" />
                              </svg>
                            </Link>
                          </div>
                          </div>
                      </div>
                    ))
                  }
                  </div>
                )}

              {/* Load More */}
              {!loading && !error && pagination.hasNextPage && (
                <div className="loadmore button-group d-flex justify-content-center mt-4">
                  <button
                    className="custom-btn primary-outline"
                    onClick={handleLoadMore}
                    disabled={loading}
                  >
                    {loading ? 'Loading...' : 'Load More'}
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>

            {/* modal bid */}
              {showBidModal && (
                <div className="modal-overlay" onClick={handleCloseCancelModal}>
                  <div className="cancel-modal" onClick={(e) => e.stopPropagation()}>
                    <div className="modal-header">
                      <h3>Buy Now Category</h3>
                      <button 
                        className="btn-close"
                        onClick={handleCloseCancelModal}                      >
                        ×
                      </button>
                    </div>
                    <div className="modal-body">
                      <div className="warning-message category-warning">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" fill="#dc3545"/>
                        </svg>
                        <p>Currently, you don’t have access to this category <b>({modalCategoryName})</b>. Once you’ve purchased it, you’ll be able to place a bid.</p>
                      </div>
                    </div>
                    <div className="modal-footer">
                      <button 
                        className="custom-btn secondary-outline"
                        onClick={handleCloseCancelModal}
                      >
                        Close
                      </button>
                      <Link href={`/${locale}/freelancer/membership${modalCategorySlug}`}  className="custom-btn primary-outline">Buy Now Category</Link>
                    </div>
                  </div>
                </div>
              )}
            {/* modal bid */}

      </section>

      {/* Post Project Section */}
      <PostProjectSection locale={locale} />

      {/* Footer */}
      <Footer locale={locale} />

      <style jsx>{`
        .project-card {
          margin-bottom: 20px;
          padding: 20px;
          border: 1px solid #e0e0e0;
          border-radius: 8px;
          background: white;
        }
        
        
        .spinner-border {
          width: 3rem;
          height: 3rem;
          border: 0.25em solid currentColor;
          border-right-color: transparent;
          border-radius: 50%;
          animation: spinner-border 0.75s linear infinite;
        }
        
        @keyframes spinner-border {
          to { transform: rotate(360deg); }
        }
        
        .sr-only {
          position: absolute;
          width: 1px;
          height: 1px;
          padding: 0;
          margin: -1px;
          overflow: hidden;
          clip: rect(0, 0, 0, 0);
          white-space: nowrap;
          border: 0;
        }
        
        .alert {
          padding: 1rem;
          border: 1px solid transparent;
          border-radius: 0.375rem;
        }
        
        .alert-danger {
          color: #721c24;
          background-color: #f8d7da;
          border-color: #f5c6cb;
        }
        
        .tag {
          display: inline-flex;
          align-items: center;
          gap: 5px;
          padding: 4px 8px;
          background: #f0f0f0;
          border-radius: 4px;
          font-size: 12px;
          margin-right: 8px;
        }
        
        .tag button {
          background: none;
          border: none;
          cursor: pointer;
          padding: 0;
          display: flex;
          align-items: center;
        }
        
        .clear-all {
          color: #EF7310;
          cursor: pointer;
          font-size: 14px;
          text-decoration: underline;
        }
        
        .show-more {
          cursor: pointer;
          color: #EF7310;
          display: flex;
          align-items: center;
          gap: 5px;
          margin-top: 10px;
        }

        .show-more {
          cursor: pointer;
          color: #EF7310;
          display: flex;
          align-items: center;
          gap: 5px;
          margin-top: 10px;
        }
        
        .share-profile {
          background: none;
          border: none;
          padding: 0;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        
        .share-profile:hover {
          opacity: 0.8;
        }
      `}</style>
    </>
  );
}
