"use client";

import { Search, MapPin, Briefcase, Clock, Bookmark, ChevronDown, ArrowLeft, Filter, Check, Loader2, Building2, X } from "lucide-react";
import { useRouter, useSearchParams } from "next/navigation";
import Image from "next/image";
import Link from "next/link";
import { useState, useEffect } from "react";
import { DownloadAppCard } from "@/components/seeker/dashboard/DownloadAppCard";
import { DirectoryLinks } from "@/components/DirectoryLinks";
import { useJobs, useFilterOptions, useIndustries, useBookmarkJob } from "@/hooks/useJobs";
import { useJobFiltersStore } from "@/store/jobFilters.store";
import { useFeaturedCompanies } from "@/hooks/useCompanies";
import { formatIndianSalaryRange } from "@/utils/formatIndianSalary";
import { useCurrentUser } from "@/hooks/useCurrentUser";
import { useAuthStore } from "@/store/auth.store";

export function JobListingClient() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const typeParam = searchParams.get('type');
  const { user } = useCurrentUser();
  const { isAuthenticated } = useAuthStore();
  const bookmarkMutation = useBookmarkJob();
  const [localSavedState, setLocalSavedState] = useState<Record<number, boolean>>({});
  
  const { filters, setFilter, toggleArrayFilter, resetFilters } = useJobFiltersStore();

  useEffect(() => {
    if (typeParam === 'profile' && filters.type !== 'profile') {
      setFilter('type', 'profile');
    } else if (typeParam !== 'profile' && filters.type === 'profile') {
      setFilter('type', undefined);
    }
  }, [typeParam, filters.type, setFilter]);

  const { data: jobData, isLoading } = useJobs(user?.id);
  const { data: filterOptions } = useFilterOptions();
  const { data: industriesData } = useIndustries();
  const { data: featuredCompaniesData } = useFeaturedCompanies();
  const featuredCompanies = featuredCompaniesData?.data?.slice(0, 6) || [];

  const [isIndustryModalOpen, setIsIndustryModalOpen] = useState(false);
  const [industrySearch, setIndustrySearch] = useState("");
  const [tempSelectedIndustries, setTempSelectedIndustries] = useState<string[]>([]);

  const [isLocationModalOpen, setIsLocationModalOpen] = useState(false);
  const [locationSearch, setLocationSearch] = useState("");
  const [tempSelectedLocations, setTempSelectedLocations] = useState<string[]>([]);

  const [showAllEducation, setShowAllEducation] = useState(false);

  const [collapsedFilters, setCollapsedFilters] = useState({
    datePosted: false,
    experience: false,
    workMode: false,
    workType: false,
    workShift: false,
    salary: false,
    industry: false,
    location: false,
    education: false
  });

  const toggleFilter = (key: keyof typeof collapsedFilters) => {
    setCollapsedFilters(prev => ({ ...prev, [key]: !prev[key] }));
  };

  const jobs = jobData?.data || [];
  const total = jobData?.total || 0;
  const totalPages = jobData?.totalPages || 1;

  // Helper to create SEO friendly slug from title and ID
  const createJobSlug = (title: string, id: number) => {
    const safeTitle = title ? title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)+/g, '') : 'job';
    return `${safeTitle}-${id}`;
  };

  // Compute active filters for the chips UI
  const activeFilters: { id: string, label: string, onRemove: () => void }[] = [];

  if (filters.datePosted && filters.datePosted !== 'all') {
    const labels = { '24h': 'Last 24 hours', '3d': 'Last 3 days', '7d': 'Last 7 days' };
    activeFilters.push({
      id: 'datePosted',
      label: labels[filters.datePosted] || filters.datePosted,
      onRemove: () => setFilter('datePosted', 'all')
    });
  }

  if (filters.minExperience) {
    activeFilters.push({
      id: 'minExperience',
      label: `${filters.minExperience}+ yrs exp`,
      onRemove: () => setFilter('minExperience', 0)
    });
  }

  if (filters.minSalary) {
    activeFilters.push({
      id: 'minSalary',
      label: `₹${filters.minSalary.toLocaleString('en-IN')}+`,
      onRemove: () => setFilter('minSalary', 0)
    });
  }

  filters.workModes.forEach(mode => {
    activeFilters.push({
      id: `workMode-${mode}`,
      label: mode,
      onRemove: () => toggleArrayFilter('workModes', mode)
    });
  });

  filters.workTypes.forEach(type => {
    activeFilters.push({
      id: `workType-${type}`,
      label: type,
      onRemove: () => toggleArrayFilter('workTypes', type)
    });
  });

  filters.workShifts.forEach(shift => {
    activeFilters.push({
      id: `workShift-${shift}`,
      label: shift,
      onRemove: () => toggleArrayFilter('workShifts', shift)
    });
  });

  filters.industries.forEach(ind => {
    activeFilters.push({
      id: `industry-${ind}`,
      label: ind,
      onRemove: () => toggleArrayFilter('industries', ind)
    });
  });

  filters.locations.forEach(loc => {
    activeFilters.push({
      id: `location-${loc}`,
      label: loc,
      onRemove: () => toggleArrayFilter('locations', loc)
    });
  });

  filters.educations.forEach(edu => {
    activeFilters.push({
      id: `education-${edu}`,
      label: edu,
      onRemove: () => toggleArrayFilter('educations', edu)
    });
  });

  // Render logo based on logoType (Reused from previous components)
  const renderLogo = (type: string) => {
    switch(type) {
      case 'multi':
        return (
          <div className="w-full h-full flex flex-wrap bg-white rounded-full overflow-hidden border border-gray-100">
             <div className="w-1/2 h-1/2 bg-red-400 rounded-bl-full"></div>
             <div className="w-1/2 h-1/2 bg-green-400 rounded-br-full"></div>
             <div className="w-1/2 h-1/2 bg-blue-400 rounded-tl-full"></div>
             <div className="w-1/2 h-1/2 bg-yellow-400 rounded-tr-full"></div>
          </div>
        );
      case 'twitch':
        return <div className="w-full h-full bg-purple-600 rounded-lg text-white flex items-center justify-center font-bold text-xl">W</div>;
      case 'target':
        return (
          <div className="w-full h-full bg-pink-500 rounded-xl flex items-center justify-center">
            <div className="w-6 h-6 bg-white rounded-full flex items-center justify-center">
              <div className="w-3 h-3 bg-pink-500 rounded-full"></div>
            </div>
          </div>
        );
      case 'snap':
        return <div className="w-full h-full bg-yellow-400 rounded-xl flex items-center justify-center text-xl">👻</div>;
      case 'penguin':
        return <div className="w-full h-full bg-gray-100 rounded-xl flex items-center justify-center text-2xl">🐧</div>;
      case 'vk':
        return <div className="w-full h-full bg-blue-500 rounded-xl flex items-center justify-center text-white font-bold text-xl">K</div>;
      default:
        return <div className="w-full h-full bg-gray-200 rounded-xl"></div>;
    }
  }

  return (
    <div className="bg-[#fcfdfd] min-h-screen pb-12 font-sans">
      
      {/* Top Header section */}
      <div className="bg-white py-4 mb-6 px-4 lg:px-8 shadow-sm">
         <div className="container mx-auto max-w-7xl flex flex-col gap-1">
            <div className="flex items-center gap-3">
               <button onClick={() => router.push('/')} className="text-gray-600 hover:text-black transition-colors">
                 <ArrowLeft className="w-5 h-5" />
               </button>
               <h1 className="text-[22px] font-bold text-gray-900 tracking-tight">
                 {filters.type === 'profile' ? 'Jobs based on Your Profile'
                  : filters.locations.length === 1 ? `Jobs in ${filters.locations[0]}` 
                  : filters.industries.length === 1 ? `${filters.industries[0]} Jobs`
                  : filters.educations.length === 1 ? `Jobs for ${filters.educations[0]} Students`
                  : filters.workTypes.length === 1 ? `${filters.workTypes[0]} Jobs`
                  : "All Available Jobs"}
               </h1>
            </div>
            <p className="text-sm text-gray-500 ml-8">{total} Open Positions found</p>
         </div>
      </div>

      <div className="container mx-auto max-w-7xl px-4 lg:px-8">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
           
           {/* LEFT COLUMN: Filters */}
           <div className="hidden lg:block lg:col-span-3 sticky top-4 max-h-[calc(100vh-2rem)] overflow-y-auto">
              <div className="bg-white border border-gray-200 rounded-xl p-5 shadow-sm">
                
                {/* Filter Header */}
                <div className={`flex items-center justify-between pb-4 ${activeFilters.length === 0 ? 'border-b border-gray-100 mb-4' : 'mb-2'}`}>
                  <div className="flex items-center gap-2">
                    <Filter className="w-4 h-4 text-gray-600" />
                    <span className="font-bold text-gray-900">Filters</span>
                  </div>
                  <button onClick={resetFilters} className="text-[13px] font-bold text-[#ff6b00] hover:text-[#e66000]">Clear All</button>
                </div>

                {/* Active Filter Chips */}
                {activeFilters.length > 0 && (
                  <div className="flex flex-wrap gap-2 mb-4 pb-4 border-b border-gray-100">
                    {activeFilters.map(filter => (
                      <span key={filter.id} className="inline-flex items-center gap-1 bg-[#ff6b00]/10 text-[#ff6b00] text-[11px] font-semibold px-2 py-1 rounded-md">
                        <span className="truncate max-w-[120px]">{filter.label}</span>
                        <button onClick={filter.onRemove} className="hover:text-red-500 transition-colors ml-0.5">
                          <X className="w-3 h-3" />
                        </button>
                      </span>
                    ))}
                  </div>
                )}

                {/* Filter Groups */}
                
                {/* Date Posted */}
                <div className="mb-6">
                  <div className="flex items-center justify-between mb-3 cursor-pointer select-none" onClick={() => toggleFilter('datePosted')}>
                    <h3 className="font-bold text-gray-900 text-sm">Date posted</h3>
                    <ChevronDown className={`w-4 h-4 text-gray-500 transition-transform ${collapsedFilters.datePosted ? 'rotate-180' : ''}`} />
                  </div>
                  {!collapsedFilters.datePosted && (
                    <div className="flex flex-col gap-2.5 text-[13px] text-gray-600">
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input type="radio" name="datePosted" value="all" checked={filters.datePosted === 'all'} onChange={() => setFilter('datePosted', 'all')} className="w-4 h-4 accent-[#ff6b00] cursor-pointer flex-shrink-0" />
                        <span className="text-gray-900 font-medium">All</span>
                      </label>
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input type="radio" name="datePosted" value="24h" checked={filters.datePosted === '24h'} onChange={() => setFilter('datePosted', '24h')} className="w-4 h-4 accent-[#ff6b00] cursor-pointer flex-shrink-0" />
                        <span>Last 24 hours</span>
                      </label>
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input type="radio" name="datePosted" value="3d" checked={filters.datePosted === '3d'} onChange={() => setFilter('datePosted', '3d')} className="w-4 h-4 accent-[#ff6b00] cursor-pointer flex-shrink-0" />
                        <span>Last 3 days</span>
                      </label>
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input type="radio" name="datePosted" value="7d" checked={filters.datePosted === '7d'} onChange={() => setFilter('datePosted', '7d')} className="w-4 h-4 accent-[#ff6b00] cursor-pointer flex-shrink-0" />
                        <span>Last 7 days</span>
                      </label>
                    </div>
                  )}
                </div>
                <hr className="border-gray-100 my-5" />

                {/* Experience */}
                <div className="mb-6">
                  <div className="flex items-center justify-between mb-1 cursor-pointer select-none" onClick={() => toggleFilter('experience')}>
                    <h3 className="font-bold text-gray-900 text-sm">Experience</h3>
                    <ChevronDown className={`w-4 h-4 text-gray-500 transition-transform ${collapsedFilters.experience ? 'rotate-180' : ''}`} />
                  </div>
                  {!collapsedFilters.experience && (
                    <>
                      <p className="text-[11px] text-gray-400 mb-4">{filters.minExperience !== undefined ? `${filters.minExperience} yrs minimum` : 'Your work experience'}</p>
                      <div className="px-2 flex flex-col gap-2">
                        <input type="range" min="0" max="30" value={filters.minExperience || 0} onChange={(e) => setFilter('minExperience', parseInt(e.target.value))} className="w-full h-1.5 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-[#ff6b00]" />
                        <div className="flex justify-between text-[10px] text-gray-400 font-medium">
                          <span>0 yr</span>
                          <span>30 yrs</span>
                        </div>
                      </div>
                    </>
                  )}
                </div>
                <hr className="border-gray-100 my-5" />

                {/* Work Mode */}
                <div className="mb-6">
                  <div className="flex items-center justify-between mb-3 cursor-pointer select-none" onClick={() => toggleFilter('workMode')}>
                    <h3 className="font-bold text-gray-900 text-sm">Work mode</h3>
                    <ChevronDown className={`w-4 h-4 text-gray-500 transition-transform ${collapsedFilters.workMode ? 'rotate-180' : ''}`} />
                  </div>
                  {!collapsedFilters.workMode && (
                    <div className="flex flex-col gap-2.5 text-[13px] text-gray-600">
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input type="checkbox" checked={filters.workModes.includes('Work from home')} onChange={() => toggleArrayFilter('workModes', 'Work from home')} className="w-4 h-4 rounded border-gray-300 accent-[#ff6b00] cursor-pointer flex-shrink-0" />
                        <span>Work from home</span>
                      </label>
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input type="checkbox" checked={filters.workModes.includes('Work from office')} onChange={() => toggleArrayFilter('workModes', 'Work from office')} className="w-4 h-4 rounded border-gray-300 accent-[#ff6b00] cursor-pointer flex-shrink-0" />
                        <span>Work from office</span>
                      </label>
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input type="checkbox" checked={filters.workModes.includes('Work from field')} onChange={() => toggleArrayFilter('workModes', 'Work from field')} className="w-4 h-4 rounded border-gray-300 accent-[#ff6b00] cursor-pointer flex-shrink-0" />
                        <span>Work from field</span>
                      </label>
                    </div>
                  )}
                </div>
                <hr className="border-gray-100 my-5" />

                {/* Work Type */}
                <div className="mb-6">
                  <div className="flex items-center justify-between mb-3 cursor-pointer select-none" onClick={() => toggleFilter('workType')}>
                    <h3 className="font-bold text-gray-900 text-sm">Work type</h3>
                    <ChevronDown className={`w-4 h-4 text-gray-500 transition-transform ${collapsedFilters.workType ? 'rotate-180' : ''}`} />
                  </div>
                  {!collapsedFilters.workType && (
                    <div className="flex flex-col gap-2.5 text-[13px] text-gray-600">
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input type="checkbox" checked={filters.workTypes.includes('Full time')} onChange={() => toggleArrayFilter('workTypes', 'Full time')} className="w-4 h-4 rounded border-gray-300 accent-[#ff6b00] cursor-pointer flex-shrink-0" />
                        <span>Full time</span>
                      </label>
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input type="checkbox" checked={filters.workTypes.includes('Part time')} onChange={() => toggleArrayFilter('workTypes', 'Part time')} className="w-4 h-4 rounded border-gray-300 accent-[#ff6b00] cursor-pointer flex-shrink-0" />
                        <span>Part time</span>
                      </label>
                    </div>
                  )}
                </div>
                <hr className="border-gray-100 my-5" />

                {/* Work Shift */}
                <div className="mb-6">
                  <div className="flex items-center justify-between mb-3 cursor-pointer select-none" onClick={() => toggleFilter('workShift')}>
                    <h3 className="font-bold text-gray-900 text-sm">Work shift</h3>
                    <ChevronDown className={`w-4 h-4 text-gray-500 transition-transform ${collapsedFilters.workShift ? 'rotate-180' : ''}`} />
                  </div>
                  {!collapsedFilters.workShift && (
                    <div className="flex flex-col gap-2.5 text-[13px] text-gray-600">
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input type="checkbox" checked={filters.workShifts.includes('Night shift')} onChange={() => toggleArrayFilter('workShifts', 'Night shift')} className="w-4 h-4 rounded border-gray-300 accent-[#ff6b00] cursor-pointer flex-shrink-0" />
                        <span>Night shift</span>
                      </label>
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input type="checkbox" checked={filters.workShifts.includes('Day shift')} onChange={() => toggleArrayFilter('workShifts', 'Day shift')} className="w-4 h-4 rounded border-gray-300 accent-[#ff6b00] cursor-pointer flex-shrink-0" />
                        <span>Day shift</span>
                      </label>
                    </div>
                  )}
                </div>
                <hr className="border-gray-100 my-5" />

                {/* Salary */}
                <div className="mb-6">
                  <div className="flex items-center justify-between mb-1 cursor-pointer select-none" onClick={() => toggleFilter('salary')}>
                    <h3 className="font-bold text-gray-900 text-sm">Salary</h3>
                    <ChevronDown className={`w-4 h-4 text-gray-500 transition-transform ${collapsedFilters.salary ? 'rotate-180' : ''}`} />
                  </div>
                  {!collapsedFilters.salary && (
                    <>
                      <p className="text-[11px] text-gray-400 mb-4">{filters.minSalary ? `₹${filters.minSalary.toLocaleString('en-IN')} minimum` : 'Minimum monthly salary'}</p>
                      <div className="px-2 flex flex-col gap-2">
                        <input type="range" min="0" max="100000" step="5000" value={filters.minSalary || 0} onChange={(e) => setFilter('minSalary', parseInt(e.target.value))} className="w-full h-1.5 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-[#ff6b00]" />
                        <div className="flex justify-between text-[10px] text-gray-400 font-medium">
                          <span>0</span>
                          <span>₹1 Lakh</span>
                        </div>
                      </div>
                    </>
                  )}
                </div>
                <hr className="border-gray-100 my-5" />

                {/* Industry */}
                <div className="mb-6">
                  <div className="flex items-center justify-between mb-3 cursor-pointer select-none" onClick={() => toggleFilter('industry')}>
                    <h3 className="font-bold text-gray-900 text-sm">Industry</h3>
                    <ChevronDown className={`w-4 h-4 text-gray-500 transition-transform ${collapsedFilters.industry ? 'rotate-180' : ''}`} />
                  </div>
                  {!collapsedFilters.industry && (
                    <>
                      <div className="flex flex-col gap-2.5 text-[13px] text-gray-600 mb-2">
                        {industriesData?.data?.slice(0, 5).map((ind: any) => (
                          <label key={ind.id} className="flex items-center gap-2 cursor-pointer">
                            <input type="checkbox" checked={filters.industries.includes(ind.name)} onChange={() => toggleArrayFilter('industries', ind.name)} className="w-4 h-4 rounded border-gray-300 accent-[#ff6b00] cursor-pointer flex-shrink-0" />
                            <span className="truncate" title={ind.name}>{ind.name}</span>
                          </label>
                        ))}
                      </div>
                      {(industriesData?.data?.length || 0) > 5 && (
                        <button 
                          onClick={() => {
                            setTempSelectedIndustries(filters.industries);
                            setIndustrySearch("");
                            setIsIndustryModalOpen(true);
                          }} 
                          className="text-[12px] font-bold text-[#ff6b00] hover:underline flex self-start"
                        >
                          View More
                        </button>
                      )}
                    </>
                  )}
                </div>
                <hr className="border-gray-100 my-5" />

                {/* Location */}
                <div className="mb-6">
                  <div className="flex items-center justify-between mb-3 cursor-pointer select-none" onClick={() => toggleFilter('location')}>
                    <h3 className="font-bold text-gray-900 text-sm">Location</h3>
                    <ChevronDown className={`w-4 h-4 text-gray-500 transition-transform ${collapsedFilters.location ? 'rotate-180' : ''}`} />
                  </div>
                  {!collapsedFilters.location && (
                    <>
                      <div className="flex flex-col gap-2.5 text-[13px] text-gray-600 mb-2">
                        {filterOptions?.cities?.slice(0, 5).map((city: any) => (
                          <label key={city.id} className="flex items-center gap-2 cursor-pointer">
                            <input type="checkbox" checked={filters.locations.includes(city.name)} onChange={() => toggleArrayFilter('locations', city.name)} className="w-4 h-4 rounded border-gray-300 accent-[#ff6b00] cursor-pointer flex-shrink-0" />
                            <span className="truncate" title={city.name}>{city.name}</span>
                          </label>
                        ))}
                      </div>
                      {(filterOptions?.cities?.length || 0) > 5 && (
                        <button 
                          onClick={() => {
                            setTempSelectedLocations(filters.locations);
                            setLocationSearch("");
                            setIsLocationModalOpen(true);
                          }} 
                          className="text-[12px] font-bold text-[#ff6b00] hover:underline flex self-start"
                        >
                          View More
                        </button>
                      )}
                    </>
                  )}
                </div>
                <hr className="border-gray-100 my-5" />

                {/* Education */}
                <div className="mb-2">
                  <div className="flex items-center justify-between mb-3 cursor-pointer select-none" onClick={() => toggleFilter('education')}>
                    <h3 className="font-bold text-gray-900 text-sm">Education</h3>
                    <ChevronDown className={`w-4 h-4 text-gray-500 transition-transform ${collapsedFilters.education ? 'rotate-180' : ''}`} />
                  </div>
                  {!collapsedFilters.education && (
                    <>
                      <div className="flex flex-col gap-2.5 text-[13px] text-gray-600">
                        {filterOptions?.educationLevels?.slice(0, showAllEducation ? undefined : 5).map((edu: any) => (
                          <label key={edu.id} className="flex items-center gap-2 cursor-pointer">
                            <input type="checkbox" checked={filters.educations.includes(edu.name)} onChange={() => toggleArrayFilter('educations', edu.name)} className="w-4 h-4 rounded border-gray-300 accent-[#ff6b00] cursor-pointer flex-shrink-0" />
                            <span className="truncate" title={edu.name}>{edu.name}</span>
                          </label>
                        ))}
                      </div>
                      {filterOptions?.educationLevels?.length > 5 && (
                        <button onClick={() => setShowAllEducation(!showAllEducation)} className="text-[12px] font-bold text-[#ff6b00] hover:underline flex self-start mt-2">
                          {showAllEducation ? "View Less" : "View More"}
                        </button>
                      )}
                    </>
                  )}
                </div>

              </div>
           </div>
           
           {/* MIDDLE COLUMN: Search & Jobs */}
           <div className="lg:col-span-6 flex flex-col gap-5">
              
              {/* Search Bar */}
              <div className="bg-white border border-gray-200 rounded-xl p-2 shadow-sm flex flex-col sm:flex-row items-center gap-2">
                <div className="flex-1 flex items-center px-3 py-2 w-full">
                  <Search className="w-4 h-4 text-gray-400 mr-2 flex-shrink-0" />
                  <input 
                    type="text" 
                    value={filters.keyword}
                    onChange={(e) => setFilter('keyword', e.target.value)}
                    placeholder="Enter Skills/Role" 
                    className="w-full text-sm outline-none placeholder:text-gray-400"
                  />
                </div>
                <div className="hidden sm:block w-[1px] h-8 bg-gray-200"></div>
                <div className="flex-1 flex items-center px-3 py-2 w-full">
                  <MapPin className="w-4 h-4 text-gray-400 mr-2 flex-shrink-0" />
                  <input 
                    type="text" 
                    placeholder="Enter Location" 
                    className="w-full text-sm outline-none placeholder:text-gray-400"
                  />
                </div>
                <button className="bg-[#ff6b00] hover:bg-[#e66000] text-white px-6 py-2.5 rounded-lg text-sm font-semibold transition-colors flex-shrink-0 w-full sm:w-auto text-center mt-2 sm:mt-0">
                  Search &rarr;
                </button>
              </div>

              {/* Job Cards */}
              <div className="flex flex-col gap-4">
                {isLoading ? (
                  <div className="flex justify-center items-center py-20">
                    <Loader2 className="w-8 h-8 animate-spin text-[#ff6b00]" />
                  </div>
                ) : jobs.length === 0 ? (
                  <div className="flex justify-center items-center py-20 text-gray-500 bg-white rounded-xl border border-gray-200">
                    No jobs found matching your filters.
                  </div>
                ) : (
                  jobs.map((job: any, index: number) => (
                    <div key={job.id || job.job_id || index} onClick={() => router.push(`/job/${createJobSlug(job.title, job.id || job.job_id)}`)} className="block group cursor-pointer">
                      <div className="bg-white rounded-xl p-5 border border-gray-200 shadow-sm flex flex-col justify-between group-hover:shadow-md transition-all group-hover:border-[#ff6b00]/30">
                        
                        {/* Top row */}
                        <div className="flex justify-between items-start mb-4">
                          <div className="flex items-center gap-4">
                            <div className="w-12 h-12 flex-shrink-0 bg-gray-50 rounded-lg flex items-center justify-center overflow-hidden border border-gray-100 p-1">
                              {job.company?.logo_url ? (
                                <img src={job.company.logo_url} alt={job.company.company_name} className="w-full h-full object-contain" />
                              ) : (
                                <Building2 className="w-6 h-6 text-gray-400" />
                              )}
                            </div>
                            <div>
                              <h3 className="text-[17px] font-bold text-gray-900 leading-tight group-hover:text-[#ff6b00] transition-colors">{job.title}</h3>
                              <p 
                                className="text-sm text-gray-500 mt-0.5 hover:text-[#ff6b00] cursor-pointer inline-block transition-colors"
                                onClick={(e) => {
                                  e.preventDefault();
                                  e.stopPropagation();
                                  if (job.company?.id) router.push(`/companies/${job.company.id}`);
                                }}
                              >
                                {job.company?.company_name}
                              </p>
                            </div>
                          </div>
                          <button 
                            className={`p-1.5 rounded-md transition-colors relative z-10 -mr-1 -mt-1 ${
                              (localSavedState[Number(job.id || job.job_id)] ?? (job.is_saved == 1 || job.is_saved === true || job.has_saved == 1 || job.has_saved === true || job.is_bookmark == 1 || job.is_bookmark === true)) || (bookmarkMutation.isPending && bookmarkMutation.variables === Number(job.id || job.job_id))
                                ? 'text-[#ff6b00] bg-[#fff6f0]' 
                                : 'text-gray-400 hover:text-gray-900 hover:bg-gray-50'
                            }`} 
                            onClick={(e) => {
                              e.preventDefault();
                              e.stopPropagation();
                              if (!isAuthenticated) {
                                router.push("/?login=true");
                                return;
                              }
                              if (job.id || job.job_id) {
                                bookmarkMutation.mutate(Number(job.id || job.job_id), {
                                  onSuccess: (data) => {
                                    if (data.success !== false) {
                                      setLocalSavedState(prev => ({
                                        ...prev,
                                        [Number(job.id || job.job_id)]: true
                                      }));
                                    }
                                  }
                                });
                              }
                            }}
                            disabled={bookmarkMutation.isPending}
                            title={(localSavedState[Number(job.id || job.job_id)] ?? (job.is_saved == 1 || job.is_saved === true || job.has_saved == 1 || job.has_saved === true || job.is_bookmark == 1 || job.is_bookmark === true)) || (bookmarkMutation.isPending && bookmarkMutation.variables === Number(job.id || job.job_id)) ? "Saved" : "Save Job"}
                          >
                            <Bookmark className="w-5 h-5" fill={(localSavedState[Number(job.id || job.job_id)] ?? (job.is_saved == 1 || job.is_saved === true || job.has_saved == 1 || job.has_saved === true || job.is_bookmark == 1 || job.is_bookmark === true)) || (bookmarkMutation.isPending && bookmarkMutation.variables === Number(job.id || job.job_id)) ? 'currentColor' : 'none'} />
                          </button>
                        </div>

                        {/* Middle row details */}
                        <div className="flex flex-col sm:flex-row sm:justify-between sm:items-end gap-3 mb-4">
                          <div className="flex flex-col gap-2">
                            <div className="flex items-center gap-2 text-[12px] text-gray-500 font-medium">
                              <Briefcase className="w-3.5 h-3.5" />
                              <span>{job.experience?.name || "Entry Level"}</span>
                              <span className="text-gray-300">|</span>
                              <Clock className="w-3.5 h-3.5" />
                              <span>{job.job_type?.name || "Full Time"}</span>
                            </div>
                            <div className="flex items-center gap-2 text-[12px] text-gray-500 font-medium">
                              <MapPin className="w-3.5 h-3.5 flex-shrink-0" />
                              <span className="truncate">{[job.city, job.state, job.country].filter(Boolean).join(', ') || "Location not specified"}</span>
                            </div>
                          </div>
                          
                          <div className="flex flex-col sm:items-end gap-1.5 mt-2 sm:mt-0">
                            <div className="flex items-center gap-1.5 text-[14px] font-bold text-gray-800 mt-1">
                              <span>{formatIndianSalaryRange(job.salary_min || 0, job.salary_max || 0)}</span>
                            </div>
                            <div className="flex items-center gap-1.5 text-[11px] text-gray-500 font-medium">
                              <Clock className="w-3.5 h-3.5" />
                              <span>{new Date(job.created_at).toLocaleDateString('en-US', { day: 'numeric', month: 'short', year: 'numeric' })}</span>
                            </div>
                          </div>
                        </div>

                        {/* Bottom tags */}
                        {job.skills && job.skills.length > 0 && (
                          <div className="flex flex-wrap gap-2">
                            {job.skills.slice(0, 4).map((skill: any, index: number) => (
                              <span key={`${skill.id || skill.skill_name || 'skill'}-${index}`} className="px-3 py-1 bg-gray-50 text-gray-600 rounded-md text-[10px] font-bold">
                                {skill.skill_name}
                              </span>
                            ))}
                          </div>
                        )}
                        
                      </div>
                    </div>
                  ))
                )}
              </div>

              {/* Pagination */}
              {totalPages > 1 && (
                <div className="flex items-center justify-between mt-2 py-4 border-t border-gray-200">
                  <span className="text-sm text-gray-500">Page {filters.page} of {totalPages}</span>
                  <div className="flex items-center gap-1.5 text-sm">
                    <button 
                      onClick={() => setFilter('page', Math.max(1, filters.page - 1))}
                      disabled={filters.page === 1}
                      className="flex items-center gap-1 px-2 py-1 text-gray-400 hover:text-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      <ChevronDown className="w-4 h-4 rotate-90" />
                      Previous
                    </button>
                    
                    {Array.from({ length: totalPages }, (_, i) => i + 1)
                      .filter(p => p === 1 || p === totalPages || Math.abs(p - filters.page) <= 1)
                      .map((p, i, arr) => (
                        <div key={p} className="flex items-center">
                          {i > 0 && p - arr[i - 1] > 1 && <span className="text-gray-400 mx-1">...</span>}
                          <button 
                            onClick={() => setFilter('page', p)}
                            className={`w-7 h-7 flex items-center justify-center rounded border transition-colors ${
                              filters.page === p 
                                ? "border-[#ff6b00] bg-[#ff6b00] text-white" 
                                : "border-gray-200 text-gray-600 hover:bg-gray-50"
                            }`}
                          >
                            {p}
                          </button>
                        </div>
                      ))}
                    
                    <button 
                      onClick={() => setFilter('page', Math.min(totalPages, filters.page + 1))}
                      disabled={filters.page === totalPages}
                      className="flex items-center gap-1 px-2 py-1 font-medium text-gray-800 hover:text-black transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      Next
                      <ChevronDown className="w-4 h-4 -rotate-90" />
                    </button>
                  </div>
                </div>
              )}

           </div>

           {/* RIGHT COLUMN: Featured & Promo */}
           <div className="hidden lg:flex lg:col-span-3 flex-col gap-6 sticky top-4 max-h-[calc(100vh-2rem)] overflow-y-auto">
              
              {/* Featured Companies */}
              <div className="bg-white border border-gray-200 rounded-xl p-5 shadow-sm">
                <h3 className="font-bold text-gray-900 mb-5">Featured Companies</h3>
                <div className="grid grid-cols-3 gap-y-6 gap-x-2">
                  {featuredCompanies.map((company: any) => (
                    <Link href={`/companies/${company.id}`} key={company.id} className="flex flex-col items-center gap-2 group cursor-pointer">
                      <div className="w-12 h-12 bg-white rounded-full border border-gray-100 flex items-center justify-center overflow-hidden p-1 shadow-sm group-hover:border-[#ff6b00] group-hover:shadow-md transition-all">
                        {company.logo ? (
                          <img src={`${process.env.NEXT_PUBLIC_BACKEND_URL || 'http://localhost:4001'}/${company.logo}`} alt={company.name} className="w-full h-full object-contain rounded-full" onError={(e) => { e.currentTarget.src = 'https://ui-avatars.com/api/?name=' + encodeURIComponent(company.name) + '&background=random' }} />
                        ) : (
                          <div className="w-full h-full bg-gray-100 rounded-full flex items-center justify-center font-bold text-gray-700">
                            {company.name.charAt(0).toUpperCase()}
                          </div>
                        )}
                      </div>
                      <span className="text-[9px] text-gray-500 font-medium text-center line-clamp-2 leading-tight group-hover:text-[#ff6b00] transition-colors" title={company.name}>{company.name}</span>
                    </Link>
                  ))}
                  {featuredCompanies.length === 0 && (
                     <div className="col-span-3 text-center text-xs text-gray-400 py-4">No featured companies</div>
                  )}
                </div>
              </div>

              {/* Promo Widget */}
              <div className="h-[340px]">
                <DownloadAppCard />
              </div>

           </div>

        </div>
      </div>
      
      {/* Directory Links Footer Section */}
      <div className="bg-white border-t border-gray-100">
        <DirectoryLinks />
      </div>
      
      {/* Industry Modal */}
      {isIndustryModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm p-4">
          <div className="bg-white rounded-2xl shadow-xl w-full max-w-2xl flex flex-col max-h-[85vh]">
            
            <div className="flex items-center justify-between p-6 pb-4 border-b border-gray-100">
              <h2 className="text-xl font-bold text-gray-900">Industry</h2>
              <button onClick={() => setIsIndustryModalOpen(false)} className="text-gray-400 hover:text-gray-600 transition-colors">
                <X className="w-6 h-6" />
              </button>
            </div>

            <div className="px-6 py-4">
              <div className="flex items-center gap-2 px-3 py-2.5 border border-gray-200 rounded-lg bg-gray-50 focus-within:bg-white focus-within:border-[#ff6b00] focus-within:ring-1 focus-within:ring-[#ff6b00] transition-all">
                <Search className="w-4 h-4 text-gray-400" />
                <input 
                  type="text"
                  placeholder="Search Industry"
                  value={industrySearch}
                  onChange={(e) => setIndustrySearch(e.target.value)}
                  className="w-full bg-transparent outline-none text-sm text-gray-700 placeholder:text-gray-400"
                />
              </div>
            </div>

            <div className="px-6 py-2 overflow-y-auto flex-1 custom-scrollbar">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-4">
                {industriesData?.data
                  ?.filter((ind: any) => ind.name.toLowerCase().includes(industrySearch.toLowerCase()))
                  .map((ind: any) => (
                  <div key={ind.id} className="flex items-start gap-3">
                    <input 
                      type="checkbox"
                      id={`modal-ind-${ind.id}`}
                      checked={tempSelectedIndustries.includes(ind.name)}
                      onChange={(e) => {
                        const val = ind.name;
                        setTempSelectedIndustries(prev => 
                          e.target.checked ? [...prev, val] : prev.filter(name => name !== val)
                        );
                      }}
                      className="w-4 h-4 mt-0.5 text-[#ff6b00] rounded border-gray-300 focus:ring-[#ff6b00]"
                    />
                    <label htmlFor={`modal-ind-${ind.id}`} className="text-sm text-gray-600 cursor-pointer flex-1 leading-snug">
                      {ind.name}
                    </label>
                  </div>
                ))}
              </div>
            </div>

            <div className="p-6 pt-4 border-t border-gray-100 flex justify-end">
              <button 
                onClick={() => {
                  setFilter('industries', tempSelectedIndustries);
                  setIsIndustryModalOpen(false);
                }}
                className="bg-[#ff6b00] hover:bg-[#e66000] text-white px-8 py-2.5 rounded-lg font-medium transition-colors"
              >
                Apply
              </button>
            </div>
            
          </div>
        </div>
      )}

      {/* Location Modal */}
      {isLocationModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm p-4">
          <div className="bg-white rounded-2xl shadow-xl w-full max-w-2xl flex flex-col max-h-[85vh]">
            
            <div className="flex items-center justify-between p-6 pb-4 border-b border-gray-100">
              <h2 className="text-xl font-bold text-gray-900">Location</h2>
              <button onClick={() => setIsLocationModalOpen(false)} className="text-gray-400 hover:text-gray-600 transition-colors">
                <X className="w-6 h-6" />
              </button>
            </div>

            <div className="px-6 py-4">
              <div className="flex items-center gap-2 px-3 py-2.5 border border-gray-200 rounded-lg bg-gray-50 focus-within:bg-white focus-within:border-[#ff6b00] focus-within:ring-1 focus-within:ring-[#ff6b00] transition-all">
                <Search className="w-4 h-4 text-gray-400" />
                <input 
                  type="text"
                  placeholder="Search Location"
                  value={locationSearch}
                  onChange={(e) => setLocationSearch(e.target.value)}
                  className="w-full bg-transparent outline-none text-sm text-gray-700 placeholder:text-gray-400"
                />
              </div>
            </div>

            <div className="px-6 py-2 overflow-y-auto flex-1 custom-scrollbar">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-4">
                {filterOptions?.cities
                  ?.filter((city: any) => city.name.toLowerCase().includes(locationSearch.toLowerCase()))
                  .map((city: any) => (
                  <div key={city.id} className="flex items-start gap-3">
                    <input 
                      type="checkbox"
                      id={`modal-loc-${city.id}`}
                      checked={tempSelectedLocations.includes(city.name)}
                      onChange={(e) => {
                        const val = city.name;
                        setTempSelectedLocations(prev => 
                          e.target.checked ? [...prev, val] : prev.filter(name => name !== val)
                        );
                      }}
                      className="w-4 h-4 mt-0.5 text-[#ff6b00] rounded border-gray-300 focus:ring-[#ff6b00]"
                    />
                    <label htmlFor={`modal-loc-${city.id}`} className="text-sm text-gray-600 cursor-pointer flex-1 leading-snug">
                      {city.name}
                    </label>
                  </div>
                ))}
              </div>
            </div>

            <div className="p-6 pt-4 border-t border-gray-100 flex justify-end">
              <button 
                onClick={() => {
                  setFilter('locations', tempSelectedLocations);
                  setIsLocationModalOpen(false);
                }}
                className="bg-[#ff6b00] hover:bg-[#e66000] text-white px-8 py-2.5 rounded-lg font-medium transition-colors"
              >
                Apply
              </button>
            </div>
            
          </div>
        </div>
      )}

    </div>
  );
}
