// Initialize SortableJS
document.addEventListener('DOMContentLoaded', function () {
    const el = document.getElementById('dynamicQuestions');
    if (el) {
        Sortable.create(el, {
            handle: '.question-handle',
            animation: 150,
            ghostClass: 'bg-blue-50'
        });
    }

    // Check for Job ID to Edit
    const urlParams = new URLSearchParams(window.location.search);
    const jobId = urlParams.get('id');

    if (jobId) {
        document.querySelector('.page-title').textContent = 'Edit Job';
        document.getElementById('btn-publish').textContent = 'Update Job';
        loadJobDetails(jobId);
    }

    const publishBtn = document.getElementById('btn-publish');
    if (publishBtn) {
        publishBtn.addEventListener('click', () => saveJob('Active', jobId));
    }

    const draftBtn = document.getElementById('btn-draft');
    if (draftBtn) {
        draftBtn.addEventListener('click', () => saveJob('Draft', jobId));
    }
});

function loadJobDetails(id) {
    fetch(`api/jobs.php?id=${id}`)
        .then(res => res.json())
        .then(job => {
            if (job.error) {
                alert('Job not found');
                return;
            }
            document.getElementById('job-title').value = job.title;
            // Handle department selection carefully (match text)
            const deptSelect = document.getElementById('job-department');
            if (deptSelect) deptSelect.value = job.department;

            document.getElementById('job-location').value = job.location;
            document.getElementById('job-type').value = job.type;
            document.getElementById('job-description').value = job.description;

            // Load Custom Questions (if stored as JSON string)
            if (job.requirements) {
                try {
                    const questions = JSON.parse(job.requirements);
                    if (Array.isArray(questions)) {
                        const container = document.getElementById('dynamicQuestions');
                        container.innerHTML = ''; // Clear defaults
                        questions.forEach(q => addQuestionSaved(q));
                    }
                } catch (e) { console.error('Error parsing questions'); }
            }
        })
        .catch(err => console.error(err));
}

function addQuestionSaved(q) {
    const container = document.getElementById('dynamicQuestions');
    const div = document.createElement('div');
    div.className = 'question-card';
    div.innerHTML = `
        <div class="question-handle"><i class="fa-solid fa-grip-vertical"></i></div>
        <div class="w-full">
            <div class="flex gap-4 mb-3">
                <div style="flex: 2;">
                    <label class="form-label text-xs text-muted mb-1">Question Text</label>
                    <input type="text" class="form-control font-bold" value="${q.question || ''}">
                </div>
                <div style="flex: 1;">
                    <label class="form-label text-xs text-muted mb-1">Answer Type</label>
                    <select class="form-control">
                        <option ${q.type === 'Text Answer' ? 'selected' : ''}>Text Answer</option>
                        <option ${q.type === 'Multiple Choice' ? 'selected' : ''}>Multiple Choice</option>
                        <option ${q.type === 'File Upload' ? 'selected' : ''}>File Upload</option>
                    </select>
                </div>
            </div>
            <div class="flex items-center justify-between border-t border-gray-100 pt-3 mt-2" style="border-top: 1px solid #f1f5f9;">
                <label class="flex items-center text-sm text-main cursor-pointer custom-checkbox select-none hover:text-primary transition-colors">
                    <input type="checkbox" style="width: 14px; height: 14px; accent-color: var(--primary-color);" ${q.required ? 'checked' : ''}> 
                    <span class="font-medium">Required Field</span>
                </label>
                <button class="btn btn-outline hover:bg-red-50" style="padding: 0.4rem 0.8rem; font-size: 0.8rem; color: #ef4444; border-color: #fca5a5;" onclick="this.closest('.question-card').remove()">
                    <i class="fa-regular fa-trash-can"></i> Remove
                </button>
            </div>
        </div>
    `;
    container.appendChild(div);
}

function saveJob(status, id = null) {
    const title = document.getElementById('job-title').value;
    const department = document.getElementById('job-department').value;
    const location = document.getElementById('job-location').value;
    const type = document.getElementById('job-type').value;
    const description = document.getElementById('job-description').value;

    // Basic Validation
    if (!title) {
        alert('Please enter a Job Title');
        return;
    }
    if (department === 'Select Department') {
        alert('Please select a Department');
        return;
    }

    // Collect Dynamic Questions
    const questions = [];
    document.querySelectorAll('.question-card').forEach(card => {
        const textInput = card.querySelector('input[type="text"]');
        const typeSelect = card.querySelector('select');
        const requiredCheck = card.querySelector('input[type="checkbox"]');

        if (textInput && textInput.value) {
            questions.push({
                question: textInput.value,
                type: typeSelect ? typeSelect.value : 'Text Answer',
                required: requiredCheck ? requiredCheck.checked : false
            });
        }
    });

    // Store complex structure as JSON string for now, or just text if simple
    const requirements = JSON.stringify(questions);

    const data = {
        title,
        department,
        location,
        type,
        status: status, // 'Active' or 'Draft'
        description,
        requirements
    };

    const method = id ? 'PUT' : 'POST';
    const payload = { ...data };
    if (id) payload.id = id;

    const actionBtn = status === 'Active' ? document.getElementById('btn-publish') : document.getElementById('btn-draft');
    const originalText = actionBtn.textContent;
    actionBtn.textContent = 'Saving...';
    actionBtn.disabled = true;

    fetch('api/jobs.php', {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
    })
        .then(async response => {
            const text = await response.text();
            try {
                const result = JSON.parse(text);
                if (!response.ok) {
                    throw new Error(result.error || 'Server responded with ' + response.status);
                }
                // Success
                if (status === 'Draft') {
                    alert('Job saved as Draft!');
                    window.location.href = 'jobs.html';
                } else {
                    alert('Job Published Successfully!');
                    window.location.href = 'jobs.html';
                }
            } catch (e) {
                console.error('Parse Error:', text);
                throw new Error('Invalid Server Response: ' + text);
            }
        })
        .catch(error => {
            console.error('Save Error:', error);
            alert('Failed to save job: ' + error.message);
        })
        .finally(() => {
            actionBtn.textContent = originalText;
            actionBtn.disabled = false;
        });
}

// Initialize Sortable for drag-and-drop questions
document.addEventListener('DOMContentLoaded', function () {
    // Event listener for "Add Question" button
    const btnAddQuestion = document.getElementById('btn-add-question');
    if (btnAddQuestion) {
        btnAddQuestion.addEventListener('click', () => addQuestion());
    }

    // Expose function for suggested buttons
    window.addSuggestedQuestion = function (type) {
        switch (type) {
            case 'Salary':
                addQuestion('What is your expected salary?', 'Text Answer', true);
                break;
            case 'Experience':
                addQuestion('How many years of valid experience do you have?', 'Text Answer', true);
                break;
            case 'Portfolio':
                addQuestion('Please provide a link to your portfolio.', 'Text Answer', false);
                break;
            case 'LinkedIn':
                addQuestion('Please provide a link to your LinkedIn profile.', 'Text Answer', false);
                break;
            case 'StartDate':
                addQuestion('What is your earliest possible start date?', 'Text Answer', true);
                break;
        }
    };
});

function addQuestion(defaultText = '', defaultType = 'Text Answer', defaultRequired = false) {
    const container = document.getElementById('dynamicQuestions');
    if (!container) return; // Guard clause

    const div = document.createElement('div');
    div.className = 'question-card';
    div.innerHTML = `
        <div class="question-handle"><i class="fa-solid fa-grip-vertical"></i></div>
        <div class="w-full">
            <div class="flex gap-4 mb-3">
                <div style="flex: 2;">
                    <label class="form-label text-xs text-muted mb-1">Question Text</label>
                    <input type="text" class="form-control font-bold" value="${defaultText}" placeholder="e.g. How many years of experience?">
                </div>
                <div style="flex: 1;">
                    <label class="form-label text-xs text-muted mb-1">Answer Type</label>
                    <select class="form-control">
                        <option ${defaultType === 'Text Answer' ? 'selected' : ''}>Text Answer</option>
                        <option ${defaultType === 'Multiple Choice' ? 'selected' : ''}>Multiple Choice</option>
                        <option ${defaultType === 'File Upload' ? 'selected' : ''}>File Upload</option>
                    </select>
                </div>
            </div>
            <div class="flex items-center justify-between border-t border-gray-100 pt-3 mt-2" style="border-top: 1px solid #f1f5f9;">
                <label class="flex items-center text-sm text-main cursor-pointer custom-checkbox select-none hover:text-primary transition-colors">
                    <input type="checkbox" style="width: 14px; height: 14px; accent-color: var(--primary-color);" ${defaultRequired ? 'checked' : ''}> 
                    <span class="font-medium">Required Field</span>
                </label>
                <button class="btn btn-outline hover:bg-red-50 text-danger border-red-200" onclick="this.closest('.question-card').remove()">
                    <i class="fa-regular fa-trash-can"></i> Remove
                </button>
            </div>
        </div>
    `;
    container.appendChild(div);

    // Auto focus the new input if it's empty
    if (!defaultText) {
        const input = div.querySelector('input[type="text"]');
        if (input) input.focus();
    }
}
