// Reels Scheduler Functionality
document.addEventListener('DOMContentLoaded', function() {
    // Initialize calendar if element exists
    initializeCalendar();
    
    // Initialize wizard if element exists
    initializeReelsWizard();
    
    // Set up polling for status updates
    setupStatusPolling();
    
    // Handle scheduled reel form submission
    handleScheduledReelFormSubmission();
});

// Initialize FullCalendar
function initializeCalendar() {
    const calendarEl = document.getElementById('reels-calendar');
    if (!calendarEl) return;
    
    const calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: 'dayGridMonth',
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay'
        },
        events: fetchCalendarEvents,
        eventClick: function(info) {
            // Handle event click if needed
            console.log('Event clicked:', info.event);
        }
    });
    
    calendar.render();
}

// Fetch calendar events (this would be replaced with actual API call)
function fetchCalendarEvents(info, successCallback, failureCallback) {
    // In a real implementation, this would fetch events from the server
    // For now, we'll just return an empty array
    // But we can also fetch events from the data attributes if available
    const calendarEl = document.getElementById('reels-calendar');
    if (calendarEl && calendarEl.dataset.events) {
        try {
            const events = JSON.parse(calendarEl.dataset.events);
            successCallback(events);
        } catch (e) {
            console.error('Failed to parse calendar events:', e);
            successCallback([]);
        }
    } else {
        successCallback([]);
    }
}

// Reels Wizard Functionality
function initializeReelsWizard() {
    // Next step button
    document.querySelectorAll('.next-step').forEach(button => {
        button.addEventListener('click', function() {
            const currentStep = document.querySelector('.step.active');
            const nextStep = currentStep.nextElementSibling;
            
            if (nextStep && nextStep.classList.contains('step')) {
                currentStep.classList.remove('active');
                nextStep.classList.add('active');
            }
        });
    });
    
    // Previous step button
    document.querySelectorAll('.prev-step').forEach(button => {
        button.addEventListener('click', function() {
            const currentStep = document.querySelector('.step.active');
            const prevStep = currentStep.previousElementSibling;
            
            if (prevStep && prevStep.classList.contains('step')) {
                currentStep.classList.remove('active');
                prevStep.classList.add('active');
            }
        });
    });
    
    // Post selection
    document.querySelectorAll('.post-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const checkedCount = document.querySelectorAll('.post-checkbox:checked').length;
            const nextButton = document.querySelector('.step-1 .next-step');
            
            if (nextButton) {
                nextButton.disabled = checkedCount === 0;
            }
        });
    });
    
    // Template selection
    document.querySelectorAll('.template-card').forEach(card => {
        card.addEventListener('click', function() {
            // Remove active class from all template cards
            document.querySelectorAll('.template-card').forEach(c => {
                c.classList.remove('border-primary', 'bg-light');
            });
            
            // Add active class to clicked card
            this.classList.add('border-primary', 'bg-light');
            
            // Check the radio button
            const radio = this.querySelector('.template-radio');
            if (radio) {
                radio.checked = true;
            }
        });
    });
    
    // Form submission with validation
    const reelForm = document.getElementById('reel-form');
    if (reelForm) {
        reelForm.addEventListener('submit', function(e) {
            const currentStep = document.querySelector('.step.active');
            const stepNumber = Array.from(document.querySelectorAll('.step')).indexOf(currentStep) + 1;
            
            // If we're not on the last step, prevent submission and go to next step
            if (stepNumber < 3) {
                e.preventDefault();
                currentStep.classList.remove('active');
                currentStep.nextElementSibling.classList.add('active');
            }
        });
    }
    
    // Schedule datetime picker
    const scheduleOption = document.querySelector('input[name="schedule_option"]');
    if (scheduleOption) {
        scheduleOption.addEventListener('change', function() {
            const scheduleFields = document.getElementById('schedule-fields');
            if (scheduleFields) {
                scheduleFields.style.display = this.value === 'schedule' ? 'block' : 'none';
            }
        });
    }
    
    // Initialize datetime picker if available
    const datetimePicker = document.getElementById('scheduled_at');
    if (datetimePicker) {
        // Set min datetime to current time
        const now = new Date();
        now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
        datetimePicker.min = now.toISOString().slice(0, 16);
    }
    
    // Timezone selector
    const timezoneSelect = document.getElementById('timezone');
    if (timezoneSelect) {
        // Set default to user's timezone if not already set
        if (!timezoneSelect.value) {
            timezoneSelect.value = Intl.DateTimeFormat().resolvedOptions().timeZone;
        }
    }
}

// Setup status polling
function setupStatusPolling() {
    // Poll for status updates every 30 seconds
    setInterval(function() {
        // In a real implementation, this would fetch status updates from the server
        console.log('Polling for status updates...');
    }, 30000);
}

// Show/hide schedule fields based on selection
function toggleScheduleFields() {
    const scheduleNow = document.getElementById('schedule-now');
    const scheduleLater = document.getElementById('schedule-later');
    const scheduleFields = document.getElementById('schedule-fields');
    
    if (scheduleNow && scheduleLater && scheduleFields) {
        scheduleFields.style.display = scheduleLater.checked ? 'block' : 'none';
    }
}

// Handle form submission with validation
function handleScheduledReelFormSubmission() {
    const form = document.getElementById('scheduled-reel-form');
    if (!form) return;
    
    form.addEventListener('submit', function(e) {
        // Get form values
        const scheduleOption = document.querySelector('input[name="schedule_option"]:checked');
        const scheduledAt = document.getElementById('scheduled_at');
        const timezone = document.getElementById('timezone');
        
        // Validate schedule option
        if (scheduleOption && scheduleOption.value === 'schedule') {
            if (!scheduledAt || !scheduledAt.value) {
                e.preventDefault();
                alert('Please select a date and time for scheduling.');
                return;
            }
            
            if (!timezone || !timezone.value) {
                e.preventDefault();
                alert('Please select a timezone.');
                return;
            }
            
            // Validate that scheduled time is in the future
            const scheduledTime = new Date(scheduledAt.value);
            const now = new Date();
            if (scheduledTime <= now) {
                e.preventDefault();
                alert('Scheduled time must be in the future.');
                return;
            }
        }
    });
}

// Show toast notification
function showToast(message, type = 'info') {
    // Create toast element
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `
        <div class="toast-header">
            <strong class="mr-auto">Notification</strong>
            <button type="button" class="ml-2 mb-1 close" data-dismiss="toast">&times;</button>
        </div>
        <div class="toast-body">
            ${message}
        </div>
    `;
    
    // Add to toast container
    const container = document.getElementById('toast-container') || document.body;
    container.appendChild(toast);
    
    // Show toast
    $(toast).toast({
        delay: 5000
    }).toast('show');
    
    // Remove toast after it's hidden
    $(toast).on('hidden.bs.toast', function() {
        toast.remove();
    });
}

// Export functions for global use
window.initializeCalendar = initializeCalendar;
window.initializeReelsWizard = initializeReelsWizard;
window.setupStatusPolling = setupStatusPolling;
window.toggleScheduleFields = toggleScheduleFields;
window.handleScheduledReelFormSubmission = handleScheduledReelFormSubmission;
window.showToast = showToast;