/**
 * Event Editor Extension for BioLink
 */

// Extend BioLink object with event editor functionality
if (typeof BioLink !== 'undefined') {
    
    console.log('✅ Event Editor Extension loading...');
    
    // Open Event Editor
    BioLink.openEventEditor = async function() {
        const container = document.getElementById('biolink-page');
        if (!container) return;

        const project = BioLink.currentProject;
        const settings = project.settings || {};
        
        // Parse settings if string
        let eventSettings = settings;
        if (typeof settings === 'string') {
            try {
                eventSettings = JSON.parse(settings);
            } catch (e) {
                eventSettings = {};
            }
        }

        // Default values
        const defaults = {
            title: project.name || '',
            short_description: '',
            long_description: '',
            start_date: '',
            end_date: '',
            timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC',
            location: '',
            address: '',
            venue_name: '',
            venue_description: '',
            cover_image: '',
            gallery: [],
            tickets: [],
            rating: '',
            enable_sales: false,
            whatsapp_number: '',
            bg_color: '#1e293b',
            card_bg_color: '#ffffff',
            text_color: '#1e293b',
            accent_color: '#667eea',
            button_color: '#667eea',
            button_text_color: '#ffffff'
        };

        const data = { ...defaults, ...eventSettings };

        // Render editor HTML
        container.innerHTML = `
            <div class="biolink-editor-container">
                <!-- Header -->
                <div class="biolink-editor-header">
                    <div class="header-left">
                        <button class="btn-back" onclick="BioLink.closeEventEditor()">
                            <i class="fas fa-arrow-left"></i> <span data-i18n="biolink.event.back">Back</span>
                        </button>
                        <h2><i class="fas fa-calendar"></i> ${BioLink.escapeHtml(project.name)}</h2>
                    </div>
                    <div class="header-right">
                        <button class="btn btn-secondary" onclick="window.open('/b/${project.slug}', '_blank')">
                            <i class="fas fa-external-link-alt"></i> <span data-i18n="biolink.event.preview">Preview</span>
                        </button>
                        <button class="btn btn-primary" onclick="BioLink.saveEvent()">
                            <i class="fas fa-save"></i> <span data-i18n="biolink.event.save">Save</span>
                        </button>
                    </div>
                </div>

                <!-- Editor Body -->
                <div class="biolink-editor-body">
                    <!-- Left Panel - Form -->
                    <div class="editor-panel-left" style="overflow-y: auto; padding: 30px;">
                        
                        <!-- Basic Info Section -->
                        <div class="editor-section">
                            <h3><i class="fas fa-info-circle"></i> <span data-i18n="biolink.event.basic_info">Basic Information</span></h3>
                            
                            <div class="form-group">
                                <label data-i18n="biolink.event.event_title">Event Title *</label>
                                <input type="text" id="eventTitle" class="form-control" value="${BioLink.escapeHtml(data.title)}" placeholder="Amazing Conference 2026">
                                <small class="form-text" data-i18n="biolink.event.title_hint">Required to activate the event</small>
                            </div>

                            <div class="form-group">
                                <label data-i18n="biolink.event.short_description">Short Description</label>
                                <textarea id="eventShortDesc" class="form-control" rows="2" placeholder="Brief description for preview">${BioLink.escapeHtml(data.short_description)}</textarea>
                                <small class="form-text" data-i18n="biolink.event.short_description_hint">Displayed in preview cards and social media</small>
                            </div>

                            <div class="form-group">
                                <label data-i18n="biolink.event.long_description">Full Description</label>
                                <div id="eventLongDescEditor"></div>
                                <textarea id="eventLongDesc" class="form-control" style="display: none;">${BioLink.escapeHtml(data.long_description)}</textarea>
                                <small class="form-text" data-i18n="biolink.event.long_description_hint">Complete event details with rich formatting</small>
                            </div>
                        </div>

                        <!-- Date & Time Section -->
                        <div class="editor-section">
                            <h3><i class="fas fa-clock"></i> <span data-i18n="biolink.event.date_time">Date & Time</span></h3>
                            
                            <div class="form-row">
                                <div class="form-group" style="flex: 1;">
                                    <label data-i18n="biolink.event.start_date">Start Date *</label>
                                    <input type="datetime-local" id="eventStartDate" class="form-control" value="${BioLink.escapeHtml(this.toInputDateTime(data.start_date))}">
                                    <small class="form-text" data-i18n="biolink.event.start_date_hint">Required to activate</small>
                                </div>
                                <div class="form-group" style="flex: 1;">
                                    <label data-i18n="biolink.event.end_date">End Date</label>
                                    <input type="datetime-local" id="eventEndDate" class="form-control" value="${BioLink.escapeHtml(this.toInputDateTime(data.end_date))}">
                                </div>
                            </div>

                            <div class="form-group">
                                <label data-i18n="biolink.event.timezone">Timezone</label>
                                <input type="text" id="eventTimezone" class="form-control" value="${BioLink.escapeHtml(data.timezone)}" placeholder="UTC">
                                <small class="form-text" data-i18n="biolink.event.timezone_hint">Event timezone (e.g., America/New_York, Europe/London)</small>
                            </div>
                        </div>

                        <!-- Location Section -->
                        <div class="editor-section">
                            <h3><i class="fas fa-map-marker-alt"></i> <span data-i18n="biolink.event.location">Location</span></h3>
                            
                            <div class="form-group">
                                <label data-i18n="biolink.event.venue_name">Venue Name</label>
                                <input type="text" id="eventVenueName" class="form-control" value="${BioLink.escapeHtml(data.venue_name)}" placeholder="Convention Center">
                            </div>

                            <div class="form-group" style="position: relative;">
                                <label data-i18n="biolink.event.address">Address</label>
                                <input type="text" id="eventAddress" class="form-control" value="${BioLink.escapeHtml(data.address)}" placeholder="Start typing address..." autocomplete="off">
                                <div id="addressAutocomplete" style="position: absolute; top: 100%; left: 0; right: 0; background: white; border: 1px solid #e2e8f0; border-radius: 8px; max-height: 300px; overflow-y: auto; z-index: 1000; display: none; box-shadow: 0 4px 12px rgba(0,0,0,0.1);"></div>
                                <small class="form-text" style="color: #10b981;"><i class="fas fa-info-circle"></i> Type to search and select from suggestions</small>
                            </div>

                            <div class="form-row" style="gap: 15px;">
                                <div class="form-group" style="flex: 1;">
                                    <label data-i18n="biolink.event.latitude">Latitude</label>
                                    <input type="number" id="eventLatitude" class="form-control" value="${data.latitude || ''}" placeholder="Auto-filled" step="any" readonly style="background: #f8fafc;">
                                    <small class="form-text" data-i18n="biolink.event.latitude_hint">Auto-filled from address</small>
                                </div>
                                <div class="form-group" style="flex: 1;">
                                    <label data-i18n="biolink.event.longitude">Longitude</label>
                                    <input type="number" id="eventLongitude" class="form-control" value="${data.longitude || ''}" placeholder="Auto-filled" step="any" readonly style="background: #f8fafc;">
                                    <small class="form-text" data-i18n="biolink.event.longitude_hint">Auto-filled from address</small>
                                </div>
                            </div>

                            <div class="form-group">
                                <label data-i18n="biolink.event.location_details">Location Details</label>
                                <textarea id="eventLocation" class="form-control" rows="2" placeholder="Additional location info">${BioLink.escapeHtml(data.location)}</textarea>
                            </div>

                            <div class="form-group">
                                <label data-i18n="biolink.event.venue_description">About the Venue</label>
                                <textarea id="eventVenueDesc" class="form-control" rows="3" placeholder="Venue description">${BioLink.escapeHtml(data.venue_description)}</textarea>
                            </div>
                        </div>

                        <!-- Cover Image Section -->
                        <div class="editor-section">
                            <h3><i class="fas fa-image"></i> <span data-i18n="biolink.event.cover_image">Cover Image</span></h3>
                            
                            <div class="form-group">
                                <div class="image-upload-area" id="coverImageArea" style="border: 2px dashed #cbd5e1; border-radius: 8px; padding: 20px; text-align: center; cursor: pointer; transition: all 0.3s;" onclick="document.getElementById('coverImageInput').click()">
                                    ${data.cover_image ? `
                                        <img src="${BioLink.escapeHtml(data.cover_image)}" style="max-width: 100%; max-height: 200px; border-radius: 8px; margin-bottom: 10px;">
                                        <div><button type="button" class="btn btn-sm btn-secondary" onclick="event.stopPropagation(); BioLink.removeCoverImage()"><i class="fas fa-trash"></i> <span data-i18n="biolink.event.remove">Remove</span></button></div>
                                    ` : `
                                        <i class="fas fa-cloud-upload-alt" style="font-size: 48px; color: #94a3b8; margin-bottom: 10px;"></i>
                                        <p style="color: #64748b;" data-i18n="biolink.event.upload_cover">Click to upload cover image</p>
                                        <small style="color: #94a3b8;" data-i18n="biolink.event.cover_size">Recommended: 1200x630px</small>
                                    `}
                                </div>
                                <input type="file" id="coverImageInput" accept="image/*" style="display: none;" onchange="BioLink.handleCoverImageUpload(event)">
                                <input type="hidden" id="eventCoverImage" value="${BioLink.escapeHtml(data.cover_image)}">
                            </div>
                        </div>

                        <!-- Gallery Section -->
                        <div class="editor-section">
                            <h3><i class="fas fa-images"></i> <span data-i18n="biolink.event.photo_gallery">Photo Gallery</span></h3>
                            
                            <div id="eventGallery" class="event-gallery" style="display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 15px;">
                                ${(data.gallery || []).map((img, idx) => `
                                    <div class="gallery-item" style="position: relative; width: 100px; height: 100px;">
                                        <img src="${BioLink.escapeHtml(img)}" style="width: 100%; height: 100%; object-fit: cover; border-radius: 8px;">
                                        <button type="button" class="btn-remove-gallery" onclick="BioLink.removeGalleryImage(${idx})" style="position: absolute; top: 5px; right: 5px; background: rgba(0,0,0,0.7); color: white; border: none; border-radius: 50%; width: 24px; height: 24px; cursor: pointer;">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </div>
                                `).join('')}
                            </div>
                            
                            <button type="button" class="btn btn-secondary" onclick="document.getElementById('galleryImageInput').click()">
                                <i class="fas fa-plus"></i> <span data-i18n="biolink.event.add_photos">Add Photos</span>
                            </button>
                            <input type="file" id="galleryImageInput" accept="image/*" multiple style="display: none;" onchange="BioLink.handleGalleryUpload(event)">
                            <small class="form-text" data-i18n="biolink.event.gallery_hint">Upload multiple photos to create a horizontal carousel</small>
                        </div>

                        <!-- Tickets Section -->
                        <div class="editor-section">
                            <h3><i class="fas fa-ticket-alt"></i> <span data-i18n="biolink.event.tickets">Tickets</span></h3>
                            
                            <div id="ticketsList">
                                ${(data.tickets || []).map((ticket, idx) => `
                                    <div class="ticket-item" style="background: #f8fafc; padding: 15px; border-radius: 8px; margin-bottom: 10px; border: 1px solid #e2e8f0;">
                                        <div class="form-row" style="gap: 10px; margin-bottom: 10px;">
                                            <input type="text" class="form-control" placeholder="Ticket name" value="${BioLink.escapeHtml(ticket.name || '')}" onchange="BioLink.updateTicket(${idx}, 'name', this.value)" style="flex: 2;">
                                            <input type="number" class="form-control" placeholder="Price" value="${ticket.price || ''}" onchange="BioLink.updateTicket(${idx}, 'price', this.value)" style="flex: 1;" step="0.01" min="0">
                                            <input type="text" class="form-control" placeholder="Currency" value="${BioLink.escapeHtml(ticket.currency || 'USD')}" onchange="BioLink.updateTicket(${idx}, 'currency', this.value)" style="flex: 1;" maxlength="3">
                                            <button type="button" class="btn btn-sm btn-danger" onclick="BioLink.removeTicket(${idx})" title="Remove ticket">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                        <textarea class="form-control" placeholder="Ticket description" rows="2" onchange="BioLink.updateTicket(${idx}, 'description', this.value)">${BioLink.escapeHtml(ticket.description || '')}</textarea>
                                    </div>
                                `).join('')}
                            </div>
                            
                            <button type="button" class="btn btn-secondary" onclick="BioLink.addTicket()">
                                <i class="fas fa-plus"></i> <span data-i18n="biolink.event.add_ticket">Add Ticket</span>
                            </button>
                        </div>

                        <!-- Sales Settings Section -->
                        <div class="editor-section">
                            <h3><i class="fas fa-shopping-cart"></i> <span data-i18n="biolink.event.sales_settings">Sales Settings</span></h3>
                            
                            <div class="form-group">
                                <label class="checkbox-label">
                                    <input type="checkbox" id="eventEnableSales" ${data.enable_sales ? 'checked' : ''} onchange="BioLink.toggleSalesFields()">
                                    <span data-i18n="biolink.event.enable_sales">Enable Ticket Sales</span>
                                </label>
                                <small class="form-text" data-i18n="biolink.event.enable_sales_hint">Allow customers to purchase tickets via WhatsApp</small>
                            </div>

                            <div id="salesFields" style="display: ${data.enable_sales ? 'block' : 'none'};">
                                <div class="form-group">
                                    <label data-i18n="biolink.event.whatsapp_number">WhatsApp Number</label>
                                    <input type="tel" id="eventWhatsAppNumber" class="form-control" value="${BioLink.escapeHtml(data.whatsapp_number)}" placeholder="+1234567890">
                                    <small class="form-text" data-i18n="biolink.event.whatsapp_hint">Include country code (e.g., +1 for US, +55 for Brazil)</small>
                                </div>
                            </div>
                        </div>

                        <!-- Additional Info Section -->
                        <div class="editor-section">
                            <h3><i class="fas fa-star"></i> <span data-i18n="biolink.event.additional_info">Additional Information</span></h3>
                            
                            <div class="form-group">
                                <label data-i18n="biolink.event.rating">Age Rating / Classification</label>
                                <input type="text" id="eventRating" class="form-control" value="${BioLink.escapeHtml(data.rating)}" placeholder="e.g., All Ages, 18+, PG-13">
                                <small class="form-text" data-i18n="biolink.event.rating_hint">Age restriction or content rating</small>
                            </div>
                        </div>

                        <!-- Customization Section -->
                        <div class="editor-section">
                            <h3><i class="fas fa-palette"></i> <span data-i18n="biolink.event.customization">Customization</span></h3>
                            
                            <div class="form-row" style="gap: 15px;">
                                <div class="form-group" style="flex: 1;">
                                    <label data-i18n="biolink.event.bg_color">Background Color</label>
                                    <input type="color" id="eventBgColor" class="form-control" value="${data.bg_color}" style="height: 50px; cursor: pointer;">
                                </div>
                                <div class="form-group" style="flex: 1;">
                                    <label data-i18n="biolink.event.card_bg_color">Card Background</label>
                                    <input type="color" id="eventCardBgColor" class="form-control" value="${data.card_bg_color}" style="height: 50px; cursor: pointer;">
                                </div>
                            </div>

                            <div class="form-row" style="gap: 15px;">
                                <div class="form-group" style="flex: 1;">
                                    <label data-i18n="biolink.event.text_color">Text Color</label>
                                    <input type="color" id="eventTextColor" class="form-control" value="${data.text_color}" style="height: 50px; cursor: pointer;">
                                </div>
                                <div class="form-group" style="flex: 1;">
                                    <label data-i18n="biolink.event.accent_color">Accent Color</label>
                                    <input type="color" id="eventAccentColor" class="form-control" value="${data.accent_color}" style="height: 50px; cursor: pointer;">
                                </div>
                            </div>

                            <div class="form-row" style="gap: 15px;">
                                <div class="form-group" style="flex: 1;">
                                    <label data-i18n="biolink.event.button_color">Button Color</label>
                                    <input type="color" id="eventButtonColor" class="form-control" value="${data.button_color}" style="height: 50px; cursor: pointer;">
                                </div>
                                <div class="form-group" style="flex: 1;">
                                    <label data-i18n="biolink.event.button_text_color">Button Text Color</label>
                                    <input type="color" id="eventButtonTextColor" class="form-control" value="${data.button_text_color}" style="height: 50px; cursor: pointer;">
                                </div>
                            </div>
                        </div>

                        <!-- Link Settings -->
                        <div class="editor-section">
                            <h3><i class="fas fa-link"></i> <span data-i18n="biolink.event.link_settings">Link Settings</span></h3>
                            
                            <div class="form-group">
                                <label data-i18n="biolink.event.custom_alias">Custom Alias</label>
                                <div class="input-group">
                                    <span class="input-prefix">/b/</span>
                                    <input type="text" id="eventCustomAlias" class="form-control" value="${BioLink.escapeHtml(project.slug)}" placeholder="my-event">
                                </div>
                                <small class="form-text" data-i18n="biolink.event.alias_hint">URL-friendly name for your event page</small>
                            </div>

                            <div class="form-group">
                                <label class="checkbox-label">
                                    <input type="checkbox" id="eventLinkStatus" ${project.status === 'active' ? 'checked' : ''}>
                                    <span data-i18n="biolink.event.active">Active</span>
                                </label>
                                <small class="form-text" data-i18n="biolink.event.active_hint">Make event page publicly accessible</small>
                            </div>
                        </div>

                    </div>

                    <!-- Right Panel - Preview -->
                    <div class="editor-panel-right" id="eventPreviewPanel" style="background: ${data.bg_color}; transition: background 0.3s;">
                        <div id="eventPreviewContent" style="background: ${data.card_bg_color}; border-radius: 20px; padding: 0; max-width: 500px; width: 100%; box-shadow: 0 20px 60px rgba(0,0,0,0.3); overflow: hidden; transition: all 0.3s; margin-bottom: 30px;">
                            <!-- Preview will be rendered here -->
                        </div>
                    </div>
                </div>
            </div>
        `;

        // Setup event listeners for real-time preview
        BioLink.setupEventPreview();
        
        // Initial preview render
        BioLink.renderEventPreview();
        
        // Apply translations
        if (typeof i18n !== 'undefined') {
            i18n.translatePage();
        }
    };

    // Setup event preview listeners
    BioLink.setupEventPreview = function() {
        const inputs = [
            'eventTitle', 'eventShortDesc', 'eventStartDate', 'eventEndDate',
            'eventTimezone', 'eventVenueName', 'eventAddress', 'eventLocation', 'eventVenueDesc',
            'eventLatitude', 'eventLongitude', 'eventRating', 'eventBgColor', 'eventCardBgColor', 
            'eventTextColor', 'eventAccentColor', 'eventButtonColor', 'eventButtonTextColor'
        ];

        inputs.forEach(id => {
            const el = document.getElementById(id);
            if (el) {
                el.addEventListener('input', () => BioLink.renderEventPreview());
            }
        });

        // Initialize Quill for long description
        if (typeof Quill !== 'undefined') {
            console.log('✅ Initializing Quill editor...');
            
            // Wait for DOM to be ready
            setTimeout(() => {
                const editorElement = document.getElementById('eventLongDescEditor');
                if (!editorElement) {
                    console.error('❌ Editor element not found');
                    return;
                }
                
                // Initialize Quill
                const quill = new Quill('#eventLongDescEditor', {
                    theme: 'snow',
                    modules: {
                        toolbar: [
                            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                            [{ 'font': [] }],
                            [{ 'size': ['small', false, 'large', 'huge'] }],
                            ['bold', 'italic', 'underline', 'strike'],
                            [{ 'color': [] }, { 'background': [] }],
                            [{ 'align': [] }],
                            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                            [{ 'indent': '-1'}, { 'indent': '+1' }],
                            ['link', 'image'],
                            ['clean']
                        ]
                    },
                    placeholder: 'Vamos ser sinceros. Esse aqui merece um container de edição mais completo com editor de fonte, cores de texto, marcador, italico, quebra linhas, quebra linhas com pontos, imagens, icones, emogis e links.'
                });
                
                // Set initial content
                const initialContent = document.getElementById('eventLongDesc')?.value || '';
                if (initialContent) {
                    quill.root.innerHTML = initialContent;
                }
                
                // Update hidden textarea on change
                quill.on('text-change', () => {
                    const content = quill.root.innerHTML;
                    document.getElementById('eventLongDesc').value = content;
                    BioLink.renderEventPreview();
                });
                
                // Store quill instance for later use
                BioLink.quillEditor = quill;
                
                console.log('✅ Quill editor initialized successfully');
            }, 100);
        } else {
            console.warn('⚠️ Quill not loaded, using fallback textarea');
            // Fallback to textarea if Quill not loaded
            const editor = document.getElementById('eventLongDescEditor');
            const textarea = document.getElementById('eventLongDesc');
            if (editor && textarea) {
                editor.style.display = 'none';
                textarea.style.display = 'block';
                textarea.rows = 8;
                textarea.addEventListener('input', () => BioLink.renderEventPreview());
            }
        }
        
        // Setup address autocomplete
        BioLink.setupAddressAutocomplete();
    };
    
    // Address autocomplete with Nominatim
    BioLink.setupAddressAutocomplete = function() {
        const addressInput = document.getElementById('eventAddress');
        const autocompleteDiv = document.getElementById('addressAutocomplete');
        
        if (!addressInput || !autocompleteDiv) return;
        
        let searchTimeout;
        
        addressInput.addEventListener('input', function() {
            const query = this.value.trim();
            
            // Clear previous timeout
            clearTimeout(searchTimeout);
            
            // Hide autocomplete if query is too short
            if (query.length < 3) {
                autocompleteDiv.style.display = 'none';
                return;
            }
            
            // Show loading
            autocompleteDiv.innerHTML = '<div style="padding: 12px; text-align: center; color: #6b7280;"><i class="fas fa-spinner fa-spin"></i> Searching...</div>';
            autocompleteDiv.style.display = 'block';
            
            // Debounce search
            searchTimeout = setTimeout(() => {
                fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(query)}&limit=5&addressdetails=1`)
                    .then(response => response.json())
                    .then(results => {
                        if (results.length === 0) {
                            autocompleteDiv.innerHTML = '<div style="padding: 12px; text-align: center; color: #6b7280;">No results found</div>';
                            return;
                        }
                        
                        let html = '';
                        results.forEach(result => {
                            html += `
                                <div class="address-suggestion" data-lat="${result.lat}" data-lon="${result.lon}" data-display="${BioLink.escapeHtml(result.display_name)}" style="padding: 12px; cursor: pointer; border-bottom: 1px solid #f1f5f9; transition: background 0.2s;">
                                    <div style="font-weight: 500; color: #1e293b; margin-bottom: 4px;">
                                        <i class="fas fa-map-marker-alt" style="color: #667eea; margin-right: 8px;"></i>
                                        ${BioLink.escapeHtml(result.display_name)}
                                    </div>
                                    <div style="font-size: 12px; color: #64748b;">
                                        <i class="fas fa-globe" style="margin-right: 4px;"></i>
                                        ${result.lat}, ${result.lon}
                                    </div>
                                </div>
                            `;
                        });
                        
                        autocompleteDiv.innerHTML = html;
                        
                        // Add click handlers
                        document.querySelectorAll('.address-suggestion').forEach(item => {
                            item.addEventListener('mouseenter', function() {
                                this.style.background = '#f8fafc';
                            });
                            item.addEventListener('mouseleave', function() {
                                this.style.background = 'white';
                            });
                            item.addEventListener('click', function() {
                                const lat = this.dataset.lat;
                                const lon = this.dataset.lon;
                                const display = this.dataset.display;
                                
                                // Fill form fields
                                document.getElementById('eventAddress').value = display;
                                document.getElementById('eventLatitude').value = lat;
                                document.getElementById('eventLongitude').value = lon;
                                
                                // Hide autocomplete
                                autocompleteDiv.style.display = 'none';
                                
                                // Update preview
                                BioLink.renderEventPreview();
                                
                                // Show success message
                                showNotification('Address selected! Coordinates auto-filled.', 'success');
                            });
                        });
                    })
                    .catch(error => {
                        console.error('Error searching address:', error);
                        autocompleteDiv.innerHTML = '<div style="padding: 12px; text-align: center; color: #ef4444;">Error searching address</div>';
                    });
            }, 500);
        });
        
        // Close autocomplete when clicking outside
        document.addEventListener('click', function(e) {
            if (!addressInput.contains(e.target) && !autocompleteDiv.contains(e.target)) {
                autocompleteDiv.style.display = 'none';
            }
        });
    };

    // Render event preview
    BioLink.renderEventPreview = function() {
        const previewContent = document.getElementById('eventPreviewContent');
        const previewPanel = document.getElementById('eventPreviewPanel');
        if (!previewContent || !previewPanel) return;

        const title = document.getElementById('eventTitle')?.value || 'Event Title';
        const shortDesc = document.getElementById('eventShortDesc')?.value || '';
        const longDesc = document.getElementById('eventLongDesc')?.value || '';
        const startDate = document.getElementById('eventStartDate')?.value || '';
        const endDate = document.getElementById('eventEndDate')?.value || '';
        const venueName = document.getElementById('eventVenueName')?.value || '';
        const address = document.getElementById('eventAddress')?.value || '';
        const location = document.getElementById('eventLocation')?.value || '';
        const venueDesc = document.getElementById('eventVenueDesc')?.value || '';
        const latitude = document.getElementById('eventLatitude')?.value || '';
        const longitude = document.getElementById('eventLongitude')?.value || '';
        const rating = document.getElementById('eventRating')?.value || '';
        const coverImage = document.getElementById('eventCoverImage')?.value || '';
        
        const bgColor = document.getElementById('eventBgColor')?.value || '#1e293b';
        const cardBgColor = document.getElementById('eventCardBgColor')?.value || '#ffffff';
        const textColor = document.getElementById('eventTextColor')?.value || '#1e293b';
        const accentColor = document.getElementById('eventAccentColor')?.value || '#667eea';
        const buttonColor = document.getElementById('eventButtonColor')?.value || '#667eea';
        const buttonTextColor = document.getElementById('eventButtonTextColor')?.value || '#ffffff';

        // Update panel background
        previewPanel.style.background = bgColor;
        previewContent.style.background = cardBgColor;

        // Format dates
        const formatDate = (dateStr) => {
            if (!dateStr) return '';
            const date = new Date(dateStr);
            return date.toLocaleDateString('en-US', { 
                weekday: 'short', 
                year: 'numeric', 
                month: 'short', 
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
        };

        // Get gallery images
        const galleryItems = Array.from(document.querySelectorAll('.gallery-item img')).map(img => img.src);

        previewContent.innerHTML = `
            ${coverImage ? `
                <div style="width: 100%; height: 250px; background: url('${BioLink.escapeHtml(coverImage)}') center/cover; position: relative;">
                    <div style="position: absolute; bottom: 0; left: 0; right: 0; background: linear-gradient(transparent, rgba(0,0,0,0.7)); padding: 20px; color: white;">
                        <h2 style="margin: 0; font-size: 24px; font-weight: 700;">${BioLink.escapeHtml(title)}</h2>
                    </div>
                </div>
            ` : ''}
            
            <div style="padding: 30px; color: ${textColor};">
                ${!coverImage ? `<h2 style="margin: 0 0 15px 0; font-size: 24px; font-weight: 700; color: ${textColor};">${BioLink.escapeHtml(title)}</h2>` : ''}
                
                ${shortDesc ? `<p style="font-size: 16px; color: ${textColor}; opacity: 0.8; margin-bottom: 20px;">${BioLink.escapeHtml(shortDesc)}</p>` : ''}
                
                <!-- Date & Time -->
                ${startDate ? `
                    <div style="background: ${accentColor}15; border-left: 4px solid ${accentColor}; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                        <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 8px;">
                            <i class="fas fa-calendar" style="color: ${accentColor};"></i>
                            <strong style="color: ${textColor};">Date & Time</strong>
                        </div>
                        <div style="color: ${textColor}; opacity: 0.9;">
                            <div><i class="fas fa-play" style="color: ${accentColor}; width: 20px;"></i> ${formatDate(startDate)}</div>
                            ${endDate ? `<div style="margin-top: 5px;"><i class="fas fa-stop" style="color: ${accentColor}; width: 20px;"></i> ${formatDate(endDate)}</div>` : ''}
                        </div>
                    </div>
                ` : ''}
                
                <!-- Location -->
                ${(venueName || address) ? `
                    <div style="background: ${accentColor}15; border-left: 4px solid ${accentColor}; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                        <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 8px;">
                            <i class="fas fa-map-marker-alt" style="color: ${accentColor};"></i>
                            <strong style="color: ${textColor};">Location</strong>
                        </div>
                        <div style="color: ${textColor}; opacity: 0.9;">
                            ${venueName ? `<div style="font-weight: 600;">${BioLink.escapeHtml(venueName)}</div>` : ''}
                            ${address ? `<div>${BioLink.escapeHtml(address)}</div>` : ''}
                            ${location ? `<div style="margin-top: 5px; opacity: 0.8;">${BioLink.escapeHtml(location)}</div>` : ''}
                        </div>
                        ${address ? `
                            <div id="previewMap" style="width: 100%; height: 200px; border-radius: 8px; overflow: hidden; margin-top: 15px; background: #e5e7eb; border: 1px solid #d1d5db; position: relative;">
                                <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; color: #6b7280;">
                                    <i class="fas fa-map-marked-alt" style="font-size: 32px; margin-bottom: 8px;"></i>
                                    <div style="font-size: 14px;">Map will be displayed on public page</div>
                                </div>
                            </div>
                        ` : ''}
                    </div>
                ` : ''}
                
                <!-- Rating -->
                ${rating ? `
                    <div style="display: inline-block; background: ${accentColor}; color: white; padding: 6px 12px; border-radius: 20px; font-size: 14px; margin-bottom: 20px;">
                        <i class="fas fa-star"></i> ${BioLink.escapeHtml(rating)}
                    </div>
                ` : ''}
                
                <!-- Description -->
                ${longDesc ? `
                    <div style="margin-bottom: 20px;">
                        <h3 style="font-size: 18px; font-weight: 600; color: ${textColor}; margin-bottom: 10px;">About This Event</h3>
                        <div style="color: ${textColor}; opacity: 0.8; line-height: 1.6;">${longDesc}</div>
                    </div>
                ` : ''}
                
                <!-- Venue Description -->
                ${venueDesc ? `
                    <div style="margin-bottom: 20px;">
                        <h3 style="font-size: 18px; font-weight: 600; color: ${textColor}; margin-bottom: 10px;">About the Venue</h3>
                        <p style="color: ${textColor}; opacity: 0.8; line-height: 1.6; white-space: pre-wrap;">${BioLink.escapeHtml(venueDesc)}</p>
                    </div>
                ` : ''}
                
                <!-- Gallery -->
                ${galleryItems.length > 0 ? `
                    <div style="margin-bottom: 20px;">
                        <h3 style="font-size: 18px; font-weight: 600; color: ${textColor}; margin-bottom: 10px;">Photo Gallery</h3>
                        <div style="display: flex; gap: 10px; overflow-x: auto; padding-bottom: 10px;">
                            ${galleryItems.map((img, idx) => `
                                <img src="${BioLink.escapeHtml(img)}" style="width: 120px; height: 120px; object-fit: cover; border-radius: 8px; flex-shrink: 0; cursor: pointer;" onclick="BioLink.openGalleryModal(${idx})">
                            `).join('')}
                        </div>
                    </div>
                ` : ''}
                
                <!-- Tickets -->
                ${BioLink.getEventTickets().length > 0 ? `
                    <div style="margin-bottom: 20px;">
                        <h3 style="font-size: 18px; font-weight: 600; color: ${textColor}; margin-bottom: 10px;">Tickets</h3>
                        ${BioLink.getEventTickets().map(ticket => `
                            <div style="background: #f8fafc; border: 2px solid #e2e8f0; border-radius: 12px; padding: 15px; margin-bottom: 10px;">
                                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                                    <strong style="color: ${textColor}; font-size: 16px;">${BioLink.escapeHtml(ticket.name || 'Ticket')}</strong>
                                    <span style="color: ${accentColor}; font-size: 20px; font-weight: 700;">${BioLink.escapeHtml(ticket.currency || '$')}${BioLink.escapeHtml(ticket.price || '0')}</span>
                                </div>
                                ${ticket.description ? `<p style="color: ${textColor}; opacity: 0.7; font-size: 14px; margin: 0;">${BioLink.escapeHtml(ticket.description)}</p>` : ''}
                            </div>
                        `).join('')}
                    </div>
                ` : ''}
                
                <!-- Button -->
                ${(() => {
                    const enableSales = document.getElementById('eventEnableSales')?.checked;
                    const whatsappNumber = document.getElementById('eventWhatsAppNumber')?.value || '';
                    
                    if (enableSales && whatsappNumber) {
                        return `<button onclick="BioLink.purchaseTicket('${BioLink.escapeHtml(title)}', '${whatsappNumber}')" style="width: 100%; background: #25D366; color: white; border: none; border-radius: 12px; padding: 15px; font-size: 16px; font-weight: 600; cursor: pointer; transition: all 0.3s;">
                            <i class="fab fa-whatsapp"></i> Purchase Tickets
                        </button>`;
                    } else {
                        return `<button style="width: 100%; background: ${buttonColor}; color: ${buttonTextColor}; border: none; border-radius: 12px; padding: 15px; font-size: 16px; font-weight: 600; cursor: pointer;">
                            <i class="fas fa-calendar-plus"></i> Add to Calendar
                        </button>`;
                    }
                })()}
            </div>
        `;
    };

    // Toggle sales fields visibility
    BioLink.toggleSalesFields = function() {
        const checkbox = document.getElementById('eventEnableSales');
        const salesFields = document.getElementById('salesFields');
        if (salesFields) {
            salesFields.style.display = checkbox?.checked ? 'block' : 'none';
        }
        BioLink.renderEventPreview();
    };

    // Gallery Modal Functions
    BioLink.openGalleryModal = function(index) {
        const galleryItems = Array.from(document.querySelectorAll('.gallery-item img')).map(img => img.src);
        const modal = document.createElement('div');
        modal.id = 'galleryModal';
        modal.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.95);z-index:10000;display:flex;align-items:center;justify-content:center;';
        
        modal.innerHTML = `
            <button onclick="BioLink.closeGalleryModal()" style="position:absolute;top:20px;right:20px;background:white;border:none;width:50px;height:50px;border-radius:50%;cursor:pointer;font-size:30px;line-height:1;z-index:10001;">×</button>
            <button onclick="BioLink.prevGalleryImage()" style="position:absolute;left:20px;background:white;border:none;width:50px;height:50px;border-radius:50%;cursor:pointer;font-size:30px;z-index:10001;">‹</button>
            <img id="galleryModalImg" src="${galleryItems[index]}" style="max-width:90%;max-height:90%;object-fit:contain;cursor:zoom-in;" onclick="this.style.transform=this.style.transform?'':'scale(1.5)';this.style.cursor=this.style.transform?'zoom-out':'zoom-in';">
            <button onclick="BioLink.nextGalleryImage()" style="position:absolute;right:20px;background:white;border:none;width:50px;height:50px;border-radius:50%;cursor:pointer;font-size:30px;z-index:10001;">›</button>
        `;
        
        document.body.appendChild(modal);
        BioLink.currentGalleryIndex = index;
        BioLink.galleryImages = galleryItems;
    };

    BioLink.closeGalleryModal = function() {
        document.getElementById('galleryModal')?.remove();
    };

    BioLink.nextGalleryImage = function() {
        BioLink.currentGalleryIndex = (BioLink.currentGalleryIndex + 1) % BioLink.galleryImages.length;
        const img = document.getElementById('galleryModalImg');
        if (img) {
            img.src = BioLink.galleryImages[BioLink.currentGalleryIndex];
            img.style.transform = '';
            img.style.cursor = 'zoom-in';
        }
    };

    BioLink.prevGalleryImage = function() {
        BioLink.currentGalleryIndex = (BioLink.currentGalleryIndex - 1 + BioLink.galleryImages.length) % BioLink.galleryImages.length;
        const img = document.getElementById('galleryModalImg');
        if (img) {
            img.src = BioLink.galleryImages[BioLink.currentGalleryIndex];
            img.style.transform = '';
            img.style.cursor = 'zoom-in';
        }
    };

    // Purchase ticket via WhatsApp
    BioLink.purchaseTicket = function(eventTitle, whatsappNumber) {
        const message = `Hi! I'm interested in purchasing tickets for: ${eventTitle}`;
        const url = `https://wa.me/${whatsappNumber.replace(/[^0-9]/g, '')}?text=${encodeURIComponent(message)}`;
        window.open(url, '_blank');
    };

    // Get event tickets from DOM
    BioLink.getEventTickets = function() {
        const tickets = [];
        document.querySelectorAll('.ticket-item').forEach((item, idx) => {
            const inputs = item.querySelectorAll('input, textarea');
            tickets.push({
                name: inputs[0]?.value || '',
                price: parseFloat(inputs[1]?.value) || 0,
                currency: inputs[2]?.value || 'USD',
                description: inputs[3]?.value || ''
            });
        });
        return tickets;
    };

    // Add ticket
    BioLink.addTicket = function() {
        const ticketsList = document.getElementById('ticketsList');
        if (!ticketsList) return;

        const idx = document.querySelectorAll('.ticket-item').length;
        const ticketHTML = `
            <div class="ticket-item" style="background: #f8fafc; padding: 15px; border-radius: 8px; margin-bottom: 10px; border: 1px solid #e2e8f0;">
                <div class="form-row" style="gap: 10px; margin-bottom: 10px;">
                    <input type="text" class="form-control" placeholder="Ticket name" onchange="BioLink.renderEventPreview()" style="flex: 2;">
                    <input type="number" class="form-control" placeholder="Price" onchange="BioLink.renderEventPreview()" style="flex: 1;" step="0.01" min="0">
                    <input type="text" class="form-control" placeholder="Currency" value="USD" onchange="BioLink.renderEventPreview()" style="flex: 1;" maxlength="3">
                    <button type="button" class="btn btn-sm btn-danger" onclick="BioLink.removeTicket(${idx})" title="Remove ticket">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
                <textarea class="form-control" placeholder="Ticket description" rows="2" onchange="BioLink.renderEventPreview()"></textarea>
            </div>
        `;
        
        ticketsList.insertAdjacentHTML('beforeend', ticketHTML);
        BioLink.renderEventPreview();
    };

    // Remove ticket
    BioLink.removeTicket = function(idx) {
        const tickets = document.querySelectorAll('.ticket-item');
        if (tickets[idx]) {
            tickets[idx].remove();
            BioLink.renderEventPreview();
        }
    };

    // Update ticket
    BioLink.updateTicket = function(idx, field, value) {
        BioLink.renderEventPreview();
    };

    // Handle cover image upload
    BioLink.handleCoverImageUpload = async function(event) {
        const file = event.target.files[0];
        if (!file) return;

        if (!file.type.startsWith('image/')) {
            showNotification('Please select an image file', 'error');
            return;
        }

        if (file.size > 5 * 1024 * 1024) {
            showNotification('Image must be less than 5MB', 'error');
            return;
        }

        try {
            const formData = new FormData();
            formData.append('file', file);

            const xhr = new XMLHttpRequest();
            
            xhr.upload.addEventListener('progress', (e) => {
                if (e.lengthComputable) {
                    const percent = (e.loaded / e.total) * 100;
                    console.log(`Upload progress: ${percent}%`);
                }
            });

            xhr.addEventListener('load', () => {
                if (xhr.status === 200) {
                    const response = JSON.parse(xhr.responseText);
                    if (response.success) {
                        document.getElementById('eventCoverImage').value = response.data.url;
                        
                        // Update preview area
                        const coverArea = document.getElementById('coverImageArea');
                        if (coverArea) {
                            coverArea.innerHTML = `
                                <img src="${response.data.url}" style="max-width: 100%; max-height: 200px; border-radius: 8px; margin-bottom: 10px;">
                                <div><button type="button" class="btn btn-sm btn-secondary" onclick="event.stopPropagation(); BioLink.removeCoverImage()"><i class="fas fa-trash"></i> <span data-i18n="biolink.event.remove">Remove</span></button></div>
                            `;
                        }
                        
                        BioLink.renderEventPreview();
                        showNotification('Cover image uploaded successfully!', 'success');
                    } else {
                        throw new Error(response.message || 'Upload failed');
                    }
                } else {
                    throw new Error('Upload failed');
                }
            });

            xhr.addEventListener('error', () => {
                showNotification('Error uploading image', 'error');
            });

            xhr.open('POST', '/api/tenant/upload/file');
            xhr.setRequestHeader('Authorization', `Bearer ${localStorage.getItem('token')}`);
            xhr.send(formData);

        } catch (error) {
            showNotification(error.message || 'Error uploading image', 'error');
        }
    };

    // Remove cover image
    BioLink.removeCoverImage = function() {
        document.getElementById('eventCoverImage').value = '';
        const coverArea = document.getElementById('coverImageArea');
        if (coverArea) {
            coverArea.innerHTML = `
                <i class="fas fa-cloud-upload-alt" style="font-size: 48px; color: #94a3b8; margin-bottom: 10px;"></i>
                <p style="color: #64748b;" data-i18n="biolink.event.upload_cover">Click to upload cover image</p>
                <small style="color: #94a3b8;" data-i18n="biolink.event.cover_size">Recommended: 1200x630px</small>
            `;
        }
        BioLink.renderEventPreview();
    };

    // Handle gallery upload
    BioLink.handleGalleryUpload = async function(event) {
        const files = Array.from(event.target.files);
        if (files.length === 0) return;

        for (const file of files) {
            if (!file.type.startsWith('image/')) {
                showNotification(`${file.name} is not an image`, 'error');
                continue;
            }

            if (file.size > 5 * 1024 * 1024) {
                showNotification(`${file.name} is too large (max 5MB)`, 'error');
                continue;
            }

            try {
                const formData = new FormData();
                formData.append('file', file);

                const response = await fetch('/api/tenant/upload/file', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    },
                    body: formData
                });

                const data = await response.json();
                
                if (data.success) {
                    const gallery = document.getElementById('eventGallery');
                    const idx = document.querySelectorAll('.gallery-item').length;
                    
                    gallery.insertAdjacentHTML('beforeend', `
                        <div class="gallery-item" style="position: relative; width: 100px; height: 100px;">
                            <img src="${data.data.url}" style="width: 100%; height: 100%; object-fit: cover; border-radius: 8px;">
                            <button type="button" class="btn-remove-gallery" onclick="BioLink.removeGalleryImage(${idx})" style="position: absolute; top: 5px; right: 5px; background: rgba(0,0,0,0.7); color: white; border: none; border-radius: 50%; width: 24px; height: 24px; cursor: pointer;">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    `);
                    
                    BioLink.renderEventPreview();
                } else {
                    throw new Error(data.message || 'Upload failed');
                }
            } catch (error) {
                showNotification(`Error uploading ${file.name}`, 'error');
            }
        }
        
        // Reset input
        event.target.value = '';
    };

    // Remove gallery image
    BioLink.removeGalleryImage = function(idx) {
        const items = document.querySelectorAll('.gallery-item');
        if (items[idx]) {
            items[idx].remove();
            BioLink.renderEventPreview();
        }
    };

    // Save event
    BioLink.saveEvent = async function() {
        const title = document.getElementById('eventTitle')?.value.trim() || '';
        const shortDesc = document.getElementById('eventShortDesc')?.value.trim() || '';
        const longDesc = document.getElementById('eventLongDesc')?.value || '';
        const startDate = document.getElementById('eventStartDate')?.value || '';
        const endDate = document.getElementById('eventEndDate')?.value || '';
        const timezone = document.getElementById('eventTimezone')?.value.trim() || 'UTC';
        const venueName = document.getElementById('eventVenueName')?.value.trim() || '';
        const address = document.getElementById('eventAddress')?.value.trim() || '';
        const location = document.getElementById('eventLocation')?.value.trim() || '';
        const venueDesc = document.getElementById('eventVenueDesc')?.value.trim() || '';
        const latitude = document.getElementById('eventLatitude')?.value || '';
        const longitude = document.getElementById('eventLongitude')?.value || '';
        const rating = document.getElementById('eventRating')?.value.trim() || '';
        const coverImage = document.getElementById('eventCoverImage')?.value || '';
        const customAlias = document.getElementById('eventCustomAlias')?.value.trim() || '';
        const linkStatus = document.getElementById('eventLinkStatus')?.checked ? 'active' : 'inactive';
        
        // Get sales settings
        const enableSales = document.getElementById('eventEnableSales')?.checked || false;
        const whatsappNumber = document.getElementById('eventWhatsAppNumber')?.value.trim() || '';

        // Get colors
        const bgColor = document.getElementById('eventBgColor')?.value || '#1e293b';
        const cardBgColor = document.getElementById('eventCardBgColor')?.value || '#ffffff';
        const textColor = document.getElementById('eventTextColor')?.value || '#1e293b';
        const accentColor = document.getElementById('eventAccentColor')?.value || '#667eea';
        const buttonColor = document.getElementById('eventButtonColor')?.value || '#667eea';
        const buttonTextColor = document.getElementById('eventButtonTextColor')?.value || '#ffffff';

        // Get gallery images
        const gallery = Array.from(document.querySelectorAll('.gallery-item img')).map(img => img.src);

        // Get tickets
        const tickets = BioLink.getEventTickets();

        // Only validate required fields if trying to activate the event
        if (linkStatus === 'active') {
            if (!title) {
                showNotification('Event title is required to activate', 'error');
                return;
            }

            if (!startDate) {
                showNotification('Start date is required to activate', 'error');
                return;
            }
        }

        // Use title or generate default name for draft events
        const eventName = title || BioLink.currentProject.name || 'Untitled Event';

        try {
            const updateData = {
                name: eventName,
                status: linkStatus,
                settings: {
                    title: title || eventName,
                    short_description: shortDesc,
                    long_description: longDesc,
                    start_date: startDate ? new Date(startDate).toISOString() : '',
                    end_date: endDate ? new Date(endDate).toISOString() : '',
                    timezone,
                    venue_name: venueName,
                    address,
                    location,
                    venue_description: venueDesc,
                    latitude: latitude ? parseFloat(latitude) : null,
                    longitude: longitude ? parseFloat(longitude) : null,
                    rating,
                    cover_image: coverImage,
                    gallery,
                    tickets,
                    enable_sales: enableSales,
                    whatsapp_number: whatsappNumber,
                    bg_color: bgColor,
                    card_bg_color: cardBgColor,
                    text_color: textColor,
                    accent_color: accentColor,
                    button_color: buttonColor,
                    button_text_color: buttonTextColor
                }
            };

            // Update slug if custom alias is provided and different from current
            if (customAlias && customAlias !== BioLink.currentProject.slug) {
                updateData.slug = customAlias;
            }

            const response = await api.put(`/biolink/projects/${BioLink.currentProject.id}`, updateData);

            if (response.success) {
                const message = linkStatus === 'active' ? 'Event saved and activated!' : 'Event saved as draft!';
                showNotification(message, 'success');
                
                // Update current project
                if (response.data) {
                    BioLink.currentProject = response.data;
                }
                
                // Reload projects list
                await this.loadProjects();
                
                // Reload usage stats
                await this.loadLimits();
            } else {
                showNotification(response.message || 'Error saving event', 'error');
            }
        } catch (error) {
            console.error('Error saving event:', error);
            showNotification(error.message || 'Error saving event', 'error');
        }
    };

    // Close event editor
    BioLink.closeEventEditor = function() {
        // Destroy Quill instance before closing
        if (BioLink.quillEditor) {
            BioLink.quillEditor = null;
        }
        
        document.body.classList.remove('biolink-editor-fullscreen');
        BioLink.render();
    };

    // Helper function to convert ISO date to input datetime format
    BioLink.toInputDateTime = function(value) {
        if (!value) return '';
        const date = new Date(value);
        if (isNaN(date.getTime())) return value;
        return date.toISOString().slice(0, 16);
    };

    console.log('✅ Event Editor Extension loaded - openEventEditor:', typeof BioLink.openEventEditor);

} else {
    console.error('❌ BioLink object not found - Event Editor Extension not loaded');
}

console.log('✅ Event Editor Extension script executed');

