<?php

namespace FleekDash\Admin;

use FleekDash\Core\ResourceBlocker;
use FleekDash\Libs\Assets as AssetsLib;

class AdminTheme
{
    private $resourceBlocker;

    public function __construct()
    {
        // Initialize resource blocker with explicit configuration
        $this->resourceBlocker = new ResourceBlocker([
            'allowed_styles' => [], // Legacy styles removed
            'allowed_scripts' => [
                'fleekdash',
                'fleekdash-theme-shortcut',
                'fleekdash-iframe',
                'fleekdash-iframe-interactions',
                'fleekdash-iframe-navigation',
                'fleekdash-essential-iframe'
            ], // Allow FleekDash scripts but block external plugins
            'condition' => function () {
                return isset($_GET['page']) && strpos($_GET['page'], 'fleekdash') === 0;
            },
            'block_patterns' => ['fleekdash'], // Only block on main FleekDash pages
            'block_third_party' => true, // Enable third party script blocking
            'allowed_paths' => array_values(array_filter([
                plugin_dir_url(FLEEKDASH_PLUGIN_FILE),
                AssetsLib\getViteDevServerOrigin(),
            ])),

        ]);

        \add_action('admin_head', [$this, 'removeAdminMenuStyles']);
        \add_action('admin_body_class', [$this, 'addBodyClass']);
        \add_action('admin_menu', [$this, 'removeAdminMenu'], 999);
        \add_action('admin_footer', [$this, 'addDebugInfo']);
    }

    /**
     * Remove default admin menu chrome styles on FleekDash screens.
     */
    public function removeAdminMenuStyles(): void
    {
        if (!$this->isFleekdashPage()) {
            return;
        }

        $this->maybeExitNestedFleekdashShell();
        $this->echoFleekdashLayoutStyles($this->shouldShowAdminBarForCurrentScreen());
    }

    /**
     * Block loading the main React shell inside a nested iframe (Sec-Fetch-Dest: iframe only).
     */
    private function maybeExitNestedFleekdashShell(): void
    {
        $secFetchDest = isset($_SERVER['HTTP_SEC_FETCH_DEST'])
            ? strtolower((string) $_SERVER['HTTP_SEC_FETCH_DEST'])
            : '';
        // Positive form: 404 only when all three hold (equivalent to early-return on NOT this).
        $shouldBlockNestedShell = $secFetchDest === 'iframe'
            && isset($_GET['page'])
            && $_GET['page'] === 'fleekdash';
        if (!$shouldBlockNestedShell) {
            return;
        }

        include_once FLEEKDASH_DIR . 'views/404.php';
        exit;
    }

    private function shouldShowAdminBarForCurrentScreen(): bool
    {
        $isReactApp = isset($_GET['page']) && $_GET['page'] === 'fleekdash';
        if ($isReactApp) {
            return false;
        }

        $adminbarParam = isset($_GET['adminbar']) ? \sanitize_text_field($_GET['adminbar']) : '';

        return $adminbarParam !== 'false' && $adminbarParam !== 'off';
    }

    private function echoFleekdashLayoutStyles(bool $showAdminbar): void
    {
        echo '<style>

 /* Not logged in; behavior differs from iframe.php */


  /* Hide WordPress Auth Check modal in iframe context.
       The modal does not work well inside iframe; parent app should detect 401/403
       and show "Session expired - please refresh" via toast. */
    #wp-auth-check-wrap,
    #wp-auth-check {
        display: none !important;
        visibility: hidden !important;
        opacity: 0 !important;
    }

    #adminmenumain,
    ' . ($showAdminbar ? '' : '#wpadminbar,') . '
    #wpfooter,
    #screen-meta,
    #screen-meta-links,
    .update-nag,
    .updated,
    .notice {
        display: none !important;
    }

    #wpcontent,
    #wpbody-content {
        margin-left: 0 !important;
        padding-left: 0 !important;
    }

    html.wp-toolbar {
        padding-top: ' . ($showAdminbar ? '32px' : '0') . ' !important;
        margin-left: 0 !important;
        overflow: hidden !important;
        height: 100vh !important;
        box-sizing: border-box !important;
    }

    /* Force body to take full width; fit below html.wp-toolbar padding (no duplicate 32px on body) */
    body {
        width: 100% !important;
        min-width: 100% !important;
        padding: 0 !important;
        margin: 0 !important;
        overflow: hidden !important;
        box-sizing: border-box !important;
        height: calc(100vh - ' . ($showAdminbar ? '32px' : '0') . ') !important;
        max-height: calc(100vh - ' . ($showAdminbar ? '32px' : '0') . ') !important;
    }

    .fleekdash-app {
        min-height: 100%;
        display: flex;
        flex-direction: column;
    }


            </style>';
    }

    /**
     * Add body class for FleekDash admin screens.
     */
    public function addBodyClass(string $classes): string
    {
        if ($this->isFleekdashPage()) {
            $classes .= ' fleekdash-active'; // Legacy admin class removed
        }
        return $classes;
    }

    /**
     * WordPress admin menu: hidden via CSS (see removeAdminMenuStyles).
     */
    public function removeAdminMenu(): void
    {
        if ($this->isFleekdashPage()) {
            // Menu is only hidden visually; do not empty global $menu.
        }
    }

    /**
     * Footer debug helpers for FleekDash screens.
     */
    public function addDebugInfo(): void
    {
        if ($this->isFleekdashPage()) {
            $page = isset($_GET['page']) ? \esc_js(\sanitize_text_field(\wp_unslash($_GET['page']))) : '';
            echo '<!-- FleekDash Debug Info -->
                  <script>
                    console.log("FleekDash Debug Info:");
                    console.log("Page:", "' . $page . '");
                    console.log("Admin Theme Active:", true);
                    console.log("Mount Element:", document.getElementById("fleekdash"));
                  </script>
                  ';
        }
    }

    private function isFleekdashPage(): bool
    {
        return isset($_GET['page']) && strpos((string) $_GET['page'], 'fleekdash') === 0;
    }
}
