import { LightningElement, track, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import getProperties from '@salesforce/apex/PropertyDataController.getProperties';
import getPropertyDetails from '@salesforce/apex/PropertyDataController.getPropertyDetails';
import generatePreview from '@salesforce/apex/PdfApiController.generatePreview';
import generatePdf from '@salesforce/apex/PdfApiController.generatePdf';

export default class PropertyTemplateSelector extends LightningElement {
    @track currentStep = 1;
    @track properties = [];
    @track selectedPropertyId = '';
    @track propertyData = {
        propertyName: '',
        propertyType: '',
        location: '',
        price: '',
        bedrooms: '',
        bathrooms: '',
        area: '',
        titleEnglish: '',
        description: '',
        images: []
    };
    @track templates = [
        {
            Id: 'custom',
            Name: 'Custom Template',
            Description__c: 'Build your own template with custom layouts',
            Icon: '📄',
            Pages: 'Custom',
            Type: 'Custom'
        },
        {
            Id: 'professional-1pager',
            Name: 'Professional 1-Pager',
            Description__c: 'Compact single-page brochure with 2x2 image grid',
            Icon: '🏠',
            Pages: '1 page',
            Type: 'Professional'
        },
        {
            Id: 'professional-3pager',
            Name: 'Professional 3-Pager',
            Description__c: 'Comprehensive three-page brochure with detailed analysis',
            Icon: '🏛️',
            Pages: '3 pages',
            Type: 'Professional'
        },
        {
            Id: 'professional-5pager',
            Name: 'Professional 5-Pager',
            Description__c: 'Premium five-page brochure with comprehensive analysis',
            Icon: '📋',
            Pages: '5 pages',
            Type: 'Professional'
        },
        {
            Id: 'luxury-villa',
            Name: 'Luxury Villa Brochure',
            Description__c: 'Exclusive villa template with premium styling',
            Icon: '💼',
            Pages: '6 pages',
            Type: 'Luxury'
        },
        {
            Id: 'dubai-penthouse',
            Name: 'Dubai Penthouse',
            Description__c: 'Dubai-specific luxury penthouse template',
            Icon: '🎨',
            Pages: '4 pages',
            Type: 'Luxury'
        },
        {
            Id: 'modern-apartment',
            Name: 'Modern Apartment',
            Description__c: 'Contemporary apartment template with clean lines',
            Icon: '⭐',
            Pages: '3 pages',
            Type: 'Modern'
        }
    ];
    @track selectedTemplate = '';
    @track selectedTemplateData = {};
    @track previewData = null;
    @track isLoading = false;
    @track error;
    @track availableAmenities = [
        'Swimming Pool', 'Gym', 'Parking', 'Garden', 'Balcony',
        'Air Conditioning', 'Heating', 'Security System', 'Elevator', 'Storage'
    ];
    @track customizationOptions = {
        headerStyle: 'modern',
        colorScheme: 'professional',
        fontStyle: 'clean'
    };
    
    // Wire service to fetch properties
    @wire(getProperties)
    wiredProperties({ error, data }) {
        if (data) {
            this.properties = data;
            this.error = undefined;
            console.log(`Loaded ${this.properties.length} properties from Salesforce`);
        } else if (error) {
            this.error = error;
            console.error('Error loading properties:', error);
        }
    }

    // Lifecycle method
    connectedCallback() {
        // Reset to clean state
        this.resetStepState();
        console.log('Component connected, current step:', this.currentStep);
    }

    // Reset step state to clean initial state
    resetStepState() {
        this.currentStep = 1;
        this.selectedTemplate = '';
        this.selectedTemplateData = {};
        this.selectedPropertyId = '';
        this.clearPropertyData();
        // Preserve customization options - don't reset them
        // this.customizationOptions = {
        //     headerStyle: 'modern',
        //     colorScheme: 'professional',
        //     fontStyle: 'clean'
        // };
        console.log('Step state reset to clean initial state');
    }

    // Getter for property options with formatted labels
    get formattedPropertyOptions() {
        return this.properties.map(property => ({
            label: `${property.Name} - ${property.Location} - ${property.PropertyType || 'N/A'}`,
            value: property.Id
        }));
    }

    // Getter for property types with readable names
    get formattedPropertyTypes() {
        const types = [...new Set(this.properties.map(p => p.PropertyType).filter(Boolean))];
        return types.map(type => ({
            label: this.mapPropertyType(type),
            value: type
        }));
    }

    // Map property type codes to readable names
    mapPropertyType(typeCode) {
        const typeMap = {
            'AP': 'Apartment',
            'VH': 'Villa',
            'BU': 'Bungalow',
            'BW': 'Warehouse'
        };
        return typeMap[typeCode] || typeCode;
    }

    // Ensure current step is always correct
    ensureCorrectStep() {
        console.log('ensureCorrectStep called - current step before:', this.currentStep);
        console.log('selectedTemplate:', this.selectedTemplate);
        console.log('propertyData:', this.propertyData);
        
        // If no template is selected, force back to step 1
        if (!this.selectedTemplate && this.currentStep > 1) {
            console.log('No template selected, forcing back to step 1');
            this.currentStep = 1;
        }
        // If step 2 is not completed, don't allow going beyond step 2
        if (!this.isStepCompleted(2) && this.currentStep > 2) {
            console.log('Step 2 not completed, forcing back to step 2');
            this.currentStep = 2;
        }
        // If step 4 is not completed, don't allow going to step 5
        if (!this.isStepCompleted(4) && this.currentStep > 4) {
            console.log('Step 4 not completed, forcing back to step 4');
            this.currentStep = 4;
        }
        console.log('Current step after ensureCorrectStep:', this.currentStep);
            }

    // Step navigation
    goToStep(event) {
        const step = parseInt(event.currentTarget.dataset.step);
        console.log('Attempting to go to step:', step, 'Current step:', this.currentStep);
        
        // Only allow navigation to accessible steps
        if (this.isStepAccessible(step)) {
            this.currentStep = step;
            console.log('Successfully navigated to step:', this.currentStep);
        } else {
            console.log('Cannot navigate to step:', step, '- not accessible');
            }
    }

    canProceedToStep(step) {
        // More restrictive step navigation
        if (step === 1) return true; // Always can go back to step 1
        if (step === 2 && this.selectedTemplate) return true;
        if (step === 3 && this.isStepCompleted(2)) return true;
        if (step === 4 && this.isStepCompleted(2)) return true;
        if (step === 5 && this.isStepCompleted(4)) return true;
        return false;
    }

    nextStep() {
        if (this.canProceed) {
            this.currentStep = Math.min(this.currentStep + 1, 5);
        }
    }

    previousStep() {
        this.currentStep = Math.max(this.currentStep - 1, 1);
    }

    // Getter to check if a step is completed
    isStepCompleted(step) {
        if (step === 1) return this.selectedTemplate;
        if (step === 2) return this.propertyData.propertyName && this.propertyData.propertyType && this.propertyData.location;
        if (step === 3) return true; // Step 3 is always accessible once step 2 is complete
        if (step === 4) return this.propertyData.propertyName && this.propertyData.description;
        return false;
    }

    // Getter to check if a step is accessible
    isStepAccessible(step) {
        if (step === 1) return true; // Step 1 is always accessible
        if (step === 2) return this.selectedTemplate; // Need template selected
        if (step === 3) return this.isStepCompleted(2); // Need step 2 completed
        if (step === 4) return this.isStepCompleted(2); // Need step 2 completed
        if (step === 5) return this.isStepCompleted(4); // Need step 4 completed
        return false;
    }

    // Template selection
    handleTemplateSelect(event) {
        const templateId = event.currentTarget.dataset.templateId;
        this.selectedTemplate = templateId;
        this.selectedTemplateData = this.templates.find(t => t.Id === templateId);
        
        // Remove previous selection from all cards
        this.template.querySelectorAll('.template-card').forEach(card => {
            card.classList.remove('selected');
        });
        
        // Add selection to clicked card
        event.currentTarget.classList.add('selected');
        
        console.log('Template selected:', this.selectedTemplateData);
    }

    // Property selection
    handlePropertySelection(event) {
        const propertyId = event.target.value;
        this.selectedPropertyId = propertyId;
        
        if (propertyId) {
            this.isLoading = true;
            
            // Get property details
            getPropertyDetails({ propertyId: propertyId })
                .then(result => {
                    if (result) {
                        // Auto-fill the form with real property data
                        this.propertyData = {
                            propertyName: result.Name || '',
                            propertyType: result.PropertyType || '',
                            location: result.Location || '',
                            price: result.Price || '',
                            bedrooms: result.Bedrooms || '',
                            bathrooms: result.Bathrooms || '',
                            area: result.Area || '',
                            titleEnglish: result.TitleEnglish || result.Name || '',
                            description: result.Description || '',
                            images: this.propertyData.images || []
                        };
                        console.log('Property data loaded and form auto-filled:', result);
                    } else {
                        this.clearPropertyData();
                        console.error('No property details returned');
                    }
                })
                .catch(error => {
                    console.error('Error loading property details:', error);
                    this.clearPropertyData();
                })
                .finally(() => {
                    this.isLoading = false;
                });
        } else {
            this.clearPropertyData();
        }
        }
        
    // Clear property data
    clearPropertyData() {
        this.propertyData = {
            propertyName: '',
            propertyType: '',
            location: '',
            price: '',
            bedrooms: '',
            bathrooms: '',
            area: '',
            titleEnglish: '',
            description: '',
            images: this.propertyData.images || []
        };
    }

    // Manually load properties (refresh button)
    manuallyLoadProperties() {
        this.isLoading = true;
        
        getProperties()
            .then(result => {
                this.properties = result || [];
                this.error = undefined;
                
                if (this.properties.length > 0) {
                    console.log(`Loaded ${this.properties.length} properties`);
                } else {
                    console.log('No properties found');
                }
            })
            .catch(error => {
                console.error('Error loading properties:', error);
                this.error = error;
                this.properties = [];
            })
            .finally(() => {
                this.isLoading = false;
        });
    }

    // Form input handling
    handleInputChange(event) {
        const field = event.target.name;
        this.propertyData[field] = event.target.value;
    }

    handlePropertyTypeChange(event) {
        this.propertyData.propertyType = event.target.value;
    }

    handleLocationChange(event) {
        this.propertyData.location = event.target.value;
    }

    // Amenities handling
    handleAmenityChange(event) {
        const amenity = event.target.value;
        const checked = event.target.checked;
        
        if (checked && !this.propertyData.amenities) {
            this.propertyData.amenities = [];
        }
        
        if (checked) {
            this.propertyData.amenities.push(amenity);
        } else if (this.propertyData.amenities) {
            this.propertyData.amenities = this.propertyData.amenities.filter(a => a !== amenity);
        }
    }

    // Customization handling
    handleCustomizationChange(event) {
        const field = event.target.name;
        this.customizationOptions[field] = event.target.value;
    }

    // Image handling
    handleImageUpload(event) {
        const files = event.target.files;
        if (files) {
            Array.from(files).forEach(file => {
                const reader = new FileReader();
                reader.onload = (e) => {
                    this.propertyData.images.push({
                        src: e.target.result,
                        name: file.name
                    });
                };
                reader.readAsDataURL(file);
            });
        }
    }

    removeImage(event) {
        const index = parseInt(event.currentTarget.dataset.index);
        this.propertyData.images.splice(index, 1);
        }

    handleImageNameChange(event) {
        const index = parseInt(event.currentTarget.dataset.index);
        const name = event.target.value;
        if (this.propertyData.images[index]) {
            this.propertyData.images[index].name = name;
        }
    }

    // Preview handling
    handlePreview() {
        this.isLoading = true;

        // Prepare data for Python API with all required fields
        const previewData = {
            template: this.selectedTemplate,
                    propertyName: this.propertyData.propertyName || 'Sample Property',
            propertyType: this.propertyData.propertyType || 'Apartment',
                    location: this.propertyData.location || 'Dubai',
            price: this.propertyData.price || '2,500,000',
                    bedrooms: this.propertyData.bedrooms || '2',
                    bathrooms: this.propertyData.bathrooms || '2',
            area: this.propertyData.area || '1,200',
            description: this.propertyData.description || 'Beautiful property with modern amenities'
        };

        console.log('Sending preview data to API:', previewData);

        // Call Apex controller for preview
        generatePreview({
            template: previewData.template,
            propertyName: previewData.propertyName,
            propertyType: previewData.propertyType,
            location: previewData.location,
            price: previewData.price,
            bedrooms: previewData.bedrooms,
            bathrooms: previewData.bathrooms,
            area: previewData.area,
            description: previewData.description
        })
        .then(result => {
            console.log('Preview API response:', result);
            if (result.success) {
                console.log('Preview generated successfully:', result);
                // Store preview data for later use
                this.previewData = result.preview;
                this.nextStep();
            } else {
                console.error('Preview generation failed:', result.error);
                this.showError(result.error || 'Preview generation failed');
            }
        })
        .catch(error => {
            console.error('Error calling preview API:', error);
            this.showError('Error calling preview service: ' + error.body?.message || error.message);
        })
        .finally(() => {
            this.isLoading = false;
        });
    }

    // Download handling
    handleDownload() {
        this.isLoading = true;

        // Prepare data for Python API with all required fields
        const pdfData = {
            template: this.selectedTemplate,
                    propertyName: this.propertyData.propertyName || 'Sample Property',
            propertyType: this.propertyData.propertyType || 'Apartment',
                    location: this.propertyData.location || 'Dubai',
            price: this.propertyData.price || '2,500,000',
                    bedrooms: this.propertyData.bedrooms || '2',
                    bathrooms: this.propertyData.bathrooms || '2',
            area: this.propertyData.area || '1,200',
            description: this.propertyData.description || 'Beautiful property with modern amenities'
        };

        console.log('Sending PDF generation data to API:', pdfData);

        // Call Apex controller to generate PDF
        generatePdf({
            templateName: pdfData.template,
            propertyName: pdfData.propertyName,
            propertyType: pdfData.propertyType,
            location: pdfData.location,
            price: pdfData.price,
            bedrooms: pdfData.bedrooms,
            bathrooms: pdfData.bathrooms,
            area: pdfData.area,
            description: pdfData.description
        })
        .then(result => {
            console.log('PDF API response:', result);
            if (result.success) {
                console.log('PDF generation response:', result);
                
                // Check if we have actual PDF data
                if (result.pdf_data && result.filename) {
                    console.log('PDF data received, downloading PDF file...');
                    console.log('Filename:', result.filename);
                    console.log('Content type:', result.content_type);
                    
                    // Download the actual PDF file
                    this.downloadPdfFile(result.pdf_data, result.filename);
                } 
                // Check if we have preview HTML content as fallback
                else if (result.preview_html) {
                    console.log('No PDF data, using preview HTML fallback');
                    console.log('Preview HTML content found, length:', result.preview_html.length);
                    console.log('Template Info:', result.template_info);
                    console.log('Property Data:', result.property_data);
                    
                    // Show the preview content and provide download instructions
                    this.showPreviewContent(result.preview_html, result.template_info, result.property_data, result.note);
                } else {
                    console.error('No PDF data or preview HTML in result:', result);
                    this.showError('No content received from the API');
                }
            } else {
                console.error('PDF generation failed:', result.error);
                this.showError(result.error || 'PDF generation failed');
            }
        })
        .catch(error => {
            console.error('Error calling PDF API:', error);
            this.showError('Error calling PDF service: ' + error.body?.message || error.message);
        })
        .finally(() => {
            this.isLoading = false;
        });
    }

    // Download PDF file from base64 data
    downloadPdfFile(base64Data, filename) {
        try {
            console.log('Starting PDF download process...');
            console.log('Base64 data length:', base64Data ? base64Data.length : 'undefined');
            console.log('Filename:', filename);
            
            if (!base64Data) {
                this.showError('No PDF data available for download');
                return;
            }
            
            // Convert base64 to binary data
            const binaryString = atob(base64Data);
            const bytes = new Uint8Array(binaryString.length);
            for (let i = 0; i < binaryString.length; i++) {
                bytes[i] = binaryString.charCodeAt(i);
            }
            
            console.log('Binary data created, size:', bytes.length);
            
            // Create a Blob with PDF content
            const pdfBlob = new Blob([bytes], { type: 'application/pdf' });
            console.log('PDF Blob created, size:', pdfBlob.size);
            
            // Use data URL approach for PDF download (LWS compatible)
            const reader = new FileReader();
            reader.onload = (event) => {
                try {
                    const dataUrl = event.target.result;
                    console.log('Data URL created for PDF');
                    
                    // Create download link
                    const downloadLink = document.createElement('a');
                    downloadLink.href = dataUrl;
                    downloadLink.download = filename;
                    downloadLink.style.display = 'none';
                    
                    console.log('Download link created, filename:', downloadLink.download);
                    
                    // Trigger download
                    document.body.appendChild(downloadLink);
                    downloadLink.click();
                    document.body.removeChild(downloadLink);
                    
                    console.log('PDF download process completed successfully');
                    
                    // Show success message
                    this.showSuccess('PDF downloaded successfully! Check your Downloads folder.');
                    
                } catch (error) {
                    console.error('Error in PDF download link creation:', error);
                    this.showError('PDF download failed: ' + error.message);
                }
            };
            
            reader.onerror = (error) => {
                console.error('Error reading PDF blob:', error);
                this.showError('PDF download failed: Error reading file data');
            };
            
            // Read the blob as data URL
            reader.readAsDataURL(pdfBlob);
            
        } catch (error) {
            console.error('Error in PDF download process:', error);
            this.showError('PDF download failed: ' + error.message);
        }
    }

    handleCreateNew() {
        this.currentStep = 1;
        this.selectedTemplate = '';
        this.selectedPropertyId = '';
        this.clearPropertyData();
        // Preserve customization options - don't reset them
        // this.customizationOptions = {
        //     headerStyle: 'modern',
        //     colorScheme: 'professional',
        //     fontStyle: 'clean'
        // };
        
        // Clear template selection
        this.template.querySelectorAll('.template-card').forEach(card => {
            card.classList.remove('selected');
        });
    }

    // Getters for step visibility
    get step1Class() { 
        this.ensureCorrectStep();
        return `step-content ${this.currentStep === 1 ? 'active' : ''}`; 
    }

    get step2Class() { 
        this.ensureCorrectStep();
        return `step-content ${this.currentStep === 2 ? 'active' : ''}`; 
    }

    get step3Class() { 
        this.ensureCorrectStep();
        return `step-content ${this.currentStep === 3 ? 'active' : ''}`; 
    }

    get step4Class() { 
        this.ensureCorrectStep();
        return `step-content ${this.currentStep === 4 ? 'active' : ''}`; 
    }

    get step5Class() { 
        this.ensureCorrectStep();
        return `step-content ${this.currentStep === 5 ? 'active' : ''}`; 
    }
    
    // Getters for step navigation classes
    get step1NavClass() {
        this.ensureCorrectStep();
        let classes = 'step-item';
        if (this.currentStep === 1) classes += ' active';
        // Only show completed if we're past step 1 AND template is selected
        if (this.currentStep > 1 && this.selectedTemplate) classes += ' completed';
        if (this.isStepAccessible(1)) classes += ' accessible';
        return classes;
    }

    get step2NavClass() {
        this.ensureCorrectStep();
        let classes = 'step-item';
        if (this.currentStep === 2) classes += ' active';
        // Only show completed if we're past step 2 AND step 2 requirements are met
        if (this.currentStep > 2 && this.isStepCompleted(2)) classes += ' completed';
        if (this.isStepAccessible(2)) classes += ' accessible';
        return classes;
    }

    get step3NavClass() {
        this.ensureCorrectStep();
        let classes = 'step-item';
        if (this.currentStep === 3) classes += ' active';
        // Only show completed if we're past step 3 AND step 3 requirements are met
        if (this.currentStep > 3 && this.isStepCompleted(3)) classes += ' completed';
        if (this.isStepAccessible(3)) classes += ' accessible';
        return classes;
    }

    get step4NavClass() {
        this.ensureCorrectStep();
        let classes = 'step-item';
        if (this.currentStep === 4) classes += ' active';
        // Only show completed if we're past step 4 AND step 4 requirements are met
        if (this.currentStep > 4 && this.isStepCompleted(4)) classes += ' completed';
        if (this.isStepAccessible(4)) classes += ' accessible';
        return classes;
    }

    get step5NavClass() {
        this.ensureCorrectStep();
        let classes = 'step-item';
        if (this.currentStep === 5) classes += ' active';
        // Step 5 is the final step, so it's completed when we're on it
        if (this.currentStep === 5) classes += ' completed';
        if (this.isStepAccessible(5)) classes += ' accessible';
        return classes;
    }

    // Getters for button states
    get canProceed() {
        if (this.currentStep === 1) {
            return this.selectedTemplate;
        }
        if (this.currentStep === 2) {
            return this.propertyData.propertyName && this.propertyData.propertyType && this.propertyData.location;
        }
        return true;
    }

    get canProceedToDownload() {
        return this.propertyData.propertyName && this.propertyData.description;
    }

    // Button disabled states (opposite of canProceed)
    get isNextButtonDisabled() {
        return !this.canProceed;
    }

    get isDownloadButtonDisabled() {
        return !this.canProceedToDownload;
    }

    get previewButtonText() {
        return this.isLoading ? 'Generating Preview...' : 'Generate Preview';
    }

    get downloadButtonText() {
        return this.isLoading ? 'Generating PDF...' : 'Download PDF';
    }

    // Dubai locations for dropdown
    get dubaiLocations() {
        return [
            'Dubai Marina', 'Jumeirah Lake Towers', 'Downtown Dubai', 'Business Bay',
            'Palm Jumeirah', 'Jumeirah Beach Residence', 'Dubai Hills Estate',
            'Emirates Hills', 'Arabian Ranches', 'Dubai Silicon Oasis'
        ];
    }

    // Computed properties for template selection
    get customBlankSelected() {
        return this.selectedTemplate === 'custom';
    }

    get template1Selected() {
        return this.selectedTemplate === 'professional-1pager';
    }

    get template2Selected() {
        return this.selectedTemplate === 'professional-3pager';
        }

    get template3Selected() {
        return this.selectedTemplate === 'professional-5pager';
    }

    get template4Selected() {
        return this.selectedTemplate === 'luxury-villa';
    }

    get template5Selected() {
        return this.selectedTemplate === 'dubai-penthouse';
    }

    get template6Selected() {
        return this.selectedTemplate === 'modern-apartment';
    }

    // Error handling
    clearError() {
        this.error = null;
    }

    // Show error message
    showError(message) {
        this.error = message;
        this.clearError();
    }

    // Show success message
    showSuccess(message) {
        this.error = null;
        // Create a temporary success message
        const successDiv = document.createElement('div');
        successDiv.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: #28a745;
            color: white;
            padding: 15px 20px;
            border-radius: 5px;
            z-index: 10000;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
            animation: slideInRight 0.3s ease;
        `;
        successDiv.textContent = message;
        
        document.body.appendChild(successDiv);
        
        // Remove after 5 seconds
        setTimeout(() => {
            if (document.body.contains(successDiv)) {
                document.body.removeChild(successDiv);
        }
        }, 5000);
    }

    // Show preview content and provide download functionality
    showPreviewContent(htmlContent, templateInfo, propertyData, note) {
        try {
            console.log('Starting download process...');
            console.log('HTML Content length:', htmlContent ? htmlContent.length : 'undefined');
            console.log('Template Info:', templateInfo);
            console.log('Property Data:', propertyData);
            
            if (!htmlContent) {
                this.showError('No content available for download');
                return;
            }
            
            // Create the full HTML document
            const fullHtml = `
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Property Report - ${propertyData?.propertyName || 'Property'}</title>
                    <meta charset="utf-8">
                    <style>
                        body { font-family: Arial, sans-serif; margin: 20px; background: #f8f9fa; }
                        .header { background: white; padding: 20px; border-radius: 10px; margin-bottom: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
                        .note { background: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
                        .download-instructions { background: #d1ecf1; border: 1px solid #bee5eb; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
                        .preview-content { margin-top: 20px; background: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
                        h1 { color: #333; margin-bottom: 10px; }
                        h2 { color: #666; margin-bottom: 15px; }
                        p { line-height: 1.6; color: #555; }
                        .property-details { display: grid; gap: 10px; margin: 20px 0; }
                        .property-detail { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #eee; }
                        .property-detail:last-child { border-bottom: none; }
                        strong { color: #333; }
                    </style>
                </head>
                <body>
                    <div class="header">
                        <h1>Property Report Generated Successfully!</h1>
                        <p><strong>Template:</strong> ${templateInfo?.display_name || 'Unknown'}</p>
                        <p><strong>Property:</strong> ${propertyData?.propertyName || 'Unknown'}</p>
                        <p><strong>Location:</strong> ${propertyData?.location || 'Unknown'}</p>
                        <p><strong>Price:</strong> ${propertyData?.price || 'Unknown'}</p>
                    </div>
                    
                    <div class="note">
                        <strong>Note:</strong> ${note || 'The PDF download endpoint is currently unavailable.'}
                    </div>
                    
                    <div class="download-instructions">
                        <h3>📥 How to Download as PDF:</h3>
                        <ol>
                            <li><strong>Print to PDF:</strong> Press Ctrl+P (or Cmd+P on Mac) and select "Save as PDF"</li>
                            <li><strong>Browser Save:</strong> Right-click on the page and select "Save as" or "Print"</li>
                            <li><strong>PDF Extension:</strong> Use browser extensions like "Save as PDF"</li>
                            <li><strong>Copy Content:</strong> Copy the content and paste into a document editor</li>
                        </ol>
                    </div>
                    
                    <div class="preview-content">
                        ${htmlContent}
                    </div>
                </body>
                </html>
            `;
            
            console.log('Full HTML created, length:', fullHtml.length);
            
            // Use data URL approach instead of Blob to avoid Lightning Web Security issues
            const dataUrl = 'data:text/html;charset=utf-8,' + encodeURIComponent(fullHtml);
            console.log('Data URL created, length:', dataUrl.length);
            
            // Create download link using data URL
            const downloadLink = document.createElement('a');
            downloadLink.href = dataUrl;
            downloadLink.download = `property_report_${propertyData?.propertyName || 'property'}_${new Date().toISOString().split('T')[0]}.html`;
            downloadLink.style.display = 'none';
            
            console.log('Download link created, filename:', downloadLink.download);
            
            // Trigger download
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
            
            console.log('Download process completed successfully');
            
            // Show success message
            this.showSuccess('Property report downloaded successfully! Check your Downloads folder.');
            
        } catch (error) {
            console.error('Error in download process:', error);
            this.showError('Download failed: ' + error.message);
        }
    }
} 

