<?php
/**
 * Vue App Mount Points
 * Controls where the Vue app is mounted in the WordPress admin
 */

// Prevent direct access to this file
if (!defined('ABSPATH')) {
    exit;
}

// Register scripts for mount points
function smartpress_register_mount_scripts() {
    // Register mount point ready script
    wp_register_script('smartpress-mount-ready', '', [], SMARTPRESS_APP_VERSION, true);
    wp_add_inline_script('smartpress-mount-ready', '
        window.vueAppMountReady = true;
        // console.log("Mount point added, waiting for Vue script...");
    ');
    
    // Register debug script if needed
    if (SMARTPRESS_ENABLE_DEBUG) {
        wp_register_script('smartpress-mount-debug', '', [], SMARTPRESS_APP_VERSION, true);
        wp_add_inline_script('smartpress-mount-debug', '
            // Check if mounting point exists
            console.log("WordPress admin loaded, checking for Vue mount point:", {
                mountExists: document.getElementById("vue-wp-app") !== null,
                url: window.location.href,
                vueReady: window.vueAppMountReady
            });

            // Add event listener for Vue script load
            document.addEventListener("DOMContentLoaded", function() {
                if (!document.getElementById("vue-wp-app")) {
                    console.error("Vue mounting point not found!");
                }
            });
        ');
    }
}
add_action('wp_enqueue_scripts', 'smartpress_register_mount_scripts');
add_action('admin_enqueue_scripts', 'smartpress_register_mount_scripts');

// Add the Vue mounting point to admin header (default location)
function smartpress_admin_header() {
    ?>
    <div id="vue-wp-app"></div>
    <?php
    // Enqueue the mount ready script
    wp_enqueue_script('smartpress-mount-ready');
}

// By default, mount on admin notices
// Comment this out if you only want the app on the plugin settings page
if(SMARTPRESS_ENABLE_BACKEND_GLOBAL){
    // DEFAULT MOUNT POINT
    // Add the Vue to the admin dashboard Global notices
    // add_action('admin_notices', 'smartpress_admin_header');


    // Add the Vue mounting point to Elementor editor
    if (defined('ELEMENTOR_VERSION')) {
        add_action('elementor/editor/footer', 'smartpress_admin_header');
    }
    // to add integration with woocommerce and other plugins
    add_action('admin_footer', 'smartpress_admin_header');
}

// Add debug and initialization code
function smartpress_admin_debug() {
    // Enqueue the debug script
    wp_enqueue_script('smartpress-mount-debug');
}

if(SMARTPRESS_ENABLE_DEBUG){
    add_action('admin_footer', 'smartpress_admin_debug');
}

// Frontend shortcode
function smartpress_shortcode() {
    wp_enqueue_script('smartpress-mount-ready');
    return '<div id="vue-wp-app"></div>';
}

if (SMARTPRESS_ENABLE_FRONTEND) {
    add_shortcode('smartpress_app', 'smartpress_shortcode'); 
}