/**
 * Draft Manager - Auto-save and Draft Restore
 * Manages form drafts with auto-save to localStorage
 * Shows draft manager UI on page load if draft exists
 */

class DraftManager {
    constructor(formId, options = {}) {
        this.formId = formId;
        this.form = document.getElementById(formId);
        this.storageKey = `draft_${formId}`;
        this.autoSaveInterval = options.autoSaveInterval || 30000; // 30 seconds
        this.enableDatabase = options.enableDatabase || false;
        this.onLoad = options.onLoad || null;
        this.onAutoSave = options.onAutoSave || null;
        
        if (!this.form) {
            console.warn(`Form with ID "${formId}" not found`);
            return;
        }
        
        this.init();
    }
    
    /**
     * Initialize draft manager
     */
    init() {
        // Check for existing draft on page load
        this.checkForExistingDraft();
        
        // Setup auto-save interval
        this.setupAutoSave();
        
        // Save draft before page unload (unsaved changes)
        window.addEventListener('beforeunload', (e) => {
            if (this.hasFormChanges()) {
                this.saveDraft();
            }
        });
    }
    
    /**
     * Check if draft exists and show manager
     */
    checkForExistingDraft() {
        const draft = this.getDraft();
        if (!draft) return;
        
        const draftTime = new Date(draft.timestamp);
        const now = new Date();
        const timeDiff = Math.round((now - draftTime) / 1000 / 60); // minutes
        
        let timeStr = `${timeDiff} minutes ago`;
        if (timeDiff < 1) timeStr = 'just now';
        else if (timeDiff === 1) timeStr = '1 minute ago';
        else if (timeDiff > 60) {
            const hours = Math.floor(timeDiff / 60);
            timeStr = `${hours} hour${hours > 1 ? 's' : ''} ago`;
        }
        
        // Show SweetAlert2 modal with draft options
        Swal.fire({
            title: 'Draft Found',
            html: `<p class="text-gray-700">A draft was saved <strong>${timeStr}</strong></p>`,
            icon: 'info',
            allowOutsideClick: false,
            allowEscapeKey: false,
            showCancelButton: true,
            confirmButtonText: 'Load Draft',
            cancelButtonText: 'Discard & Start Fresh',
            confirmButtonColor: '#3b82f6',
            cancelButtonColor: '#ef4444'
        }).then((result) => {
            if (result.isConfirmed) {
                this.loadDraft();
            } else {
                this.deleteDraft();
            }
        });
    }
    
    /**
     * Setup auto-save interval
     */
    setupAutoSave() {
        setInterval(() => {
            if (this.hasFormChanges()) {
                this.saveDraft();
                if (this.onAutoSave) {
                    this.onAutoSave();
                }
            }
        }, this.autoSaveInterval);
    }
    
    /**
     * Check if form has changes from initial state
     */
    hasFormChanges() {
        const currentData = new FormData(this.form);
        const storedDraft = this.getDraft();
        
        if (!storedDraft) return true; // No draft yet, so there are changes
        
        // Compare form data with stored draft
        for (let [key, value] of currentData.entries()) {
            if ((storedDraft.data[key] || '') !== value) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Save form data as draft
     */
    saveDraft() {
        const formData = new FormData(this.form);
        const data = {};
        
        for (let [key, value] of formData.entries()) {
            data[key] = value;
        }
        
        const draft = {
            formId: this.formId,
            data: data,
            timestamp: new Date().toISOString(),
            url: window.location.href
        };
        
        // Save to localStorage
        localStorage.setItem(this.storageKey, JSON.stringify(draft));
        
        // Optionally save to database via AJAX
        if (this.enableDatabase) {
            this.saveDraftToDatabase(draft);
        }
        
        console.log(`Draft saved for form: ${this.formId}`);
    }
    
    /**
     * Save draft to server via AJAX
     */
    saveDraftToDatabase(draft) {
        fetch('/api.php?endpoint=draft/save', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({
                formId: draft.formId,
                data: draft.data
            })
        }).catch(err => console.error('Failed to save draft to database:', err));
    }
    
    /**
     * Get stored draft
     */
    getDraft() {
        const stored = localStorage.getItem(this.storageKey);
        return stored ? JSON.parse(stored) : null;
    }
    
    /**
     * Load draft into form
     */
    loadDraft() {
        const draft = this.getDraft();
        if (!draft) {
            Swal.fire('No Draft', 'Could not find draft to load', 'warning');
            return;
        }
        
        // Populate form fields from draft data
        for (let [key, value] of Object.entries(draft.data)) {
            const field = this.form.elements[key];
            if (!field) continue;
            
            if (field.type === 'radio') {
                const radio = this.form.querySelector(`[name="${key}"][value="${value}"]`);
                if (radio) radio.checked = true;
            } else if (field.type === 'checkbox') {
                field.checked = value === 'on' || value === '1';
            } else {
                field.value = value;
            }
            
            // Trigger change event to update UI
            field.dispatchEvent(new Event('change', { bubbles: true }));
        }
        
        // Clear draft from storage
        this.deleteDraft();
        
        Swal.fire('Draft Loaded', 'Your draft has been restored', 'success');
        
        if (this.onLoad) {
            this.onLoad(draft);
        }
    }
    
    /**
     * Delete stored draft
     */
    deleteDraft() {
        localStorage.removeItem(this.storageKey);
        console.log(`Draft deleted for form: ${this.formId}`);
    }
    
    /**
     * Clear draft when form is successfully submitted
     */
    clearDraftOnSubmit() {
        this.form.addEventListener('submit', () => {
            // Give time for submission to process
            setTimeout(() => {
                this.deleteDraft();
            }, 500);
        });
    }
    
    /**
     * Get draft metadata (for display purposes)
     */
    getDraftMetadata() {
        const draft = this.getDraft();
        if (!draft) return null;
        
        return {
            timestamp: draft.timestamp,
            url: draft.url,
            fieldCount: Object.keys(draft.data).length
        };
    }
}

/**
 * Initialize draft managers for forms on page load
 */
document.addEventListener('DOMContentLoaded', () => {
    // Auto-initialize draft manager for forms with data-draft attribute
    document.querySelectorAll('form[data-draft]').forEach(form => {
        const formId = form.id || form.getAttribute('data-draft');
        const autoSaveInterval = form.getAttribute('data-autosave-interval') || 30000;
        
        const draftManager = new DraftManager(formId, {
            autoSaveInterval: parseInt(autoSaveInterval),
            enableDatabase: form.getAttribute('data-draft-db') === 'true'
        });
        
        // Clear draft on successful form submission
        draftManager.clearDraftOnSubmit();
        
        // Store reference for manual access
        form._draftManager = draftManager;
    });
});

// Export for use in modules
if (typeof module !== 'undefined' && module.exports) {
    module.exports = DraftManager;
}
