// Job vacancies database with actual posting dates
const jobVacancies = [
  //   {
  //     id: 1,
  //     title: "Logistics Manager",
  //     department: "operations",
  //     location: "accra",
  //     type: "full-time",
  //     status: "open",
  //     postedDate: new Date("2025-07-05T11:49:37"),
  //     description:
  //       "Oversee and manage all logistics operations, ensuring efficient transportation and delivery of goods across our network. Lead a team of logistics coordinators and drivers.",
  //     responsibilities: [
  //       "Oversee daily logistics operations and transportation activities",
  //       "Manage and lead a team of logistics coordinators and drivers",
  //       "Develop and implement efficient routing and delivery schedules",
  //       "Monitor and analyze logistics performance metrics",
  //       "Ensure compliance with transportation regulations and safety standards",
  //       "Collaborate with other departments to optimize supply chain processes",
  //       "Handle logistics-related customer inquiries and resolve issues",
  //       "Manage relationships with transportation vendors and partners",
  //     ],
  //     requirements: [
  //       "Bachelor's degree in Logistics, Supply Chain Management, or related field",
  //       "Minimum 5 years experience in logistics or transportation management",
  //       "Proven leadership and team management skills",
  //       "Strong analytical and problem-solving abilities",
  //       "Excellent communication and interpersonal skills",
  //       "Knowledge of transportation regulations and compliance",
  //       "Proficiency in logistics software and Microsoft Office",
  //     ],
  //     benefits: [
  //       "Competitive salary with performance bonuses",
  //       "Comprehensive health insurance",
  //       "Professional development opportunities",
  //       "Company vehicle for work-related travel",
  //       "Paid time off and holidays",
  //       "Employee discount on shipping services",
  //       "Dynamic and supportive work environment",
  //     ],
  //     skills: ["Management", "Transportation", "Team Leadership"],
  //     icon: "ri-truck-line",
  //     color: "orange",
  //   },
  //   {
  //     id: 2,
  //     title: "Customer Support Specialist",
  //     department: "Customer Service",
  //     location: "kumasi",
  //     type: "full-time",
  //     status: "open",
  //     postedDate: new Date("2025-07-08T13:03:19"),
  //     description:
  //       "Provide exceptional customer service to our clients, handling inquiries, resolving issues, and ensuring a positive customer experience with our services.",
  //     responsibilities: [
  //       "Respond to customer inquiries via phone, email, and live chat",
  //       "Resolve customer complaints and issues efficiently",
  //       "Provide information about our services and pricing",
  //       "Process orders, forms, and applications",
  //       "Maintain customer records and update account information",
  //       "Collaborate with other departments to resolve customer issues",
  //       "Identify and escalate priority issues to management",
  //       "Collect and report customer feedback to improve services",
  //     ],
  //     requirements: [
  //       "Diploma or degree in any field",
  //       "Minimum 2 years experience in customer service",
  //       "Excellent communication and interpersonal skills",
  //       "Strong problem-solving abilities",
  //       "Patience and ability to handle difficult customers",
  //       "Basic computer skills and CRM experience",
  //       "Ability to work in a fast-paced environment",
  //     ],
  //     benefits: [
  //       "Competitive salary with monthly bonuses",
  //       "Health and dental insurance",
  //       "Paid training and development",
  //       "Opportunities for career advancement",
  //       "Employee wellness programs",
  //       "Team building activities",
  //       "Positive and supportive work culture",
  //     ],
  //     skills: ["Communication", "Problem Solving", "CRM"],
  //     icon: "ri-customer-service-2-line",
  //     color: "blue",
  //   },
  //   {
  //     id: 3,
  //     title: "Full Stack Developer",
  //     department: "IT",
  //     location: "tarkwa",
  //     type: "full-time",
  //     status: "open",
  //     postedDate: new Date("2025-05-18T11:37:11"),
  //     description:
  //       "Develop and maintain our web applications and internal systems. Work with modern technologies to improve our digital platforms and customer experience.",
  //     responsibilities: [
  //       "Develop and maintain web applications using modern JavaScript frameworks",
  //       "Design and implement RESTful APIs for internal and external use",
  //       "Collaborate with cross-functional teams to define, design, and ship new features",
  //       "Optimize applications for maximum speed and scalability",
  //       "Implement security and data protection measures",
  //       "Write clean, maintainable, and efficient code",
  //       "Troubleshoot and debug applications",
  //       "Stay updated with emerging technologies and industry trends",
  //     ],
  //     requirements: [
  //       "Bachelor's degree in Computer Science or related field",
  //       "3+ years experience in full stack development",
  //       "Proficiency in JavaScript, React, Node.js, and Express",
  //       "Experience with databases (SQL and NoSQL)",
  //       "Familiarity with cloud platforms (AWS, Azure, or GCP)",
  //       "Understanding of CI/CD pipelines",
  //       "Strong problem-solving skills",
  //       "Excellent collaboration and communication abilities",
  //     ],
  //     benefits: [
  //       "Competitive salary with performance bonuses",
  //       "Flexible remote work options",
  //       "Latest technology equipment",
  //       "Professional development budget",
  //       "Health and wellness benefits",
  //       "Generous vacation policy",
  //       "Opportunity to work on impactful projects",
  //     ],
  //     skills: ["JavaScript", "React", "Node.js", "API"],
  //     icon: "ri-code-line",
  //     color: "purple",
  //   },
  //   {
  //     id: 4,
  //     title: "Administrative Officer",
  //     department: "administration",
  //     location: "accra",
  //     type: "full-time",
  //     status: "filled",
  //     postedDate: new Date("2025-02-08T10:43:47"),
  //     description:
  //       "Provide comprehensive administrative support to ensure efficient office operations. Manage documentation, coordinate schedules, and serve as the organizational hub for our Accra headquarters.",
  //     responsibilities: [
  //       "Manage day-to-day office operations and administrative systems",
  //       "Handle correspondence, filing, and document control",
  //       "Coordinate meetings, schedules, and travel arrangements",
  //       "Maintain office supplies and equipment inventory",
  //       "Serve as first point of contact for visitors and calls",
  //       "Prepare reports, presentations, and meeting minutes",
  //       "Assist with HR and finance documentation as needed",
  //       "Support event planning and company initiatives",
  //       "Implement and improve administrative processes",
  //     ],
  //     requirements: [
  //       "Bachelor's degree in Business Administration or related field",
  //       "2+ years experience in office administration",
  //       "Proficiency in MS Office (Word, Excel, PowerPoint, Outlook)",
  //       "Excellent written and verbal communication skills",
  //       "Strong organizational and time-management abilities",
  //       "Attention to detail and problem-solving skills",
  //       "Ability to multitask and prioritize effectively",
  //       "Professional demeanor and customer service orientation",
  //     ],
  //     benefits: [
  //       "Competitive salary with annual reviews",
  //       "Comprehensive health insurance package",
  //       "Professional development opportunities",
  //       "Modern office environment",
  //       "Paid time off and holidays",
  //       "Team building activities",
  //       "Opportunity to grow within the organization",
  //     ],
  //     skills: [
  //       "Office Management",
  //       "Document Control",
  //       "Communication",
  //       "MS Office",
  //     ],
  //     icon: "ri-file-copy-2-line",
  //     color: "blue",
  //   },
  //   {
  //     id: 5,
  //     title: "Finance Officer",
  //     department: "finance",
  //     location: "accra",
  //     type: "full-time",
  //     status: "open",
  //     postedDate: new Date("2025-06-28T08:10:19"),
  //     description:
  //       "Manage financial operations including accounts, reporting, and budgeting to support our growing logistics business. Ensure compliance with financial regulations and maintain accurate records.",
  //     responsibilities: [
  //       "Maintain accurate accounting records and financial statements",
  //       "Process accounts payable/receivable and reconcile transactions",
  //       "Prepare monthly, quarterly and annual financial reports",
  //       "Assist with budget preparation and expenditure monitoring",
  //       "Ensure compliance with tax regulations and filing requirements",
  //       "Support audit processes and maintain proper documentation",
  //       "Analyze financial data to identify cost-saving opportunities",
  //       "Implement and improve financial controls and processes",
  //       "Collaborate with departments on financial matters",
  //     ],
  //     requirements: [
  //       "Bachelor's degree in Accounting, Finance or related field",
  //       "Professional qualification (ICA, ACCA, CIMA) or in progress",
  //       "3+ years experience in accounting/finance role",
  //       "Proficiency in accounting software (QuickBooks, Sage, etc.)",
  //       "Strong knowledge of accounting standards and tax laws",
  //       "Advanced Excel skills for financial analysis",
  //       "Excellent attention to detail and analytical skills",
  //       "Ability to meet tight deadlines and work under pressure",
  //     ],
  //     benefits: [
  //       "Competitive salary with performance bonuses",
  //       "Comprehensive health and retirement benefits",
  //       "Support for professional certification",
  //       "Modern financial systems and tools",
  //       "Opportunities for career advancement",
  //       "Collaborative team environment",
  //       "Continuous training and development",
  //     ],
  //     skills: [
  //       "Financial Reporting",
  //       "Budget Management",
  //       "QuickBooks",
  //       "Tax Compliance",
  //     ],
  //     icon: "ri-bank-card-line",
  //     color: "green",
  //   },
  //   {
  //     id: 6,
  //     title: "Digital Marketing Specialist",
  //     department: "marketing",
  //     location: "accra",
  //     type: "full-time",
  //     status: "open",
  //     postedDate: new Date("2025-01-08T16:13:07"),
  //     description:
  //       "Develop and implement digital marketing strategies to enhance our online presence, engage customers, and drive business growth through various digital channels.",
  //     responsibilities: [
  //       "Develop and implement digital marketing strategies",
  //       "Manage and optimize paid advertising campaigns (Google Ads, social media ads)",
  //       "Create and schedule engaging content for social media platforms",
  //       "Optimize website content for SEO and lead generation",
  //       "Analyze campaign performance and adjust strategies accordingly",
  //       "Manage email marketing campaigns and automation",
  //       "Collaborate with designers and content creators",
  //       "Monitor industry trends and competitor activities",
  //       "Report on key metrics and ROI of digital initiatives",
  //     ],
  //     requirements: [
  //       "Bachelor's degree in Marketing, Communications, or related field",
  //       "2+ years experience in digital marketing",
  //       "Proficiency in Google Analytics, Ads, and SEO tools",
  //       "Experience with social media management and advertising",
  //       "Strong analytical and reporting skills",
  //       "Excellent written and verbal communication",
  //       "Creative thinking and problem-solving abilities",
  //       "Ability to work independently and in a team",
  //     ],
  //     benefits: [
  //       "Competitive salary with performance bonuses",
  //       "Flexible work arrangements",
  //       "Professional development opportunities",
  //       "Creative and collaborative work environment",
  //       "Health and wellness benefits",
  //       "Latest marketing tools and software",
  //       "Opportunity to shape brand's digital presence",
  //     ],
  //     skills: ["SEO", "Social Media", "Content Marketing", "Google Ads"],
  //     icon: "ri-megaphone-line",
  //     color: "yellow",
  //   },
  //   {
  //     id: 7,
  //     title: "HR Coordinator",
  //     department: "HR",
  //     location: "accra",
  //     type: "full-time",
  //     status: "closed",
  //     postedDate: new Date("2025-07-02T09:03:17"),
  //     description:
  //       "Support HR operations including recruitment, employee relations, and HR administration to ensure smooth human resources processes within the company.",
  //     responsibilities: [
  //       "Assist with full-cycle recruitment processes",
  //       "Coordinate interviews and candidate communications",
  //       "Conduct new employee onboarding and orientation",
  //       "Maintain employee records and HR documentation",
  //       "Assist with payroll preparation and benefits administration",
  //       "Support employee relations and engagement initiatives",
  //       "Help organize training and development programs",
  //       "Respond to employee inquiries about HR policies",
  //       "Assist with HR projects and process improvements",
  //     ],
  //     requirements: [
  //       "Bachelor's degree in Human Resources or related field",
  //       "2+ years experience in HR or administrative role",
  //       "Knowledge of HR practices and labor laws",
  //       "Excellent organizational and time management skills",
  //       "Strong interpersonal and communication abilities",
  //       "Discretion and ability to handle confidential information",
  //       "Proficiency in MS Office and HR software",
  //       "Positive attitude and team player mentality",
  //     ],
  //     benefits: [
  //       "Competitive salary with benefits",
  //       "Professional HR certification support",
  //       "Opportunities for career growth in HR",
  //       "Positive and inclusive work environment",
  //       "Health and wellness programs",
  //       "Employee recognition initiatives",
  //       "Regular team building activities",
  //     ],
  //     skills: ["Recruitment", "Employee Relations", "HR Administration"],
  //     icon: "ri-team-line",
  //     color: "pink",
  //   },
  //   {
  //     id: 8,
  //     title: "Delivery Driver",
  //     department: "operations",
  //     location: "accra",
  //     type: "full-time",
  //     status: "open",
  //     postedDate: new Date("2025-05-12T13:23:26"),
  //     description:
  //       "Safely operate company vehicles to deliver packages to customers across Accra and nearby regions. Maintain vehicle condition and ensure timely, professional deliveries.",
  //     responsibilities: [
  //       "Safely operate company vehicles for package deliveries",
  //       "Follow planned delivery routes efficiently",
  //       "Inspect vehicle before and after each shift",
  //       "Maintain accurate delivery records and documentation",
  //       "Provide professional customer service during deliveries",
  //       "Report any vehicle issues or accidents immediately",
  //       "Adhere to all traffic and safety regulations",
  //       "Handle packages with care to prevent damage",
  //       "Communicate effectively with dispatch team",
  //     ],
  //     requirements: [
  //       "Valid driver's license (Class C minimum)",
  //       "Clean driving record with no major violations",
  //       "Minimum 2 years professional driving experience",
  //       "Good knowledge of Accra and surrounding areas",
  //       "Ability to lift up to 25kg packages",
  //       "Excellent time management skills",
  //       "Basic vehicle maintenance knowledge",
  //       "Professional demeanor and customer service skills",
  //     ],
  //     benefits: [
  //       "Competitive hourly wages + performance bonuses",
  //       "Company-provided vehicle and fuel",
  //       "Comprehensive insurance coverage",
  //       "Paid training and safety certifications",
  //       "Uniforms and protective gear provided",
  //       "Opportunities for career advancement",
  //       "Supportive team environment",
  //     ],
  //     skills: [
  //       "Safe Driving",
  //       "Route Planning",
  //       "Vehicle Maintenance",
  //       "Customer Service",
  //     ],
  //     icon: "ri-truck-line",
  //     color: "orange",
  //   },
  //   {
  //     id: 9,
  //     title: "Operations Supervisor",
  //     department: "operations",
  //     location: "kumasi",
  //     type: "full-time",
  //     status: "open",
  //     postedDate: new Date("2025-04-08T11:24:07"),
  //     description:
  //       "Supervise daily operations at our Kumasi facility, ensuring efficient workflow, quality service, and adherence to company policies and procedures.",
  //     responsibilities: [
  //       "Supervise and coordinate daily operations activities",
  //       "Monitor workflow and adjust schedules as needed",
  //       "Train and mentor operations staff",
  //       "Ensure compliance with safety and operational procedures",
  //       "Resolve operational issues and customer complaints",
  //       "Maintain accurate records and reports",
  //       "Collaborate with other departments to improve processes",
  //       "Implement efficiency improvements and cost-saving measures",
  //     ],
  //     requirements: [
  //       "Bachelor's degree in Business Administration or related field",
  //       "3+ years experience in operations or logistics supervision",
  //       "Strong leadership and team management skills",
  //       "Excellent problem-solving and decision-making abilities",
  //       "Knowledge of logistics and supply chain processes",
  //       "Ability to work in a fast-paced environment",
  //       "Proficiency in Microsoft Office and operations software",
  //     ],
  //     benefits: [
  //       "Competitive salary with performance bonuses",
  //       "Health and dental insurance",
  //       "Retirement savings plan",
  //       "Paid time off and holidays",
  //       "Professional development opportunities",
  //       "Employee assistance program",
  //       "Positive work environment",
  //     ],
  //     skills: ["Supervision", "Operations", "Team Leadership", "Logistics"],
  //     icon: "ri-settings-3-line",
  //     color: "blue",
  //   },
  //   {
  //     id: 10,
  //     title: "IT Support Specialist",
  //     department: "IT",
  //     location: "accra",
  //     type: "full-time",
  //     status: "open",
  //     postedDate: new Date("2025-02-08T16:33:17"),
  //     description:
  //       "Provide technical support to our staff, troubleshoot hardware and software issues, and maintain our IT infrastructure to ensure smooth business operations.",
  //     responsibilities: [
  //       "Provide technical support to end-users",
  //       "Troubleshoot hardware, software, and network issues",
  //       "Install and configure computer systems and applications",
  //       "Maintain IT equipment and inventory",
  //       "Assist with IT projects and system upgrades",
  //       "Train staff on software and hardware usage",
  //       "Document technical procedures and solutions",
  //       "Ensure security and privacy of networks and computer systems",
  //     ],
  //     requirements: [
  //       "Bachelor's degree in Computer Science or related field",
  //       "2+ years experience in IT support role",
  //       "Knowledge of computer systems, networks, and troubleshooting",
  //       "Experience with Windows and macOS environments",
  //       "Familiarity with help desk software and remote support tools",
  //       "Excellent problem-solving and communication skills",
  //       "Customer service orientation and patience",
  //     ],
  //     benefits: [
  //       "Competitive salary with benefits",
  //       "Health and wellness programs",
  //       "Professional certification support",
  //       "Flexible work arrangements",
  //       "Latest technology tools",
  //       "Collaborative team environment",
  //       "Opportunities for career growth",
  //     ],
  //     skills: [
  //       "Technical Support",
  //       "Troubleshooting",
  //       "Hardware",
  //       "Software",
  //       "Networking",
  //     ],
  //     icon: "ri-computer-line",
  //     color: "purple",
  //   },
  //   {
  //     id: 11,
  //     title: "Marketing Coordinator",
  //     department: "marketing",
  //     location: "accra",
  //     type: "full-time",
  //     status: "open",
  //     postedDate: new Date("2025-05-08T06:40:20"),
  //     description:
  //       "Support marketing initiatives, coordinate campaigns, and assist with content creation to promote our services and enhance brand awareness.",
  //     responsibilities: [
  //       "Assist in developing and implementing marketing strategies",
  //       "Coordinate marketing campaigns and promotional activities",
  //       "Create content for social media, website, and email marketing",
  //       "Monitor and report on campaign performance metrics",
  //       "Assist with event planning and execution",
  //       "Maintain marketing materials and collateral",
  //       "Conduct market research and competitor analysis",
  //       "Support sales team with marketing materials and tools",
  //     ],
  //     requirements: [
  //       "Bachelor's degree in Marketing, Communications, or related field",
  //       "1-2 years experience in marketing or related role",
  //       "Strong written and verbal communication skills",
  //       "Familiarity with social media platforms and digital marketing",
  //       "Basic graphic design skills (Canva, Adobe Creative Suite)",
  //       "Organizational and project management skills",
  //       "Creative thinking and problem-solving abilities",
  //     ],
  //     benefits: [
  //       "Competitive salary with performance bonuses",
  //       "Health and wellness benefits",
  //       "Professional development opportunities",
  //       "Creative and dynamic work environment",
  //       "Opportunity to work on diverse projects",
  //       "Team building activities",
  //       "Flexible work arrangements",
  //     ],
  //     skills: [
  //       "Marketing",
  //       "Content Creation",
  //       "Social Media",
  //       "Campaign Management",
  //     ],
  //     icon: "ri-megaphone-line",
  //     color: "yellow",
  //   },
  //   {
  //     id: 12,
  //     title: "Warehouse Associate",
  //     department: "operations",
  //     location: "tema",
  //     type: "full-time",
  //     status: "open",
  //     postedDate: new Date("2025-07-01T12:00:17"),
  //     description:
  //       "Perform warehouse operations including receiving, storing, picking, packing, and shipping goods while maintaining accurate inventory records.",
  //     responsibilities: [
  //       "Receive, inspect, and store incoming goods",
  //       "Pick, pack, and prepare orders for shipment",
  //       "Operate warehouse equipment (forklifts, pallet jacks, etc.)",
  //       "Maintain accurate inventory records",
  //       "Perform regular inventory counts and audits",
  //       "Ensure warehouse cleanliness and organization",
  //       "Follow safety procedures and guidelines",
  //       "Assist with loading and unloading trucks",
  //     ],
  //     requirements: [
  //       "High school diploma or equivalent",
  //       "1+ years warehouse experience preferred",
  //       "Ability to lift up to 50 pounds",
  //       "Basic computer skills for inventory tracking",
  //       "Attention to detail and accuracy",
  //       "Ability to work in a fast-paced environment",
  //       "Forklift certification is a plus",
  //     ],
  //     benefits: [
  //       "Competitive hourly wages",
  //       "Overtime opportunities",
  //       "Health insurance options",
  //       "Paid time off",
  //       "Safety training and certifications",
  //       "Opportunities for advancement",
  //       "Team-oriented work environment",
  //     ],
  //     skills: [
  //       "Warehouse Operations",
  //       "Inventory Management",
  //       "Forklift Operation",
  //       "Shipping/Receiving",
  //     ],
  //     icon: "ri-store-2-line",
  //     color: "orange",
  //   },
];

// Function to calculate days since posting with improved "Today" handling
function getDaysSincePosted(postedDate) {
  const today = new Date();
  const posted = new Date(postedDate);

  // Reset both dates to midnight for accurate day comparison
  today.setHours(0, 0, 0, 0);
  posted.setHours(0, 0, 0, 0);

  const diffTime = Math.abs(today - posted);
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));

  if (diffDays === 0) return "Today";
  if (diffDays === 1) return "1 day ago";
  if (diffDays < 7) return `${diffDays} days ago`;

  const diffWeeks = Math.floor(diffDays / 7);
  if (diffWeeks === 1) return "1 week ago";
  return `${diffWeeks} weeks ago`;
}

// Initialize AOS animation library
AOS.init({
  duration: 800,
  easing: "ease-in-out",
  once: false,
  mirror: true,
});

// Mobile menu toggle
const mobileMenuButton = document.getElementById("mobile-menu-button");
const mobileMenu = document.getElementById("mobile-menu");

if (mobileMenuButton && mobileMenu) {
  mobileMenuButton.addEventListener("click", () => {
    mobileMenu.classList.toggle("hidden");
  });
}

// Helper function to escape HTML attributes
function escapeHtmlAttribute(str) {
  return str.replace(/"/g, "&quot;").replace(/\n/g, "\\n");
}

// Pagination variables
let currentPage = 1;
const jobsPerPage = 6;
let filteredJobs = [...jobVacancies];

// Render job listings from database with pagination
function renderJobListings(jobs, page = 1) {
  const jobListings = document.getElementById("job-listings");
  jobListings.innerHTML = "";

  if (jobs.length === 0) {
    document.getElementById("no-jobs-message").classList.remove("hidden");
    document.getElementById("pagination-container").innerHTML = "";
    return;
  } else {
    document.getElementById("no-jobs-message").classList.add("hidden");
  }

  // Calculate pagination
  const totalPages = Math.ceil(jobs.length / jobsPerPage);
  const startIndex = (page - 1) * jobsPerPage;
  const endIndex = Math.min(startIndex + jobsPerPage, jobs.length);
  const paginatedJobs = jobs.slice(startIndex, endIndex);

  // Render jobs for current page
  paginatedJobs.forEach((job, index) => {
    const jobCard = document.createElement("div");
    jobCard.className = `job-card bg-white rounded-xl shadow-md overflow-hidden fade-in`;
    jobCard.setAttribute("data-aos", "fade-up");
    jobCard.setAttribute("data-aos-delay", `${100 + index * 100}`);
    jobCard.setAttribute("data-department", job.department);
    jobCard.setAttribute("data-location", job.location);
    jobCard.setAttribute("data-status", job.status);

    // Determine status badge
    let statusBadge = "";
    if (job.status === "open") {
      statusBadge = '<span class="status-badge status-open">Open</span>';
    } else if (job.status === "filled") {
      statusBadge = '<span class="status-badge status-filled">Filled</span>';
    } else {
      statusBadge = '<span class="status-badge status-closed">Closed</span>';
    }

    // Calculate days since posting
    const daysSincePosted = getDaysSincePosted(job.postedDate);

    // Create job card HTML with proper escaping
    jobCard.innerHTML = `
      <div class="p-6">
        <div class="flex justify-between items-start mb-4">
          <div>
            <span class="inline-block px-3 py-1 bg-${job.color}-100 text-${
      job.color
    }-800 text-xs font-semibold rounded-full mb-2 job-tag">
              ${
                job.department.charAt(0).toUpperCase() + job.department.slice(1)
              }
            </span>
            <h3 class="text-xl font-bold text-gray-900 mb-1">${job.title}</h3>
            <div class="flex items-center text-gray-600 text-sm">
              <i class="ri-map-pin-line mr-1"></i>
              <span>${
                job.location.charAt(0).toUpperCase() + job.location.slice(1)
              }</span>
              <span class="mx-2">•</span>
              <span>${
                job.type === "full-time"
                  ? "Full-time"
                  : job.type === "part-time"
                  ? "Part-time"
                  : "Contract"
              }</span>
              <span class="mx-2">•</span>
              ${statusBadge}
            </div>
          </div>
          <div class="w-12 h-12 bg-${
            job.color
          }-100 rounded-full flex items-center justify-center">
            <i class="${job.icon} text-${job.color}-800 text-xl"></i>
          </div>
        </div>
        <p class="text-gray-600 mb-4 line-clamp-3">${job.description}</p>
        <div class="flex flex-wrap gap-2 mb-4">
          ${job.skills
            .map(
              (skill) =>
                `<span class="px-2 py-1 bg-gray-100 text-gray-800 text-xs rounded-full">${skill}</span>`
            )
            .join("")}
        </div>
        <div class="flex justify-between items-center">
          <span class="text-sm text-gray-500">Posted ${daysSincePosted}</span>
          <button
            class="apply-btn px-4 py-2 border border-${job.color}-500 text-${
      job.color
    }-500 rounded-lg font-medium hover:bg-${
      job.color
    }-500 hover:text-white transition-colors ${
      job.status !== "open" ? "opacity-50 cursor-not-allowed" : ""
    }"
            ${job.status !== "open" ? "disabled" : ""}
            data-job-title="${escapeHtmlAttribute(job.title)}"
            data-job-department="${escapeHtmlAttribute(job.department)}"
            data-job-location="${escapeHtmlAttribute(
              job.location.charAt(0).toUpperCase() + job.location.slice(1)
            )}"
            data-job-type="${escapeHtmlAttribute(job.type)}"
            data-job-description="${escapeHtmlAttribute(job.description)}"
            data-job-responsibilities="${escapeHtmlAttribute(
              JSON.stringify(job.responsibilities)
            )}"
            data-job-requirements="${escapeHtmlAttribute(
              JSON.stringify(job.requirements)
            )}"
            data-job-benefits="${escapeHtmlAttribute(
              JSON.stringify(job.benefits)
            )}"
          >
            ${
              job.status === "open"
                ? "Apply Now"
                : job.status === "filled"
                ? "Position Filled"
                : "Closed"
            }
          </button>
        </div>
      </div>
    `;

    jobListings.appendChild(jobCard);
  });

  // Render pagination buttons
  renderPagination(jobs.length, page);

  // Add event listener for apply buttons
  document.querySelectorAll(".apply-btn").forEach((button) => {
    button.addEventListener("click", function () {
      if (this.disabled) return;

      openJobModal(
        this.dataset.jobTitle,
        this.dataset.jobDepartment,
        this.dataset.jobLocation,
        this.dataset.jobType,
        this.dataset.jobDescription,
        this.dataset.jobResponsibilities,
        this.dataset.jobRequirements,
        this.dataset.jobBenefits
      );
    });
  });
}

// Render pagination buttons
function renderPagination(totalJobs, currentPage) {
  const totalPages = Math.ceil(totalJobs / jobsPerPage);
  const paginationContainer = document.getElementById("pagination-container");
  paginationContainer.innerHTML = "";

  if (totalPages <= 1) return;

  // Previous button
  const prevButton = document.createElement("button");
  prevButton.className = `pagination-btn rounded-l-md ${
    currentPage === 1 ? "disabled" : ""
  }`;
  prevButton.innerHTML = '<i class="ri-arrow-left-s-line"></i>';
  prevButton.addEventListener("click", () => {
    if (currentPage > 1) {
      currentPage--;
      renderJobListings(filteredJobs, currentPage);
      window.scrollTo({
        top: document.getElementById("current-openings").offsetTop - 100,
        behavior: "smooth",
      });
    }
  });
  paginationContainer.appendChild(prevButton);

  // Page buttons
  const maxVisiblePages = 5;
  let startPage, endPage;

  if (totalPages <= maxVisiblePages) {
    startPage = 1;
    endPage = totalPages;
  } else {
    const maxPagesBeforeCurrent = Math.floor(maxVisiblePages / 2);
    const maxPagesAfterCurrent = Math.ceil(maxVisiblePages / 2) - 1;

    if (currentPage <= maxPagesBeforeCurrent) {
      startPage = 1;
      endPage = maxVisiblePages;
    } else if (currentPage + maxPagesAfterCurrent >= totalPages) {
      startPage = totalPages - maxVisiblePages + 1;
      endPage = totalPages;
    } else {
      startPage = currentPage - maxPagesBeforeCurrent;
      endPage = currentPage + maxPagesAfterCurrent;
    }
  }

  // Add first page button if needed
  if (startPage > 1) {
    const firstButton = document.createElement("button");
    firstButton.className = `pagination-btn ${
      currentPage === 1 ? "active" : ""
    }`;
    firstButton.textContent = "1";
    firstButton.addEventListener("click", () => {
      currentPage = 1;
      renderJobListings(filteredJobs, currentPage);
      window.scrollTo({
        top: document.getElementById("current-openings").offsetTop - 100,
        behavior: "smooth",
      });
    });
    paginationContainer.appendChild(firstButton);

    if (startPage > 2) {
      const ellipsis = document.createElement("span");
      ellipsis.className = "px-3 py-2";
      ellipsis.textContent = "...";
      paginationContainer.appendChild(ellipsis);
    }
  }

  // Add page buttons
  for (let i = startPage; i <= endPage; i++) {
    const pageButton = document.createElement("button");
    pageButton.className = `pagination-btn ${
      currentPage === i ? "active" : ""
    }`;
    pageButton.textContent = i;
    pageButton.addEventListener("click", () => {
      currentPage = i;
      renderJobListings(filteredJobs, currentPage);
      window.scrollTo({
        top: document.getElementById("current-openings").offsetTop - 100,
        behavior: "smooth",
      });
    });
    paginationContainer.appendChild(pageButton);
  }

  // Add last page button if needed
  if (endPage < totalPages) {
    if (endPage < totalPages - 1) {
      const ellipsis = document.createElement("span");
      ellipsis.className = "px-3 py-2";
      ellipsis.textContent = "...";
      paginationContainer.appendChild(ellipsis);
    }

    const lastButton = document.createElement("button");
    lastButton.className = `pagination-btn ${
      currentPage === totalPages ? "active" : ""
    }`;
    lastButton.textContent = totalPages;
    lastButton.addEventListener("click", () => {
      currentPage = totalPages;
      renderJobListings(filteredJobs, currentPage);
      window.scrollTo({
        top: document.getElementById("current-openings").offsetTop - 100,
        behavior: "smooth",
      });
    });
    paginationContainer.appendChild(lastButton);
  }

  // Next button
  const nextButton = document.createElement("button");
  nextButton.className = `pagination-btn rounded-r-md ${
    currentPage === totalPages ? "disabled" : ""
  }`;
  nextButton.innerHTML = '<i class="ri-arrow-right-s-line"></i>';
  nextButton.addEventListener("click", () => {
    if (currentPage < totalPages) {
      currentPage++;
      renderJobListings(filteredJobs, currentPage);
      window.scrollTo({
        top: document.getElementById("current-openings").offsetTop - 100,
        behavior: "smooth",
      });
    }
  });
  paginationContainer.appendChild(nextButton);
}

// Initial render of all jobs
renderJobListings(jobVacancies);

// Job search and filter functionality
const jobSearch = document.getElementById("job-search");
const jobDepartment = document.getElementById("job-department");
const jobLocation = document.getElementById("job-location");
const jobStatus = document.getElementById("job-status");

function filterJobs() {
  const searchTerm = jobSearch.value.toLowerCase();
  const departmentFilter = jobDepartment.value;
  const locationFilter = jobLocation.value;
  const statusFilter = jobStatus.value;

  filteredJobs = jobVacancies.filter((job) => {
    const matchesSearch =
      job.title.toLowerCase().includes(searchTerm) ||
      job.description.toLowerCase().includes(searchTerm) ||
      job.skills.some((skill) => skill.toLowerCase().includes(searchTerm));
    const matchesDepartment =
      !departmentFilter || job.department === departmentFilter;
    const matchesLocation = !locationFilter || job.location === locationFilter;
    const matchesStatus = !statusFilter || job.status === statusFilter;

    return (
      matchesSearch && matchesDepartment && matchesLocation && matchesStatus
    );
  });

  currentPage = 1; // Reset to first page when filters change
  renderJobListings(filteredJobs);
}

function resetJobFilters() {
  jobSearch.value = "";
  jobDepartment.value = "";
  jobLocation.value = "";
  jobStatus.value = "";
  filteredJobs = [...jobVacancies];
  currentPage = 1;
  renderJobListings(filteredJobs);
}

jobSearch.addEventListener("input", filterJobs);
jobDepartment.addEventListener("change", filterJobs);
jobLocation.addEventListener("change", filterJobs);
jobStatus.addEventListener("change", filterJobs);

// Job modal functionality
function openJobModal(
  title,
  department,
  location,
  type,
  description,
  responsibilities,
  requirements,
  benefits
) {
  const modal = document.getElementById("job-modal");
  const jobTitle = document.getElementById("modal-job-title");
  const jobDept = document.getElementById("modal-job-department");
  const jobLoc = document.getElementById("modal-job-location");
  const jobType = document.getElementById("modal-job-type");
  const jobDesc = document.getElementById("modal-job-description");
  const jobResp = document.getElementById("modal-job-responsibilities");
  const jobReq = document.getElementById("modal-job-requirements");
  const jobBenefits = document.getElementById("modal-job-benefits");
  const appliedPosition = document.getElementById("applied-position");
  const modalContent = document.querySelector(".modal-content-container");

  // Reset form fields when opening a new job modal
  document.getElementById("job-application-form").reset();
  document.getElementById("resume-name").classList.add("hidden");
  document.getElementById("cover-name").classList.add("hidden");
  document.getElementById("email-preview-container").classList.add("hidden");

  // Clear file inputs
  document.getElementById("resume-upload").value = "";
  document.getElementById("cover-upload").value = "";

  // Reset scroll position to top
  modalContent.scrollTop = 0;

  // Set job details
  jobTitle.textContent = title;
  jobDept.textContent =
    department.charAt(0).toUpperCase() + department.slice(1);
  jobLoc.textContent = location;
  jobType.textContent =
    type === "full-time"
      ? "Full-time"
      : type === "part-time"
      ? "Part-time"
      : "Contract";
  jobDesc.textContent = description;
  appliedPosition.value = title;

  // Clear existing content
  jobResp.innerHTML = "";
  jobReq.innerHTML = "";
  jobBenefits.innerHTML = "";

  // Function to create list items
  function populateList(container, items) {
    try {
      // Parse the JSON string if it's a string
      const itemsArray = typeof items === "string" ? JSON.parse(items) : items;

      itemsArray.forEach((item) => {
        const li = document.createElement("li");
        li.textContent = item;
        container.appendChild(li);
      });
    } catch (e) {
      console.error("Error parsing items:", e);
    }
  }

  // Populate all sections
  populateList(jobResp, responsibilities);
  populateList(jobReq, requirements);
  populateList(jobBenefits, benefits);

  // Show modal
  modal.classList.remove("hidden");
  document.body.style.overflow = "hidden";
}

function closeJobModal() {
  const modal = document.getElementById("job-modal");
  modal.classList.add("hidden");
  document.body.style.overflow = "auto";
}

// File upload handling
document
  .getElementById("resume-upload")
  .addEventListener("change", function (e) {
    const file = e.target.files[0];
    if (file) {
      const fileName = file.name;
      const fileSize = (file.size / (1024 * 1024)).toFixed(2); // MB
      const display = document.getElementById("resume-name");
      display.textContent = `${fileName} (${fileSize}MB)`;
      display.classList.remove("hidden");
    }
  });

document
  .getElementById("cover-upload")
  .addEventListener("change", function (e) {
    const file = e.target.files[0];
    if (file) {
      const fileName = file.name;
      const fileSize = (file.size / (1024 * 1024)).toFixed(2); // MB
      const display = document.getElementById("cover-name");
      display.textContent = `${fileName} (${fileSize}MB)`;
      display.classList.remove("hidden");
    }
  });

// Update email preview when form fields change
document
  .getElementById("job-application-form")
  .addEventListener("input", function () {
    updateEmailPreview();
  });

function updateEmailPreview() {
  const form = document.getElementById("job-application-form");
  const previewContainer = document.getElementById("email-preview-container");
  const previewJobTitle = document.getElementById("preview-job-title");
  const previewPosition = document.getElementById("preview-position");
  const previewName = document.getElementById("preview-name");
  const previewEmail = document.getElementById("preview-email");
  const previewPhone = document.getElementById("preview-phone");
  const previewLocation = document.getElementById("preview-location");
  const previewSalary = document.getElementById("preview-salary");
  const previewNotice = document.getElementById("preview-notice");
  const previewPortfolio = document.getElementById("preview-portfolio");
  const previewPortfolioValue = document.getElementById(
    "preview-portfolio-value"
  );
  const previewMessageContainer = document.getElementById(
    "preview-message-container"
  );
  const previewMessage = document.getElementById("preview-message");
  const previewNameFooter = document.getElementById("preview-name-footer");

  // Get form values
  const position = document.getElementById("applied-position").value;
  const name = form.elements["name"].value;
  const email = form.elements["email"].value;
  const phone = form.elements["phone"].value;
  const location = form.elements["location"].value;
  const salary = form.elements["salary"].value;
  const notice = form.elements["notice"].value;
  const portfolio = form.elements["portfolio"].value;
  const message = form.elements["message"].value;

  // Update preview
  previewJobTitle.textContent = position;
  previewPosition.textContent = position;
  previewName.textContent = name;
  previewEmail.textContent = email;
  previewPhone.textContent = phone;
  previewLocation.textContent = location;
  previewSalary.textContent = salary;
  previewNotice.textContent = notice;
  previewNameFooter.textContent = name;

  // Show/hide portfolio section
  if (portfolio) {
    previewPortfolioValue.textContent = portfolio;
    previewPortfolio.classList.remove("hidden");
  } else {
    previewPortfolio.classList.add("hidden");
  }

  // Show/hide message section
  if (message) {
    previewMessage.textContent = message;
    previewMessageContainer.classList.remove("hidden");
  } else {
    previewMessageContainer.classList.add("hidden");
  }

  // Show preview container if at least one field is filled
  if (
    name ||
    email ||
    phone ||
    location ||
    salary ||
    notice ||
    portfolio ||
    message
  ) {
    previewContainer.classList.remove("hidden");
  } else {
    previewContainer.classList.add("hidden");
  }
}

// Update email preview for general application
document
  .getElementById("general-application-form")
  .addEventListener("input", function () {
    updateGeneralEmailPreview();
  });

function updateGeneralEmailPreview() {
  const form = document.getElementById("general-application-form");
  const previewContainer = document.getElementById(
    "general-email-preview-container"
  );
  const previewName = document.getElementById("general-preview-name");
  const previewEmail = document.getElementById("general-preview-email");
  const previewPhone = document.getElementById("general-preview-phone");
  const previewLocation = document.getElementById("general-preview-location");
  const previewDepartment = document.getElementById(
    "general-preview-department"
  );
  const previewPortfolio = document.getElementById("general-preview-portfolio");
  const previewPortfolioValue = document.getElementById(
    "general-preview-portfolio-value"
  );
  const previewMessage = document.getElementById("general-preview-message");
  const previewNameFooter = document.getElementById(
    "general-preview-name-footer"
  );

  // Get form values
  const name = form.elements["name"].value;
  const email = form.elements["email"].value;
  const phone = form.elements["phone"].value;
  const location = form.elements["location"].value;
  const department = form.elements["department"].value;
  const portfolio = form.elements["portfolio"].value;
  const message = form.elements["message"].value;

  // Update preview
  previewName.textContent = name;
  previewEmail.textContent = email;
  previewPhone.textContent = phone;
  previewLocation.textContent =
    location.charAt(0).toUpperCase() + location.slice(1);
  previewDepartment.textContent =
    department.charAt(0).toUpperCase() + department.slice(1);
  previewMessage.textContent = message;
  previewNameFooter.textContent = name;

  // Show/hide portfolio section
  if (portfolio) {
    previewPortfolioValue.textContent = portfolio;
    previewPortfolio.classList.remove("hidden");
  } else {
    previewPortfolio.classList.add("hidden");
  }

  // Show preview container if at least one field is filled
  if (
    name ||
    email ||
    phone ||
    location ||
    department ||
    portfolio ||
    message
  ) {
    previewContainer.classList.remove("hidden");
  } else {
    previewContainer.classList.add("hidden");
  }
}

// Form submission handling with email sending
document
  .getElementById("job-application-form")
  .addEventListener("submit", function (e) {
    e.preventDefault();

    // Show loading state
    const submitText = document.getElementById("submit-text");
    const submitSpinner = document.getElementById("submit-spinner");
    submitText.textContent = "Submitting...";
    submitSpinner.classList.remove("hidden");

    // Collect form data
    const formData = new FormData(this);
    const resumeFile = document.getElementById("resume-upload").files[0];
    const coverFile = document.getElementById("cover-upload").files[0];

    if (resumeFile) {
      formData.append("resume", resumeFile);
    }
    if (coverFile) {
      formData.append("cover_letter", coverFile);
    }

    // Send data to our PHP endpoint
    fetch("submit_application.php", {
      method: "POST",
      body: formData,
      headers: {
        Accept: "application/json",
      },
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        return response.json();
      })
      .then((data) => {
        // Hide loading state
        submitText.textContent = "Submit Application";
        submitSpinner.classList.add("hidden");

        if (data.success) {
          // Reset form
          this.reset();
          document.getElementById("resume-name").classList.add("hidden");
          document.getElementById("cover-name").classList.add("hidden");
          document
            .getElementById("email-preview-container")
            .classList.add("hidden");

          // Close job modal and show success
          closeJobModal();
          showSuccessModal(data.message);
        } else {
          throw new Error(data.message);
        }
      })
      .catch((error) => {
        console.error("Error:", error);
        submitText.textContent = "Submit Application";
        submitSpinner.classList.add("hidden");
        showSuccessModal(
          error.message ||
            "There was an error submitting your application. Please try again later."
        );
      });
  });

// Form submission handling for general application (single instance)
document
  .getElementById("general-application-form")
  .addEventListener("submit", function (e) {
    e.preventDefault();

    // Show loading state
    const submitText = document.getElementById("general-submit-text");
    const submitSpinner = document.getElementById("general-submit-spinner");
    submitText.textContent = "Submitting...";
    submitSpinner.classList.remove("hidden");

    // Collect form data
    const formData = new FormData(this);
    const resumeFile = document.getElementById("general-resume-upload")
      .files[0];
    const coverFile = document.getElementById("general-cover-upload").files[0];

    if (resumeFile) {
      formData.append("resume", resumeFile);
    }
    if (coverFile) {
      formData.append("cover_letter", coverFile);
    }

    // Send data to our PHP endpoint
    fetch("submit_application.php", {
      method: "POST",
      body: formData,
      headers: {
        Accept: "application/json",
      },
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        return response.json();
      })
      .then((data) => {
        // Hide loading state
        submitText.textContent = "Submit Application";
        submitSpinner.classList.add("hidden");

        if (data.success) {
          // Reset form
          this.reset();
          document
            .getElementById("general-resume-name")
            .classList.add("hidden");
          document.getElementById("general-cover-name").classList.add("hidden");
          document
            .getElementById("general-email-preview-container")
            .classList.add("hidden");

          // Close general modal and show success
          closeGeneralApplicationModal();
          showSuccessModal(data.message);
        } else {
          throw new Error(data.message);
        }
      })
      .catch((error) => {
        console.error("Error:", error);
        submitText.textContent = "Submit Application";
        submitSpinner.classList.add("hidden");
        showSuccessModal(
          error.message ||
            "There was an error submitting your application. Please try again later."
        );
      });
  });

// General application modal
function openGeneralApplicationModal() {
  document.getElementById("general-modal").classList.remove("hidden");
  document.body.style.overflow = "hidden";
}

function closeGeneralApplicationModal() {
  document.getElementById("general-modal").classList.add("hidden");
  document.body.style.overflow = "auto";
}

// Success modal
function showSuccessModal(message) {
  if (message) {
    document.getElementById("success-message").textContent = message;
  }
  document.getElementById("success-modal").classList.remove("hidden");
  document.body.style.overflow = "hidden";
}

function closeSuccessModal() {
  document.getElementById("success-modal").classList.add("hidden");
  document.body.style.overflow = "auto";
}

// File upload handling for general application
document
  .getElementById("general-resume-upload")
  .addEventListener("change", function (e) {
    const fileName = e.target.files[0]?.name || "No file selected";
    const display = document.getElementById("general-resume-name");
    display.textContent = fileName;
    display.classList.remove("hidden");
  });

document
  .getElementById("general-cover-upload")
  .addEventListener("change", function (e) {
    const fileName = e.target.files[0]?.name || "No file selected";
    const display = document.getElementById("general-cover-name");
    display.textContent = fileName;
    display.classList.remove("hidden");
  });

// Smooth scrolling for anchor links
document.querySelectorAll('a[href^="#"]').forEach((anchor) => {
  anchor.addEventListener("click", function (e) {
    e.preventDefault();

    const targetId = this.getAttribute("href");
    if (targetId === "#") return;

    const targetElement = document.querySelector(targetId);
    if (targetElement) {
      const header = document.querySelector("header");
      const headerHeight = header ? header.offsetHeight : 0;
      const targetPosition =
        targetElement.getBoundingClientRect().top +
        window.pageYOffset -
        headerHeight;

      window.scrollTo({
        top: targetPosition,
        behavior: "smooth",
      });

      // Close mobile menu if open
      if (mobileMenu && !mobileMenu.classList.contains("hidden")) {
        mobileMenu.classList.add("hidden");
      }
    }
  });
});
