// Current step tracking
let currentStep = 1;
const totalSteps = 4;
let propertyImportQuantity = 10;
let isImporting = false;
let selectedDepartment = 'sale';

// Import cancellation and pause variables
let importCancelled = false;
let importPaused = false;
let currentImportData = null;
let currentBatch = 0;
let currentImported = 0;
let currentCsrfToken = '';

// Track if builders have been reset during this import session
let buildersReset = false;

// Store taxonomy selections per department
const departmentSelections = {
    sale: {
        types: [],
        status: [],
        badges: [],
        tags: [],
        locations: [],
        features: []
    },
    rent: {
        types: [],
        status: [],
        badges: [],
        tags: [],
        locations: [],
        features: []
    },
    commercial: {
        types: [],
        status: [],
        badges: [],
        tags: [],
        locations: [],
        features: []
    },
    let: {
        types: [],
        status: [],
        badges: [],
        tags: [],
        locations: [],
        features: []
    }
};

// All taxonomy data organized by department
const departmentTaxonomies = {
    sale: {
        types: {
            label: 'Property Type',
            taxonomy: 'types',
            items: [
                { value: 'cottage', label: 'Cottage' },
                { value: 'duplex', label: 'Duplex' },
                { value: 'flat', label: 'Flat' },
                { value: 'land', label: 'Land' },
                { value: 'garage', label: 'Garage' },
                { value: 'mews', label: 'Mews' },
                { value: 'triplex', label: 'Triplex' }
            ]
        },
        status: {
            label: 'Property Status',
            taxonomy: 'status',
            items: [
                { value: 'for-sale', label: 'For Sale' },
                { value: 'pending', label: 'Pending' },
                { value: 'sold', label: 'Sold' },
                { value: 'under-offer', label: 'Under Offer' },
                { value: 'exchanged', label: 'Exchanged' }
            ]
        },
        badges: {
            label: 'Badges',
            taxonomy: 'badges',
            items: [
                { value: 'featured', label: 'Featured' },
                { value: 'new', label: 'New' },
                { value: 'popular', label: 'Popular' }
            ]
        },
        tags: {
            label: 'Tags',
            taxonomy: 'tags',
            items: [
                { value: 'apartment', label: 'Apartment' },
                { value: 'bungalow', label: 'Bungalow' },
                { value: 'commercial', label: 'Commercial' },
                { value: 'cottage', label: 'Cottage' },
                { value: 'duplex', label: 'Duplex' },
                { value: 'flat', label: 'Flat' },
                { value: 'house', label: 'House' },
                { value: 'land', label: 'Land' },
                { value: 'office', label: 'Office' },
                { value: 'retail', label: 'Retail' },
                { value: 'studio', label: 'Studio' },
                { value: 'townhouse', label: 'Townhouse' },
                { value: 'warehouse', label: 'Warehouse' }
            ]
        },
        locations: {
            label: 'Property Locations',
            taxonomy: 'locations',
            items: [
                { value: 'abu-dhabi', label: 'Abu Dhabi' },
                { value: 'berlin', label: 'Berlin' },
                { value: 'boston', label: 'Boston' },
                { value: 'chicago', label: 'Chicago' },
                { value: 'coastal', label: 'Coastal' },
                { value: 'dallas', label: 'Dallas' },
                { value: 'dubai', label: 'Dubai' },
                { value: 'hong-kong', label: 'Hong Kong' },
                { value: 'london', label: 'London' },
                { value: 'los-angeles', label: 'Los Angeles' },
                { value: 'miami', label: 'Miami' },
                { value: 'new-york', label: 'New York' },
                { value: 'paris', label: 'Paris' },
                { value: 'san-francisco', label: 'San Francisco' },
                { value: 'seattle', label: 'Seattle' },
                { value: 'singapore', label: 'Singapore' },
                { value: 'sydney', label: 'Sydney' },
                { value: 'tokyo', label: 'Tokyo' },
                { value: 'toronto', label: 'Toronto' },
                { value: 'vancouver', label: 'Vancouver' }
            ]
        },
        features: {
            label: 'Features',
            taxonomy: 'features',
            items: [
                { value: 'studio', label: 'Studio' },
                { value: 'premium', label: 'Premium' },
                { value: 'privacy', label: 'Privacy' },
                { value: 'rooftop-terrace', label: 'Rooftop Terrace' },
                { value: 'hardwood-floors', label: 'Hardwood Floors' },
                { value: 'central-air', label: 'Central Air' },
                { value: 'fireplace', label: 'Fireplace' },
                { value: 'pool', label: 'Pool' },
                { value: 'gym', label: 'Gym' },
                { value: 'parking', label: 'Parking' },
                { value: 'elevator', label: 'Elevator' },
                { value: 'balcony', label: 'Balcony' },
                { value: 'garden', label: 'Garden' },
                { value: 'security', label: 'Security' }
            ]
        }
    },
    rent: {
        types: {
            label: 'Property Type',
            taxonomy: 'types',
            items: [
                { value: 'cottage', label: 'Cottage' },
                { value: 'duplex', label: 'Duplex' },
                { value: 'flat', label: 'Flat' },
                { value: 'garage', label: 'Garage' },
                { value: 'mews', label: 'Mews' },
                { value: 'triplex', label: 'Triplex' }
            ]
        },
        status: {
            label: 'Property Status',
            taxonomy: 'status',
            items: [
                { value: 'for-rent', label: 'For Rent' }
            ]
        },
        badges: {
            label: 'Badges',
            taxonomy: 'badges',
            items: [
                { value: 'featured', label: 'Featured' },
                { value: 'new', label: 'New' },
                { value: 'popular', label: 'Popular' }
            ]
        },
        tags: {
            label: 'Tags',
            taxonomy: 'tags',
            items: [
                { value: 'apartment', label: 'Apartment' },
                { value: 'bungalow', label: 'Bungalow' },
                { value: 'cottage', label: 'Cottage' },
                { value: 'duplex', label: 'Duplex' },
                { value: 'flat', label: 'Flat' },
                { value: 'house', label: 'House' },
                { value: 'studio', label: 'Studio' },
                { value: 'townhouse', label: 'Townhouse' }
            ]
        },
        locations: {
            label: 'Property Locations',
            taxonomy: 'locations',
            items: [
                { value: 'berlin', label: 'Berlin' },
                { value: 'boston', label: 'Boston' },
                { value: 'chicago', label: 'Chicago' },
                { value: 'dubai', label: 'Dubai' },
                { value: 'hong-kong', label: 'Hong Kong' },
                { value: 'london', label: 'London' },
                { value: 'los-angeles', label: 'Los Angeles' },
                { value: 'miami', label: 'Miami' },
                { value: 'new-york', label: 'New York' },
                { value: 'paris', label: 'Paris' },
                { value: 'san-francisco', label: 'San Francisco' },
                { value: 'seattle', label: 'Seattle' },
                { value: 'singapore', label: 'Singapore' },
                { value: 'sydney', label: 'Sydney' },
                { value: 'tokyo', label: 'Tokyo' },
                { value: 'toronto', label: 'Toronto' },
                { value: 'vancouver', label: 'Vancouver' }
            ]
        },
        features: {
            label: 'Features',
            taxonomy: 'features',
            items: [
                { value: 'studio', label: 'Studio' },
                { value: 'premium', label: 'Premium' },
                { value: 'privacy', label: 'Privacy' },
                { value: 'rooftop-terrace', label: 'Rooftop Terrace' },
                { value: 'hardwood-floors', label: 'Hardwood Floors' },
                { value: 'central-air', label: 'Central Air' },
                { value: 'fireplace', label: 'Fireplace' },
                { value: 'pool', label: 'Pool' },
                { value: 'gym', label: 'Gym' },
                { value: 'parking', label: 'Parking' },
                { value: 'elevator', label: 'Elevator' },
                { value: 'balcony', label: 'Balcony' },
                { value: 'garden', label: 'Garden' },
                { value: 'security', label: 'Security' }
            ]
        }
    },
    commercial: {
        types: {
            label: 'Property Type',
            taxonomy: 'types',
            items: [
                { value: 'land', label: 'Land' },
                { value: 'garage', label: 'Garage' }
            ]
        },
        status: {
            label: 'Property Status',
            taxonomy: 'status',
            items: [
                { value: 'for-sale', label: 'For Sale' },
                { value: 'for-rent', label: 'For Rent' },
                { value: 'pending', label: 'Pending' },
                { value: 'sold', label: 'Sold' },
                { value: 'under-offer', label: 'Under Offer' },
                { value: 'exchanged', label: 'Exchanged' }
            ]
        },
        badges: {
            label: 'Badges',
            taxonomy: 'badges',
            items: [
                { value: 'featured', label: 'Featured' },
                { value: 'new', label: 'New' },
                { value: 'popular', label: 'Popular' }
            ]
        },
        tags: {
            label: 'Tags',
            taxonomy: 'tags',
            items: [
                { value: 'commercial', label: 'Commercial' },
                { value: 'land', label: 'Land' },
                { value: 'office', label: 'Office' },
                { value: 'retail', label: 'Retail' },
                { value: 'warehouse', label: 'Warehouse' }
            ]
        },
        locations: {
            label: 'Property Locations',
            taxonomy: 'locations',
            items: [
                { value: 'abu-dhabi', label: 'Abu Dhabi' },
                { value: 'berlin', label: 'Berlin' },
                { value: 'boston', label: 'Boston' },
                { value: 'chicago', label: 'Chicago' },
                { value: 'dallas', label: 'Dallas' },
                { value: 'dubai', label: 'Dubai' },
                { value: 'hong-kong', label: 'Hong Kong' },
                { value: 'london', label: 'London' },
                { value: 'los-angeles', label: 'Los Angeles' },
                { value: 'miami', label: 'Miami' },
                { value: 'new-york', label: 'New York' },
                { value: 'paris', label: 'Paris' },
                { value: 'san-francisco', label: 'San Francisco' },
                { value: 'seattle', label: 'Seattle' },
                { value: 'singapore', label: 'Singapore' },
                { value: 'sydney', label: 'Sydney' },
                { value: 'tokyo', label: 'Tokyo' },
                { value: 'toronto', label: 'Toronto' },
                { value: 'vancouver', label: 'Vancouver' }
            ]
        },
        features: {
            label: 'Features',
            taxonomy: 'features',
            items: [
                { value: 'premium', label: 'Premium' },
                { value: 'privacy', label: 'Privacy' },
                { value: 'parking', label: 'Parking' },
                { value: 'elevator', label: 'Elevator' },
                { value: 'security', label: 'Security' }
            ]
        }
    },
    let: {
        types: {
            label: 'Property Type',
            taxonomy: 'types',
            items: [
                { value: 'flat', label: 'Flat' },
                { value: 'garage', label: 'Garage' },
                { value: 'mews', label: 'Mews' }
            ]
        },
        status: {
            label: 'Property Status',
            taxonomy: 'status',
            items: [
                { value: 'for-rent', label: 'For Rent' }
            ]
        },
        badges: {
            label: 'Badges',
            taxonomy: 'badges',
            items: [
                { value: 'featured', label: 'Featured' },
                { value: 'new', label: 'New' },
                { value: 'popular', label: 'Popular' }
            ]
        },
        tags: {
            label: 'Tags',
            taxonomy: 'tags',
            items: [
                { value: 'apartment', label: 'Apartment' },
                { value: 'flat', label: 'Flat' },
                { value: 'house', label: 'House' },
                { value: 'studio', label: 'Studio' },
                { value: 'townhouse', label: 'Townhouse' }
            ]
        },
        locations: {
            label: 'Property Locations',
            taxonomy: 'locations',
            items: [
                { value: 'london', label: 'London' },
                { value: 'paris', label: 'Paris' },
                { value: 'new-york', label: 'New York' },
                { value: 'hong-kong', label: 'Hong Kong' },
                { value: 'singapore', label: 'Singapore' }
            ]
        },
        features: {
            label: 'Features',
            taxonomy: 'features',
            items: [
                { value: 'studio', label: 'Studio' },
                { value: 'premium', label: 'Premium' },
                { value: 'privacy', label: 'Privacy' },
                { value: 'hardwood-floors', label: 'Hardwood Floors' },
                { value: 'central-air', label: 'Central Air' },
                { value: 'fireplace', label: 'Fireplace' },
                { value: 'parking', label: 'Parking' },
                { value: 'balcony', label: 'Balcony' },
                { value: 'garden', label: 'Garden' },
                { value: 'security', label: 'Security' }
            ]
        }
    }
};

// Step content definitions - Step 2 & 3 with READ-ONLY fields
const stepContents = {
    1: `
        <h2 class="hvnly--property--import-card-title">Select Department & Taxonomies</h2>
        <p class="hvnly--property--import-card-description">Choose a department first, then select taxonomies for your properties. Each department maintains its own selection.</p>
        
        <div class="hvnly--property--import-divider"></div>
        
        <div class="hvnly--property--import-department-tabs">
            <div class="hvnly--property--import-department-tab ${selectedDepartment === 'sale' ? 'active' : ''}" data-department="sale">
                <i class="fas fa-tag"></i>
                Sale
            </div>
            <div class="hvnly--property--import-department-tab ${selectedDepartment === 'rent' ? 'active' : ''}" data-department="rent">
                <i class="fas fa-key"></i>
                Rent
            </div>
            <div class="hvnly--property--import-department-tab ${selectedDepartment === 'commercial' ? 'active' : ''}" data-department="commercial">
                <i class="fas fa-building"></i>
                Commercial
            </div>
            <div class="hvnly--property--import-department-tab ${selectedDepartment === 'let' ? 'active' : ''}" data-department="let">
                <i class="fas fa-hand-holding-usd"></i>
                Let
            </div>
        </div>
        
        <div class="hvnly--property--import-taxonomy-container" id="taxonomyContainer">
            ${generateTaxonomyHTML(selectedDepartment)}
        </div>
        
        <div class="hvnly--property--import-info-box">
            <div class="hvnly--property--import-info-icon">
                <i class="fas fa-info-circle"></i>
            </div>
            <div class="hvnly--property--import-info-text">
                Select a department first, then choose taxonomies. Each department has its own independent selections.
            </div>
        </div>
    `,
    
    // Step 2: Location & Address - READ-ONLY with professional styling
    2: `
        <h2 class="hvnly--property--import-card-title">Configure Location & Address</h2>
        <p class="hvnly--property--import-card-description">Demo location data will be used for all imported properties. Fields are read-only.</p>
        
        <div class="hvnly--property--import-divider"></div>
        
        <div class="hvnly--property--import-form-row">
            <div class="hvnly--property--import-form-label">Reference Number</div>
            <div class="hvnly--property--import-form-controls">
                <input type="text" class="hvnly--property--import-text-input hvnly-readonly-field" id="reference-number" placeholder="REF-2024-001" value="REF-2024-001" readonly>
            </div>
        </div>
        
        <div class="hvnly--property--import-form-row">
            <div class="hvnly--property--import-form-label">Building Number</div>
            <div class="hvnly--property--import-form-controls">
                <input type="text" class="hvnly--property--import-text-input hvnly-readonly-field" id="building-number" placeholder="123" value="123" readonly>
            </div>
        </div>
        
        <div class="hvnly--property--import-form-row">
            <div class="hvnly--property--import-form-label">Street</div>
            <div class="hvnly--property--import-form-controls">
                <input type="text" class="hvnly--property--import-text-input hvnly-readonly-field" id="street" placeholder="Main Street" value="Main Street" readonly>
            </div>
        </div>
        
        <div class="hvnly--property--import-form-row">
            <div class="hvnly--property--import-form-label">Address Line 1</div>
            <div class="hvnly--property--import-form-controls">
                <input type="text" class="hvnly--property--import-text-input hvnly-readonly-field" id="address-line-1" placeholder="123 Main Street" value="123 Main Street" readonly>
            </div>
        </div>
        
        <div class="hvnly--property--import-form-row">
            <div class="hvnly--property--import-form-label">Address Line 2</div>
            <div class="hvnly--property--import-form-controls">
                <input type="text" class="hvnly--property--import-text-input hvnly-readonly-field" id="address-line-2" placeholder="Apt 4B" value="Apt 4B" readonly>
            </div>
        </div>
        
        <div class="hvnly--property--import-form-row">
            <div class="hvnly--property--import-form-label">Town/City</div>
            <div class="hvnly--property--import-form-controls">
                <input type="text" class="hvnly--property--import-text-input hvnly-readonly-field" id="town-city" placeholder="Austin" value="Austin" readonly>
            </div>
        </div>
        
        <div class="hvnly--property--import-form-row">
            <div class="hvnly--property--import-form-label">Country/State</div>
            <div class="hvnly--property--import-form-controls">
                <input type="text" class="hvnly--property--import-text-input hvnly-readonly-field" id="country-state" placeholder="TX" value="TX" readonly>
            </div>
        </div>
        
        <div class="hvnly--property--import-form-row">
            <div class="hvnly--property--import-form-label">Zip Code</div>
            <div class="hvnly--property--import-form-controls">
                <input type="text" class="hvnly--property--import-text-input hvnly-readonly-field" id="zip-code" placeholder="78701" value="78701" readonly>
            </div>
        </div>
        
        <div class="hvnly--property--import-info-box hvnly-info-box-readonly">
            <div class="hvnly--property--import-info-icon">
                <i class="fas fa-lock"></i>
            </div>
            <div class="hvnly--property--import-info-text">
                <strong>Demo Data Only:</strong> These address values are from demo data and will be used for imported properties.
            </div>
        </div>
    `,
    
    // Step 3: Media - READ-ONLY with professional styling
    3: `
        <h2 class="hvnly--property--import-card-title">Property Media</h2>
        <p class="hvnly--property--import-card-description">Demo media data will be used for all imported properties. Fields are read-only.</p>
        
        <div class="hvnly--property--import-divider"></div>
        
        <div class="hvnly--property--import-form-row">
            <div class="hvnly--property--import-form-label">YouTube Video</div>
            <div class="hvnly--property--import-form-controls">
                <div style="margin-bottom: 10px;">
                    <input type="text" class="hvnly--property--import-text-input hvnly-readonly-field" id="youtube-title" placeholder="Video Title" value="Property Tour" readonly>
                </div>
                <div style="margin-bottom: 10px;">
                    <input type="url" class="hvnly--property--import-text-input hvnly-readonly-field" id="youtube-url" placeholder="YouTube URL" value="https://youtube.com/watch?v=dQw4w9WgXcQ" readonly>
                </div>
                <div>
                    <input type="url" class="hvnly--property--import-text-input hvnly-readonly-field" id="youtube-thumbnail" placeholder="Thumbnail URL" value="https://img.youtube.com/vi/dQw4w9WgXcQ/maxresdefault.jpg" readonly>
                </div>
            </div>
        </div>
        
        <div class="hvnly--property--import-form-row">
            <div class="hvnly--property--import-form-label">Gallery</div>
            <div class="hvnly--property--import-form-controls">
                <div style="margin-bottom: 10px;">
                    <input type="text" class="hvnly--property--import-text-input hvnly-readonly-field" id="gallery-title" placeholder="Gallery Title" value="Property Gallery" readonly>
                </div>
                <div class="hvnly--property--import-info-text" style="margin-top: 5px;">
                    <i class="fas fa-images"></i> 3 demo images will be automatically added to each property
                </div>
            </div>
        </div>
        
        <div class="hvnly--property--import-form-row">
            <div class="hvnly--property--import-form-label">Map Location</div>
            <div class="hvnly--property--import-form-controls" style="position: relative;">
                <div style="margin-bottom: 10px;">
                    <input type="text" class="hvnly--property--import-text-input hvnly-readonly-field" id="map-address" placeholder="Type address for suggestions" value="Austin, TX" autocomplete="off" readonly>
                </div>
                <div style="display:flex; gap:10px; margin-bottom:10px;">
                    <input type="text" class="hvnly--property--import-text-input hvnly-readonly-field" id="map-latitude" placeholder="Latitude" value="30.2672" style="width:50%;" readonly>
                    <input type="text" class="hvnly--property--import-text-input hvnly-readonly-field" id="map-longitude" placeholder="Longitude" value="-97.7431" style="width:50%;" readonly>
                </div>
                <div id="map-preview" style="height:200px; background:#f0f0f0; border-radius:4px; margin-top:10px; position:relative;">
                    <div style="position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); text-align:center; color:#666;">
                        <i class="fas fa-map-marked-alt" style="font-size:40px; margin-bottom:10px; display:block;"></i>
                        <span>Map preview would appear here</span><br>
                        <small>Address: <span id="preview-address">Austin, TX</span></small>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="hvnly--property--import-info-box hvnly-info-box-readonly">
            <div class="hvnly--property--import-info-icon">
                <i class="fas fa-lock"></i>
            </div>
            <div class="hvnly--property--import-info-text">
                <strong>Demo Data Only:</strong> YouTube video, gallery title, and map coordinates are from demo data.
            </div>
        </div>
    `,
    
    4: `
        <h2 class="hvnly--property--import-card-title">Set Import Preferences</h2>
        <p class="hvnly--property--import-card-description">Configure your import preferences and property details.</p>
        
        <div class="hvnly--property--import-divider"></div>
        
        <div class="hvnly--property--import-form-row">
            <div class="hvnly--property--import-form-label">Properties to Import</div>
            <div class="hvnly--property--import-form-controls">
                <div class="hvnly--property--import-quantity-slider-container">
                    <div class="hvnly--property--import-slider-wrapper">
                        <input type="range" min="10" max="200" value="${propertyImportQuantity}" 
                               class="hvnly--property--import-quantity-slider" 
                               id="propertyQuantitySlider">
                        <div class="hvnly--property--import-quantity-value" id="quantityValue">${propertyImportQuantity}</div>
                    </div>
                    <div class="hvnly--property--import-slider-ticks">
                        <div class="hvnly--property--import-slider-tick"><span class="hvnly--property--import-slider-tick-label">10</span></div>
                        <div class="hvnly--property--import-slider-tick"></div>
                        <div class="hvnly--property--import-slider-tick"></div>
                        <div class="hvnly--property--import-slider-tick"></div>
                        <div class="hvnly--property--import-slider-tick"><span class="hvnly--property--import-slider-tick-label">50</span></div>
                        <div class="hvnly--property--import-slider-tick"></div>
                        <div class="hvnly--property--import-slider-tick"></div>
                        <div class="hvnly--property--import-slider-tick"></div>
                        <div class="hvnly--property--import-slider-tick"><span class="hvnly--property--import-slider-tick-label">100</span></div>
                        <div class="hvnly--property--import-slider-tick"></div>
                        <div class="hvnly--property--import-slider-tick"></div>
                        <div class="hvnly--property--import-slider-tick"></div>
                        <div class="hvnly--property--import-slider-tick"><span class="hvnly--property--import-slider-tick-label">150</span></div>
                        <div class="hvnly--property--import-slider-tick"></div>
                        <div class="hvnly--property--import-slider-tick"></div>
                        <div class="hvnly--property--import-slider-tick"></div>
                        <div class="hvnly--property--import-slider-tick"><span class="hvnly--property--import-slider-tick-label">200</span></div>
                    </div>
                    <div class="hvnly--property--import-quantity-description">
                        <i class="fas fa-info-circle" style="margin-right: 8px; color: var(--hvnly-brand-primary);"></i>
                        Set how many properties you want to import. Default is 10. You can import up to 200 properties at once.
                    </div>
                </div>
            </div>
        </div>
        
        <div class="hvnly--property--import-form-row">
            <div class="hvnly--property--import-form-label">Include Images</div>
            <div class="hvnly--property--import-form-controls">
                <label class="hvnly--property--import-toggle-switch" style="margin-right:15px;">
                    <input type="checkbox" id="include-images" checked>
                    <span class="hvnly--property--import-toggle-slider"></span>
                </label>
                <span style="font-size: 14px; color: var(--hvnly-text-secondary);">Include property images (3 per property)</span>
            </div>
        </div>
        
        <div class="hvnly--property--import-form-row">
            <div class="hvnly--property--import-form-label">Email Notifications</div>
            <div class="hvnly--property--import-form-controls">
                <label class="hvnly--property--import-toggle-switch" style="margin-right:15px;">
                    <input type="checkbox" id="email-notifications" checked>
                    <span class="hvnly--property--import-toggle-slider"></span>
                </label>
                <span style="font-size: 14px; color: var(--hvnly-text-secondary);">Receive email updates about import status</span>
            </div>
        </div>
        
        <div class="hvnly--property--import-info-box">
            <div class="hvnly--property--import-info-icon">
                <i class="fas fa-info-circle"></i>
            </div>
            <div class="hvnly--property--import-info-text">
                Click Complete to start importing your properties with all the selected options.
            </div>
        </div>
    `
};

// Helper function to generate taxonomy HTML for a department with saved selections
function generateTaxonomyHTML(department) {
    const deptData = departmentTaxonomies[department];
    if (!deptData) return '';
    
    let html = '';
    html += `<input type="hidden" id="selected-department" value="${department}">`;
    
    for (const [key, taxonomy] of Object.entries(deptData)) {
        const savedSelections = departmentSelections[department][key] || [];
        
        html += `
            <div class="hvnly--property--import-taxonomy-section">
                <h3 class="hvnly--property--import-taxonomy-title">${escapeHtml(taxonomy.label)}</h3>
                <div class="hvnly--property--import-checkbox-group" data-taxonomy="${escapeHtml(taxonomy.taxonomy)}" data-department="${escapeHtml(department)}">
        `;
        
        taxonomy.items.forEach(item => {
            const isSelected = savedSelections.includes(item.value);
            html += `
                <div class="hvnly--property--import-checkbox-item ${isSelected ? 'selected' : ''}" data-value="${escapeHtml(item.value)}" data-taxonomy="${escapeHtml(key)}">
                    <div class="hvnly--property--import-checkbox"></div>
                    <div class="hvnly--property--import-checkbox-label">${escapeHtml(item.label)}</div>
                </div>
            `;
        });
        
        html += `
                </div>
            </div>
        `;
        
        if (key !== Object.keys(deptData).pop()) {
            html += `<div class="hvnly--property--import-taxonomy-divider"></div>`;
        }
    }
    
    return html;
}

// Escape HTML to prevent XSS
function escapeHtml(unsafe) {
    if (!unsafe) return '';
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

// Save current department selections
function saveCurrentSelections() {
    const currentDept = selectedDepartment;
    
    departmentSelections[currentDept] = {
        types: [],
        status: [],
        badges: [],
        tags: [],
        locations: [],
        features: []
    };
    
    const checkboxGroups = document.querySelectorAll('.hvnly--property--import-checkbox-group');
    
    checkboxGroups.forEach(group => {
        const taxonomy = group.getAttribute('data-taxonomy');
        if (!taxonomy) return;
        
        const selectedItems = group.querySelectorAll('.hvnly--property--import-checkbox-item.selected');
        const values = Array.from(selectedItems).map(item => item.getAttribute('data-value'));
        
        if (departmentSelections[currentDept].hasOwnProperty(taxonomy)) {
            departmentSelections[currentDept][taxonomy] = values;
        }
    });
}

// Setup checkbox selection with automatic saving
function setupCheckboxSelection() {
    const checkboxItems = document.querySelectorAll('.hvnly--property--import-checkbox-item');
    checkboxItems.forEach(item => {
        item.removeEventListener('click', handleCheckboxClick);
        item.addEventListener('click', handleCheckboxClick);
    });
    
    // Add select all checkboxes
    addSelectAllCheckboxes();
}

// Handle checkbox click
function handleCheckboxClick(e) {
    e.preventDefault();
    e.stopPropagation();
    
    this.classList.toggle('selected');
    
    const group = this.closest('.hvnly--property--import-checkbox-group');
    if (group) {
        const taxonomy = group.getAttribute('data-taxonomy');
        const department = group.getAttribute('data-department') || selectedDepartment;
        
        if (taxonomy && departmentSelections[department]) {
            const selectedItems = group.querySelectorAll('.hvnly--property--import-checkbox-item.selected');
            const values = Array.from(selectedItems).map(item => item.getAttribute('data-value'));
            
            if (departmentSelections[department].hasOwnProperty(taxonomy)) {
                departmentSelections[department][taxonomy] = values;
            }
        }
    }
    
    // Update select all state
    updateSelectAllState(this);
}

// Add "Select all" checkbox functionality with proper saving
function addSelectAllCheckboxes() {
    const taxonomySections = document.querySelectorAll('.hvnly--property--import-taxonomy-section');
    
    taxonomySections.forEach(section => {
        const title = section.querySelector('.hvnly--property--import-taxonomy-title');
        const checkboxGroup = section.querySelector('.hvnly--property--import-checkbox-group');
        
        if (!title || !checkboxGroup) return;
        
        // Check if select all already exists
        if (section.querySelector('.hvnly--property--import-select-all')) return;
        
        // Get taxonomy info
        const taxonomy = checkboxGroup.getAttribute('data-taxonomy');
        const department = checkboxGroup.getAttribute('data-department') || selectedDepartment;
        
        // Create select all container
        const selectAllDiv = document.createElement('div');
        selectAllDiv.className = 'hvnly--property--import-select-all';
        selectAllDiv.innerHTML = `
            <div class="hvnly--property--import-select-all-item" data-select-all="true" data-taxonomy="${taxonomy}" data-department="${department}">
                <div class="hvnly--property--import-checkbox"></div>
                <div class="hvnly--property--import-checkbox-label">Select All</div>
                <span class="hvnly--property--import-select-all-count" style="margin-left: auto; font-size: 12px; color: #666;">0/${checkboxGroup.querySelectorAll('.hvnly--property--import-checkbox-item').length}</span>
            </div>
        `;
        
        // Insert after title
        title.insertAdjacentElement('afterend', selectAllDiv);
        
        // Get checkboxes and update count
        const checkboxes = checkboxGroup.querySelectorAll('.hvnly--property--import-checkbox-item');
        const selectedCheckboxes = checkboxGroup.querySelectorAll('.hvnly--property--import-checkbox-item.selected');
        const selectAllItem = selectAllDiv.querySelector('.hvnly--property--import-select-all-item');
        const countSpan = selectAllDiv.querySelector('.hvnly--property--import-select-all-count');
        
        // Update count
        if (countSpan) {
            countSpan.textContent = `${selectedCheckboxes.length}/${checkboxes.length}`;
        }
        
        // Check if all checkboxes are selected to set initial select all state
        if (checkboxes.length === selectedCheckboxes.length && checkboxes.length > 0) {
            selectAllItem.classList.add('selected');
        }
        
        // Add click handler to select all
        if (selectAllItem) {
            selectAllItem.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                const isSelected = this.classList.contains('selected');
                const checkboxes = checkboxGroup.querySelectorAll('.hvnly--property--import-checkbox-item');
                const countSpan = this.querySelector('.hvnly--property--import-select-all-count');
                
                // Toggle all checkboxes
                checkboxes.forEach(checkbox => {
                    if (isSelected) {
                        checkbox.classList.remove('selected');
                    } else {
                        checkbox.classList.add('selected');
                    }
                });
                
                // Toggle select all
                this.classList.toggle('selected');
                
                // Update count
                const newSelectedCount = isSelected ? 0 : checkboxes.length;
                if (countSpan) {
                    countSpan.textContent = `${newSelectedCount}/${checkboxes.length}`;
                }
                
                // Save selections to departmentSelections
                const taxonomy = checkboxGroup.getAttribute('data-taxonomy');
                const department = checkboxGroup.getAttribute('data-department') || selectedDepartment;
                
                if (taxonomy && departmentSelections[department]) {
                    const selectedItems = checkboxGroup.querySelectorAll('.hvnly--property--import-checkbox-item.selected');
                    const values = Array.from(selectedItems).map(item => item.getAttribute('data-value'));
                    
                    // Map taxonomy string to the correct key in departmentSelections
                    let taxonomyKey = taxonomy;
                    if (taxonomy === 'types') taxonomyKey = 'types';
                    else if (taxonomy === 'status') taxonomyKey = 'status';
                    else if (taxonomy === 'badges') taxonomyKey = 'badges';
                    else if (taxonomy === 'tags') taxonomyKey = 'tags';
                    else if (taxonomy === 'locations') taxonomyKey = 'locations';
                    else if (taxonomy === 'features') taxonomyKey = 'features';
                    
                    if (departmentSelections[department].hasOwnProperty(taxonomyKey)) {
                        departmentSelections[department][taxonomyKey] = values;
                    }
                }
            });
        }
    });
}

// Update the updateSelectAllState function to also update the count
function updateSelectAllState(clickedItem) {
    const section = clickedItem.closest('.hvnly--property--import-taxonomy-section');
    if (!section) return;
    
    const selectAllItem = section.querySelector('.hvnly--property--import-select-all-item');
    const checkboxGroup = section.querySelector('.hvnly--property--import-checkbox-group');
    const countSpan = selectAllItem?.querySelector('.hvnly--property--import-select-all-count');
    
    if (!selectAllItem || !checkboxGroup) return;
    
    const checkboxes = checkboxGroup.querySelectorAll('.hvnly--property--import-checkbox-item');
    const selectedCheckboxes = checkboxGroup.querySelectorAll('.hvnly--property--import-checkbox-item.selected');
    
    // Update count
    if (countSpan) {
        countSpan.textContent = `${selectedCheckboxes.length}/${checkboxes.length}`;
    }
    
    if (checkboxes.length === selectedCheckboxes.length && checkboxes.length > 0) {
        selectAllItem.classList.add('selected');
    } else {
        selectAllItem.classList.remove('selected');
    }
    
    // Also save to departmentSelections when individual checkbox is clicked
    const taxonomy = checkboxGroup.getAttribute('data-taxonomy');
    const department = checkboxGroup.getAttribute('data-department') || selectedDepartment;
    
    if (taxonomy && departmentSelections[department]) {
        const values = Array.from(selectedCheckboxes).map(item => item.getAttribute('data-value'));
        
        let taxonomyKey = taxonomy;
        if (taxonomy === 'types') taxonomyKey = 'types';
        else if (taxonomy === 'status') taxonomyKey = 'status';
        else if (taxonomy === 'badges') taxonomyKey = 'badges';
        else if (taxonomy === 'tags') taxonomyKey = 'tags';
        else if (taxonomy === 'locations') taxonomyKey = 'locations';
        else if (taxonomy === 'features') taxonomyKey = 'features';
        
        if (departmentSelections[department].hasOwnProperty(taxonomyKey)) {
            departmentSelections[department][taxonomyKey] = values;
        }
    }
}

// ========== BUILDER RESET FUNCTION ==========
// Reset and save both builders before import
async function resetAndSaveBuildersBeforeImport() {
    const updateProgressMessage = (message) => {
        const importMessage = document.getElementById('importMessage');
        if (importMessage) {
            importMessage.textContent = message;
        }
    };
    
    const REST_URL = hvnlyImportWizard.resturl;
    const REST_NONCE = hvnlyImportWizard.rest_nonce;
    
    if (!REST_URL || !REST_NONCE) {
        return true;
    }
    
    try {
        updateProgressMessage('Resetting Add Property Form builder...');
        const resetFormResponse = await fetch(`${REST_URL}/pb-dnd-sections`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce': REST_NONCE
            },
            credentials: 'same-origin'
        });
        
        updateProgressMessage('Resetting Property Card Layout builder...');
        const resetCardResponse = await fetch(`${REST_URL}/pb-card-builder`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce': REST_NONCE
            },
            credentials: 'same-origin'
        });
        
        updateProgressMessage('Loading default Add Property Form sections...');
        const getFormResponse = await fetch(`${REST_URL}/pb-dnd-sections`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce': REST_NONCE
            },
            credentials: 'same-origin'
        });
        
        let defaultFormSections = [];
        if (getFormResponse.ok) {
            const formData = await getFormResponse.json();
            if (formData.success && formData.data && formData.data.length > 0) {
                defaultFormSections = formData.data;
            }
        }
        
        updateProgressMessage('Loading default Property Card Layout sections...');
        const getCardResponse = await fetch(`${REST_URL}/pb-card-builder`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce': REST_NONCE
            },
            credentials: 'same-origin'
        });
        
        let defaultCardSections = [];
        if (getCardResponse.ok) {
            const cardData = await getCardResponse.json();
            if (cardData.success && cardData.data && cardData.data.length > 0) {
                defaultCardSections = cardData.data;
            }
        }
        
        if (defaultFormSections.length > 0) {
            updateProgressMessage('Saving Add Property Form configuration...');
            await fetch(`${REST_URL}/pb-dnd-sections`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': REST_NONCE
                },
                credentials: 'same-origin',
                body: JSON.stringify({
                    tabs: defaultFormSections
                })
            });
        }
        
        if (defaultCardSections.length > 0) {
            updateProgressMessage('Saving Property Card Layout configuration...');
            await fetch(`${REST_URL}/pb-card-builder`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': REST_NONCE
                },
                credentials: 'same-origin',
                body: JSON.stringify({
                    sections: defaultCardSections
                })
            });
        }
        
        updateProgressMessage('Builders reset and saved successfully!');
        await new Promise(resolve => setTimeout(resolve, 500));
        
        return true;
        
    } catch (error) {
        return true;
    }
}
// =========================================
// IMPORT CANCELLATION & ERROR HANDLING
// =========================================

// Create cancellation button HTML
function createCancelButton() {
    return `
        <div class="hvnly--property--import-cancel-container" style="margin-top: var(--hvnly-space-lg); text-align: center;">
            <button class="hvnly--property--import-cancel-button" id="cancelImportBtn">
                <i class="fas fa-stop-circle"></i>
                <span>${hvnlyImportWizard.strings.cancel}</span>
            </button>
            <button class="hvnly--property--import-pause-button" id="pauseImportBtn" style="margin-left: var(--hvnly-space-md);">
                <i class="fas fa-pause-circle"></i>
                <span>${hvnlyImportWizard.strings.pause}</span>
            </button>
        </div>
    `;
}

// Create error popup HTML
function createErrorPopup(errorMessage, errorDetails = null) {
    const errorId = 'import-error-' + Date.now();
    const errorHTML = `
        <div class="hvnly--property--import-error-popup" id="${errorId}">
            <div style="display: flex; align-items: center; gap: var(--hvnly-space-md); margin-bottom: var(--hvnly-space-lg);">
                <div style="width: 48px; height: 48px; border-radius: 50%; background: var(--hvnly-brand-error); display: flex; align-items: center; justify-content: center; color: var(--hvnly-color-white); font-size: 24px;">
                    <i class="fas fa-exclamation-triangle"></i>
                </div>
                <h3 style="font-size: var(--hvnly-font-size-xl); font-weight: var(--hvnly-font-weight-bold); color: var(--hvnly-text-primary); margin: 0;">Import Error</h3>
            </div>
            
            <p style="font-size: var(--hvnly-font-size-lg); color: var(--hvnly-text-primary); margin-bottom: var(--hvnly-space-md);">
                ${escapeHtml(errorMessage)}
            </p>
            
            ${errorDetails ? `
                <div style="background: rgba(255, 77, 79, 0.05); border: 1px solid rgba(255, 77, 79, 0.2); border-radius: var(--hvnly-border-radius-sm); padding: var(--hvnly-space-md); margin-bottom: var(--hvnly-space-lg);">
                    <p style="font-size: var(--hvnly-font-size-sm); color: var(--hvnly-text-secondary); margin-bottom: var(--hvnly-space-sm);">
                        <strong>Debug Information:</strong>
                    </p>
                    <pre style="font-size: var(--hvnly-font-size-xs); color: var(--hvnly-brand-error); white-space: pre-wrap; word-wrap: break-word; margin: 0;">${escapeHtml(errorDetails)}</pre>
                </div>
            ` : ''}
            
            <div style="display: flex; gap: var(--hvnly-space-md); justify-content: flex-end;">
                <button class="hvnly--property--import-completion-button secondary" id="closeErrorBtn" style="border-color: var(--hvnly-text-secondary); color: var(--hvnly-text-secondary);">
                    <i class="fas fa-times"></i>
                    Close
                </button>
            </div>
        </div>
        <div class="hvnly--property--import-error-overlay" onclick="document.getElementById('${errorId}')?.remove(); this.remove();"></div>
    `;
    
    return errorHTML;
}

// Show error popup
function showErrorPopup(message, errorDetails = null) {
    document.querySelectorAll('.hvnly--property--import-error-popup, .hvnly--property--import-error-overlay').forEach(el => el.remove());
    
    const errorHTML = createErrorPopup(message, errorDetails);
    document.body.insertAdjacentHTML('beforeend', errorHTML);
    
    const closeBtn = document.getElementById('closeErrorBtn');
    if (closeBtn) {
        closeBtn.addEventListener('click', function() {
            document.querySelectorAll('.hvnly--property--import-error-popup, .hvnly--property--import-error-overlay').forEach(el => el.remove());
            isImporting = false;
            importCancelled = false;
            currentStep = 4;
            updateStepProgress();
            updateStepContent();
            const navigation = document.querySelector('.hvnly--property--import-navigation');
            if (navigation) navigation.style.display = 'flex';
        });
    }
}

// Handle import error
function handleImportError(errorMsg, errorDetails, importData, csrfToken) {
    isImporting = false;
    showErrorPopup(errorMsg, errorDetails);
}

// Handle import cancellation
function handleImportCancellation() {
    isImporting = false;
    importCancelled = true;
    
    const contentCard = document.querySelector('.hvnly--property--import-content-card');
    
    const cancelledHTML = `
        <div class="hvnly--property--import-completion-screen">
            <div class="hvnly--property--import-completion-icon" style="background: var(--hvnly-brand-warning);">
                <i class="fas fa-stop-circle"></i>
            </div>
            <h2 class="hvnly--property--import-completion-title">Import Cancelled</h2>
            <p class="hvnly--property--import-completion-description">
                The import was cancelled at <strong>${currentImported} of ${currentImportData?.total_to_import || 0} properties</strong>.
                <br><br>
                Already imported properties have been saved successfully.
            </p>
            <div class="hvnly--property--import-completion-actions">
                <a href="edit.php?post_type=hvnly_property" class="hvnly--property--import-completion-button primary">
                    <i class="fas fa-eye"></i>
                    View Imported Properties
                </a>
                <button class="hvnly--property--import-completion-button secondary" id="resumeImportBtn">
                    <i class="fas fa-play"></i>
                    Resume Import
                </button>
                <button class="hvnly--property--import-completion-button secondary" id="restartImportBtn" style="border-color: var(--hvnly-brand-primary);">
                    <i class="fas fa-redo-alt"></i>
                    Start Over
                </button>
            </div>
        </div>
    `;
    
    contentCard.innerHTML = cancelledHTML;
    
    document.getElementById('resumeImportBtn')?.addEventListener('click', function() {
        importCancelled = false;
        importPaused = false;
        window.importBatch(currentBatch, currentImported, currentImportData, currentCsrfToken);
    });
    
    document.getElementById('restartImportBtn')?.addEventListener('click', function() {
        importCancelled = false;
        importPaused = false;
        buildersReset = false;
        currentStep = 1;
        updateStepProgress();
        updateStepContent();
        const navigation = document.querySelector('.hvnly--property--import-navigation');
        if (navigation) navigation.style.display = 'flex';
    });
    
    const navigation = document.querySelector('.hvnly--property--import-navigation');
    if (navigation) navigation.style.display = 'none';
}

// Add cancellation buttons to progress screen
function addCancellationButtons() {
    const progressContainer = document.querySelector('.hvnly--property--import-progress-container');
    if (progressContainer && !document.getElementById('cancelImportBtn')) {
        progressContainer.insertAdjacentHTML('afterend', createCancelButton());
        
        document.getElementById('cancelImportBtn')?.addEventListener('click', function() {
            if (confirm(hvnlyImportWizard.strings.cancelConfirm)) {
                importCancelled = true;
                importPaused = false;
                const btn = this;
                btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> ' + hvnlyImportWizard.strings.cancelling;
                btn.disabled = true;
                
                jQuery.ajax({
                    url: hvnlyImportWizard.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'hvnly_cancel_import',
                        nonce: hvnlyImportWizard.nonce,
                        csrf_token: currentCsrfToken
                    },
                    complete: function() {
                        handleImportCancellation();
                    }
                });
            }
        });
        
        document.getElementById('pauseImportBtn')?.addEventListener('click', function() {
            if (importPaused) {
                importPaused = false;
                this.innerHTML = '<i class="fas fa-pause-circle"></i> <span>' + hvnlyImportWizard.strings.pause + '</span>';
                this.style.background = 'var(--hvnly-brand-warning)';
                
                const importMessage = document.getElementById('importMessage');
                if (importMessage) {
                    importMessage.textContent = 'Resuming import...';
                }
                
                if (!importCancelled) {
                    window.importBatch(currentBatch, currentImported, currentImportData, currentCsrfToken);
                }
            } else {
                importPaused = true;
                this.innerHTML = '<i class="fas fa-play-circle"></i> <span>' + hvnlyImportWizard.strings.resume + '</span>';
                this.style.background = 'var(--hvnly-brand-success)';
                
                const importMessage = document.getElementById('importMessage');
                if (importMessage) {
                    importMessage.textContent = hvnlyImportWizard.strings.paused;
                }
            }
        });
    }
}

// Main import batch function
window.importBatch = function(batch, imported, importData, csrfToken) {
    currentBatch = batch;
    currentImported = imported;
    currentImportData = importData;
    currentCsrfToken = csrfToken;
    
    if (importCancelled) {
        handleImportCancellation();
        return;
    }
    
    if (importPaused) {
        setTimeout(() => {
            if (!importPaused && !importCancelled) {
                window.importBatch(batch, imported, importData, csrfToken);
            }
        }, 1000);
        return;
    }
    
    jQuery.ajax({
        url: hvnlyImportWizard.ajaxurl,
        type: 'POST',
        data: {
            action: 'hvnly_import_properties',
            nonce: hvnlyImportWizard.nonce,
            csrf_token: csrfToken,
            batch: batch,
            imported: imported,
            total_to_import: importData.total_to_import,
            options: importData,
            skip_builder_reset: buildersReset ? 1 : 0
        },
        success: function(response) {
            if (importCancelled) {
                handleImportCancellation();
                return;
            }
            
            if (response.success) {
                const data = response.data;
                updateProgress(data);
                
                if (data.complete) {
                    setTimeout(() => {
                        showCelebration(data.imported);
                    }, 500);
                } else if (!importCancelled && !importPaused) {
                    window.importBatch(data.next_batch, data.imported, importData, csrfToken);
                }
            } else {
                const errorMsg = response.data || 'An error occurred during import.';
                handleImportError(errorMsg, null, importData, csrfToken);
            }
        },
        error: function(xhr, status, error) {
            if (importCancelled) {
                handleImportCancellation();
                return;
            }
            
            if (status !== 'timeout' && error) {
                const errorMsg = error || 'Connection error';
                const errorDetails = `Status: ${status}\nResponse: ${xhr.responseText || 'No response'}`;
                handleImportError(errorMsg, errorDetails, importData, csrfToken);
            }
        }
    });
};

// Start import process with progress animation
async function startImportProcess() {
    if (currentStep === 1) {
        saveCurrentSelections();
    }
    
    if (propertyImportQuantity > 200) {
        alert('Maximum import limit is 200 properties.');
        return;
    }
    
    isImporting = true;
    importCancelled = false;
    importPaused = false;
    
    const contentCard = document.querySelector('.hvnly--property--import-content-card');
    const navigation = document.querySelector('.hvnly--property--import-navigation');
    
    const quantitySlider = document.getElementById('propertyQuantitySlider');
    if (quantitySlider) {
        propertyImportQuantity = Math.min(parseInt(quantitySlider.value), 200);
    }
    
    const csrfToken = document.getElementById('hvnly_csrf_token')?.value || '';
    
    // Read values from Step 2 & 3 (read-only but still capture them)
    const importData = {
        total_to_import: propertyImportQuantity,
        include_images: document.getElementById('include-images')?.checked || true,
        email_notifications: document.getElementById('email-notifications')?.checked || true,
        
        // Step 2 values (read-only - using demo data)
        reference_number: document.getElementById('reference-number')?.value || 'REF-2024-001',
        building_number: document.getElementById('building-number')?.value || '123',
        street: document.getElementById('street')?.value || 'Main Street',
        address_line_1: document.getElementById('address-line-1')?.value || '123 Main Street',
        address_line_2: document.getElementById('address-line-2')?.value || 'Apt 4B',
        town_city: document.getElementById('town-city')?.value || 'Austin',
        country_state: document.getElementById('country-state')?.value || 'TX',
        zip_code: document.getElementById('zip-code')?.value || '78701',
        
        // Step 3 values (read-only - using demo data)
        youtube_title: document.getElementById('youtube-title')?.value || 'Property Tour',
        youtube_url: document.getElementById('youtube-url')?.value || 'https://youtube.com/watch?v=dQw4w9WgXcQ',
        youtube_thumbnail: document.getElementById('youtube-thumbnail')?.value || 'https://img.youtube.com/vi/dQw4w9WgXcQ/maxresdefault.jpg',
        gallery_title: document.getElementById('gallery-title')?.value || 'Property Gallery',
        map_address: document.getElementById('map-address')?.value || 'Austin, TX',
        map_latitude: document.getElementById('map-latitude')?.value || '30.2672',
        map_longitude: document.getElementById('map-longitude')?.value || '-97.7431',
        
        departments: {}
    };
    
    for (const dept of ['sale', 'rent', 'commercial', 'let']) {
        const selections = departmentSelections[dept];
        const hasSelections = Object.values(selections).some(arr => arr && arr.length > 0);
        
        if (hasSelections) {
            importData.departments[dept] = {
                department: dept,
                property_types: selections.types || [],
                property_status: selections.status || [],
                badges: selections.badges || [],
                tags: selections.tags || [],
                locations: selections.locations || [],
                features: selections.features || []
            };
        }
    }
    
    if (Object.keys(importData.departments).length === 0) {
        importData.departments[selectedDepartment] = {
            department: selectedDepartment,
            property_types: departmentSelections[selectedDepartment].types || [],
            property_status: departmentSelections[selectedDepartment].status || [],
            badges: departmentSelections[selectedDepartment].badges || [],
            tags: departmentSelections[selectedDepartment].tags || [],
            locations: departmentSelections[selectedDepartment].locations || [],
            features: departmentSelections[selectedDepartment].features || []
        };
    }
    
    // Progress screen with spinning icon
    const progressHTML = `
        <div class="hvnly--property--import-completion-screen">
            <div class="hvnly--property--import-completion-icon">
                <i class="fas fa-sync fa-spin"></i>
            </div>
            <h2 class="hvnly--property--import-completion-title">Importing Properties</h2>
            <p class="hvnly--property--import-completion-description" id="importMessage">
                Please wait while we import your ${propertyImportQuantity} properties. This may take a few minutes.
            </p>
            <div class="hvnly--property--import-progress-container">
                <div class="hvnly--property--import-progress-bar">
                    <div class="hvnly--property--import-progress-fill" id="progressFill"></div>
                </div>
                <div class="hvnly--property--import-progress-text" id="progressText">0%</div>
            </div>
        </div>
    `;
    
    contentCard.innerHTML = progressHTML;
    navigation.style.display = 'none';
    
    // Reset and save builders before starting import (only once)
    if (!buildersReset) {
        try {
            await resetAndSaveBuildersBeforeImport();
        } catch (error) {
            // Continue import even if builder reset fails
        }
        buildersReset = true;
    }
    
    setTimeout(addCancellationButtons, 100);
    window.importBatch(0, 0, importData, csrfToken);
}

// Preserve original updateProgress function
const originalUpdateProgress = updateProgress;
updateProgress = function(data) {
    if (originalUpdateProgress) {
        originalUpdateProgress(data);
    }
    
    if (!document.getElementById('cancelImportBtn') && isImporting && !importCancelled) {
        addCancellationButtons();
    }
};

function updateProgress(data) {
    const progressFill = document.getElementById('progressFill');
    const progressText = document.getElementById('progressText');
    const importMessage = document.getElementById('importMessage');
    
    if (progressFill) progressFill.style.width = data.percent + '%';
    if (progressText) progressText.textContent = data.percent + '%';
    if (importMessage) importMessage.textContent = data.message;
}

function showCelebration(importedCount) {
    const celebration = document.querySelector('.hvnly--property--import-celebration');
    const contentCard = document.querySelector('.hvnly--property--import-content-card');
    
    const finalHTML = `
        <div class="hvnly--property--import-completion-screen">
            <div class="hvnly--property--import-completion-icon">
                <i class="fas fa-check"></i>
            </div>
            <h2 class="hvnly--property--import-completion-title">Import Complete!</h2>
            <p class="hvnly--property--import-completion-description">
                Your properties have been successfully imported! All <strong>${importedCount} properties</strong> are now available in your dashboard.
            </p>
            <div class="hvnly--property--import-completion-actions">
                <a href="edit.php?post_type=hvnly_property" class="hvnly--property--import-completion-button primary">
                    <i class="fas fa-eye"></i>
                    View Properties
                </a>
                <a href="admin.php?page=havenlytics" class="hvnly--property--import-completion-button secondary">
                    <i class="fas fa-home"></i>
                    Return to Dashboard
                </a>
            </div>
        </div>
    `;
    
    contentCard.innerHTML = finalHTML;
    
    celebration.classList.add('active');
    triggerConfetti();
    
    setTimeout(() => {
        celebration.classList.remove('active');
        stopConfetti();
    }, 5000);
    
    const closeCelebration = document.getElementById('celebration-close');
    if (closeCelebration) {
        closeCelebration.addEventListener('click', function() {
            celebration.classList.remove('active');
            stopConfetti();
        });
    }
}

// Confetti animation
let W = window.innerWidth;
let H = window.innerHeight;
const canvas = document.getElementById("confetti-canvas");
const context = canvas?.getContext("2d");
const maxConfettis = 150;
const particles = [];
let animationId = null;

const possibleColors = [
    "#6C60FE", "#764ba2", "#00B46A", "#FF9AA2", 
    "#FFB507", "#00C2A8", "#FF4D4F", "#E68F17",
    "#FAB005", "#FA5252", "#E64980", "#BE4BDB",
    "#0B7285", "#15AABF", "#EE1233", "#40C057"
];

function randomFromTo(from, to) {
    return Math.floor(Math.random() * (to - from + 1) + from);
}

function confettiParticle() {
    this.x = Math.random() * W;
    this.y = Math.random() * H - H;
    this.r = randomFromTo(11, 33);
    this.d = Math.random() * maxConfettis + 11;
    this.color = possibleColors[Math.floor(Math.random() * possibleColors.length)];
    this.tilt = Math.floor(Math.random() * 33) - 11;
    this.tiltAngleIncremental = Math.random() * 0.07 + 0.05;
    this.tiltAngle = 0;

    this.draw = function() {
        context.beginPath();
        context.lineWidth = this.r / 2;
        context.strokeStyle = this.color;
        context.moveTo(this.x + this.tilt + this.r / 3, this.y);
        context.lineTo(this.x + this.tilt, this.y + this.tilt + this.r / 5);
        context.stroke();
    };
}

function Draw() {
    animationId = requestAnimationFrame(Draw);
    context.clearRect(0, 0, W, H);

    for (var i = 0; i < maxConfettis; i++) {
        if (particles[i]) particles[i].draw();
    }

    for (var i = 0; i < maxConfettis; i++) {
        let particle = particles[i];
        if (!particle) continue;

        particle.tiltAngle += particle.tiltAngleIncremental;
        particle.y += (Math.cos(particle.d) + 3 + particle.r / 2) / 2;
        particle.tilt = Math.sin(particle.tiltAngle - i / 3) * 15;

        if (particle.x > W + 30 || particle.x < -30 || particle.y > H) {
            particle.x = Math.random() * W;
            particle.y = -30;
            particle.tilt = Math.floor(Math.random() * 10) - 20;
        }
    }
}

function triggerConfetti() {
    if (!canvas || !context) return;
    
    W = window.innerWidth;
    H = window.innerHeight;
    canvas.width = W;
    canvas.height = H;
    
    particles.length = 0;
    for (var i = 0; i < maxConfettis; i++) {
        particles.push(new confettiParticle());
    }
    Draw();
}

function stopConfetti() {
    if (animationId) {
        cancelAnimationFrame(animationId);
        animationId = null;
    }
    if (context) {
        context.clearRect(0, 0, W, H);
    }
}

window.addEventListener("resize", function() {
    W = window.innerWidth;
    H = window.innerHeight;
    if (canvas) {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
    }
}, false);

// =========================================
// MODERN ENTRANCE ANIMATION - FIRST TIME ONLY
// =========================================

// Add modern entrance animation when page loads
document.addEventListener('DOMContentLoaded', function() {
    // Add entrance animation class to body
    document.body.classList.add('wizard-entrance-active');
    
    // Create floating particles effect on page load
    const container = document.querySelector('.hvnly--property--import-wrapper');
    if (container) {
        for (let i = 0; i < 30; i++) {
            const particle = document.createElement('div');
            particle.className = 'hvnly-entrance-particle';
            particle.style.cssText = `
                position: fixed;
                width: ${Math.random() * 8 + 2}px;
                height: ${Math.random() * 8 + 2}px;
                background: linear-gradient(135deg, var(--hvnly-brand-primary), var(--hvnly-brand-secondary));
                border-radius: 50%;
                pointer-events: none;
                z-index: 9999;
                left: ${Math.random() * 100}%;
                top: ${Math.random() * 100}%;
                animation: particleFloat 1.2s ease-out forwards;
                opacity: 0;
            `;
            document.body.appendChild(particle);
            
            setTimeout(() => {
                particle.remove();
            }, 1200);
        }
    }
    
    // Add shine effect on main card
    const contentCard = document.querySelector('.hvnly--property--import-content-card');
    if (contentCard) {
        contentCard.classList.add('card-shine-effect');
        setTimeout(() => {
            contentCard.classList.remove('card-shine-effect');
        }, 800);
    }
    
    // Remove entrance class after animation completes
    setTimeout(() => {
        document.body.classList.remove('wizard-entrance-active');
    }, 1000);
});

// Add particle float animation to CSS dynamically
const entranceStyle = document.createElement('style');
entranceStyle.textContent = `
    @keyframes particleFloat {
        0% {
            opacity: 0;
            transform: translateY(0) scale(0);
        }
        20% {
            opacity: 0.8;
            transform: translateY(-30px) scale(1);
        }
        100% {
            opacity: 0;
            transform: translateY(-150px) scale(0);
        }
    }
    
    @keyframes cardShine {
        0% {
            box-shadow: 0 0 0 0 rgba(108, 96, 254, 0);
        }
        50% {
            box-shadow: 0 0 30px 10px rgba(108, 96, 254, 0.3);
        }
        100% {
            box-shadow: 0 0 0 0 rgba(108, 96, 254, 0);
        }
    }
    
    .card-shine-effect {
        animation: cardShine 0.8s ease-out;
    }
`;
document.head.appendChild(entranceStyle);

// =========================================
// END OF MODERN ENTRANCE ANIMATION
// =========================================

// =========================================
// VIDEO TUTORIAL POPUP - WITH BODY SCROLL LOCK
// =========================================

document.addEventListener('DOMContentLoaded', function() {
    // Get all elements
    const videoPopup = document.getElementById('hvnly-video-tutorial-popup');
    const closeBtn = document.getElementById('hvnlyVideoTutorialClose');
    const dontShowBtn = document.getElementById('hvnlyVideoTutorialDontShow');
    const getStartedBtn = document.getElementById('hvnlyVideoTutorialGetStarted');
    let videoIframe = document.getElementById('hvnlyTutorialIframe');
    
    // Exit if popup doesn't exist
    if (!videoPopup) return;
    
    // Function to lock body scroll
    function lockBodyScroll() {
        document.body.classList.add('hvnly-video-popup-open');
        // Store current scroll position
        const scrollY = window.scrollY;
        document.body.style.top = '-' + scrollY + 'px';
    }
    
    // Function to unlock body scroll
    function unlockBodyScroll() {
        const scrollY = document.body.style.top;
        document.body.classList.remove('hvnly-video-popup-open');
        document.body.style.top = '';
        // Restore scroll position
        if (scrollY) {
            window.scrollTo(0, parseInt(scrollY || '0') * -1);
        }
    }
    
    // Store original iframe source
    let originalIframeSrc = '';
    if (videoIframe) {
        originalIframeSrc = videoIframe.src;
    }
    
    // Function to completely stop video
    function stopVideoCompletely() {
        if (videoIframe && videoIframe.parentNode) {
            try {
                // Method 1: Try YouTube API to pause
                if (videoIframe.contentWindow) {
                    videoIframe.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
                }
                
                // Method 2: Clear the src (most reliable)
                const iframeParent = videoIframe.parentNode;
                const iframeId = videoIframe.id;
                
                // Remove old iframe
                iframeParent.removeChild(videoIframe);
                
                // Create new empty iframe
                const newIframe = document.createElement('iframe');
                newIframe.id = iframeId;
                newIframe.width = '100%';
                newIframe.height = '100%';
                newIframe.frameBorder = '0';
                newIframe.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share';
                newIframe.allowFullscreen = true;
                newIframe.title = 'YouTube video player';
                
                // Set empty src first, then restore without autoplay
                newIframe.src = 'about:blank';
                iframeParent.appendChild(newIframe);
                
                // Update reference
                videoIframe = newIframe;
                window.hvnlyTutorialIframe = newIframe;
                
                // Restore src without autoplay after a short delay
                setTimeout(function() {
                    if (originalIframeSrc) {
                        newIframe.src = originalIframeSrc.replace('autoplay=1', 'autoplay=0');
                    }
                }, 100);
                
            } catch(e) {
                // Fallback: just clear the src
                if (videoIframe) {
                    videoIframe.src = 'about:blank';
                }
            }
        }
    }
    
    // Function to close popup smoothly
    function closeVideoPopup() {
        // Stop the video first
        stopVideoCompletely();
        
        // Add fade out class
        videoPopup.classList.remove('hvnly-video-tutorial-show');
        videoPopup.classList.add('hvnly-video-tutorial-fade-out');
        
        // Unlock body scroll
        unlockBodyScroll();
        
        // Hide after animation completes
        setTimeout(function() {
            videoPopup.style.display = 'none';
            videoPopup.classList.remove('hvnly-video-tutorial-fade-out');
        }, 300);
    }
    
    // Function to dismiss video permanently via AJAX
    function dismissVideoPermanently() {
        if (typeof jQuery !== 'undefined' && typeof hvnlyImportWizard !== 'undefined') {
            jQuery.ajax({
                url: hvnlyImportWizard.ajaxurl,
                type: 'POST',
                data: {
                    action: 'hvnly_dismiss_video_tutorial',
                    nonce: hvnlyImportWizard.nonce,
                    csrf_token: document.getElementById('hvnly_csrf_token')?.value || ''
                },
                success: function(response) {
                    // Video dismissed successfully
                },
                error: function() {
                    // Silently fail
                }
            });
        }
    }
    
    // Close button click event
    if (closeBtn) {
        closeBtn.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            closeVideoPopup();
        });
    }
    
    // "Don't show again" button click event
    if (dontShowBtn) {
        dontShowBtn.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            dismissVideoPermanently();
            closeVideoPopup();
        });
    }
    
    // "Get Started" button click event
    if (getStartedBtn) {
        getStartedBtn.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            closeVideoPopup();
        });
    }
    
    // Click outside to close
    videoPopup.addEventListener('click', function(e) {
        if (e.target === videoPopup) {
            e.preventDefault();
            closeVideoPopup();
        }
    });
    
    // Show popup smoothly after 2 seconds and lock scroll
    setTimeout(function() {
        if (videoPopup && videoPopup.style.display !== 'none') {
            videoPopup.classList.add('hvnly-video-tutorial-show');
            // Lock body scroll when popup opens
            lockBodyScroll();
        }
    }, 2000);
});

document.addEventListener('DOMContentLoaded', function() {
    updateStepContent();
    setupNavigationButtons();
    
    const closeButton = document.querySelector('.hvnly--property--import-close-button');
    if (closeButton) {
        closeButton.addEventListener('click', function(e) {
            e.preventDefault();
            if(confirm('Are you sure you want to close the wizard?')) {
                window.location.href = 'edit.php?post_type=hvnly_property';
            }
        });
    }
    
    const docButton = document.querySelector('.hvnly--property--import-doc-button');
    if (docButton) {
        docButton.addEventListener('click', function(e) {
            e.preventDefault();
            window.open('https://havenlytics.com/documentation/havenlytics-setup-wizard', '_blank');
        });
    }
});

function setupNavigationButtons() {
    const prevButton = document.querySelector('.hvnly--property--import-nav-button.prev');
    const nextButton = document.querySelector('.hvnly--property--import-nav-button.next');
    const skipButton = document.querySelector('.hvnly--property--import-nav-button.skip');
    
    if (prevButton) {
        prevButton.addEventListener('click', function() {
            if (currentStep > 1 && !isImporting) {
                if (currentStep === 1) {
                    saveCurrentSelections();
                }
                currentStep--;
                updateStepProgress();
                updateStepContent();
            }
        });
    }
    
    if (nextButton) {
        nextButton.addEventListener('click', function() {
            if (currentStep < totalSteps && !isImporting) {
                if (currentStep === 1) {
                    saveCurrentSelections();
                }
                currentStep++;
                updateStepProgress();
                updateStepContent();
            } else if (currentStep === totalSteps && !isImporting) {
                startImportProcess();
            }
        });
    }
    
    if (skipButton) {
        skipButton.addEventListener('click', function() {
            if(confirm('Are you sure you want to skip this step?') && !isImporting) {
                if (currentStep === 1) {
                    saveCurrentSelections();
                }
                if (currentStep < totalSteps) {
                    currentStep++;
                    updateStepProgress();
                    updateStepContent();
                } else {
                    startImportProcess();
                }
            }
        });
    }
}

// Update step progress
function updateStepProgress() {
    const stepItems = document.querySelectorAll('.hvnly--property--import-step-item');
    stepItems.forEach((item, index) => {
        item.classList.remove('active', 'completed');
        
        if (index + 1 < currentStep) {
            item.classList.add('completed');
        } else if (index + 1 === currentStep) {
            item.classList.add('active');
        }
    });
    
    const progressBar = document.querySelector('.hvnly--property--import-step-progress-bar');
    const progressPercentage = ((currentStep - 1) / (totalSteps - 1)) * 100;
    if (progressBar) {
        progressBar.style.width = `${progressPercentage}%`;
    }
}

// Update step content
function updateStepContent() {
    const stepContent = document.querySelector('.hvnly--property--import-step-content');
    if (!stepContent) return;
    
    stepContent.style.animation = 'none';
    setTimeout(() => {
        stepContent.style.animation = 'slideIn 0.5s ease-out';
    }, 10);
    
    stepContent.innerHTML = stepContents[currentStep];
    
    const nextButton = document.querySelector('.hvnly--property--import-nav-button.next');
    if (nextButton) {
        if (currentStep === totalSteps) {
            nextButton.innerHTML = 'Complete <i class="fas fa-check"></i>';
        } else {
            nextButton.innerHTML = 'Next <i class="fas fa-arrow-right"></i>';
        }
    }
    
    if (currentStep === 4) {
        setupQuantitySlider();
    }
    
    if (currentStep === 3) {
        // Map fields are read-only - just update preview display
        const previewAddress = document.getElementById('preview-address');
        const mapAddress = document.getElementById('map-address');
        if (previewAddress && mapAddress) {
            previewAddress.textContent = mapAddress.value;
        }
    }
    
    if (currentStep === 1) {
        setupDepartmentTabs();
        setTimeout(() => {
            setupCheckboxSelection();
        }, 50);
    }
}

// Setup department tabs
function setupDepartmentTabs() {
    const departmentTabs = document.querySelectorAll('.hvnly--property--import-department-tab');
    
    departmentTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            saveCurrentSelections();
            
            departmentTabs.forEach(t => t.classList.remove('active'));
            this.classList.add('active');
            
            selectedDepartment = this.getAttribute('data-department');
            
            const taxonomyContainer = document.getElementById('taxonomyContainer');
            if (taxonomyContainer) {
                taxonomyContainer.innerHTML = generateTaxonomyHTML(selectedDepartment);
                setTimeout(() => {
                    setupCheckboxSelection();
                }, 50);
            }
        });
    });
}

// Setup property quantity slider functionality
function setupQuantitySlider() {
    const quantitySlider = document.getElementById('propertyQuantitySlider');
    const quantityValue = document.getElementById('quantityValue');
    
    if (quantitySlider && quantityValue) {
        quantitySlider.value = propertyImportQuantity;
        quantityValue.textContent = propertyImportQuantity;
        
        quantitySlider.addEventListener('input', function() {
            propertyImportQuantity = parseInt(this.value);
            if (propertyImportQuantity > 200) {
                propertyImportQuantity = 200;
                this.value = 200;
            }
            quantityValue.textContent = propertyImportQuantity;
        });
    }
}