<?php

namespace Trstemp\StarterTemplates;

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

class Trstemp_PreviewListener {
    
    public function __construct() {
        add_action( 'wp_enqueue_scripts', array( $this, 'register_and_add_inline_script' ) );
    }
    
    /**
     * Register script and add inline script properly
     */
    public function register_and_add_inline_script() {
        // Register a dummy handle
        wp_register_script( 'trstemp-preview-handle', '', array(), '1.0.5', true );
        wp_enqueue_script( 'trstemp-preview-handle' );
        
        // Add inline script properly
        $inline_script = "
            (function() {
                console.log('TRSTEMP: Preview listener loaded');
                window.addEventListener('message', function(event) {
                    console.log('TRSTEMP: Message received:', event.data);
                    if (event.data && event.data.type === 'INJECT_CSS') {
                        console.log('TRSTEMP: Injecting CSS:', event.data.css);
                        let existingStyle = document.getElementById('trstemp-preview-styles');
                        if (existingStyle) {
                            existingStyle.remove();
                        }
                        let style = document.createElement('style');
                        style.id = 'trstemp-preview-styles';
                        style.textContent = event.data.css;
                        document.head.appendChild(style);
                        console.log('TRSTEMP: CSS applied successfully');
                    } else if (event.data && event.data.type === 'REMOVE_CSS') {
                        console.log('TRSTEMP: Removing custom CSS');
                        let style = document.getElementById('trstemp-preview-styles');
                        if (style) {
                            style.remove();
                            console.log('TRSTEMP: Custom CSS removed successfully');
                        }
                    }
                });
            })();
        ";
        
        wp_add_inline_script( 'trstemp-preview-handle', $inline_script );
    }
}