document.addEventListener('DOMContentLoaded', () => {
    const form = document.getElementById('resume-form');
    const preview = document.getElementById('resume-preview');
    const downloadBtn = document.getElementById('download-btn');

    // Real-time preview update
    form.addEventListener('input', (e) => {
        const targetId = e.target.id;
        const value = e.target.value;

        if (targetId.startsWith('preview-')) {
            // This case handles elements that don't need special logic
            document.getElementById(targetId).textContent = value;
        } else {
            // Mapping input IDs to preview IDs
            const mapping = {
                'name': 'preview-name',
                'email': 'preview-email',
                'phone': 'preview-phone',
                'summary': 'preview-summary'
            };

            if (mapping[targetId]) {
                document.getElementById(mapping[targetId]).textContent = value;
            } else if (targetId === 'linkedin') {
                const linkedinLink = document.getElementById('preview-linkedin');
                if (value) {
                    linkedinLink.href = value;
                    linkedinLink.textContent = 'LinkedIn';
                } else {
                    linkedinLink.href = '#';
                    linkedinLink.textContent = '';
                }
            } else if (targetId === 'skills') {
                const skillsList = document.getElementById('preview-skills');
                skillsList.innerHTML = '';
                value.split(',').forEach(skill => {
                    const trimmedSkill = skill.trim();
                    if (trimmedSkill) {
                        const li = document.createElement('li');
                        li.textContent = trimmedSkill;
                        li.className = 'list-inline-item'; // For inline display with Bootstrap
                        skillsList.appendChild(li);
                    }
                });
            }
        }
    });

    // Dynamic field functionality for Education and Experience
    const addEducationBtn = document.getElementById('add-education');
    const educationContainer = document.getElementById('education-container');
    const previewEducation = document.getElementById('preview-education');

    addEducationBtn.addEventListener('click', () => {
        const count = educationContainer.children.length + 1;
        const newEducationHtml = `
            <div class="education-item mb-3 p-3 border rounded">
                <div class="mb-2">
                    <label for="degree${count}" class="form-label">Degree</label>
                    <input type="text" class="form-control" id="degree${count}" placeholder="Degree">
                </div>
                <div class="mb-2">
                    <label for="university${count}" class="form-label">University</label>
                    <input type="text" class="form-control" id="university${count}" placeholder="University">
                </div>
                <div class="row">
                    <div class="col">
                        <label for="edu-start${count}" class="form-label">Start Year</label>
                        <input type="text" class="form-control" id="edu-start${count}" placeholder="Start Year">
                    </div>
                    <div class="col">
                        <label for="edu-end${count}" class="form-label">End Year</label>
                        <input type="text" class="form-control" id="edu-end${count}" placeholder="End Year">
                    </div>
                </div>
            </div>
        `;
        educationContainer.insertAdjacentHTML('beforeend', newEducationHtml);
    });

    const addExperienceBtn = document.getElementById('add-experience');
    const experienceContainer = document.getElementById('experience-container');
    const previewExperience = document.getElementById('preview-experience');

    addExperienceBtn.addEventListener('click', () => {
        const count = experienceContainer.children.length + 1;
        const newExperienceHtml = `
            <div class="experience-item mb-3 p-3 border rounded">
                <div class="mb-2">
                    <label for="job-title${count}" class="form-label">Job Title</label>
                    <input type="text" class="form-control" id="job-title${count}" placeholder="Job Title">
                </div>
                <div class="mb-2">
                    <label for="company${count}" class="form-label">Company</label>
                    <input type="text" class="form-control" id="company${count}" placeholder="Company">
                </div>
                <div class="row">
                    <div class="col">
                        <label for="job-start${count}" class="form-label">Start Date</label>
                        <input type="text" class="form-control" id="job-start${count}" placeholder="Start Date">
                    </div>
                    <div class="col">
                        <label for="job-end${count}" class="form-label">End Date</label>
                        <input type="text" class="form-control" id="job-end${count}" placeholder="End Date">
                    </div>
                </div>
                <div class="mb-2 mt-2">
                    <label for="job-desc${count}" class="form-label">Responsibilities</label>
                    <textarea class="form-control" id="job-desc${count}" rows="3" placeholder="Responsibilities"></textarea>
                </div>
            </div>
        `;
        experienceContainer.insertAdjacentHTML('beforeend', newExperienceHtml);
    });

    // Handle real-time updates for dynamically added fields
    form.addEventListener('input', () => {
        // Update Education
        previewEducation.innerHTML = '';
        educationContainer.querySelectorAll('.education-item').forEach(item => {
            const degree = item.querySelector('[id^="degree"]').value;
            const university = item.querySelector('[id^="university"]').value;
            const start = item.querySelector('[id^="edu-start"]').value;
            const end = item.querySelector('[id^="edu-end"]').value;

            if (degree || university || start || end) {
                const div = document.createElement('div');
                div.innerHTML = `
                    <h4 class="mb-0">${degree} at ${university}</h4>
                    <p class="text-muted">${start} - ${end}</p>
                `;
                previewEducation.appendChild(div);
            }
        });

        // Update Experience
        previewExperience.innerHTML = '';
        experienceContainer.querySelectorAll('.experience-item').forEach(item => {
            const title = item.querySelector('[id^="job-title"]').value;
            const company = item.querySelector('[id^="company"]').value;
            const start = item.querySelector('[id^="job-start"]').value;
            const end = item.querySelector('[id^="job-end"]').value;
            const desc = item.querySelector('[id^="job-desc"]').value;

            if (title || company || start || end || desc) {
                const div = document.createElement('div');
                div.innerHTML = `
                    <h4 class="mb-0">${title} at ${company}</h4>
                    <p class="text-muted">${start} - ${end}</p>
                    <p>${desc}</p>
                `;
                previewExperience.appendChild(div);
            }
        });
    });

    // PDF Download functionality
    downloadBtn.addEventListener('click', () => {
        const element = document.getElementById('resume-preview');
        // Temporarily adjust styles for better PDF output
        element.style.padding = '30px';
        element.style.backgroundColor = '#fff';

        html2canvas(element).then(canvas => {
            const imgData = canvas.toDataURL('image/png');
            const { jsPDF } = window.jspdf;
            const pdf = new jsPDF('p', 'mm', 'a4');
            const imgProps = pdf.getImageProperties(imgData);
            const pdfWidth = pdf.internal.pageSize.getWidth();
            const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
            pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
            pdf.save('resume.pdf');
        });

        // Reset styles after download
        element.style.padding = '';
        element.style.backgroundColor = '';
    });
});