// Alpine.js components for LeadIntelligence AI
document.addEventListener('alpine:init', () => {
    // Form Builder Component
    Alpine.data('formBuilder', () => ({
        fields: [],
        newField: { type: 'text', label: '', name: '', required: false },
        
        addField() {
            if (!this.newField.label || !this.newField.name) return;
            
            this.fields.push({
                ...this.newField,
                id: Date.now() + Math.random()
            });
            
            this.newField = { type: 'text', label: '', name: '', required: false };
        },
        
        removeField(index) {
            this.fields.splice(index, 1);
        },
        
        moveField(index, direction) {
            const newIndex = index + direction;
            if (newIndex >= 0 && newIndex < this.fields.length) {
                [this.fields[index], this.fields[newIndex]] = [this.fields[newIndex], this.fields[index]];
            }
        },
        
        get fieldsJson() {
            return JSON.stringify(this.fields);
        }
    }));

    // Lead Filter Component
    Alpine.data('leadFilter', () => ({
        filters: {
            status: '',
            score: '',
            source: '',
            date_range: ''
        },
        
        appliedFilters: {},
        
        applyFilters() {
            this.appliedFilters = { ...this.filters };
            // Trigger AJAX request or form submission
            this.$dispatch('filters-changed', this.appliedFilters);
        },
        
        clearFilters() {
            this.filters = {
                status: '',
                score: '',
                source: '',
                date_range: ''
            };
            this.applyFilters();
        }
    }));

    // Real-time Dashboard Updates
    Alpine.data('dashboard', () => ({
        stats: {},
        loading: false,
        
        async refreshStats() {
            this.loading = true;
            try {
                const response = await fetch('/api/analytics/overview');
                this.stats = await response.json();
            } catch (error) {
                console.error('Failed to fetch stats:', error);
            }
            this.loading = false;
        },
        
        init() {
            this.refreshStats();
            // Refresh every 30 seconds
            setInterval(() => this.refreshStats(), 30000);
        }
    }));

    // AI Lead Scoring Preview
    Alpine.data('leadScoring', () => ({
        leadData: {
            email: '',
            company: '',
            industry: '',
            website: '',
            message: ''
        },
        score: null,
        loading: false,
        factors: [],
        
        async calculateScore() {
            if (!this.leadData.email) return;
            
            this.loading = true;
            try {
                const response = await fetch('/api/leads/score-preview', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(this.leadData)
                });
                const result = await response.json();
                
                this.score = result.score;
                this.factors = result.factors || [];
            } catch (error) {
                console.error('Scoring failed:', error);
            }
            this.loading = false;
        }
    }));
});