<?php
// Allow all origins
header("Access-Control-Allow-Origin: *");

// Allow common HTTP methods
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

// Allow common headers
header("Access-Control-Allow-Headers: Content-Type, Authorization");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Car Image Gallery</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* Self-contained gallery styles that don't affect parent site */
        .car-gallery-plugin {
            --cg-primary: #8B7355;
            --cg-primary-light: #A6927A;
            --cg-primary-dark: #5D4A30;
            --cg-text: inherit;
            --cg-bg: transparent;
            --cg-border: rgba(0, 0, 0, 0.1);
            --cg-shadow: rgba(0, 0, 0, 0.1);
            
            font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            color: var(--cg-text);
            background: var(--cg-bg);
            width: 100%;
        }
        
        .car-gallery-plugin * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        .car-gallery-plugin .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .car-gallery-plugin .header {
            text-align: center;
            margin-bottom: 40px;
            padding: 30px;
            background: linear-gradient(135deg, var(--cg-primary) 0%, var(--cg-primary-dark) 100%);
            border-radius: 15px;
            box-shadow: 0 10px 30px var(--cg-shadow);
            position: relative;
            overflow: hidden;
            color: white;
        }
        
        .car-gallery-plugin .header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 5px;
            background: var(--cg-primary-light);
        }
        
        .car-gallery-plugin .header h1 {
            font-size: 2.8rem;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
        }
        
        .car-gallery-plugin .header .subtitle {
            font-size: 1.2rem;
            opacity: 0.9;
        }
        
        .car-gallery-plugin .loading {
            text-align: center;
            padding: 40px;
            display: none;
        }
        
        .car-gallery-plugin .loading-spinner {
            width: 50px;
            height: 50px;
            border: 5px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top-color: var(--cg-primary);
            animation: cg-spin 1s ease-in-out infinite;
            margin: 0 auto 20px;
        }
        
        @keyframes cg-spin {
            to { transform: rotate(360deg); }
        }
        
        .car-gallery-plugin .gallery-container {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 30px;
            margin-top: 40px;
        }
        
        @media (max-width: 1024px) {
            .car-gallery-plugin .gallery-container {
                grid-template-columns: 1fr;
            }
        }
        
        .car-gallery-plugin .main-image-section {
            background: rgba(0, 0, 0, 0.02);
            border-radius: 15px;
            padding: 25px;
            border: 1px solid var(--cg-border);
            box-shadow: 0 5px 15px var(--cg-shadow);
        }
        
        .car-gallery-plugin .main-image-section h2 {
            color: var(--cg-primary);
            margin-bottom: 20px;
            font-size: 1.5rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .car-gallery-plugin .main-image-display {
            position: relative;
            width: 100%;
            height: 500px;
            background: rgba(0, 0, 0, 0.02);
            border-radius: 12px;
            overflow: hidden;
            margin-bottom: 20px;
            border: 1px solid var(--cg-border);
        }
        
        .car-gallery-plugin .main-image-display img {
            width: 100%;
            height: 100%;
            object-fit: contain;
            background: white;
        }
        
        .car-gallery-plugin .overlay-controls {
            background: rgba(0, 0, 0, 0.02);
            padding: 20px;
            border-radius: 10px;
            margin-top: 20px;
            border: 1px solid var(--cg-border);
        }
        
        .car-gallery-plugin .overlay-controls h3 {
            color: var(--cg-primary);
            margin-bottom: 15px;
            font-size: 1.2rem;
        }
        
        .car-gallery-plugin .overlay-options {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 15px;
        }
        
        @media (max-width: 768px) {
            .car-gallery-plugin .overlay-options {
                grid-template-columns: repeat(2, 1fr);
            }
        }
        
        .car-gallery-plugin .overlay-btn {
            background: rgba(0, 0, 0, 0.05);
            border: 2px solid transparent;
            border-radius: 8px;
            padding: 15px 10px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            color: var(--cg-text);
        }
        
        .car-gallery-plugin .overlay-btn:hover {
            background: rgba(139, 115, 85, 0.1);
            border-color: var(--cg-primary);
        }
        
        .car-gallery-plugin .overlay-btn.active {
            background: rgba(139, 115, 85, 0.15);
            border-color: var(--cg-primary);
            color: var(--cg-primary);
            font-weight: 600;
        }
        
        .car-gallery-plugin .overlay-btn i {
            font-size: 1.5rem;
            margin-bottom: 8px;
            display: block;
            color: var(--cg-primary);
        }
        
        .car-gallery-plugin .thumbnail-section {
            background: rgba(0, 0, 0, 0.02);
            border-radius: 15px;
            padding: 25px;
            border: 1px solid var(--cg-border);
            box-shadow: 0 5px 15px var(--cg-shadow);
            max-height: 800px;
            overflow-y: auto;
        }
        
        .car-gallery-plugin .thumbnail-section h2 {
            color: var(--cg-primary);
            margin-bottom: 20px;
            font-size: 1.5rem;
            display: flex;
            align-items: center;
            gap: 10px;
            position: sticky;
            top: 0;
            background: inherit;
            padding: 10px 0;
            z-index: 10;
        }
        
        .car-gallery-plugin .thumbnails-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
        }
        
        @media (max-width: 768px) {
            .car-gallery-plugin .thumbnails-grid {
                grid-template-columns: repeat(3, 1fr);
            }
        }
        
        .car-gallery-plugin .thumbnail-item {
            position: relative;
            border-radius: 8px;
            overflow: hidden;
            cursor: pointer;
            transition: all 0.3s ease;
            aspect-ratio: 4/3;
            background: rgba(0, 0, 0, 0.05);
            border: 2px solid transparent;
        }
        
        .car-gallery-plugin .thumbnail-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px var(--cg-shadow);
            border-color: var(--cg-primary-light);
        }
        
        .car-gallery-plugin .thumbnail-item.active {
            border-color: var(--cg-primary);
        }
        
        .car-gallery-plugin .thumbnail-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s ease;
        }
        
        .car-gallery-plugin .thumbnail-item:hover img {
            transform: scale(1.05);
        }
        
        .car-gallery-plugin .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }
        
        .car-gallery-plugin .empty-state i {
            font-size: 4rem;
            margin-bottom: 20px;
            color: var(--cg-primary);
            opacity: 0.5;
        }
        
        .car-gallery-plugin .empty-state h3 {
            font-size: 1.5rem;
            margin-bottom: 10px;
            color: var(--cg-primary);
        }
        
        .car-gallery-plugin .error-message {
            background: rgba(255, 87, 87, 0.1);
            border-left: 4px solid #ff5757;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
            color: #d32f2f;
            display: none;
        }
        
        .car-gallery-plugin .stats {
            display: flex;
            justify-content: space-between;
            background: rgba(0, 0, 0, 0.02);
            padding: 15px;
            border-radius: 10px;
            margin-top: 20px;
            font-size: 0.9rem;
            color: #666;
            border: 1px solid var(--cg-border);
        }
        
        .car-gallery-plugin .stats span {
            color: var(--cg-primary);
            font-weight: 600;
        }
        
        .car-gallery-plugin .overlay-image-container {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 5;
        }
        
        .car-gallery-plugin .overlay-image-container.active {
            display: flex;
        }
        
        .car-gallery-plugin .overlay-image {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
            mix-blend-mode: multiply;
        }
        
        .car-gallery-plugin .download-btn {
            position: absolute;
            bottom: 20px;
            right: 20px;
            background: var(--cg-primary);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            z-index: 10;
            transition: background 0.3s ease;
            font-family: inherit;
        }
        
        .car-gallery-plugin .download-btn:hover {
            background: var(--cg-primary-dark);
        }
        
        .car-gallery-plugin .car-info-header {
            background: rgba(0, 0, 0, 0.02);
            padding: 15px;
            border-radius: 10px;
            margin: 20px 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
            border: 1px solid var(--cg-border);
        }
        
        .car-gallery-plugin .car-title {
            font-size: 1.8rem;
            color: var(--cg-primary);
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .car-gallery-plugin .car-meta {
            display: flex;
            gap: 20px;
            color: #666;
        }
        
        .car-gallery-plugin .car-meta span {
            color: var(--cg-primary);
            font-weight: 600;
        }
        
        /* Models Grid View - Keep original design */
        .car-gallery-plugin .models-grid-view {
            display: none;
        }
        
        .car-gallery-plugin .models-grid-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        
        .car-gallery-plugin .model-card {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            border: 1px solid var(--cg-border);
            box-shadow: 0 4px 8px var(--cg-shadow);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        
        .car-gallery-plugin .model-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px var(--cg-shadow);
        }
        
        .car-gallery-plugin .model-card-image {
            height: 200px;
            overflow: hidden;
        }
        
        .car-gallery-plugin .model-card-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s ease;
        }
        
        .car-gallery-plugin .model-card:hover .model-card-image img {
            transform: scale(1.05);
        }
        
        .car-gallery-plugin .model-card-info {
            padding: 15px;
        }
        
        .car-gallery-plugin .model-card-name {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--cg-primary);
            margin-bottom: 5px;
        }
        
        .car-gallery-plugin .model-card-years {
            font-size: 0.9rem;
            color: #666;
            margin-bottom: 10px;
        }
        
        .car-gallery-plugin .model-card-view-btn {
            background: var(--cg-primary);
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.9rem;
            transition: background 0.3s ease;
            width: 100%;
        }
        
        .car-gallery-plugin .model-card-view-btn:hover {
            background: var(--cg-primary-dark);
        }
        
        /* Back Button - Minimal design */
        .car-gallery-plugin .back-to-models-btn {
            background: transparent;
            color: var(--cg-primary);
            border: 1px solid var(--cg-primary);
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.9rem;
            transition: all 0.3s ease;
            margin-left: 10px;
        }
        
        .car-gallery-plugin .back-to-models-btn:hover {
            background: rgba(139, 115, 85, 0.1);
        }
        
        /* Scrollbar Styling */
        .car-gallery-plugin ::-webkit-scrollbar {
            width: 8px;
        }
        
        .car-gallery-plugin ::-webkit-scrollbar-track {
            background: rgba(0, 0, 0, 0.05);
            border-radius: 10px;
        }
        
        .car-gallery-plugin ::-webkit-scrollbar-thumb {
            background: var(--cg-primary);
            border-radius: 10px;
        }
        
        .car-gallery-plugin ::-webkit-scrollbar-thumb:hover {
            background: var(--cg-primary-dark);
        }
        
        /* Ensure plugin doesn't affect parent site */
        body {
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
    <div class="car-gallery-plugin">
        <div class="container">
            <div class="header">
                <h1><i class="fas fa-car"></i>Image Gallery</h1>
                <p class="subtitle">Explore detailed car images for color inspection</p>
            </div>
            
            <div class="car-info-header" id="carInfoHeader" style="display: none;">
                <div class="car-title">
                    <i class="fas fa-car"></i>
                    <span id="carTitle">Loading...</span>
                </div>
                <div class="car-meta">
                    <div><i class="fas fa-images"></i> <span id="imageCount">0</span> images</div>
                    <div><i class="fas fa-palette"></i> Overlay: <span id="overlayType">None</span></div>
                </div>
            </div>
            
            <div class="error-message" id="errorMessage"></div>
            
            <div class="loading" id="loading">
                <div class="loading-spinner"></div>
                <p>Loading car images...</p>
            </div>
            
            <!-- Models Grid View (for "all models") -->
            <div class="models-grid-view" id="modelsGridView">
                <div class="models-grid-container" id="modelsGridContainer">
                    <!-- Model cards will be inserted here -->
                </div>
            </div>
            
            <!-- Gallery Container (for single model) -->
            <div class="gallery-container" id="galleryContainer" style="display: none;">
                <div class="main-image-section">
                    <h2><i class="fas fa-image"></i> Main Display</h2>
                    <div class="main-image-display" id="mainImageDisplay">
                        <img id="mainImage" src="" alt="Car Image">
                        <div class="overlay-image-container" id="overlayContainer">
                            <img class="overlay-image" id="overlayImage" src="" alt="Overlay">
                        </div>
                        <button class="download-btn" id="downloadBtn">
                            <i class="fas fa-download"></i> Download
                        </button>
                    </div>
                    
                    <div class="overlay-controls">
                        <h3><i class="fas fa-layer-group"></i> Product Overlays</h3>
                        <div class="overlay-options">
                            <div class="overlay-btn" data-overlay="tin.png">
                                <i class="fas fa-box"></i>
                                Tin
                            </div>
                            <div class="overlay-btn" data-overlay="pen.png">
                                <i class="fas fa-pen"></i>
                                Pen
                            </div>
                            <div class="overlay-btn" data-overlay="spray.png">
                                <i class="fas fa-spray-can"></i>
                                Spray
                            </div>
                            <div class="overlay-btn" data-overlay="bottle.png">
                                <i class="fas fa-wine-bottle"></i>
                                Bottle
                            </div>
                        </div>
                    </div>
                    
                    <div class="stats">
                        <div><i class="fas fa-expand-arrows-alt"></i> Navigation: Use ← → arrow keys</div>
                        <div><i class="fas fa-keyboard"></i> Shortcuts: 1-4 for overlays, 0 to remove</div>
                    </div>
                </div>
                
                <div class="thumbnail-section">
                    <h2><i class="fas fa-th"></i> Image Gallery</h2>
                    <div class="thumbnails-grid" id="thumbnailsGrid">
                        <!-- Thumbnails will be inserted here -->
                    </div>
                </div>
            </div>
            
            <div class="empty-state" id="emptyState">
                <i class="fas fa-car"></i>
                <h3>No Images Loaded</h3>
                <p>Unable to load car images from the provided URL parameters</p>
            </div>
        </div>
    </div>

    <script>
        // Self-contained JavaScript to avoid conflicts
        (function() {
            // DOM Elements - scoped to plugin
            const plugin = document.querySelector('.car-gallery-plugin');
            const loading = plugin.querySelector('#loading');
            const errorMessage = plugin.querySelector('#errorMessage');
            const galleryContainer = plugin.querySelector('#galleryContainer');
            const modelsGridView = plugin.querySelector('#modelsGridView');
            const emptyState = plugin.querySelector('#emptyState');
            const mainImage = plugin.querySelector('#mainImage');
            const overlayContainer = plugin.querySelector('#overlayContainer');
            const overlayImage = plugin.querySelector('#overlayImage');
            const thumbnailsGrid = plugin.querySelector('#thumbnailsGrid');
            const modelsGridContainer = plugin.querySelector('#modelsGridContainer');
            const carTitle = plugin.querySelector('#carTitle');
            const imageCount = plugin.querySelector('#imageCount');
            const overlayType = plugin.querySelector('#overlayType');
            const downloadBtn = plugin.querySelector('#downloadBtn');
            const overlayBtns = plugin.querySelectorAll('.overlay-btn');
            const carInfoHeader = plugin.querySelector('#carInfoHeader');
            
            // State variables
            let currentImages = [];
            let currentOverlay = null;
            let currentImageIndex = 0;
            let manufacturer = '';
            let model = '';
            
            // Overlay options
            const overlayUrls = {
                'tin.png': 'https://development.hatinco.com/vehicle-car-details/overlay/?image=tin.png',
                'pen.png': 'https://development.hatinco.com/vehicle-car-details/overlay/?image=pen.png',
                'spray.png': 'https://development.hatinco.com/vehicle-car-details/overlay/?image=spray.png',
                'bottle.png': 'https://development.hatinco.com/vehicle-car-details/overlay/?image=bottle.png'
            };
            
            // Get URL parameters
            function getUrlParams() {
                const urlParams = new URLSearchParams(window.location.search);
                return {
                    manufacturer: urlParams.get('manufacturer') || 'audi',
                    model: urlParams.get('model') || ''
                };
            }
            
            // Fetch car images from API
            async function fetchCarImages() {
                try {
                    showLoading();
                    hideError();
                    
                    const params = getUrlParams();
                    manufacturer = params.manufacturer;
                    model = params.model;
                    
                    const response = await fetch(`https://development.hatinco.com/vehicle-car-details/get_car_image_by_model.php?manufacturer=${encodeURIComponent(manufacturer)}&model=${encodeURIComponent(model)}`);
                    
                    if (!response.ok) {
                        throw new Error(`HTTP error! Status: ${response.status}`);
                    }
                    
                    const data = await response.json();
                    
                    if (data.success) {
                        // Check if this is "all models" response
                        if (data.all_models_data) {
                            displayAllModels(data);
                        } else {
                            displaySingleModel(data);
                        }
                    } else {
                        throw new Error(data.error || 'Failed to fetch images');
                    }
                } catch (error) {
                    showError(error.message);
                } finally {
                    hideLoading();
                }
            }
            
            // Display all models in grid view
            function displayAllModels(data) {
                // Hide single model gallery, show models grid
                galleryContainer.style.display = 'none';
                modelsGridView.style.display = 'block';
                emptyState.style.display = 'none';
                carInfoHeader.style.display = 'flex';
                
                // Update car info header
                carTitle.textContent = `${manufacturer.toUpperCase()} - All Models`;
                imageCount.textContent = data.total_images_found || 0;
                
                // Clear and populate models grid
                modelsGridContainer.innerHTML = '';
                
                if (!data.all_models_data || data.all_models_data.length === 0) {
                    showEmptyState();
                    return;
                }
                
                // Flatten all models into a single array
                const allModels = [];
                data.all_models_data.forEach(range => {
                    if (range.models && range.models.length > 0) {
                        range.models.forEach(model => {
                            allModels.push({
                                ...model,
                                range_name: range.range_name
                            });
                        });
                    }
                });
                
                if (allModels.length === 0) {
                    showEmptyState();
                    return;
                }
                
                // Create model cards
                allModels.forEach((modelItem, index) => {
                    const modelCard = createModelCard(modelItem, index);
                    modelsGridContainer.appendChild(modelCard);
                });
            }
            
            // Create a model card for grid view
            function createModelCard(modelItem, index) {
                const card = document.createElement('div');
                card.className = 'model-card';
                
                // Image
                const imageDiv = document.createElement('div');
                imageDiv.className = 'model-card-image';
                
                const img = document.createElement('img');
                img.src = modelItem.image_url || 'https://via.placeholder.com/300x200?text=No+Image';
                img.alt = modelItem.alt_text || modelItem.model_name;
                img.loading = 'lazy';
                
                imageDiv.appendChild(img);
                
                // Info
                const infoDiv = document.createElement('div');
                infoDiv.className = 'model-card-info';
                
                const name = document.createElement('div');
                name.className = 'model-card-name';
                name.textContent = modelItem.model_name;
                
                const years = document.createElement('div');
                years.className = 'model-card-years';
                years.textContent = modelItem.model_years || '';
                
                const viewBtn = document.createElement('button');
                viewBtn.className = 'model-card-view-btn';
                viewBtn.innerHTML = '<i class="fas fa-external-link-alt"></i> View Gallery';
                viewBtn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    viewModelGallery(modelItem);
                });
                
                infoDiv.appendChild(name);
                infoDiv.appendChild(years);
                infoDiv.appendChild(viewBtn);
                
                card.appendChild(imageDiv);
                card.appendChild(infoDiv);
                
                return card;
            }
            
            // View specific model gallery
            function viewModelGallery(modelItem) {
                // Extract model slug from the model_link
                const modelSlug = extractModelSlug(modelItem.model_link);
                if (!modelSlug) return;
                
                // Update URL and reload
                const url = new URL(window.location);
                url.searchParams.set('model', modelSlug);
                window.history.pushState({}, '', url);
                
                // Add back button to header
                addBackButton();
                
                // Reload with new model
                fetchCarImages();
            }
            
            // Add back button to car info header
            function addBackButton() {
                // Check if back button already exists
                if (!document.querySelector('.back-to-models-btn')) {
                    const backBtn = document.createElement('button');
                    backBtn.className = 'back-to-models-btn';
                    backBtn.innerHTML = '<i class="fas fa-arrow-left"></i> Back to All Models';
                    backBtn.addEventListener('click', goBackToAllModels);
                    
                    const carMeta = carInfoHeader.querySelector('.car-meta');
                    if (carMeta) {
                        carMeta.appendChild(backBtn);
                    }
                }
            }
            
            // Go back to all models view
            function goBackToAllModels() {
                const url = new URL(window.location);
                url.searchParams.set('model', 'all models');
                window.history.pushState({}, '', url);
                
                // Remove back button
                const backBtn = document.querySelector('.back-to-models-btn');
                if (backBtn) {
                    backBtn.remove();
                }
                
                fetchCarImages();
            }
            
            // Extract model slug from URL
                function extractModelSlug(url) {
                    if (!url) return '';
                    
                    // Remove leading/trailing slashes
                    const cleanUrl = url.replace(/^\/|\/$/g, '');
                    const parts = cleanUrl.split('/');
                    
                    // URL format: manufacturer/model/variant-year/specs
                    // We want: model/variant (without year)
                    
                    if (parts.length >= 3) {
                        const manufacturer = parts[0]; // fiat
                        const model = parts[1]; // 500-electric
                        const variantWithYear = parts[2]; // convertible-2020 or suv-2024
                        
                        // Remove the year part (anything after the last hyphen that looks like a year)
                        // Convertible-2020 → convertible
                        // Hatchback-2020 → hatchback
                        // Suv-2024 → suv
                        let variant = variantWithYear;
                        
                        // Check if variant contains a year pattern (20xx or xx)
                        const yearMatch = variantWithYear.match(/-(\d{2,4})$/);
                        if (yearMatch) {
                            // Remove the year part including the hyphen
                            variant = variantWithYear.replace(/-(\d{2,4})$/, '');
                        }
                        
                        return `${model}/${variant}`; // 500-electric/convertible
                    }
                    
                    return '';
                }
            
            // Display single model gallery
            function displaySingleModel(data) {
                currentImages = data.gallery_images || [];
                
                // Show gallery and hide models grid
                galleryContainer.style.display = 'grid';
                modelsGridView.style.display = 'none';
                emptyState.style.display = 'none';
                
                // Update car info header
                const manufacturerName = data.manufacturer.toUpperCase();
                const modelName = data.model.toUpperCase();
                carTitle.textContent = `${manufacturerName} ${modelName}`;
                imageCount.textContent = data.total_gallery_images || currentImages.length;
                carInfoHeader.style.display = 'flex';
                
                if (currentImages.length === 0) {
                    showEmptyState();
                    return;
                }
                
                // Display thumbnails
                displayThumbnails();
                
                // Display first image
                displayImage(0);
                
                // Reset overlay
                resetOverlay();
            }
            
            // Display thumbnails
            function displayThumbnails() {
                thumbnailsGrid.innerHTML = '';
                
                currentImages.forEach((image, index) => {
                    const thumbnailItem = document.createElement('div');
                    thumbnailItem.className = 'thumbnail-item';
                    thumbnailItem.dataset.index = index;
                    
                    if (index === currentImageIndex) {
                        thumbnailItem.classList.add('active');
                    }
                    
                    const img = document.createElement('img');
                    img.src = image.thumbnail || image.small || image.medium;
                    img.alt = image.title || `${manufacturer} ${model} - Image ${index + 1}`;
                    img.loading = 'lazy';
                    
                    thumbnailItem.appendChild(img);
                    thumbnailItem.addEventListener('click', () => displayImage(index));
                    
                    thumbnailsGrid.appendChild(thumbnailItem);
                });
            }
            
            // Display main image
            function displayImage(index) {
                if (index < 0 || index >= currentImages.length) return;
                
                currentImageIndex = index;
                
                const image = currentImages[index];
                mainImage.src = image.large || image.medium_large || image.medium;
                mainImage.alt = image.title || `${manufacturer} ${model} - Image ${index + 1}`;
                
                // Update active thumbnail
                plugin.querySelectorAll('.thumbnail-item').forEach((item, idx) => {
                    item.classList.toggle('active', idx === index);
                });
                
                // Update overlay if one is active
                if (currentOverlay) {
                    applyOverlay(currentOverlay);
                }
            }
            
            // Apply overlay to current image
            function applyOverlay(overlayKey) {
                if (!currentImages[currentImageIndex]) return;
                
                const imageUrl = currentImages[currentImageIndex].large || 
                               currentImages[currentImageIndex].medium_large || 
                               currentImages[currentImageIndex].medium;
                
                // Construct overlay URL
                const overlayUrl = `${overlayUrls[overlayKey]}&car=${encodeURIComponent(imageUrl)}`;
                overlayImage.src = overlayUrl;
                overlayContainer.classList.add('active');
                
                // Update overlay type display
                overlayType.textContent = overlayKey.replace('.png', '').toUpperCase();
                
                // Update active overlay button
                overlayBtns.forEach(btn => {
                    btn.classList.toggle('active', btn.dataset.overlay === overlayKey);
                });
            }
            
            // Reset overlay
            function resetOverlay() {
                overlayContainer.classList.remove('active');
                overlayImage.src = '';
                currentOverlay = null;
                overlayType.textContent = 'None';
                
                overlayBtns.forEach(btn => btn.classList.remove('active'));
            }
            
            // Download current image with overlay
            function downloadCurrentImage() {
                if (!currentImages[currentImageIndex]) return;
                
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                const mainImg = new Image();
                const overlayImg = new Image();
                
                mainImg.crossOrigin = 'anonymous';
                overlayImg.crossOrigin = 'anonymous';
                
                mainImg.onload = function() {
                    canvas.width = mainImg.width;
                    canvas.height = mainImg.height;
                    ctx.drawImage(mainImg, 0, 0);
                    
                    if (currentOverlay) {
                        overlayImg.onload = function() {
                            ctx.drawImage(overlayImg, 0, 0, canvas.width, canvas.height);
                            finalizeDownload();
                        };
                        
                        const imageUrl = currentImages[currentImageIndex].large || 
                                       currentImages[currentImageIndex].medium_large || 
                                       currentImages[currentImageIndex].medium;
                        const overlayUrl = `${overlayUrls[currentOverlay]}&car=${encodeURIComponent(imageUrl)}`;
                        overlayImg.src = overlayUrl;
                    } else {
                        finalizeDownload();
                    }
                };
                
                mainImg.src = currentImages[currentImageIndex].large || 
                             currentImages[currentImageIndex].medium_large || 
                             currentImages[currentImageIndex].medium;
                
                function finalizeDownload() {
                    const link = document.createElement('a');
                    link.download = `${manufacturer}-${model}-image-${currentImageIndex + 1}-${currentOverlay || 'no-overlay'}.png`;
                    link.href = canvas.toDataURL('image/png');
                    link.click();
                }
            }
            
            // UI Helper Functions
            function showLoading() {
                loading.style.display = 'block';
                galleryContainer.style.display = 'none';
                modelsGridView.style.display = 'none';
                emptyState.style.display = 'none';
                carInfoHeader.style.display = 'none';
            }
            
            function hideLoading() {
                loading.style.display = 'none';
            }
            
            function showError(message) {
                errorMessage.textContent = `Error: ${message}`;
                errorMessage.style.display = 'block';
            }
            
            function hideError() {
                errorMessage.style.display = 'none';
            }
            
            function showEmptyState() {
                galleryContainer.style.display = 'none';
                modelsGridView.style.display = 'none';
                emptyState.style.display = 'block';
                carInfoHeader.style.display = 'none';
            }
            
            // Overlay button click handlers
            overlayBtns.forEach(btn => {
                btn.addEventListener('click', () => {
                    const overlayKey = btn.dataset.overlay;
                    
                    if (currentOverlay === overlayKey) {
                        resetOverlay();
                    } else {
                        currentOverlay = overlayKey;
                        applyOverlay(overlayKey);
                    }
                });
            });
            
            // Download button
            downloadBtn.addEventListener('click', downloadCurrentImage);
            
            // Keyboard navigation - scoped to plugin
            document.addEventListener('keydown', (e) => {
                if (!currentImages.length || !plugin.contains(document.activeElement)) return;
                
                switch(e.key) {
                    case 'ArrowLeft':
                        e.preventDefault();
                        displayImage((currentImageIndex - 1 + currentImages.length) % currentImages.length);
                        break;
                    case 'ArrowRight':
                        e.preventDefault();
                        displayImage((currentImageIndex + 1) % currentImages.length);
                        break;
                    case 'Escape':
                        resetOverlay();
                        break;
                    case '1':
                        applyOverlay('tin.png');
                        break;
                    case '2':
                        applyOverlay('pen.png');
                        break;
                    case '3':
                        applyOverlay('spray.png');
                        break;
                    case '4':
                        applyOverlay('bottle.png');
                        break;
                    case '0':
                        resetOverlay();
                        break;
                }
            });
            
            // Handle browser back/forward navigation
            window.addEventListener('popstate', () => {
                fetchCarImages();
            });
            
            // Load images on page load
            window.addEventListener('DOMContentLoaded', () => {
                fetchCarImages();
            });
            
            // Expose public API for external use
            window.carGalleryPlugin = {
                refresh: fetchCarImages,
                setOverlay: applyOverlay,
                resetOverlay: resetOverlay,
                downloadImage: downloadCurrentImage,
                nextImage: () => displayImage((currentImageIndex + 1) % currentImages.length),
                prevImage: () => displayImage((currentImageIndex - 1 + currentImages.length) % currentImages.length)
            };
        })();
    </script>
</body>
</html>