// job-detail.js
$(document).ready(function() {
    const jobId = window.location.pathname.split('/').pop();
    let jobData = null;
    let isJobSaved = false;

    // Initialize page
    loadJobDetails();
    checkIfJobSaved();

    // Load job details
    function loadJobDetails() {
        showLoader();
        axios.get(`${base_url}/webapi/jobs/detail/${jobId}`)
            .then(response => {
                if (response.data.code === 200) {
                    jobData = response.data.data;
                    renderJobDetails(jobData);
                    renderSimilarJobs(response.data.similar_jobs);
                    updateApplicationStats();
                }
            })
            .catch(error => {
                console.error('Error loading job details:', error);
                showError('Error loading job details. Please try again.');
            })
            .finally(() => hideLoader());
    }

    // Render job details
    function renderJobDetails(job) {
        // Update page title
        document.title = `${job.job_title} at ${job.company_name}`;

        // Company logo
        $('#companyLogo, #companyLogoLarge').attr('src', job.company_logo || '/assets/images/companies/default.jpg');
        
        // Job title and company
        $('#jobTitle').text(job.job_title);
        $('#companyName, #companyNameLarge').text(job.company_name);
        
        // Job meta badges
        const metaBadges = `
            <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>
            ${job.is_urgent_hiring ? '<span class="badge bg-danger">Urgent Hiring</span>' : ''}
            ${job.is_featured ? '<span class="badge bg-primary">Featured</span>' : ''}
        `;
        $('#jobMeta').html(metaBadges);

        // Job description
        $('#jobDescription').html(job.job_description);

        // Responsibilities
        const responsibilitiesArray = JSON.parse(job.key_responsibilities);
        const responsibilities = responsibilitiesArray.map(resp => 
            `<li class="mb-2">
                <i class="fas fa-check-circle text-success me-2"></i>${resp}
            </li>`
        ).join('');
        $('#responsibilities').html(responsibilities);

        // Requirements
        const requirementsArray = JSON.parse(job.requirements);
        const requirements = requirementsArray.map(req => 
            `<li class="mb-2">
                <i class="fas fa-check-circle text-success me-2"></i>${req}
            </li>`
        ).join('');
        $('#requirements').html(requirements);

        // Skills
        
        const skills = job.skills.map(skill =>
            `<span class="badge bg-secondary bg-opacity-10 text-secondary">${skill}</span>`
        ).join('');
        $('#skills').html(skills);

        // Benefits
        const benefitsArray = JSON.parse(job.benefits);
        const benefits = benefitsArray.map(benefit => 
            `<div class="col-md-6">
                <div class="card h-100 border-0 shadow-sm benefit-card">
                    <div class="card-body">
                        <div class="d-flex align-items-center">
                            <span class="icon-circle bg-primary bg-opacity-10 text-primary me-3">
                                <i class="fas fa-check"></i>
                            </span>
                            <h6 class="mb-0">${formatBenefitName(benefit)}</h6>
                        </div>
                    </div>
                </div>
            </div>`
        ).join('');
        $('#benefits').html(benefits);

        // Application process
        const applicationProcess = `
            <div class="alert ${job.application_method === 'email' ? 'alert-info' : 'alert-primary'} mb-4">
                <h6 class="alert-heading">Application Method</h6>
                <p class="mb-0">
                    ${getApplicationMethodText(job)}
                </p>
            </div>
            ${job.screening_questions.length > 0 ? `
                <div class="alert alert-warning">
                    <h6 class="alert-heading">Please Note</h6>
                    <p class="mb-0">This position requires answering ${job.screening_questions.length} screening questions during the application process.</p>
                </div>
            ` : ''}
        `;
        $('#applicationProcess').html(applicationProcess);

        // Job overview sidebar
        $('#datePosted').text(moment(job.created_at).format('MMMM D, YYYY'));
        $('#location').text(job.job_location);
        $('#jobType').text(job.job_type);
        $('#salaryRange').text(`${job.currency} ${job.minimum_salary.toLocaleString()} - ${job.maximum_salary.toLocaleString()}`);
        $('#experience').text(`${job.experience_years}+ years`);
        $('#deadline').text(moment(job.expiry_date).format('MMMM D, YYYY'));

        // Company information
        $('#companyLocation').text(job.job_location);
        if (job.company_website) {
            $('#companyWebsite').attr('href', job.company_website).show();
        } else {
            $('#companyWebsite').hide();
        }
        $('#companyDescription').html(job.company_description || '');
    }

    // Render similar jobs
    function renderSimilarJobs(jobs) {
        if (!jobs || !Array.isArray(jobs)) {
            $('#similarJobs').html('<p>No similar jobs available.</p>');
            return;
        }
        const similarJobsHtml = jobs.map(job => `
            <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">
                            <h6 class="mb-1">${job.job_title}</h6>
                            <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>
                            </div>
                        </div>
                        <div class="col-auto">
                            <a href="${base_url}/jobs/detail/${job.id}" class="btn btn-sm btn-outline-primary">
                                View Details
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        `).join('');
        $('#similarJobs').html(similarJobsHtml);
    }

    // Update application stats
    function updateApplicationStats() {
        if (!jobData) return;

        $('#totalApplicants').text(jobData.applications_count || 0);
        $('#totalViews').text(jobData.views || 0);
        
        const timeLeft = moment(jobData.expiry_date).diff(moment(), 'days');
        $('#timeLeft').text(`${timeLeft} days`);
    }

    // Check if job is saved
    function checkIfJobSaved() {
        axios.get(`${base_url}/webapi/jobs/saved`)
            .then(response => {
                if (response.data.code === 200) {
                    isJobSaved = response.data.data.some(job => job.id === parseInt(jobId));
                    updateSaveButton();
                }
            })
            .catch(error => console.error('Error checking saved status:', error));
    }

    // Event Handlers
    
    // Apply Now button
    $('#applyNow').click(function() {
        $('#jobId').val(jobId);
        if (jobData.screening_questions.length > 0) {
            renderScreeningQuestions(jobData.screening_questions);
        }
        $('#applyJobModal').modal('show');
    });

    // Quick Apply button
    $('#quickApply').click(function() {
        $('#jobId').val(jobId);
        $('#quickApplyModal').modal('show');
    });

    // Save Job button
    $('#saveJob').click(function() {
        const action = isJobSaved ? 'unsave' : 'save';
        axios.post(`${base_url}/webapi/jobs/${action}`, { job_id: jobId })
            .then(response => {
                if (response.data.code === 200) {
                    isJobSaved = !isJobSaved;
                    updateSaveButton();
                    showSuccess(isJobSaved ? 'Job saved successfully' : 'Job removed from saved jobs');
                }
            })
            .catch(error => showError('Error updating job save status'));
    });

    // Share Job button
    $('#shareJob').click(function() {
        const jobUrl = window.location.href;
        $('#jobLink').val(jobUrl);
        $('#shareJobModal').modal('show');
    });

    // Share buttons
    $('.share-btn').click(function() {
        const platform = $(this).data('platform');
        const jobUrl = encodeURIComponent(window.location.href);
        const title = encodeURIComponent(`${jobData.job_title} at ${jobData.company_name}`);
        
        let shareUrl;
        switch (platform) {
            case 'facebook':
                shareUrl = `https://www.facebook.com/sharer/sharer.php?u=${jobUrl}`;
                break;
            case 'twitter':
                shareUrl = `https://twitter.com/intent/tweet?url=${jobUrl}&text=${title}`;
                break;
            case 'linkedin':
                shareUrl = `https://www.linkedin.com/sharing/share-offsite/?url=${jobUrl}`;
                break;
            case 'whatsapp':
                shareUrl = `https://wa.me/?text=${title}%20${jobUrl}`;
                break;
        }
        
        window.open(shareUrl, '_blank', 'width=600,height=400');
    });

    // Copy link button
    $('#copyLinkBtn').click(function() {
        const jobUrl = $('#jobLink').val();
        navigator.clipboard.writeText(jobUrl).then(() => {
            showSuccess('Link copied to clipboard');
        });
    });

    // Submit application
    $('#submitApplication').click(function() {
        const form = $('#jobApplicationForm')[0];
        const formData = new FormData(form);
        formData.append('job_id', jobId);

        if (!validateApplicationForm(formData)) {
            return;
        }

        showLoader();
        axios.post(`${base_url}/webapi/jobs/apply`, formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        .then(response => {
            if (response.data.code === 201) {
                $('#applyJobModal').modal('hide');
                showSuccess('Application submitted successfully');
                form.reset();
                updateApplicationStats();
            }else{
                showError(response.data.message ); 
            }
        })
        .catch(error => {
            
            
                showError('Error submitting application. Please try again.');
            
            
            
        })
        .finally(() => hideLoader());
    });

    // Helper Functions

    function formatBenefitName(benefit) {
        return benefit.split('_').map(word => 
            word.charAt(0).toUpperCase() + word.slice(1)
        ).join(' ');
    }

    function getApplicationMethodText(job) {
        switch (job.application_method) {
            case 'email':
                return `Please send your application to: <strong>${job.application_email}</strong>`;
            case 'website':
                return `Apply through company website: <a href="${job.application_url}" target="_blank">Click here</a>`;
            default:
                return 'Apply through our platform using the Apply Now button';
        }
    }

    function renderScreeningQuestions(questions) {
        const questionsHtml = questions.map((question, index) => `
            <div class="mb-3">
                <label class="form-label">
                    ${question}
                    ${questions[index].required ? '<span class="text-danger">*</span>' : ''}
                </label>
                <textarea class="form-control" name="screening_answers[${index}]" rows="3" 
                    ${questions[index].required ? 'required' : ''}></textarea>
            </div>
        `).join('');

        $('#screeningQuestions').html(`
            <div class="mb-4">
                <h6 class="mb-3">Screening Questions</h6>
                ${questionsHtml}
            </div>
        `);
    }

    function validateApplicationForm(formData) {
        // Check required fields
        const requiredFields = ['phone', 'cv_file'];
        for (const field of requiredFields) {
            if (!formData.get(field)) {
                showError(`Please fill in all required fields`);
                return false;
            }
        }

        // Validate phone number
        const phone = formData.get('phone');
        // if (!/^\+?[\d\s-]{10,}$/.test(phone)) {
        //     showError('Please enter a valid phone number');
        //     return false;
        // }

        // Validate CV file
        const cvFile = formData.get('cv_file');
        if (cvFile && cvFile.size > 0) {
            if (cvFile.size > 2 * 1024 * 1024) { // 2MB limit
                showError('CV file size must be less than 2MB');
                return false;
            }
            
            const allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
            if (!allowedTypes.includes(cvFile.type)) {
                showError('Please upload CV in PDF or DOC format');
                return false;
            }
        }

        // Validate URLs if provided
        const urlFields = ['linkedin_url', 'portfolio_url'];
        for (const field of urlFields) {
            const url = formData.get(field);
            if (url && !isValidUrl(url)) {
                showError(`Please enter a valid URL for ${field.replace('_', ' ')}`);
                return false;
            }
        }

        // Validate expected salary if provided
        const salary = formData.get('expected_salary');
        if (salary && (isNaN(salary) || salary < 0)) {
            showError('Please enter a valid expected salary');
            return false;
        }

        // Validate screening questions
        if (jobData.screening_questions) {
            const answers = formData.getAll('screening_answers[]');
            for (let i = 0; i < jobData.screening_questions.length; i++) {
                if (jobData.screening_questions[i].required && !answers[i]) {
                    showError('Please answer all required screening questions');
                    return false;
                }
            }
        }

        return true;
    }

    function updateSaveButton() {
        const $saveBtn = $('#saveJob');
        if (isJobSaved) {
            $saveBtn.removeClass('btn-light').addClass('btn-primary');
            $saveBtn.html('<i class="fas fa-bookmark me-2"></i>Saved');
        } else {
            $saveBtn.removeClass('btn-primary').addClass('btn-light');
            $saveBtn.html('<i class="far fa-bookmark me-2"></i>Save');
        }
    }

    function isValidUrl(string) {
        try {
            new URL(string);
            return true;
        } catch (_) {
            return false;
        }
    }

    function showLoader() {
        // You can implement your loader here
        $('body').append('<div class="page-loader"><div class="spinner-border text-primary"></div></div>');
    }

    function hideLoader() {
        $('.page-loader').remove();
    }

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

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

    // Add CSS for loader
    $('<style>')
        .text(`
            .page-loader {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(255, 255, 255, 0.8);
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 9999;
            }
        `)
        .appendTo('head');
});