document.addEventListener('DOMContentLoaded', function() {

    // Initialize new order form
    initNewOrderForm();

    // File Upload Component
    let dentalFileUpload = null;

    // Make setupFileUpload globally accessible
    window.setupFileUpload = function() {
        // Check if the upload container exists
        const uploadContainer = document.getElementById('dental-file-upload');
        if (!uploadContainer) {
            return;
        }
        
        // Prevent multiple initializations
        if (window.dentalFileUploadInitialized) {
            return;
        }
        
        // Check if localization data is available
        if (!window.newOrderLocalization) {
            return;
        }
        
        // Provide WordPress data to the component
        window.dentalUploadUserId = window.newOrderLocalization?.userId || 0;
        window.dentalUploadNonces = {
            'dental_file_upload': window.newOrderLocalization?.nonces?.dental_file_upload || '',
            'dental_file_delete': window.newOrderLocalization?.nonces?.dental_file_delete || ''
        };
        window.dentalUploadAjaxUrl = window.newOrderLocalization?.ajaxUrl || '';
    
        // Check if DentalFileUpload class is available
        if (typeof DentalFileUpload === 'undefined') {
            return;
        }
        
        // Initialize the upload component
        dentalFileUpload = new DentalFileUpload({
            showFormatInfo: false, // Disable format info display
            onFileAdded: function(file, uploadData) {
                // File added successfully
            },
            onFileRemoved: function(file) {
                // File removed successfully
            },
            onUploadComplete: function(file, uploadData) {
                // File uploaded successfully
            },
            onUploadError: function(file, error) {
                // Handle upload error
            },
            onValidationError: function(file, errors) {
                // Handle validation error
            }
        });
        
        // Initialize the component (HTML already exists in the page)
        dentalFileUpload.mount();
        
        // Mark as initialized to prevent duplicates
        window.dentalFileUploadInitialized = true;
    };

    // Initialize file upload with a small delay to ensure DOM is ready
    setTimeout(() => {
        setupFileUpload();
    }, 100);
    
    // Also try to initialize when the new order section becomes visible
    const newOrderSection = document.getElementById('new-order-section');
    if (newOrderSection) {
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                    if (newOrderSection.classList.contains('active')) {
                        // New order section is now visible, try to initialize file upload
                        setTimeout(() => {
                            if (!window.dentalFileUploadInitialized) {
                                setupFileUpload();
                            }
                        }, 200);
                    }
                }
            });
        });
        
        observer.observe(newOrderSection, {
            attributes: true,
            attributeFilter: ['class']
        });
    }

    // New Order Form Functionality
    function initNewOrderForm() {

        let currentStep = 1;
        const totalSteps = 4;
        let step2Skipped = false;
        
        // Step navigation texts
        const stepTexts = {
            1: {
                next: 'انتخاب زیر خدمات',
                prev: ''
            },
            2: {
                next: 'جزئیات دستور کار',
                prev: 'انتخاب خدمات'
            },
            3: {
                next: 'آپلود فایل ها',
                prev: 'انتخاب زیر خدمات'
            },
            4: {
                next: 'ثبت سفارش',
                prev: 'جزئیات دستور کار'
            }
        };
        
        // Initialize form
        function initForm() {
            setupEventListeners();
            updateProgress();
            updateNavigationButtons();
        }
        
        // Setup event listeners
        function setupEventListeners() {
            // Next button
            document.getElementById('next_step').addEventListener('click', nextStep);
            
            // Previous button
            document.getElementById('prev_step').addEventListener('click', prevStep);
            
            // Form submission
            document.getElementById('new-order-form').addEventListener('submit', function(e) {
                e.preventDefault();
                showOrderSummary();
            });
            
            // Service selection with auto-advance
            setupServiceSelection();
            
                    // Sub-services conditional display
            setupSubServicesLogic();
            
            // Step 3 form validation
            setupStep3Validation();
            
            // Skip step functionality
            setupSkipStep();
        }
        
        // Next step
        function nextStep() {
            if (currentStep < totalSteps) {
                currentStep++;
                updateForm();
                scrollToFormTop();
            }
        }

        // Previous step
        function prevStep() {
            if (currentStep > 1) {
                currentStep--;
                updateForm();
                scrollToFormTop();
            }
        }
        
        // Collect sub-services in hierarchical structure
        function collectSubServicesHierarchically() {
            const subServices = [];
            
            // Only collect radio buttons from service-field containers (sub-services)
            const serviceFields = document.querySelectorAll('.service-field');
            
            serviceFields.forEach(field => {
                const checkedRadios = field.querySelectorAll('input[type="radio"]:checked');
                checkedRadios.forEach(radio => {
                    subServices.push(radio.value);
                });
            });
            
            return subServices;
        }
        
        // Show order summary overlay
        function showOrderSummary() {
            // Populate summary sections
            populateSummaryStep1();
            populateSummaryStep2();
            populateSummaryStep3();
            populateSummaryStep4();
            
            // Show overlay
            const overlay = document.getElementById('order-summary-overlay');
            if (overlay) {
                overlay.style.display = 'flex';
                document.body.style.overflow = 'hidden'; // Prevent background scrolling
            }
            
            // Setup overlay button handlers
            setupSummaryButtons();
        }
        
        // Hide order summary overlay
        function hideOrderSummary() {
            const overlay = document.getElementById('order-summary-overlay');
            if (overlay) {
                overlay.style.display = 'none';
                document.body.style.overflow = ''; // Restore scrolling
            }
        }
        
        // Setup summary overlay buttons
        function setupSummaryButtons() {
            // Cancel button - hide overlay
            const cancelBtn = document.getElementById('summary-cancel-btn');
            if (cancelBtn) {
                cancelBtn.onclick = function() {
                    hideOrderSummary();
                };
            }
            
            // Submit button - actually submit the order
            const submitBtn = document.getElementById('summary-submit-btn');
            if (submitBtn) {
                submitBtn.onclick = function() {
                    // Disable button to prevent double submission
                    submitBtn.disabled = true;
                    submitBtn.innerHTML = '<i class="bi bi-arrow-clockwise"></i> در حال ثبت...';
                    
                    // Submit the order
                    completeOrder();
                };
            }
        }
        
        // Populate Step 1 summary
        function populateSummaryStep1() {
            const container = document.getElementById('summary-step-1');
            if (!container) return;
            
            const selectedService = document.querySelector('input[name="service_type"]:checked');
            if (selectedService) {
                const label = selectedService.closest('.field-option').querySelector('.option-title');
                const serviceName = label ? label.textContent.trim() : selectedService.value;
                container.innerHTML = `
                    <div class="summary-item">
                        <i class="bi bi-check-circle-fill"></i>
                        <span>${serviceName}</span>
                    </div>
                `;
            } else {
                container.innerHTML = '<div class="summary-item empty">هیچ خدماتی انتخاب نشده است</div>';
            }
        }
        
        // Populate Step 2 summary
        function populateSummaryStep2() {
            const container = document.getElementById('summary-step-2');
            if (!container) return;
            
            // Check if step 2 was skipped
            if (step2Skipped) {
                container.innerHTML = `
                    <div class="summary-item info">
                        <i class="bi bi-info-circle-fill"></i>
                        <span>این مرحله رد شده است و توسط متخصصین لابراتوار تکمیل می‌شود</span>
                    </div>
                `;
                return;
            }
            
            const summaries = [];
            const visibleFields = document.querySelectorAll('.service-field[style*="display: block"]');
            
            visibleFields.forEach(field => {
                // Get checked radio buttons
                const checkedRadios = field.querySelectorAll('input[type="radio"]:checked');
                checkedRadios.forEach(radio => {
                    const label = radio.closest('.field-option').querySelector('.option-title');
                    if (label) {
                        summaries.push({
                            type: 'radio',
                            text: label.textContent.trim()
                        });
                    }
                });
                
                // Get checked checkboxes
                const checkedCheckboxes = field.querySelectorAll('input[type="checkbox"]:checked');
                checkedCheckboxes.forEach(checkbox => {
                    const label = checkbox.closest('.field-option').querySelector('.option-title');
                    if (label) {
                        summaries.push({
                            type: 'checkbox',
                            text: label.textContent.trim()
                        });
                    }
                });
            });
            
            if (summaries.length === 0) {
                container.innerHTML = '<div class="summary-item empty">هیچ زیر خدماتی انتخاب نشده است</div>';
            } else {
                container.innerHTML = summaries.map(item => `
                    <div class="summary-item">
                        <i class="bi bi-check-circle-fill"></i>
                        <span>${item.text}</span>
                    </div>
                `).join('');
            }
        }
        
        // Populate Step 3 summary
        function populateSummaryStep3() {
            const container = document.getElementById('summary-step-3');
            if (!container) return;
            
            const items = [];
            
            // Patient name
            const patientName = document.getElementById('patient_name');
            if (patientName && patientName.value.trim()) {
                items.push(`
                    <div class="summary-item summary-patient-name">
                        <i class="bi bi-person-fill"></i>
                        <div class="summary-item-content">
                            <span class="summary-item-label">نام بیمار:</span>
                            <span class="summary-item-value">${patientName.value.trim()}</span>
                        </div>
                    </div>
                `);
            }
            
            // Patient age
            const patientAge = document.querySelector('input[name="patient_age"]:checked');
            if (patientAge) {
                const ageLabel = patientAge.closest('.age-option').querySelector('.age-text');
                if (ageLabel) {
                    items.push(`
                        <div class="summary-item summary-patient-age">
                            <i class="bi bi-calendar3"></i>
                            <div class="summary-item-content">
                                <span class="summary-item-label">سن بیمار:</span>
                                <span class="summary-item-value">${ageLabel.textContent.trim()}</span>
                            </div>
                        </div>
                    `);
                }
            }
            
            // Order note - show full text, no truncation
            const orderNote = document.getElementById('order_note');
            if (orderNote && orderNote.value.trim()) {
                const noteText = orderNote.value.trim();
                items.push(`
                    <div class="summary-item summary-order-note">
                        <i class="bi bi-file-text"></i>
                        <div class="summary-item-content">
                            <span class="summary-item-label">دستور کار:</span>
                            <span class="summary-item-value">${noteText}</span>
                        </div>
                    </div>
                `);
            }
            
            if (items.length === 0) {
                container.innerHTML = '<div class="summary-item empty">اطلاعاتی وارد نشده است</div>';
            } else {
                container.innerHTML = items.join('');
            }
        }
        
        // Populate Step 4 summary
        function populateSummaryStep4() {
            const container = document.getElementById('summary-step-4');
            if (!container) return;
            
            const uploadedFiles = dentalFileUpload ? dentalFileUpload.getSelectedFiles() : [];
            
            if (uploadedFiles.length === 0) {
                container.innerHTML = '<div class="summary-item empty">هیچ فایلی آپلود نشده است</div>';
            } else {
                const fileItems = uploadedFiles.map(fileData => {
                    const fileName = fileData.file.name;
                    const fileSize = formatFileSize(fileData.file.size);
                    const fileIcon = getFileIcon(fileData.file.type || fileName);
                    
                    return `
                        <div class="summary-item file-item">
                            <i class="bi ${fileIcon}"></i>
                            <div class="summary-item-content">
                                <span class="summary-item-value file-name">${fileName}</span>
                                <span class="summary-item-label file-size">${fileSize}</span>
                            </div>
                        </div>
                    `;
                }).join('');
                
                container.innerHTML = `
                    <div class="summary-files-count">
                        <i class="bi bi-files"></i>
                        <span>تعداد فایل‌ها: ${uploadedFiles.length}</span>
                    </div>
                    <div class="summary-files-list">
                        ${fileItems}
                    </div>
                `;
            }
        }
        
        // Format file size
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
        }
        
        // Get file icon based on file type
        function getFileIcon(fileType) {
            if (!fileType) return 'bi-file-earmark';
            
            if (fileType.startsWith('image/')) return 'bi-image';
            if (fileType.startsWith('video/')) return 'bi-camera-video';
            if (fileType.startsWith('audio/')) return 'bi-music-note-beamed';
            if (fileType.includes('pdf')) return 'bi-file-earmark-pdf';
            if (fileType.includes('word') || fileType.includes('document')) return 'bi-file-earmark-word';
            if (fileType.includes('excel') || fileType.includes('spreadsheet')) return 'bi-file-earmark-excel';
            if (fileType.includes('zip') || fileType.includes('rar') || fileType.includes('archive')) return 'bi-file-earmark-zip';
            if (fileType.includes('stl') || fileType.includes('3d')) return 'bi-box';
            
            return 'bi-file-earmark';
        }
        
        // Complete order function
        function completeOrder() {
            const progressFill = document.querySelector('.progress-fill');
            
            progressFill.style.width = '100%';
            progressFill.classList.add('completed');
            
            // Collect form data
            const formData = new FormData();
            
            // Add form fields
            formData.append('action', 'submit_dental_order');
            formData.append('nonce', window.newOrderLocalization?.nonces?.dental_order_submit || '');
            
            // Add service type
            const serviceType = document.querySelector('input[name="service_type"]:checked');
            if (serviceType) {
                formData.append('service_type', serviceType.value);
            }
            
            // Collect sub-services in hierarchical structure
            const subServices = collectSubServicesHierarchically();
            
            if (subServices.length > 0) {
                formData.append('sub_services', JSON.stringify(subServices));
            }
            
            // Collect removable services (checkboxes)
            const removableServices = [];
            const checkboxes = document.querySelectorAll('input[name="removable_services[]"]:checked');
            checkboxes.forEach(checkbox => {
                removableServices.push(checkbox.value);
            });
            
            if (removableServices.length > 0) {
                formData.append('removable_services', JSON.stringify(removableServices));
            }
            
            // Add patient information
            const patientName = document.getElementById('patient_name');
            const patientAge = document.querySelector('input[name="patient_age"]:checked');
            const orderInstructions = document.getElementById('order_note');
            
            if (patientName) {
                formData.append('patient_name', patientName.value);
            }
            if (patientAge) {
                formData.append('patient_age', patientAge.value);
            }
            if (orderInstructions) {
                formData.append('order_note', orderInstructions.value);
            }
            
            // Add uploaded file data
            const uploadedFiles = dentalFileUpload ? dentalFileUpload.getSelectedFiles() : [];
            
            if (uploadedFiles.length > 0) {
                // Extract attachment data from uploaded files
                const attachments = uploadedFiles
                    .filter(fileData => fileData.uploadData && fileData.uploadData.attachment_id)
                    .map(fileData => ({
                        attachment_id: fileData.uploadData.attachment_id,
                        original_name: fileData.file.name,
                        file_size: fileData.file.size,
                        file_type: fileData.file.type
                    }));
                
                formData.append('attachments', JSON.stringify(attachments));
            }
            
            // Submit order
            fetch(window.newOrderLocalization?.ajaxUrl || '', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                console.log('Server response:', data);
                // Hide summary overlay
                hideOrderSummary();
                
                if (data.success) {
                    // Show success message
                    showOrderSuccess(data.data);
                } else {
                    // Show error message
                    showOrderError(data.message || 'خطا در ثبت سفارش');
                    
                    // Re-enable submit button in case of error
                    const submitBtn = document.getElementById('summary-submit-btn');
                    if (submitBtn) {
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = '<i class="bi bi-check-circle"></i> ثبت نهایی سفارش';
                    }
                }
            })
            .catch(error => {
                // Hide summary overlay
                hideOrderSummary();
                
                // Show error message
                showOrderError('خطا در اتصال به سرور');
                
                // Re-enable submit button in case of error
                const submitBtn = document.getElementById('summary-submit-btn');
                if (submitBtn) {
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '<i class="bi bi-check-circle"></i> ثبت نهایی سفارش';
                }
            });
        }
        
        // Show order success
        function showOrderSuccess(orderData) {
            // Redirect to single order page
            if (orderData && orderData.dental_id) {
                const orderUrl = window.location.origin + '/d/' + orderData.dental_id;
                window.location.href = orderUrl;
            } else {
                // Fallback: show success message if redirect fails
                const successMessage = `
                    <div class="order-success">
                        <div class="success-icon">
                            <i class="bi bi-check-circle"></i>
                        </div>
                        <h3>سفارش شما با موفقیت ثبت شد!</h3>
                        <p>شماره سفارش: ${orderData.dental_id || 'نامشخص'}</p>
                        <p>سفارش شما در حال بررسی است و به زودی با شما تماس خواهیم گرفت.</p>
                        <button class="btn btn-primary" onclick="window.location.reload()">
                            سفارش جدید
                        </button>
                    </div>
                `;
                
                const formContainer = document.querySelector('.order-form');
                if (formContainer) {
                    formContainer.innerHTML = successMessage;
                }
            }
        }
        
        // Show order error
        function showOrderError(message) {
            alert('خطا: ' + message);
        }

        // Update form display
        function updateForm() {
            
            // Update form steps
            document.querySelectorAll('.form-step').forEach(step => {
                step.classList.remove('active');
            });
            
            const activeStep = document.querySelector(`.form-step[data-step="${currentStep}"]`);
            if (activeStep) {
                activeStep.classList.add('active');
            }
            
            // Update progress
            updateProgress();
            
            // Update navigation buttons
            updateNavigationButtons();
            
            // Handle step 2 field display based on step 1 selection
            if (currentStep === 2) {
                showFieldsBasedOnStep1Selection();
                // Ensure validation runs after fields are shown
                setTimeout(() => {
                    updateStep2Validation();
                }, 100);
            }
            
            // Handle step 3 validation
            if (currentStep === 3) {
                // Ensure validation runs immediately for step 3
                setTimeout(() => {
                    updateStep3Validation();
                }, 100);
            }
            
            // Handle step 4 validation
            if (currentStep === 4) {
                // Ensure file upload is initialized and validation runs
                setTimeout(() => {
                    // Re-initialize file upload if not already done
                    if (!dentalFileUpload) {
                        // Call the global setupFileUpload function
                        if (typeof window.setupFileUpload === 'function') {
                            window.setupFileUpload();
                        }
                    }
                    
                    if (typeof updateStep4Validation === 'function') {
                        updateStep4Validation();
                    }
                }, 100);
            }
        }
        
        // Get step 1 summary (service type)
        function getStep1Summary() {
            const selectedService = document.querySelector('input[name="service_type"]:checked');
            if (selectedService) {
                const label = selectedService.closest('.field-option').querySelector('.option-title');
                return label ? label.textContent.trim() : '';
            }
            return '';
        }
        
        // Get step 2 summary (selected sub-services)
        function getStep2Summary() {
            // Check if step 2 was skipped
            if (step2Skipped) {
                return 'توسط لابراتوار تکمیل می‌شود';
            }
            
            const summaries = [];
            const visibleFields = document.querySelectorAll('.service-field[style*="display: block"]');
            
            visibleFields.forEach(field => {
                // Get checked radio buttons
                const checkedRadios = field.querySelectorAll('input[type="radio"]:checked');
                checkedRadios.forEach(radio => {
                    const label = radio.closest('.field-option').querySelector('.option-title');
                    if (label) {
                        summaries.push(label.textContent.trim());
                    }
                });
                
                // Get checked checkboxes
                const checkedCheckboxes = field.querySelectorAll('input[type="checkbox"]:checked');
                checkedCheckboxes.forEach(checkbox => {
                    const label = checkbox.closest('.field-option').querySelector('.option-title');
                    if (label) {
                        summaries.push(label.textContent.trim());
                    }
                });
            });
            
            if (summaries.length === 0) {
                return '';
            } else {
                return summaries.join('، ');
            }
        }
        
        // Get step 3 summary (patient name, age, and order note)
        function getStep3Summary() {
            const parts = [];
            
            // Patient name
            const patientName = document.getElementById('patient_name');
            if (patientName && patientName.value.trim()) {
                parts.push(patientName.value.trim());
            }
            
            // Patient age
            const patientAge = document.querySelector('input[name="patient_age"]:checked');
            if (patientAge) {
                const ageLabel = patientAge.closest('.age-option').querySelector('.age-text');
                if (ageLabel) {
                    parts.push(ageLabel.textContent.trim());
                }
            }
            
            // Order note
            const orderNote = document.getElementById('order_note');
            if (orderNote && orderNote.value.trim()) {
                parts.push('دستورکار');
            }
            
            return parts.join(' + ');
        }
        
        // Update step summaries
        function updateStepSummaries() {
            // Step 1 summary
            const step1Summary = document.querySelector('.progress-step[data-step="1"] .step-summary');
            if (step1Summary) {
                const summary = getStep1Summary();
                step1Summary.textContent = summary;
            }
            
            // Step 2 summary
            const step2Summary = document.querySelector('.progress-step[data-step="2"] .step-summary');
            if (step2Summary) {
                const summary = getStep2Summary();
                step2Summary.textContent = summary;
            }
            
            // Step 3 summary
            const step3Summary = document.querySelector('.progress-step[data-step="3"] .step-summary');
            if (step3Summary) {
                const summary = getStep3Summary();
                step3Summary.textContent = summary;
            }
            
            // Step 4 summary (empty)
            const step4Summary = document.querySelector('.progress-step[data-step="4"] .step-summary');
            if (step4Summary) {
                step4Summary.textContent = '';
            }
        }
        
        // Update progress bar
        function updateProgress() {

            // Calculate progress percentage to align with step circles
            const progressFill = document.querySelector('.progress-fill');
            // Calculate percentage per step (100% divided by double total steps to align with circle centers)
            const stepPercentage = 100 / (totalSteps * 2);
            let progressPercentage = stepPercentage + ((currentStep - 1) * (stepPercentage * 2));
            
            progressFill.style.width = progressPercentage + '%';
            
            // Update step indicators
            document.querySelectorAll('.progress-step').forEach((step, index) => {
                const stepNumber = index + 1;
                step.classList.remove('active', 'completed');
                
                if (stepNumber === currentStep) {
                    step.classList.add('active');
                } else if (stepNumber < currentStep) {
                    step.classList.add('completed');
                }
            });
            
            // Update step summaries
            updateStepSummaries();
        }
        
        // Update navigation buttons
        function updateNavigationButtons() {
            const formNavigation = document.querySelector('.form-navigation');
            const prevBtn = document.getElementById('prev_step');
            const nextBtn = document.getElementById('next_step');
            const submitBtn = document.getElementById('submit_order');
            const prevText = document.getElementById('prev_step_text');
            const nextText = document.getElementById('next_step_text');
            
            // Previous button
            if (currentStep === 1) {
                prevBtn.style.display = 'none';
                formNavigation.classList.add('reverse');
            } else {
                prevBtn.style.display = 'flex';
                formNavigation.classList.remove('reverse');
                prevText.textContent = stepTexts[currentStep].prev;
            }
            
            // Next/Submit button
            if (currentStep === totalSteps) {
                nextBtn.style.display = 'none';
                submitBtn.style.display = 'inline-flex';
            } else {
                nextBtn.style.display = 'inline-flex';
                submitBtn.style.display = 'none';
                nextText.textContent = stepTexts[currentStep].next;
                
                // Update button state for step 1
                if (currentStep === 1) {
                    updateNextButtonState();
                }
            }
        }
        
            // Setup service selection with auto-advance
        function setupServiceSelection() {
            const serviceRadios = document.querySelectorAll('input[name="service_type"]');
            let autoAdvanceTimeout = null;
            let lastSelectedService = null;
            
            serviceRadios.forEach(radio => {
                radio.addEventListener('change', function() {
                    if (this.checked) {
                        // Check if service selection changed
                        if (lastSelectedService && lastSelectedService !== this.id) {
                            // Service changed, clear step 2 selections
                            clearAllSubServiceFields();
                            // Reset skip flag when service changes
                            step2Skipped = false;
                        }
                        
                        lastSelectedService = this.id;
                        
                        // Clear any existing timeout
                        if (autoAdvanceTimeout) {
                            clearTimeout(autoAdvanceTimeout);
                        }
                        
                        // Auto-advance to next step after a short delay
                        autoAdvanceTimeout = setTimeout(() => {
                            nextStep();
                        }, 250);
                    }
                    
                    // Update next button state
                    updateNextButtonState();
                    
                    // Update step 1 summary
                    updateStepSummaries();
                });
            });
            
            // Allow unselecting by clicking on the same option
            const serviceCards = document.querySelectorAll('input[name="service_type"] + .option-card');
            serviceCards.forEach(card => {
                card.addEventListener('click', function(e) {
                    const radio = this.previousElementSibling;
                    if (radio && radio.checked) {
                        // If already selected, unselect it
                        e.preventDefault();
                        e.stopPropagation();
                        
                        // Clear auto-advance timeout
                        if (autoAdvanceTimeout) {
                            clearTimeout(autoAdvanceTimeout);
                            autoAdvanceTimeout = null;
                        }
                        
                        radio.checked = false;
                        lastSelectedService = null;
                        // Reset skip flag when service is unselected
                        step2Skipped = false;
                        // Trigger change event to update styling
                        radio.dispatchEvent(new Event('change'));
                    }
                });
            });
            
            // Initial button state
            updateNextButtonState();
        }
        
        // Update next button state based on service selection
        function updateNextButtonState() {
            const nextBtn = document.getElementById('next_step');
            
            if (currentStep === 1) {
                const selectedService = document.querySelector('input[name="service_type"]:checked');
                if (selectedService) {
                    nextBtn.disabled = false;
                    nextBtn.classList.remove('btn-disabled');
                } else {
                    nextBtn.disabled = true;
                    nextBtn.classList.add('btn-disabled');
                }
            } else if (currentStep === 2) {
                updateStep2Validation();
            } else if (currentStep === 3) {
                updateStep3Validation();
            }
        }
        
        // Setup sub-services conditional logic
        function setupSubServicesLogic() {
            // Listen for service type changes (step 1)
            document.querySelectorAll('input[name="service_type"]').forEach(radio => {
                radio.addEventListener('change', function() {
                    if (currentStep === 1) {
                        // Clear all sub-service fields when service type changes
                        clearAllSubServiceFields();
                    }
                });
            });
            
            // Listen for all sub-service radio and checkbox changes
            document.querySelectorAll('.service-field input[type="radio"], .service-field input[type="checkbox"]').forEach(input => {
                input.addEventListener('change', function() {
                    // If user makes a selection, step 2 is no longer skipped
                    if (step2Skipped && this.checked) {
                        step2Skipped = false;
                    }
                    handleSubServiceChange(this);
                    // Update step 2 summary
                    updateStepSummaries();
                });
            });
            
            // Allow unselecting radio options
            document.querySelectorAll('.option-card').forEach(card => {
                card.addEventListener('click', function(e) {
                    const input = this.previousElementSibling;
                    if (input.type === 'radio' && input.checked) {
                        e.preventDefault();
                        e.stopPropagation();
                        input.checked = false;
                        input.dispatchEvent(new Event('change'));
                    }
                });
            });
        }
        
        // Handle sub-service field changes
        function handleSubServiceChange(changedInput) {
            const currentField = changedInput.closest('.service-field');
            const fieldId = currentField.id;
            
            // Check if this is a parent field change (not a selection within a child field)
            const isParentFieldChange = isParentField(fieldId);
            
            if (isParentFieldChange) {
                // Hide all dependent fields first
                hideDependentFields(fieldId);
                
                // Show dependent fields based on selection
                if (changedInput.checked) {
                    showDependentFields(changedInput);
                }
            }
            
            // Update validation
            updateStep2Validation();
        }
        
        // Show dependent fields based on selection
        function showDependentFields(selectedInput) {
            const inputId = selectedInput.id;
            
            // Mapping of input IDs to dependent field IDs
            const dependencies = {
                'service_orthodontics': ['field_1'],
                'service_fixed': ['field_2'],
                'service_removable': ['field_3', 'field_14'],
                'fixed_crown': ['field_4'],
                'fixed_abutment': ['field_5'],
                'fixed_laminate': ['field_6'],
                'crown_zirconia': ['field_7'],
                'crown_pmma': ['field_8'],
                'laminate_laminate': ['field_9'],
                'laminate_core': ['field_10'],
                'removable_denture': ['field_11'],
                'removable_partial': ['field_12'],
                'partial_acrylic': ['field_13']
            };
            
            if (dependencies[inputId]) {
                dependencies[inputId].forEach(fieldId => {
                    const field = document.getElementById(fieldId);
                    if (field) {
                        field.style.display = 'block';
                        // Make required fields required again
                        field.querySelectorAll('input[required]').forEach(input => {
                            input.required = true;
                        });
                        
                        // Scroll to the newly visible field
                        scrollToField(field);
                    }
                });
            }
        }
        
            // Hide dependent fields
        function hideDependentFields(currentFieldId) {
            // Get all fields that should be hidden when current field changes
            const fieldsToHide = getFieldsToHide(currentFieldId);
            
            fieldsToHide.forEach(fieldId => {
                const field = document.getElementById(fieldId);
                if (field) {
                    field.style.display = 'none';
                    // Clear and unrequire all inputs in this field
                    field.querySelectorAll('input').forEach(input => {
                        input.checked = false;
                        input.required = false;
                    });
                }
            });
            
            // Also hide any fields that are dependent on the current field's options
            hideOptionDependentFields(currentFieldId);
            
            // Validate all visible fields based on current selections
            validateAllVisibleFields();
        }
        
        // Get fields that should be hidden based on current field
        function getFieldsToHide(currentFieldId) {
            const hideMap = {
                'field_1': ['field_2', 'field_3', 'field_4', 'field_5', 'field_6', 'field_7', 'field_8', 'field_9', 'field_10', 'field_11', 'field_12', 'field_13', 'field_14'],
                'field_2': ['field_1', 'field_3', 'field_14'],
                'field_3': ['field_1', 'field_2', 'field_4', 'field_5', 'field_6', 'field_7', 'field_8', 'field_9', 'field_10'],
                'field_4': ['field_5', 'field_6', 'field_7', 'field_8', 'field_9', 'field_10', 'field_11', 'field_12', 'field_13'],
                'field_5': ['field_4', 'field_6', 'field_7', 'field_8', 'field_9', 'field_10', 'field_11', 'field_12', 'field_13'],
                'field_6': ['field_4', 'field_5', 'field_7', 'field_8', 'field_9', 'field_10', 'field_11', 'field_12', 'field_13'],
                'field_7': ['field_8', 'field_9', 'field_10', 'field_11', 'field_12', 'field_13'],
                'field_8': ['field_7', 'field_9', 'field_10', 'field_11', 'field_12', 'field_13'],
                'field_9': ['field_7', 'field_8', 'field_10', 'field_11', 'field_12', 'field_13'],
                'field_10': ['field_7', 'field_8', 'field_9', 'field_11', 'field_12', 'field_13'],
                'field_11': ['field_4', 'field_5', 'field_6', 'field_7', 'field_8', 'field_9', 'field_10', 'field_12', 'field_13'],
                'field_12': ['field_4', 'field_5', 'field_6', 'field_7', 'field_8', 'field_9', 'field_10', 'field_11', 'field_13'],
                'field_13': ['field_4', 'field_5', 'field_6', 'field_7', 'field_8', 'field_9', 'field_10', 'field_11', 'field_12']
            };
            
            return hideMap[currentFieldId] || [];
        }
        
            // Hide fields that are dependent on specific options within a field
        function hideOptionDependentFields(currentFieldId) {
            const optionDependencies = {
                'field_2': {
                    'fixed_crown': ['field_4'],
                    'fixed_abutment': ['field_5'],
                    'fixed_laminate': ['field_6']
                },
                'field_4': {
                    'crown_zirconia': ['field_7'],
                    'crown_pmma': ['field_8']
                },
                'field_6': {
                    'laminate_laminate': ['field_9'],
                    'laminate_core': ['field_10']
                },
                'field_3': {
                    'removable_denture': ['field_11'],
                    'removable_partial': ['field_12']
                },
                'field_12': {
                    'partial_acrylic': ['field_13']
                }
            };
            
            const currentField = document.getElementById(currentFieldId);
            if (!currentField) return;
            
            // Get all checked inputs in the current field
            const checkedInputs = currentField.querySelectorAll('input:checked');
            
            // Hide all dependent fields for this field
            if (optionDependencies[currentFieldId]) {
                Object.values(optionDependencies[currentFieldId]).forEach(dependentFields => {
                    dependentFields.forEach(fieldId => {
                        const field = document.getElementById(fieldId);
                        if (field) {
                            field.style.display = 'none';
                            // Clear and unrequire all inputs in this field
                            field.querySelectorAll('input').forEach(input => {
                                input.checked = false;
                                input.required = false;
                            });
                        }
                    });
                });
            }
            
            // Also hide fields that are dependent on options that are no longer selected
            hideCrossFieldDependencies(currentFieldId);
        }
        
        // Hide fields that are dependent on options in other fields
        function hideCrossFieldDependencies(currentFieldId) {
            // Get all currently visible fields
            const visibleFields = document.querySelectorAll('.service-field[style*="display: block"]');
            
            visibleFields.forEach(field => {
                const fieldId = field.id;
                if (fieldId === currentFieldId) return; // Skip current field
                
                // Check if this field has any checked inputs
                const checkedInputs = field.querySelectorAll('input:checked');
                if (checkedInputs.length === 0) return; // No selections in this field
                
                // Get the expected dependent fields for this field's selections
                const expectedDependentFields = getExpectedDependentFields(fieldId, checkedInputs);
                
                // Check if any of the expected dependent fields are currently visible
                expectedDependentFields.forEach(dependentFieldId => {
                    const dependentField = document.getElementById(dependentFieldId);
                    if (dependentField && dependentField.style.display === 'block') {
                        // Check if the dependent field should still be visible based on current selections
                        const shouldBeVisible = checkIfFieldShouldBeVisible(dependentFieldId);
                        if (!shouldBeVisible) {
                            dependentField.style.display = 'none';
                            // Clear and unrequire all inputs in this field
                            dependentField.querySelectorAll('input').forEach(input => {
                                input.checked = false;
                                input.required = false;
                            });
                        }
                    }
                });
            });
        }
        
        // Get expected dependent fields for a field's selections
        function getExpectedDependentFields(fieldId, checkedInputs) {
            const dependencies = {
                'field_2': {
                    'fixed_crown': ['field_4'],
                    'fixed_abutment': ['field_5'],
                    'fixed_laminate': ['field_6']
                },
                'field_4': {
                    'crown_zirconia': ['field_7'],
                    'crown_pmma': ['field_8']
                },
                'field_6': {
                    'laminate_laminate': ['field_9'],
                    'laminate_core': ['field_10']
                },
                'field_3': {
                    'removable_denture': ['field_11'],
                    'removable_partial': ['field_12']
                },
                'field_12': {
                    'partial_acrylic': ['field_13']
                }
            };
            
            const expectedFields = [];
            checkedInputs.forEach(input => {
                if (dependencies[fieldId] && dependencies[fieldId][input.id]) {
                    expectedFields.push(...dependencies[fieldId][input.id]);
                }
            });
            
            return expectedFields;
        }
        
                // Check if a field should be visible based on current selections
        function checkIfFieldShouldBeVisible(fieldId) {
            // Define the exact conditions from sub-services-conditions.txt
            const fieldConditions = {
                'field_1': ['service_orthodontics'], // #option_1
                'field_2': ['service_fixed'], // #option_2
                'field_3': ['service_removable'], // #option_3
                'field_4': ['service_fixed', 'fixed_crown'], // #option_2 AND #option_4
                'field_5': ['service_fixed', 'fixed_abutment'], // #option_2 AND #option_5
                'field_6': ['service_fixed', 'fixed_laminate'], // #option_2 AND #option_6
                'field_7': ['service_fixed', 'fixed_crown', 'crown_zirconia'], // #option_2 AND #option_4 AND #option_7
                'field_8': ['service_fixed', 'fixed_crown', 'crown_pmma'], // #option_2 AND #option_4 AND #option_8
                'field_9': ['service_fixed', 'fixed_laminate', 'laminate_laminate'], // #option_2 AND #option_6 AND #option_9
                'field_10': ['service_fixed', 'fixed_laminate', 'laminate_core'], // #option_2 AND #option_6 AND #option_10
                'field_11': ['service_removable', 'removable_denture'], // #option_3 AND #option_11
                'field_12': ['service_removable', 'removable_partial'], // #option_3 AND #option_12
                'field_13': ['service_removable', 'removable_partial', 'partial_acrylic'], // #option_3 AND #option_12 AND #option_13
                'field_14': ['service_removable'] // #option_3 (checkbox field, always show when removable is selected)
            };
            
            if (!fieldConditions[fieldId]) return false;
            
            // Check if ALL required options are selected
            return fieldConditions[fieldId].every(optionId => {
                const option = document.getElementById(optionId);
                return option && option.checked;
            });
        }
        
        // Check if a field is a parent field (not a child field)
        function isParentField(fieldId) {
            // Parent fields are the ones that can trigger showing/hiding of other fields
            const parentFields = ['field_1', 'field_2', 'field_3', 'field_4', 'field_5', 'field_6', 'field_11', 'field_12'];
            
            return parentFields.includes(fieldId);
        }
        
        // Validate all visible fields and hide those that don't meet conditions
        function validateAllVisibleFields() {
            const allFields = ['field_1', 'field_2', 'field_3', 'field_4', 'field_5', 'field_6', 'field_7', 'field_8', 'field_9', 'field_10', 'field_11', 'field_12', 'field_13', 'field_14'];
            
            allFields.forEach(fieldId => {
                const field = document.getElementById(fieldId);
                if (field && field.style.display === 'block') {
                    const shouldBeVisible = checkIfFieldShouldBeVisible(fieldId);
                    
                    if (!shouldBeVisible) {
                        field.style.display = 'none';
                        // Clear and unrequire all inputs in this field
                        field.querySelectorAll('input').forEach(input => {
                            input.checked = false;
                            input.required = false;
                        });
                    }
                }
            });
        }
        
        // Clear all sub-service fields
        function clearAllSubServiceFields() {
            const allFields = ['field_1', 'field_2', 'field_3', 'field_4', 'field_5', 'field_6', 'field_7', 'field_8', 'field_9', 'field_10', 'field_11', 'field_12', 'field_13', 'field_14'];
            
            allFields.forEach(fieldId => {
                const field = document.getElementById(fieldId);
                if (field) {
                    field.style.display = 'none';
                    field.querySelectorAll('input').forEach(input => {
                        input.checked = false;
                        input.required = false;
                    });
                }
            });
        }
        
        // Show fields based on step 1 selection
        function showFieldsBasedOnStep1Selection() {
            const selectedService = document.querySelector('input[name="service_type"]:checked');
            
            if (!selectedService) {
                return;
            }
            
            // Check if fields are already shown for this service
            const serviceId = selectedService.id;
            const expectedFields = getExpectedFieldsForService(serviceId);
            const allFieldsShown = expectedFields.every(fieldId => {
                const field = document.getElementById(fieldId);
                return field && field.style.display === 'block';
            });
            
            // Only clear and show fields if they're not already shown correctly
            if (!allFieldsShown) {
                // Clear all fields first
                clearAllSubServiceFields();
                
                // Show appropriate fields based on selection
                if (serviceId === 'service_orthodontics') {
                    showField('field_1');
                } else if (serviceId === 'service_fixed') {
                    showField('field_2');
                } else if (serviceId === 'service_removable') {
                    showField('field_3');
                    showField('field_14');
                }
            }
        }
        
        // Helper function to get expected fields for a service
        function getExpectedFieldsForService(serviceId) {
            if (serviceId === 'service_orthodontics') {
                return ['field_1'];
            } else if (serviceId === 'service_fixed') {
                return ['field_2'];
            } else if (serviceId === 'service_removable') {
                return ['field_3', 'field_14'];
            }
            return [];
        }
        
        // Helper function to show a field
        function showField(fieldId) {
            const field = document.getElementById(fieldId);
            if (field) {
                field.style.display = 'block';
                // Make required fields required again
                field.querySelectorAll('input[required]').forEach(input => {
                    input.required = true;
                });
                
                // Scroll to the newly visible field
                scrollToField(field);
            }
        }
        
        // Scroll to a field with smooth animation and offset
        function scrollToField(field) {
            const offset = 120; // Offset from top of screen
            const fieldTop = field.offsetTop;
            const scrollTop = fieldTop - offset;
            
            // Smooth scroll to the field
            window.scrollTo({
                top: scrollTop,
                behavior: 'smooth'
            });
        }
        
        // Scroll to top of the form
        function scrollToFormTop() {
            const form = document.getElementById('new-order-form');
            if (form) {
                const formTop = form.offsetTop;
                const offset = 20; // Small offset from top
                const scrollTop = formTop - offset;
                
                // Smooth scroll to the form top
                window.scrollTo({
                    top: scrollTop,
                    behavior: 'smooth'
                });
            }
        }
        
        // Update step 2 validation
        function updateStep2Validation() {
            const nextBtn = document.getElementById('next_step');
            const visibleFields = document.querySelectorAll('.service-field[style*="display: block"]');
            
            let isValid = true;
            
            visibleFields.forEach(field => {
                // Check if this field has any required inputs
                const requiredInputs = field.querySelectorAll('input[required]');
                
                if (requiredInputs.length > 0) {
                    // For radio buttons, we need exactly one checked
                    const radioInputs = field.querySelectorAll('input[type="radio"][required]');
                    const checkedRadioInputs = field.querySelectorAll('input[type="radio"][required]:checked');
                    
                    if (radioInputs.length > 0 && checkedRadioInputs.length === 0) {
                        isValid = false;
                    }
                    
                    // For checkboxes, at least one should be checked (if any are required)
                    const checkboxInputs = field.querySelectorAll('input[type="checkbox"][required]');
                    const checkedCheckboxInputs = field.querySelectorAll('input[type="checkbox"][required]:checked');
                    
                    if (checkboxInputs.length > 0 && checkedCheckboxInputs.length === 0) {
                        isValid = false;
                    }
                }
            });
            
            // If no visible fields with required inputs, then it's valid
            if (visibleFields.length === 0) {
                isValid = true;
            }
            
            if (isValid) {
                nextBtn.disabled = false;
                nextBtn.classList.remove('btn-disabled');
            } else {
                nextBtn.disabled = true;
                nextBtn.classList.add('btn-disabled');
            }
        }
        
        // Update step 3 validation
        function updateStep3Validation() {
            const nextBtn = document.getElementById('next_step');
            let isValid = true;
            
            // Check patient name (required field)
            const patientName = document.getElementById('patient_name');
            
            if (patientName && patientName.value.trim()) {
                const nameValidation = validatePersianName(patientName.value);
                if (!nameValidation.isValid) {
                    isValid = false;
                    // Don't show persistent error here since we handle it with temporary errors
                }
            } else {
                isValid = false;
            }
            
            // Patient age is optional, so no validation needed
            
            if (isValid) {
                nextBtn.disabled = false;
                nextBtn.classList.remove('btn-disabled');
            } else {
                nextBtn.disabled = true;
                nextBtn.classList.add('btn-disabled');
            }
        }
        
        // Validate Persian name
        function validatePersianName(name) {
            // Persian letters regex (including ی and ک)
            const persianRegex = /^[\u0600-\u06FF\s]+$/;
            
            // Check if contains only Persian letters and spaces
            if (!persianRegex.test(name)) {
                return {
                    isValid: false,
                    error: 'فقط حروف فارسی مجاز است.'
                };
            }
            
            // Check for multiple consecutive spaces
            if (/\s{2,}/.test(name)) {
                return {
                    isValid: false,
                    error: 'حداکثر یک فاصله بین کلمات مجاز است.'
                };
            }
            
            // Check for at least 2 words
            const words = name.trim().split(/\s+/);
            if (words.length < 2) {
                return {
                    isValid: false,
                    error: 'لطفاً حداقل دو کلمه وارد کنید (نام و نام خانوادگی).'
                };
            }
            
            // Check each word has at least 2 characters
            for (let word of words) {
                if (word.length < 2) {
                    return {
                        isValid: false,
                        error: 'هر کلمه باید حداقل ۲ حرف داشته باشد.'
                    };
                }
            }
            
            return { isValid: true };
        }
        
        // Setup step 3 validation
        function setupStep3Validation() {
            // Patient name validation
            const patientName = document.getElementById('patient_name');
            if (patientName) {
                patientName.addEventListener('input', function(e) {
                    // Prevent non-Persian characters from being entered
                    const persianRegex = /^[\u0600-\u06FF\s]*$/;
                    const currentValue = this.value;
                    
                    // Check if the new character is allowed
                    if (!persianRegex.test(currentValue)) {
                        // Remove the last character that was entered
                        this.value = currentValue.slice(0, -1);
                        
                        // Show error for 5 seconds
                        showTemporaryError('فقط حروف فارسی مجاز است.', 5000);
                        
                        // Prevent the default action
                        e.preventDefault();
                        return false;
                    }
                    
                    // Check for multiple consecutive spaces
                    if (/\s{2,}/.test(currentValue)) {
                        // Remove extra spaces
                        this.value = currentValue.replace(/\s{2,}/g, ' ');
                        
                        // Show error for 5 seconds
                        showTemporaryError('حداکثر یک فاصله بین کلمات مجاز است.', 5000);
                        
                        e.preventDefault();
                        return false;
                    }
                    
                    updateStep3Validation();
                    
                    // Update step 3 summary
                    updateStepSummaries();
                });
                
                patientName.addEventListener('blur', function() {
                    updateStep3Validation();
                    // Update step 3 summary
                    updateStepSummaries();
                });
            }
            
            // Patient age validation (radio buttons)
            const ageRadios = document.querySelectorAll('input[name="patient_age"]');
            ageRadios.forEach(radio => {
                radio.addEventListener('change', function() {
                    updateStep3Validation();
                    // Update step 3 summary
                    updateStepSummaries();
                });
            });
            
            // Allow unselecting age options by clicking on the same option
            const ageLabels = document.querySelectorAll('.age-radio-label');
            ageLabels.forEach(label => {
                label.addEventListener('click', function(e) {
                    const radio = this.previousElementSibling;
                    if (radio.checked) {
                        // If already selected, unselect it
                        e.preventDefault();
                        e.stopPropagation();
                        radio.checked = false;
                        // Trigger change event to update validation and summary
                        radio.dispatchEvent(new Event('change'));
                    }
                });
            });
            
            // Order instructions textarea direction handling
            const orderInstructions = document.getElementById('order_note');
            if (orderInstructions) {
                orderInstructions.addEventListener('input', function() {
                    handleTextDirection(this);
                    updateCharCounter(this);
                    autoResizeTextarea(this);
                    // Update step 3 summary
                    updateStepSummaries();
                });
            }
        }
        
        // Setup skip step functionality
        function setupSkipStep() {
            const skipStepBtn = document.getElementById('skip_step_2');
            if (skipStepBtn) {
                skipStepBtn.addEventListener('click', function() {
                    // Clear any existing sub-service selections
                    clearAllSubServiceFields();
                    
                    // Mark step 2 as skipped
                    step2Skipped = true;
                    
                    // Update step 2 summary (will show skip message)
                    updateStepSummaries();
                    
                    // Move to next step
                    nextStep();
                });
            }
        }
        
        // Show temporary error message
        function showTemporaryError(message, duration) {
            const patientNameError = document.getElementById('patient_name_error');
            const patientName = document.getElementById('patient_name');
            
            if (patientNameError && patientName) {
                // Add error class to input
                patientName.classList.add('error');
                
                // Show error message
                patientNameError.textContent = message;
                patientNameError.style.display = 'block';
                
                // Hide error after specified duration
                setTimeout(() => {
                    patientNameError.textContent = '';
                    patientNameError.style.display = 'none';
                    patientName.classList.remove('error');
                }, duration);
            }
        }
        
        // Handle text direction for textarea
        function handleTextDirection(textarea) {
            const text = textarea.value;
            
            // Check if text starts with English letter
            const startsWithEnglish = /^[a-zA-Z]/.test(text.trim());
            
            // Check if text contains both Persian and English
            const hasPersian = /[\u0600-\u06FF]/.test(text);
            const hasEnglish = /[a-zA-Z]/.test(text);
            const hasBoth = hasPersian && hasEnglish;
            
            if (startsWithEnglish && !hasBoth) {
                // If starts with English and doesn't have both, use LTR
                textarea.style.direction = 'ltr';
                textarea.style.textAlign = 'left';
            } else {
                // Default to RTL for Persian or mixed content
                textarea.style.direction = 'rtl';
                textarea.style.textAlign = 'right';
            }
        }
        
        // Update character counter
        function updateCharCounter(textarea) {
            const charCount = document.getElementById('char_count');
            const charCounter = document.getElementById('char_counter');
            if (charCount && charCounter) {
                const currentLength = textarea.value.length;
                const limit = 500;
                const remaining = limit - currentLength;
                
                // Only show counter when 100 characters or less remaining
                if (remaining <= 100) {
                    charCounter.style.display = 'block';
                    charCount.textContent = currentLength;
                    
                    // Change color when approaching limit
                    if (remaining <= 20) {
                        charCount.style.color = '#dc3545';
                    } else if (remaining <= 50) {
                        charCount.style.color = '#ffc107';
                    } else {
                        charCount.style.color = '#6c757d';
                    }
                } else {
                    charCounter.style.display = 'none';
                }
            }
        }
        
        // Auto-resize textarea height
        function autoResizeTextarea(textarea) {
            // Reset height to auto to get the correct scrollHeight
            textarea.style.height = 'auto';
            
            // Get the minimum height (from CSS min-height: 150px)
            const minHeight = 150;
            
            // Calculate the required height
            const scrollHeight = textarea.scrollHeight;
            const newHeight = Math.max(scrollHeight, minHeight);
            
            // Set the new height
            textarea.style.height = newHeight + 'px';
        }

        // Initialize the form
        initForm();
    }
});