<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * VMO Animated Overlays System
 * 
 * Generates and manages transparent animated overlays for websites:
 * - Clouds, smoke, particles, ripples, sparkles, fog, etc.
 * - Interactive mouse/touch displacement effects
 * - Parallax scrolling animations
 * - Context-aware overlay suggestions
 * 
 * Uses GPT Image 1.5 for generating transparent overlay assets
 * 
 * @package VMO_AI_Builder
 * @since 1.0.0
 */

if (!defined('ABSPATH')) {
    exit;
}

class VMO_Animated_Overlays {
    
    /**
     * OpenAI API URL for image generation
     */
    private $image_api_url = 'https://api.openai.com/v1/images/generations';
    
    /**
     * Available overlay types with their properties
     */
    private $overlay_types = array(
        'clouds' => array(
            'name' => 'Clouds',
            'description' => 'Realistic moving clouds',
            'suitable_for' => array('outdoor', 'sky', 'building_exterior', 'landscape', 'aerial', 'rooftop'),
            'not_suitable_for' => array('indoor', 'interior', 'office', 'room', 'studio'),
            'default_speed' => 0.3,
            'default_opacity' => 0.7,
            'interactive' => true,
            'layers' => 3
        ),
        'smoke' => array(
            'name' => 'Smoke',
            'description' => 'Ethereal smoke wisps',
            'suitable_for' => array('atmospheric', 'dramatic', 'dark', 'mysterious', 'industrial', 'fire', 'cooking'),
            'not_suitable_for' => array('clean', 'medical', 'children', 'bright_cheerful'),
            'default_speed' => 0.5,
            'default_opacity' => 0.5,
            'interactive' => true,
            'layers' => 2
        ),
        'particles' => array(
            'name' => 'Particles',
            'description' => 'Floating light particles',
            'suitable_for' => array('magical', 'technology', 'luxury', 'celebration', 'fantasy', 'space'),
            'not_suitable_for' => array('minimalist', 'corporate_formal'),
            'default_speed' => 0.8,
            'default_opacity' => 0.6,
            'interactive' => true,
            'layers' => 2
        ),
        'sparkles' => array(
            'name' => 'Sparkles',
            'description' => 'Glittering light flares',
            'suitable_for' => array('jewelry', 'luxury', 'beauty', 'fashion', 'celebration', 'wedding'),
            'not_suitable_for' => array('industrial', 'medical', 'legal'),
            'default_speed' => 1.0,
            'default_opacity' => 0.8,
            'interactive' => true,
            'layers' => 2
        ),
        'fog' => array(
            'name' => 'Fog',
            'description' => 'Ground-level atmospheric mist',
            'suitable_for' => array('forest', 'mountain', 'mysterious', 'horror', 'nature', 'dawn', 'dusk'),
            'not_suitable_for' => array('indoor', 'bright', 'cheerful'),
            'default_speed' => 0.2,
            'default_opacity' => 0.4,
            'interactive' => false,
            'layers' => 2
        ),
        'ripples' => array(
            'name' => 'Water Ripples',
            'description' => 'Interactive water ripple effects',
            'suitable_for' => array('water', 'spa', 'pool', 'beach', 'ocean', 'wellness', 'calm'),
            'not_suitable_for' => array('fire', 'desert', 'industrial'),
            'default_speed' => 0.6,
            'default_opacity' => 0.5,
            'interactive' => true,
            'layers' => 1
        ),
        'bubbles' => array(
            'name' => 'Bubbles',
            'description' => 'Floating translucent bubbles',
            'suitable_for' => array('underwater', 'playful', 'children', 'cleaning', 'soap', 'fun'),
            'not_suitable_for' => array('formal', 'corporate', 'serious'),
            'default_speed' => 0.4,
            'default_opacity' => 0.7,
            'interactive' => true,
            'layers' => 2
        ),
        'snow' => array(
            'name' => 'Snow',
            'description' => 'Falling snowflakes',
            'suitable_for' => array('winter', 'christmas', 'holiday', 'cold', 'mountain'),
            'not_suitable_for' => array('summer', 'tropical', 'beach'),
            'default_speed' => 0.5,
            'default_opacity' => 0.8,
            'interactive' => true,
            'layers' => 3
        ),
        'rain' => array(
            'name' => 'Rain',
            'description' => 'Falling rain drops',
            'suitable_for' => array('storm', 'dramatic', 'moody', 'nature', 'urban'),
            'not_suitable_for' => array('indoor', 'sunny', 'bright_cheerful'),
            'default_speed' => 1.5,
            'default_opacity' => 0.6,
            'interactive' => false,
            'layers' => 3
        ),
        'leaves' => array(
            'name' => 'Falling Leaves',
            'description' => 'Autumn leaves drifting down',
            'suitable_for' => array('autumn', 'fall', 'nature', 'garden', 'park', 'forest'),
            'not_suitable_for' => array('spring', 'summer', 'indoor', 'modern_tech'),
            'default_speed' => 0.4,
            'default_opacity' => 0.9,
            'interactive' => true,
            'layers' => 2
        ),
        'dust' => array(
            'name' => 'Dust Motes',
            'description' => 'Floating dust particles in light',
            'suitable_for' => array('vintage', 'nostalgic', 'sunbeam', 'atmospheric', 'old'),
            'not_suitable_for' => array('clean', 'modern', 'medical', 'tech'),
            'default_speed' => 0.2,
            'default_opacity' => 0.5,
            'interactive' => true,
            'layers' => 1
        ),
        'aurora' => array(
            'name' => 'Aurora',
            'description' => 'Northern lights effect',
            'suitable_for' => array('night', 'space', 'arctic', 'magical', 'cosmic'),
            'not_suitable_for' => array('daytime', 'indoor', 'tropical'),
            'default_speed' => 0.15,
            'default_opacity' => 0.6,
            'interactive' => false,
            'layers' => 2
        ),
        'fireflies' => array(
            'name' => 'Fireflies',
            'description' => 'Glowing firefly lights',
            'suitable_for' => array('night', 'garden', 'summer', 'magical', 'romantic', 'forest'),
            'not_suitable_for' => array('daytime', 'indoor', 'winter', 'urban'),
            'default_speed' => 0.6,
            'default_opacity' => 0.8,
            'interactive' => true,
            'layers' => 2
        ),
        'embers' => array(
            'name' => 'Embers',
            'description' => 'Floating fire embers',
            'suitable_for' => array('fire', 'campfire', 'forge', 'dramatic', 'warm'),
            'not_suitable_for' => array('water', 'cold', 'medical', 'clean'),
            'default_speed' => 0.7,
            'default_opacity' => 0.9,
            'interactive' => true,
            'layers' => 2
        ),
        'petals' => array(
            'name' => 'Flower Petals',
            'description' => 'Floating flower petals',
            'suitable_for' => array('spring', 'wedding', 'romantic', 'beauty', 'spa', 'garden'),
            'not_suitable_for' => array('industrial', 'tech', 'winter', 'formal_corporate'),
            'default_speed' => 0.35,
            'default_opacity' => 0.85,
            'interactive' => true,
            'layers' => 2
        )
    );
    
    /**
     * Scene type to overlay mapping for AI guidance
     */
    private $scene_overlay_map = array(
        // Outdoor scenes
        'outdoor_sky' => array('clouds', 'aurora'),
        'outdoor_building' => array('clouds'),
        'outdoor_night' => array('fireflies', 'aurora', 'particles'),
        'nature_forest' => array('fog', 'leaves', 'fireflies', 'dust'),
        'nature_water' => array('ripples', 'fog'),
        'nature_beach' => array('bubbles', 'particles'),
        'nature_mountain' => array('clouds', 'fog', 'snow'),
        'nature_garden' => array('petals', 'leaves', 'fireflies', 'bubbles'),
        
        // Weather/Atmosphere
        'weather_storm' => array('rain', 'clouds'),
        'weather_winter' => array('snow', 'fog'),
        'weather_autumn' => array('leaves', 'fog'),
        
        // Indoor/Special
        'luxury_interior' => array('sparkles', 'particles', 'dust'),
        'spa_wellness' => array('ripples', 'fog', 'petals'),
        'tech_modern' => array('particles'),
        'romantic' => array('petals', 'sparkles', 'fireflies'),
        'celebration' => array('sparkles', 'particles', 'bubbles'),
        'dramatic' => array('smoke', 'embers', 'fog'),
        'magical' => array('particles', 'sparkles', 'fireflies', 'aurora')
    );
    
    /**
     * Constructor
     */
    public function __construct() {
        // Register AJAX handlers
        add_action('wp_ajax_vmo_generate_overlay', array($this, 'ajax_generate_overlay'));
        add_action('wp_ajax_vmo_analyze_scene_for_overlay', array($this, 'ajax_analyze_scene'));
        add_action('wp_ajax_vmo_get_overlay_types', array($this, 'ajax_get_overlay_types'));
        
        // Register shortcode for overlays
        add_shortcode('vmo_overlay', array($this, 'render_overlay_shortcode'));
    }

    private function prepare_long_running_runtime() {
        if (function_exists('set_time_limit')) {
            @set_time_limit(0);
        }
        if (function_exists('ignore_user_abort')) {
            @ignore_user_abort(true);
        }
        if (function_exists('ini_set')) {
            @ini_set('memory_limit', '512M');
        }
    }
    
    /**
     * Get all available overlay types
     */
    public function get_overlay_types() {
        return $this->overlay_types;
    }
    
    /**
     * Analyze scene/content to suggest appropriate overlays
     * 
     * @param string $scene_description Description of the scene or image
     * @param string $business_type Type of business
     * @param array $context Additional context
     * @return array Suggested overlays with suitability scores
     */
    public function analyze_scene_for_overlays($scene_description, $business_type = '', $context = array()) {
        $suggestions = array();
        $scene_lower = strtolower($scene_description);
        $business_lower = strtolower($business_type);
        
        // Keywords that indicate outdoor/sky scenes (good for clouds)
        $outdoor_sky_keywords = array(
            'sky', 'building', 'exterior', 'outdoor', 'rooftop', 'aerial',
            'cityscape', 'skyline', 'tower', 'skyscraper', 'office building',
            'storefront', 'facade', 'architecture', 'landmark'
        );
        
        // Keywords that indicate indoor scenes (avoid clouds)
        $indoor_keywords = array(
            'indoor', 'interior', 'room', 'office', 'living room', 'bedroom',
            'kitchen', 'bathroom', 'studio', 'inside', 'table', 'desk',
            'couch', 'furniture', 'ceiling', 'wall'
        );
        
        // Check for indoor scene - clouds would be inappropriate
        $is_indoor = false;
        foreach ($indoor_keywords as $keyword) {
            if (strpos($scene_lower, $keyword) !== false) {
                $is_indoor = true;
                break;
            }
        }
        
        // Analyze each overlay type
        foreach ($this->overlay_types as $type => $config) {
            $score = 0;
            $reasons = array();
            
            // Check suitable_for matches
            foreach ($config['suitable_for'] as $suitable) {
                if (strpos($scene_lower, $suitable) !== false || 
                    strpos($business_lower, $suitable) !== false) {
                    $score += 25;
                    $reasons[] = "Matches theme: $suitable";
                }
            }
            
            // Check not_suitable_for (penalties)
            foreach ($config['not_suitable_for'] as $unsuitable) {
                if (strpos($scene_lower, $unsuitable) !== false) {
                    $score -= 50;
                    $reasons[] = "Not suitable for: $unsuitable";
                }
            }
            
            // Special handling for clouds
            if ($type === 'clouds') {
                if ($is_indoor) {
                    $score = -100; // Strongly discourage clouds indoors
                    $reasons[] = "Indoor scene detected - clouds inappropriate";
                } else {
                    foreach ($outdoor_sky_keywords as $keyword) {
                        if (strpos($scene_lower, $keyword) !== false) {
                            $score += 30;
                            $reasons[] = "Outdoor/sky scene detected";
                            break;
                        }
                    }
                }
            }
            
            // Industry-specific bonuses
            $industry_bonuses = array(
                'spa' => array('ripples' => 40, 'fog' => 30, 'petals' => 25),
                'jewelry' => array('sparkles' => 50, 'particles' => 30),
                'beauty' => array('sparkles' => 40, 'petals' => 35, 'particles' => 20),
                'wedding' => array('petals' => 50, 'sparkles' => 40, 'bubbles' => 25),
                'restaurant' => array('smoke' => 30, 'embers' => 25),
                'tech' => array('particles' => 40),
                'luxury' => array('sparkles' => 45, 'particles' => 35),
                'winter' => array('snow' => 60, 'fog' => 20),
                'christmas' => array('snow' => 70, 'sparkles' => 40)
            );
            
            foreach ($industry_bonuses as $industry => $bonuses) {
                if (strpos($business_lower, $industry) !== false || 
                    strpos($scene_lower, $industry) !== false) {
                    if (isset($bonuses[$type])) {
                        $score += $bonuses[$type];
                        $reasons[] = "Industry match bonus: $industry";
                    }
                }
            }
            
            // Only include if score is positive
            if ($score > 0) {
                $suggestions[$type] = array(
                    'type' => $type,
                    'name' => $config['name'],
                    'description' => $config['description'],
                    'score' => min(100, max(0, $score)),
                    'reasons' => $reasons,
                    'config' => $config
                );
            }
        }
        
        // Sort by score descending
        uasort($suggestions, function($a, $b) {
            return $b['score'] - $a['score'];
        });
        
        return array_values($suggestions);
    }
    
    /**
     * Check if an overlay is appropriate for a given context
     * 
     * @param string $overlay_type The overlay type to check
     * @param string $scene_description The scene description
     * @return array Appropriateness result with reason
     */
    public function is_overlay_appropriate($overlay_type, $scene_description) {
        if (!isset($this->overlay_types[$overlay_type])) {
            return array(
                'appropriate' => false,
                'reason' => 'Unknown overlay type'
            );
        }
        
        $config = $this->overlay_types[$overlay_type];
        $scene_lower = strtolower($scene_description);
        
        // Check for disqualifying factors
        foreach ($config['not_suitable_for'] as $unsuitable) {
            if (strpos($scene_lower, $unsuitable) !== false) {
                return array(
                    'appropriate' => false,
                    'reason' => "This overlay is not suitable for {$unsuitable} scenes",
                    'alternative' => $this->suggest_alternative($overlay_type, $scene_description)
                );
            }
        }
        
        // Check for qualifying factors
        foreach ($config['suitable_for'] as $suitable) {
            if (strpos($scene_lower, $suitable) !== false) {
                return array(
                    'appropriate' => true,
                    'reason' => "Excellent match - scene contains {$suitable} elements"
                );
            }
        }
        
        // No strong match or mismatch - neutral
        return array(
            'appropriate' => true,
            'reason' => 'No conflicts detected, overlay may be used if specifically requested',
            'warning' => 'Consider if this overlay fits the visual style of the content'
        );
    }
    
    /**
     * Suggest an alternative overlay when requested one is inappropriate
     */
    private function suggest_alternative($requested_type, $scene_description) {
        $suggestions = $this->analyze_scene_for_overlays($scene_description);
        
        if (!empty($suggestions) && $suggestions[0]['type'] !== $requested_type) {
            return $suggestions[0];
        }
        
        return null;
    }
    
    /**
     * Generate overlay image using GPT Image 1.5
     * 
     * @param string $type Overlay type
     * @param string $style Visual style (realistic, stylized, etc.)
     * @param array $options Additional options
     * @return array Result with image data or error
     */
    public function generate_overlay_image($type, $style = 'realistic', $options = array()) {
        $this->prepare_long_running_runtime();

        $api_key = get_option('vmo_openai_api_key');
        
        if (empty($api_key)) {
            return array(
                'success' => false,
                'error' => 'AI API key not configured'
            );
        }
        
        if (!isset($this->overlay_types[$type])) {
            return array(
                'success' => false,
                'error' => 'Unknown overlay type: ' . $type
            );
        }
        
        // Build prompt based on overlay type
        $prompts = array(
            'clouds' => 'Multiple wispy realistic cumulus clouds with soft edges, scattered across the frame, isolated on transparent background, photorealistic fluffy white clouds, varying sizes, seamless tileable edges',
            'smoke' => 'Elegant wisps of translucent smoke curling and flowing, ethereal mist tendrils, isolated on transparent background, soft gray smoke, atmospheric',
            'particles' => 'Hundreds of tiny floating glowing particles, magical dust specks, light orbs scattered randomly at various distances, isolated on transparent background, bokeh effect',
            'sparkles' => 'Brilliant glittering sparkles and diamond light flares, magical shimmer effect, star-like glints, isolated on transparent background, luxury feel',
            'fog' => 'Soft atmospheric low-lying fog layer, misty ground effect rolling across, isolated on transparent background, realistic morning mist',
            'ripples' => 'Concentric water ripples expanding outward, circular wave patterns, isolated on transparent background, realistic water surface effect',
            'bubbles' => 'Assorted translucent soap bubbles floating, iridescent spheres with rainbow reflections, various sizes, isolated on transparent background',
            'snow' => 'Falling white snowflakes of various sizes and shapes, winter snow particles, isolated on transparent background, realistic gentle snowfall',
            'rain' => 'Diagonal rain drops and streaks, realistic rainfall effect, motion blur, isolated on transparent background, stormy rain',
            'leaves' => 'Scattered falling autumn leaves in red, orange and gold colors, natural foliage tumbling, isolated on transparent background',
            'dust' => 'Floating dust particles illuminated by light beam, atmospheric dust motes dancing, isolated on transparent background, vintage feel',
            'aurora' => 'Northern lights aurora borealis effect, flowing green and purple light ribbons, isolated on transparent background, cosmic',
            'fireflies' => 'Glowing firefly lights scattered in darkness, bioluminescent specks, isolated on transparent background, magical night',
            'embers' => 'Floating red and orange fire embers, glowing sparks rising, isolated on transparent background, warm campfire feel',
            'petals' => 'Scattered falling flower petals in pink and white, cherry blossom petals floating, isolated on transparent background, romantic spring'
        );
        
        $prompt = isset($prompts[$type]) ? $prompts[$type] : $prompts['particles'];
        $prompt .= ', ' . $style . ' style, high quality, suitable for web overlay animation';
        
        // ✅ TOKEN DEDUCTION v8.1.0: Charge for overlay image generation
        $user_id = get_current_user_id();
        if (function_exists('vmo_deduct_tokens')) {
            $token_cost = function_exists('vmo_get_token_cost') ? (int) vmo_get_token_cost('dalle_image') : 1080;
            if (!vmo_deduct_tokens($user_id, $token_cost, 'gpt_image', 'Animated overlay image: ' . $type)) {
                return array(
                    'success' => false,
                    'error' => 'Insufficient tokens for overlay generation'
                );
            }
        }
        
        // Build request
        $request_body = array(
            'model' => 'gpt-image-1',
            'prompt' => $prompt,
            'n' => 1,
            'size' => isset($options['size']) ? $options['size'] : '1024x1024',
            'quality' => 'high',
            'output_format' => 'png',
            'background' => 'transparent'
        );
        
        $response = wp_remote_post($this->image_api_url, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type' => 'application/json'
            ),
            'body' => json_encode($request_body),
            'timeout' => 120
        ));
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'error' => $response->get_error_message()
            );
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);
        
        if ($response_code !== 200) {
            return array(
                'success' => false,
                'error' => 'API error: ' . $response_body
            );
        }
        
        $data = json_decode($response_body, true);
        
        if (isset($data['data'][0]['b64_json'])) {
            // Save to media library
            $image_url = $this->save_overlay_image($data['data'][0]['b64_json'], $type);
            
            return array(
                'success' => true,
                'type' => $type,
                'image_url' => $image_url,
                'base64' => 'data:image/png;base64,' . $data['data'][0]['b64_json'],
                'config' => $this->overlay_types[$type]
            );
        }
        
        return array(
            'success' => false,
            'error' => 'No image data in response'
        );
    }
    
    /**
     * Save overlay image to media library
     */
    private function save_overlay_image($base64_data, $type) {
        $upload_dir = wp_upload_dir();
        $filename = 'vmo-overlay-' . $type . '-' . uniqid() . '.png';
        $file_path = $upload_dir['path'] . '/' . $filename;
        
        // Decode and save
        $image_data = base64_decode($base64_data); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- data decoding
        vmo_get_filesystem()->put_contents($file_path, $image_data, FS_CHMOD_FILE);
        
        // Add to media library
        $attachment = array(
            'post_mime_type' => 'image/png',
            'post_title' => 'VMO Overlay - ' . ucfirst($type),
            'post_content' => '',
            'post_status' => 'inherit'
        );
        
        $attach_id = wp_insert_attachment($attachment, $file_path);
        
        if (!is_wp_error($attach_id)) {
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
            wp_update_attachment_metadata($attach_id, $attach_data);
            
            // Add meta to identify as overlay
            update_post_meta($attach_id, '_vmo_overlay_type', $type);
            update_post_meta($attach_id, '_vmo_overlay_config', $this->overlay_types[$type]);
            
            return wp_get_attachment_url($attach_id);
        }
        
        return $upload_dir['url'] . '/' . $filename;
    }
    
    /**
     * Generate overlay configuration for JavaScript
     */
    public function get_overlay_config($type, $custom_options = array()) {
        if (!isset($this->overlay_types[$type])) {
            return null;
        }
        
        $base_config = $this->overlay_types[$type];
        
        $config = array(
            'type' => $type,
            'name' => $base_config['name'],
            'speed' => isset($custom_options['speed']) ? $custom_options['speed'] : $base_config['default_speed'],
            'opacity' => isset($custom_options['opacity']) ? $custom_options['opacity'] : $base_config['default_opacity'],
            'interactive' => isset($custom_options['interactive']) ? $custom_options['interactive'] : $base_config['interactive'],
            'layers' => isset($custom_options['layers']) ? $custom_options['layers'] : $base_config['layers'],
            'parallax' => isset($custom_options['parallax']) ? $custom_options['parallax'] : true,
            'mouse_influence' => isset($custom_options['mouse_influence']) ? $custom_options['mouse_influence'] : 0.3,
            'touch_enabled' => isset($custom_options['touch_enabled']) ? $custom_options['touch_enabled'] : true
        );
        
        return $config;
    }
    
    /**
     * AJAX: Generate overlay image
     */
    public function ajax_generate_overlay() {
        $this->prepare_long_running_runtime();

        check_ajax_referer('vmo_builder_nonce', 'security');
        
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => 'Insufficient permissions'));
        }
        
        $type = sanitize_text_field(wp_unslash($_POST['type']));
        $style = isset($_POST['style']) ? sanitize_text_field(wp_unslash($_POST['style'])) : 'realistic';
        $options = isset($_POST['options']) ? map_deep(wp_unslash($_POST['options']), 'sanitize_text_field') : array();
        
        $result = $this->generate_overlay_image($type, $style, $options);
        
        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result);
        }
    }
    
    /**
     * AJAX: Analyze scene for overlay suggestions
     */
    public function ajax_analyze_scene() {
        check_ajax_referer('vmo_builder_nonce', 'security');
        
        $scene = sanitize_text_field(wp_unslash($_POST['scene_description']));
        $business = isset($_POST['business_type']) ? sanitize_text_field(wp_unslash($_POST['business_type'])) : '';
        
        $suggestions = $this->analyze_scene_for_overlays($scene, $business);
        
        wp_send_json_success(array(
            'suggestions' => $suggestions
        ));
    }
    
    /**
     * AJAX: Get available overlay types
     */
    public function ajax_get_overlay_types() {
        check_ajax_referer('vmo_builder_nonce', 'security');
        
        wp_send_json_success(array(
            'types' => $this->overlay_types
        ));
    }
    
    /**
     * Render overlay shortcode
     * 
     * Usage: [vmo_overlay type="clouds" speed="0.3" opacity="0.7" interactive="true"]
     */
    public function render_overlay_shortcode($atts) {
        $atts = shortcode_atts(array(
            'type' => 'particles',
            'image' => '',
            'speed' => '',
            'opacity' => '',
            'interactive' => 'true',
            'parallax' => 'true',
            'mouse_influence' => '0.3',
            'class' => ''
        ), $atts);
        
        $type = sanitize_text_field($atts['type']);
        
        if (!isset($this->overlay_types[$type])) {
            return '<!-- Unknown overlay type: ' . esc_html($type) . ' -->';
        }
        
        $config = $this->get_overlay_config($type, array(
            'speed' => $atts['speed'] ? floatval($atts['speed']) : null,
            'opacity' => $atts['opacity'] ? floatval($atts['opacity']) : null,
            'interactive' => $atts['interactive'] === 'true',
            'parallax' => $atts['parallax'] === 'true',
            'mouse_influence' => floatval($atts['mouse_influence'])
        ));
        
        $config_json = esc_attr(json_encode($config));
        $image_url = esc_url($atts['image']);
        $class = esc_attr($atts['class']);
        
        return sprintf(
            '<div class="vmo-animated-overlay %s" data-vmo-overlay="%s" data-overlay-type="%s" data-overlay-image="%s"></div>',
            $class,
            $config_json,
            esc_attr($type),
            $image_url
        );
    }
    
    /**
     * Get AI prompt guidance for overlay selection
     * Used by the consultation system to make smart overlay decisions
     */
    public function get_ai_guidance() {
        return array(
            'overlay_types' => $this->overlay_types,
            'scene_mappings' => $this->scene_overlay_map,
            'rules' => array(
                'NEVER place clouds over indoor scenes (rooms, offices, interiors)',
                'ONLY use clouds when sky or outdoor building exterior is visible',
                'Ripples are ONLY for water-related imagery (pools, spas, beaches)',
                'Snow is ONLY for winter/holiday themes',
                'Smoke should be used sparingly for dramatic or atmospheric scenes',
                'Sparkles work best for luxury, jewelry, beauty, wedding themes',
                'Particles are versatile but avoid in minimalist designs',
                'Fog works for nature, mysterious, or dawn/dusk scenes',
                'Leaves are ONLY for autumn/fall themed content',
                'When in doubt, suggest particles as they are most versatile',
                'Always respect user preferences - if they specifically request an overlay, comply even if unusual'
            ),
            'default_behavior' => 'Overlays should enhance, not distract. Use sparingly and purposefully.'
        );
    }
}

// Initialize
new VMO_Animated_Overlays();
