$(document).ready(function() {
    // Initialize rich text editor if CKEditor is available
    if (typeof ClassicEditor !== 'undefined') {
        ClassicEditor
            .create(document.querySelector('#description'))
            .catch(error => {
                console.error(error);
            });
    }

    // Initialize select2 for multiple select fields if available
    if ($.fn.select2) {
        $('.select2').select2({
            theme: 'bootstrap-5'
        });
    }

    // Handle dynamic field additions
    let skillCounter = 1;
    let languageCounter = 1;
    let questionCounter = 1;
    let requirementCounter = 1;
    let responsibilityCounter = 1;

    // Add Skill Field
    $('.add-skill').click(function() {
        skillCounter++;
        const newSkill = `
            <div class="input-group mb-2 skill-item">
                <input type="text" class="form-control" name="skills[]" placeholder="Add a required skill">
                <button type="button" class="btn btn-outline-danger remove-field">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;
        $('#skills-container').append(newSkill);
    });

    // Add Language Field
    $('.add-language').click(function() {
        languageCounter++;
        const newLanguage = `
            <div class="row mb-2 language-item">
                <div class="col-md-5">
                    <select class="form-select" name="languages[][language]" required>
                        <option value="">Select language</option>
                        <option value="english">English</option>
                        <option value="spanish">Spanish</option>
                        <option value="french">French</option>
                        <option value="german">German</option>
                        <option value="chinese">Chinese</option>
                    </select>
                </div>
                <div class="col-md-5">
                    <select class="form-select" name="languages[][level]" required>
                        <option value="">Select proficiency level</option>
                        <option value="basic">Basic</option>
                        <option value="intermediate">Intermediate</option>
                        <option value="advanced">Advanced</option>
                        <option value="native">Native</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-outline-danger remove-field">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        `;
        $('#languages-container').append(newLanguage);
    });

    // Add Requirement Field
    $('.add-requirement').click(function() {
        requirementCounter++;
        const newRequirement = `
            <div class="input-group mb-2 requirement-item">
                <input type="text" class="form-control" name="requirements[]" 
                       placeholder="Enter job requirement">
                <button type="button" class="btn btn-outline-danger remove-field">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;
        $('#requirements-container').append(newRequirement);
    });

    // Add Responsibility Field
    $('.add-responsibility').click(function() {
        responsibilityCounter++;
        const newResponsibility = `
            <div class="input-group mb-2 responsibility-item">
                <input type="text" class="form-control" name="key_responsibilities[]" 
                       placeholder="Enter key responsibility">
                <button type="button" class="btn btn-outline-danger remove-field">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;
        $('#responsibilities-container').append(newResponsibility);
    });

    // Add Screening Question
    $('.add-question').click(function() {
        questionCounter++;
        const newQuestion = `
            <div class="screening-question mb-3">
                <div class="input-group">
                    <input type="text" class="form-control" name="screening_questions[]" 
                           placeholder="Enter your screening question">
                    <button type="button" class="btn btn-outline-danger remove-field">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="form-check mt-2">
                    <input class="form-check-input" type="checkbox" name="required_questions[]" 
                           value="${questionCounter}">
                    <label class="form-check-label">Make this question required</label>
                </div>
            </div>
        `;
        $('#screening-questions-container').append(newQuestion);
    });

    // Remove dynamic field
    $(document).on('click', '.remove-field', function() {
        $(this).closest('.skill-item, .language-item, .screening-question, .requirement-item, .responsibility-item').remove();
    });

    // Toggle application method fields
    $('input[name="application_method"]').change(function() {
        const method = $(this).val();
        $('#email-application-details').toggleClass('d-none', method !== 'email');
        $('#website-application-details').toggleClass('d-none', method !== 'website');
    });

    // Toggle location fields based on work type
    function updateLocationFields(locationType) {
        const isRemote = locationType === 'remote';
        const locationFields = $('#city, #state, #country');

        $('#location-details').toggleClass('d-none', isRemote);
        locationFields.each(function() {
            $(this).prop('required', !isRemote);
            if (isRemote) {
                $(this).removeClass('is-invalid');
            }
        });
    }

    $('input[name="work_location_type"]').change(function() {
        updateLocationFields($(this).val());
    });

    updateLocationFields($('input[name="work_location_type"]:checked').val());

    // Form validation function
    function validateForm() {
        let isValid = true;
        const errors = [];

        // Validate requirements
        const requirementInputs = $('#requirements-container').find('input[name="requirements[]"]');
        let hasRequirement = false;
        let requirementTooShort = false;

        requirementInputs.each(function() {
            const value = $(this).val().trim();
            if (value.length) {
                hasRequirement = true;
                if (value.length < 5) {
                    requirementTooShort = true;
                    $(this).addClass('is-invalid');
                } else {
                    $(this).removeClass('is-invalid');
                }
            } else {
                $(this).removeClass('is-invalid');
            }
        });

        if (!hasRequirement) {
            errors.push('Please add at least one job requirement');
            requirementInputs.addClass('is-invalid');
            isValid = false;
        }

        if (requirementTooShort) {
            errors.push('Each requirement must be at least 5 characters long');
            isValid = false;
        }

        // Validate responsibilities
        const responsibilityInputs = $('#responsibilities-container').find('input[name="responsibilities[]"], input[name="key_responsibilities[]"]');
        let hasResponsibility = false;
        let responsibilityTooShort = false;

        responsibilityInputs.each(function() {
            const value = $(this).val().trim();
            if (value.length) {
                hasResponsibility = true;
                if (value.length < 5) {
                    responsibilityTooShort = true;
                    $(this).addClass('is-invalid');
                } else {
                    $(this).removeClass('is-invalid');
                }
            } else {
                $(this).removeClass('is-invalid');
            }
        });

        if (!hasResponsibility) {
            errors.push('Please add at least one key responsibility');
            responsibilityInputs.addClass('is-invalid');
            isValid = false;
        }

        if (responsibilityTooShort) {
            errors.push('Each responsibility must be at least 5 characters long');
            isValid = false;
        }

       // Define required fields and their labels
       const requiredFields = {
        'job-title': 'Job Title',
        'company-name': 'Company Name',
        'category': 'Job Category',
        'description': 'Job Description',
        'job-type': 'Job Type',
        'minimum-salary': 'Minimum Salary',
        'maximum-salary': 'Maximum Salary',
        'currency': 'Currency',
        'experience-years': 'Experience Years',
        'expiry-date': 'Expiry Date'
    };

    // Loop through each required field to validate
    for (const [field, label] of Object.entries(requiredFields)) {
        const value = $(`#${field}`).val();
        if (!value || value.trim() === '') {
            errors.push(`${label} is required`);
            $(`#${field}`).addClass('is-invalid');
            isValid = false;
        } else {
            $(`#${field}`).removeClass('is-invalid');
        }
    }

        // Job title length validation
        const jobTitle = $('#job-title').val();
        if (jobTitle && (jobTitle.length < 5 || jobTitle.length > 100)) {
            errors.push('Job title must be between 5 and 100 characters');
            isValid = false;
        }

        // Description length validation
        const description = $('#description').val();
        if (description && description.length < 50) {
            errors.push('Job description must be at least 50 characters');
            isValid = false;
        }

        // Salary validation
        const minSalary = parseFloat($('#minimum-salary').val());
        const maxSalary = parseFloat($('#maximum-salary').val());
        if (!isNaN(minSalary) && !isNaN(maxSalary)) {
            if (maxSalary <= minSalary) {
                errors.push('Maximum salary must be greater than minimum salary');
                isValid = false;
            }
        }

        // Experience validation
        const experience = parseInt($('#experience-years').val());
        if (isNaN(experience) || experience < 0) {
            errors.push('Please enter a valid number of years for experience');
            isValid = false;
        }

        // Date validation
        const expiryDate = new Date($('#expiry-date').val());
        const today = new Date();
        if (expiryDate <= today) {
            errors.push('Expiry date must be in the future');
            isValid = false;
        }

        // Location validation for onsite/hybrid
        const locationType = $('input[name="work_location_type"]:checked').val();
        if (locationType !== 'remote') {
            if (!$('#city').val() || !$('#state').val() || !$('#country').val()) {
                errors.push('Please fill in all location fields for onsite/hybrid positions');
                isValid = false;
            }
        }

        // Application method validation
        const applicationMethod = $('input[name="application_method"]:checked').val();
        if (applicationMethod === 'email') {
            const email = $('#application-email').val();
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!email || !emailRegex.test(email)) {
                errors.push('Please provide a valid application email address');
                isValid = false;
            }
        } else if (applicationMethod === 'website') {
            const url = $('#application-url').val();
            const urlRegex = /^https?:\/\/[^\s/$.?#].[^\s]*$/;
            if (!url || !urlRegex.test(url)) {
                errors.push('Please provide a valid application URL');
                isValid = false;
            }
        }

        // Display errors if any
        if (!isValid) {
            myAlert.fire({
                icon: 'error',
                title: 'Validation Error',
                html: errors.join('<br>')
            });
        }

        return isValid;
    }

    // Handle form submission
    $('#create-job-form').on('submit', function(e) {
        e.preventDefault();

        if (!validateForm()) {
            return;
        }

        // Create FormData object
        const formData = new FormData(this);

        // Add additional data
        formData.append('status', 'pending');
        formData.append('salary_date', new Date().toISOString().split('T')[0]);

        // Convert benefits array
        const benefits = [];
        $('input[name="benefits[]"]:checked').each(function() {
            benefits.push($(this).val());
        });
        formData.append('benefits', JSON.stringify(benefits));

        // Convert requirements array
        const requirements = [];
        $('#requirements-container').find('input[name="requirements[]"]').each(function() {
            const requirement = $(this).val().trim();
            if (requirement) {
                requirements.push(requirement);
            }
        });
        formData.append('requirements', JSON.stringify(requirements));

        // Convert responsibilities array
        const responsibilities = [];
        $('#responsibilities-container').find('input[name="responsibilities[]"], input[name="key_responsibilities[]"]').each(function() {
            const responsibility = $(this).val().trim();
            if (responsibility) {
                responsibilities.push(responsibility);
            }
        });
        formData.append('key_responsibilities', JSON.stringify(responsibilities));

        // Convert languages array
        const languages = [];
        $('.language-item').each(function() {
            const language = $(this).find('select[name="languages[][language]"]').val();
            const level = $(this).find('select[name="languages[][level]"]').val();
            if (language && level) {
                languages.push({ language, level });
            }
        });
        formData.append('languages', JSON.stringify(languages));

        // Show loading state
        const submitBtn = $(this).find('button[type="submit"]');
        const originalText = submitBtn.html();
        submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Posting...');
        submitBtn.prop('disabled', true);

        // Submit the form
        axios.post(`${base_url}/webapi/jobs/create`, formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        .then(response => {
            const responseCode = response.data.code ?? response.data.status ?? response.status;
            if (responseCode === 201) {
                myAlert.fire({
                    icon: 'success',
                    title: 'Success',
                    text: 'Job posted successfully!'
                });

                // Redirect after success
                setTimeout(() => {
                    window.location.href = `${base_url}/jobs`;
                }, 2000);
            } else {
                throw new Error(response.data.message || 'Failed to create job');
            }
        })
        .catch(error => {
            console.error('Error creating job:', error);
            
            // Handle validation errors from backend
            if (error.response && error.response.data && error.response.data.errors) {
                const errorMessages = Object.values(error.response.data.errors).flat();
                myAlert.fire({
                    icon: 'error',
                    title: 'Validation Error',
                    html: errorMessages.join('<br>')
                });
            } else {
                myAlert.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'An error occurred while creating the job. Please try again.'
                });
            }
        })
        .finally(() => {
            // Reset button state
            submitBtn.html(originalText);
            submitBtn.prop('disabled', false);
        });
    });

    // Preview functionality
    $('#preview-button').click(function() {
        if (!validateForm()) {
            return;
        }

        const formData = new FormData($('#create-job-form')[0]);
        const jobData = {};
        formData.forEach((value, key) => {
            jobData[key] = value;
        });

        // Generate preview HTML
        const previewHtml = generatePreviewHtml(jobData);

        // Show preview in modal
        $('#previewModal .modal-body').html(previewHtml);
        $('#previewModal').modal('show');
    });

    // Helper function to generate preview HTML
    function generatePreviewHtml(data) {
        return `
            <div class="preview-content">
                <h3>${data.job_title}</h3>
                <h5>${data.company_name}</h5>
                
                <div class="job-meta mt-3">
                    <p><strong>Location:</strong> ${data.job_location}</p>
                    <p><strong>Job Type:</strong> ${data.job_type}</p>
                    <p><strong>Salary:</strong> ${data.currency} ${data.minimum_salary} - ${data.maximum_salary}</p>
                    <p><strong>Experience Required:</strong> ${data.experience_years} years</p>
                </div>

                <div class="job-description mt-3">
                    <h5>Job Description</h5>
                    ${data.job_description}
                </div>

                <div class="requirements mt-3">
                    <h5>Requirements</h5>
                    <ul>
                        ${data.requirements ? JSON.parse(data.requirements).map(req => `<li>${req}</li>`).join('') : ''}
                    </ul>
                </div>

                <div class="responsibilities mt-3">
                    <h5>Key Responsibilities</h5>
                    <ul>
                        ${data.key_responsibilities ? JSON.parse(data.key_responsibilities).map(resp => `<li>${resp}</li>`).join('') : ''}
                    </ul>
                </div>

                <div class="benefits mt-3">
                    <h5>Benefits</h5>
                    <ul>
                        ${data.benefits ? JSON.parse(data.benefits).map(benefit => `<li>${benefit.replace('_', ' ')}</li>`).join('') : ''}
                    </ul>
                </div>
            </div>
        `;
    }
});


// jobs.js
$(document).ready(function() {
    // State management
    let currentFilters = {
        keyword: '',
        location: '',
        job_type: [],
        work_location_type: [],
        experience_level: [],
        min_salary: null,
        max_salary: null,
        category_id: null,
        status: 'approved',
        sort_by: 'created_at',
        sort_order: 'desc',
        limit: 9,
        offset: 0
    };

    // Initial load
    loadStats();
    loadJobs();
    loadRecommendedJobs();

    // Search handling
    let searchTimeout;
    $('#searchKeyword, #searchLocation').on('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(function() {
            currentFilters.keyword = $('#searchKeyword').val();
            currentFilters.location = $('#searchLocation').val();
            currentFilters.offset = 0; // Reset pagination
            loadJobs();
        }, 500);
    });

    // Quick filter pills
    $('.filter-pill').on('click', function() {
        $('.filter-pill').removeClass('active');
        $(this).addClass('active');
        
        const filterType = $(this).data('filter');
        if (filterType === 'all') {
            currentFilters.job_type = [];
            currentFilters.work_location_type = [];
        } else if (filterType === 'remote') {
            currentFilters.work_location_type = ['remote'];
        } else {
            currentFilters.job_type = [filterType];
        }
        
        currentFilters.offset = 0;
        loadJobs();
    });

    // Advanced filters handling
    $('#applyFilters').on('click', function() {
        // Location type
        currentFilters.work_location_type = [];
        $('input[name="location_type"]:checked').each(function() {
            currentFilters.work_location_type.push($(this).val());
        });

        // Experience level
        currentFilters.experience_level = [];
        $('input[name="experience_level"]:checked').each(function() {
            currentFilters.experience_level.push($(this).val());
        });

        // Salary range
        currentFilters.min_salary = parseInt($('#salaryRange').val());
        currentFilters.max_salary = parseInt($('#salaryRange').val());

        // Job type
        currentFilters.job_type = [];
        $('input[name="job_type"]:checked').each(function() {
            currentFilters.job_type.push($(this).val());
        });

        currentFilters.offset = 0;
        loadJobs();
    });

    // Reset filters
    $('#resetFilters').on('click', function() {
        // Reset checkboxes
        $('input[type="checkbox"]').prop('checked', false);
        
        // Reset salary range
        $('#salaryRange').val(30000);
        
        // Reset filter state
        currentFilters = {
            keyword: '',
            location: '',
            job_type: [],
            work_location_type: [],
            experience_level: [],
            min_salary: 30000,
            max_salary: 200000,
            category_id: null,
            status: 'approved',
            sort_by: 'created_at',
            sort_order: 'desc',
            limit: 9,
            offset: 0
        };
        
        // Reset search inputs
        $('#searchKeyword, #searchLocation').val('');
        
        // Reset pills
        $('.filter-pill').removeClass('active');
        $('.filter-pill[data-filter="all"]').addClass('active');
        
        loadJobs();
    });

    // Load dashboard stats
    function loadStats() {
        axios.get(`${base_url}/webapi/jobs/dashboard-stats`)
            .then(response => {
                if (response.data.code === 200) {
                    const stats = response.data.data;
                    // Update dashboard stats
                    $('#totalJobs').text(stats.total_jobs.toLocaleString());
                    $('#appliedJobs').text(stats.applied_jobs.toLocaleString());
                    $('#savedJobs').text(stats.saved_jobs.toLocaleString());
                    $('#jobAlerts').text(stats.job_alerts.toLocaleString());
    
                    // Update Quick Filter Pills counts
                    $('#allJobsCount').text(stats.total_jobs.toLocaleString());
                    $('#remoteJobsCount').text(stats.remote_jobs.toLocaleString());
                    $('#fulltimeJobsCount').text(stats.job_types_count["full-time"].toLocaleString());
                    $('#parttimeJobsCount').text(stats.job_types_count["part-time"].toLocaleString());
                    $('#internshipJobsCount').text(stats.job_types_count["internship"].toLocaleString());
                }
            })
            .catch(error => console.error('Error loading stats:', error));
    }
    

    // Load jobs
    function loadJobs() {
        showLoader('#jobsGrid');
        
        axios.post(`${base_url}/webapi/jobs/all`, currentFilters)
            .then(response => {
                if (response.data.code === 200) {
                    renderJobs(response.data.data);
                }
            })
            .catch(error => {
                console.error('Error loading jobs:', error);
                showError('Error loading jobs. Please try again.');
            })
            .finally(() => hideLoader('#jobsGrid'));
    }

    // Load recommended jobs
    function loadRecommendedJobs() {
        showLoader('#recommendedJobs');
        
        axios.get(`${base_url}/webapi/jobs/recommended`)
            .then(response => {
                if (response.data.code === 200) {
                    renderRecommendedJobs(response.data.data);
                }
            })
            .catch(error => console.error('Error loading recommended jobs:', error))
            .finally(() => hideLoader('#recommendedJobs'));
    }

    // Render jobs grid
    function renderJobs(jobs) {
        const container = $('#jobsGrid');
        container.empty();

        jobs.forEach(job => {
            container.append(createJobCard(job));
        });

        // Initialize tooltips
        $('[data-bs-toggle="tooltip"]').tooltip();
    }

    // Render recommended jobs
    function renderRecommendedJobs(jobs) {
        const container = $('#recommendedJobs');
        container.empty();

        jobs.forEach(job => {
            container.append(createRecommendedJobItem(job));
        });
    }

    // Create job card HTML
    function createJobCard(job) {
        const timeDiff = moment(job.created_at).fromNow();
        const skills = job.skills.slice(0, 3);
        const remainingSkills = job.skills.length - 3;

        return `
            <div class="col-md-6 col-lg-4 mb-4">
                <div class="card h-100 border-0 shadow-sm hover-shadow-md transition-hover">
                    <div class="position-relative">
                        <div class="bg-${job.is_featured ? 'primary' : job.is_urgent_hiring ? 'danger' : 'success'} bg-opacity-10 p-3">
                            <img src="${job.company_logo || 'assets/images/companies/default.jpg'}" class="rounded-3" style="width: 80px; height: 80px;" alt="${job.company_name}">
                        </div>
                        <span class="position-absolute top-0 end-0 m-3">
                            <button class="btn btn-icon btn-sm btn-outline-primary rounded-circle save-job" data-id="${job.id}" data-bs-toggle="tooltip" data-bs-placement="top" title="Save Job">
                                <i class="fas fa-bookmark"></i>
                            </button>
                        </span>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            ${job.is_featured ? '<span class="badge bg-primary-subtle text-primary">Featured</span>' : 
              job.is_urgent_hiring ? '<span class="badge bg-danger-subtle text-danger">Urgent Hiring</span>' : 
              job.work_location_type === 'remote' ? '<span class="badge bg-success-subtle text-success">Remote</span>' : ''}
                            <span class="text-success small">
                                <i class="fas fa-clock me-1"></i>Posted ${timeDiff}
                            </span>
                        </div>
                        <h5 class="card-title mb-1">${job.job_title}</h5>
                        <p class="text-primary fw-bold mb-2">${job.company_name}</p>
                        <div class="d-flex flex-wrap gap-2 mb-3">
                            <span class="badge bg-light text-dark">
                                <i class="fas fa-map-marker-alt me-1"></i>${job.job_location}
                            </span>
                            <span class="badge bg-light text-dark">
                                <i class="fas fa-briefcase me-1"></i>${job.job_type}
                            </span>
                            <span class="badge bg-light text-dark">
                                <i class="fas fa-dollar-sign me-1"></i>${job.minimum_salary.toLocaleString()} - ${job.maximum_salary.toLocaleString()}/${job.salary_period}
                            </span>
                        </div>
                        <p class="card-text small text-muted mb-3">${job.job_description.substring(0, 100)}...</p>
                        <div class="d-flex flex-wrap gap-2 mb-3">
                            ${skills.map(skill => `
                                <span class="badge bg-secondary bg-opacity-10 text-secondary">${skill}</span>
                            `).join('')}
                            ${remainingSkills > 0 ? `
                                <span class="badge bg-secondary bg-opacity-10 text-secondary">+${remainingSkills} more</span>
                            ` : ''}
                        </div>
                    </div>
                    <div class="card-footer bg-white border-0 pt-0">
                        <div class="d-grid gap-2">
                            <button class="btn btn-primary quick-apply" data-id="${job.id}">
                                <i class="fas fa-paper-plane me-2"></i>Quick Apply
                            </button>
                            <button class="btn btn-outline-primary view-details" data-id="${job.id}">View Details</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    // Create recommended job item HTML
    function createRecommendedJobItem(job) {
        return `
            <div class="card border-0 shadow-sm mb-3">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-auto">
                            <img src="${job.company_logo || 'assets/images/companies/default.jpg'}" class="rounded-3" style="width: 60px; height: 60px;" alt="${job.company_name}">
                        </div>
                        <div class="col">
                            <h5 class="mb-1">${job.job_title}</h5>
                            <p class="text-primary mb-1">${job.company_name}</p>
                            <div class="d-flex flex-wrap gap-2">
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-map-marker-alt me-1"></i>${job.job_location}
                                </span>
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-briefcase me-1"></i>${job.job_type}
                                </span>
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-dollar-sign me-1"></i>${job.minimum_salary.toLocaleString()} - ${job.maximum_salary.toLocaleString()}/${job.salary_period}
                                </span>
                            </div>
                        </div>
                        <div class="col-auto">
                            <div class="d-flex gap-2">
                                <button class="btn btn-sm btn-primary quick-apply" data-id="${job.id}">Quick Apply</button>
                                <button class="btn btn-sm btn-outline-primary view-details" data-id="${job.id}">View Details</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    // Quick Apply handler
    $(document).on('click', '.quick-apply', function() {
        const jobId = $(this).data('id');
        // Show quick apply modal
        $('#quickApplyModal').modal('show');
        $('#quickApplyJobId').val(jobId);
    });

    // View Details handler
    $(document).on('click', '.view-details', function() {
        const jobId = $(this).data('id');
        window.location.href = `${base_url}/jobs/detail/${jobId}`;
    });

    // Save Job handler
    $(document).on('click', '.save-job', function(e) {
        e.preventDefault();
        const jobId = $(this).data('id');
        const button = $(this);

        axios.post(`${base_url}/webapi/jobs/save`, { job_id: jobId })
            .then(response => {
                if (response.data.code === 200) {
                    button.toggleClass('btn-outline-primary btn-primary');
                    showSuccess('Job saved successfully');
                }
            })
            .catch(error => showError('Error saving job. Please try again.'));
    });

    // Helper functions
    function showLoader(container) {
        $(container).html('<div class="text-center p-5"><div class="spinner-border text-primary" role="status"></div></div>');
    }

    function hideLoader(container) {
        $(container).find('.spinner-border').parent().remove();
    }

    function showSuccess(message) {
        myAlert.fire({
            icon: 'success',
            title: 'Success',
            text: message
        });
    }

    function showError(message) {
        myAlert.fire({
            icon: 'error',
            title: 'Error',
            text: message
        });
    }
});
