<?php

namespace GriffinForms\Admin;

class StyleSheets extends \GriffinForms\Admin\Format
{
    protected $pages;
    protected $package_state_resolver;

    protected function setPages()
    {
        $this->pages = Pages::getInstance();
    }

    protected function setPackageStateResolver()
    {
        $this->package_state_resolver = \GriffinForms\Includes\Packages\PackageStateResolver::getInstance();
    }

    protected function isPluginPage()
    {
        $page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
        return $page && strncmp($page, $this->config::PREFIX, strlen($this->config::PREFIX)) === 0;
    }

    protected function isSettingsPage()
    {
        $page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
        $settings_prefix = $this->config::PREFIX . '-settings';
        return $page && strncmp($page, $settings_prefix, strlen($settings_prefix)) === 0;
    }

    protected function isPluginNonSettingsPage()
    {
        return $this->isPluginPage() && !$this->isSettingsPage();
    }

    protected function isFreemiusManagedPage(): bool
    {
        $page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';

        return in_array($page, [
            'griffinforms-forms-account',
            'griffinforms-forms-pricing',
        ], true);
    }
    
    protected function pluginLevelScripts()
    {
        // Define version numbers
        $css_version = $this->config::CSS_VER;
        $js_version = $this->config::JS_VER;
        $bootstrap_version = '5.3.2';
        $material_symbols_version = '1.0';
        $jqueryui_version = '1.14.0'; // Ensure version is correct
    
        // Define URLs
        $plugin_url = plugin_dir_url(__FILE__);
        $plugin_root_url = $this->config->getRootUrl();
    
        // External resources (no jQuery UI since we use the WordPress version)
        $bootstrap_css = $plugin_root_url . 'external/bootstrap/css/bootstrap.min.css';
        $bootstrap_js = $plugin_root_url . 'external/bootstrap/js/bootstrap.min.js';
        $material_symbols_outlined = $plugin_root_url . 'external/google/material-symbols/css/outlined.css';
        $material_symbols_rounded = $plugin_root_url . 'external/google/material-symbols/css/rounded.css';
        $jquery_ui_css = $plugin_root_url . 'external/jquery-ui/jquery-ui.min.css';
        $jquery_ui_theme_css = $plugin_root_url . 'external/jquery-ui/jquery-ui.theme.min.css';
        
        // Enqueue global styles and scripts (available on all pages)
        wp_enqueue_style('griffinforms-global-css', $plugin_url . 'css/griffinforms-global.css', array(), $css_version, 'all');
        wp_enqueue_script('griffinforms-global-js', $plugin_url . 'js/griffinforms-global.js', array('jquery', 'wp-api-fetch'), $js_version, true);
    
        if ($this->isPluginNonSettingsPage()) {
            // Enqueue Google Material Symbols styles
            wp_enqueue_style('griffinforms-material-symbols-rounded', $material_symbols_rounded, array(), $material_symbols_version, 'all');
            wp_enqueue_style('griffinforms-material-symbols-outlined', $material_symbols_outlined, array(), $material_symbols_version, 'all');

            // Enqueue plugin core styles and scripts
            wp_enqueue_style('griffinforms', $plugin_url . 'css/griffinforms.css', array('griffinforms-bootstrap'), $css_version, 'all');
            wp_enqueue_style('griffinforms-modal', $plugin_url . 'css/griffinforms-modal.css', array(), $css_version, 'all');
            wp_enqueue_script('griffinforms', $plugin_url . 'js/griffinforms.js', array('jquery', 'griffinforms-bootstrap-js'), $js_version, true);
            
            // Enqueue WordPress Core jQuery UI styles and scripts (No need for custom versions)
            wp_enqueue_style('jquery-ui-css', $jquery_ui_css, array(), '1.14.1', 'all');
            wp_enqueue_style('jquery-ui-theme', $jquery_ui_theme_css, array(), '1.14.1', 'all');
            wp_enqueue_script('jquery-ui-core');       // WordPress core jQuery UI
            wp_enqueue_script('jquery-ui-widget');     // For the Datepicker widget and others
            wp_enqueue_script('jquery-ui-mouse');      // For mouse-related widgets (draggable, sortable)
            wp_enqueue_script('jquery-ui-datepicker');   // For datepicker widget
            wp_enqueue_script('jquery-ui-selectable');   // For selectable widget
            wp_enqueue_script('jquery-ui-sortable');   // For sortable widget
            wp_enqueue_script('jquery-ui-draggable');  // For draggable widget
            wp_enqueue_script('jquery-ui-droppable');  // For droppable widget
            wp_enqueue_script('jquery-ui-resizable');  // For resizable widget
    
            // Enqueue Bootstrap styles and scripts
            wp_enqueue_style('griffinforms-bootstrap', $bootstrap_css, array(), $bootstrap_version, 'all');
            wp_enqueue_script('griffinforms-bootstrap-js', $bootstrap_js, array('jquery'), $bootstrap_version, true);
        }
    }

    private function pageSpecificStyles()
    {
        $page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
        if (!empty($page) && $page === 'griffinforms-submission') {
            $submission_font_file = $this->config->getRootUrl() . 'external/google/fonts/kalam.css';
            wp_enqueue_style('griffinforms-submission-font', $submission_font_file, array(), '1.0', false);
        }

        if (!empty($page) && $page === 'griffinforms-app') {
            wp_enqueue_media();
        }

        if (!empty($page) && $page === 'griffinforms-formtheme') {
            $this->enqueueSpectrumColorPicker();
        }
    }

    private function enqueueSpectrumColorPicker()
    {
        $plugin_root_url = $this->config->getRootUrl();
        $spectrum_version = '1.8.1';
        $css_version = $this->config::CSS_VER;

        // Enqueue Spectrum.js CSS
        wp_enqueue_style(
            'spectrum-css',
            $plugin_root_url . 'external/spectrum/spectrum.min.css',
            array(),
            $spectrum_version,
            'all'
        );

        // Enqueue custom Spectrum styling (modern theme overrides)
        wp_enqueue_style(
            'spectrum-custom-css',
            $plugin_root_url . 'admin/css/spectrum-custom.css',
            array('spectrum-css'),
            $css_version,
            'all'
        );

        // Enqueue Spectrum.js JavaScript (depends on jQuery)
        wp_enqueue_script(
            'spectrum-js',
            $plugin_root_url . 'external/spectrum/spectrum.min.js',
            array('jquery'),
            $spectrum_version,
            true
        );

        // Enqueue WordPress Media Library for background image picker
        wp_enqueue_media();
    }

    protected function colorStyle()
    {
        if ($this->isPluginPage()) {
            $color = get_user_option('admin_color');
            $file = plugin_dir_path(__FILE__) . 'css/color/griffinforms-' . $color . '.css';
            if (file_exists($file)) {
                wp_enqueue_style('griffinforms-color', plugin_dir_url(__FILE__) . 'css/color/griffinforms-' . $color . '.css', array(), '1.0', false);
            }
        }
    }

    protected function getFreemiusAdminPageCss(): string
    {
        if (!$this->isFreemiusManagedPage()) {
            return '';
        }

        return '
        .fs-header-actions a,
        .fs-header-actions a:visited,
        .fs-header-actions a:active,
        .fs-header-actions a:focus {
            color: var(--wp-admin-theme-color, #3858e9);
        }

        .fs-header-actions a:hover {
            color: var(--wp-admin-theme-color-darker-20, #135e96);
        }

        .wrap > .nav-tab-wrapper {
            display: none;
        }
        ';
    }

    protected function freemiusAdminLinkReset(): void
    {
        $css = $this->getFreemiusAdminPageCss();
        if ($css === '') {
            return;
        }

        wp_add_inline_style('griffinforms-global-css', $css);
    }

    public function printFreemiusAdminPageCss(): void
    {
        $css = $this->getFreemiusAdminPageCss();
        if ($css === '') {
            return;
        }

        echo '<style id="griffinforms-freemius-admin-page-css">' . $css . '</style>';
    }

    public function printAdminBackgroundBootstrap()
    {
        if (!$this->isPluginPage()) {
            return;
        }

        ?>
        <script>
        (function () {
            var root = document.documentElement;
            var body = document.body;

            if (!root || !body) {
                return;
            }

            var probeStyle = document.createElement('style');
            probeStyle.id = 'gf-admin-bg-probe-style';
            probeStyle.textContent = 'html.gf-admin-bg-probe body{background-color:revert !important;}';
            document.head.appendChild(probeStyle);
            root.classList.add('gf-admin-bg-probe');

            var backgroundColor = window.getComputedStyle(body).backgroundColor;

            root.classList.remove('gf-admin-bg-probe');
            probeStyle.remove();

            if (!backgroundColor || backgroundColor === 'transparent' || backgroundColor === 'rgba(0, 0, 0, 0)') {
                backgroundColor = '#f0f0f1';
            }

            root.style.setProperty('--gf-color-bg', backgroundColor);
        }());
        </script>
        <?php
    }

    public function addPackageStateBodyClasses($classes)
    {
        if (!$this->isPluginPage()) {
            return $classes;
        }

        $classes = is_string($classes) ? trim($classes) : '';
        $state = $this->package_state_resolver->getState();
        $packages = is_array($state['packages'] ?? null) ? $state['packages'] : [];

        foreach ($packages as $package_id => $package_state) {
            $package_id = sanitize_key((string) $package_id);
            if ($package_id === '') {
                continue;
            }

            $classes .= ' gf-package-' . $package_id;
            $classes .= !empty($package_state['is_present']) ? ' gf-package-' . $package_id . '-present' : ' gf-package-' . $package_id . '-absent';
            $classes .= !empty($package_state['is_active']) ? ' gf-package-' . $package_id . '-active' : ' gf-package-' . $package_id . '-inactive';

            $approval_status = sanitize_html_class((string) ($package_state['approval_status'] ?? 'unknown'));
            $compatibility_state = sanitize_html_class((string) ($package_state['compatibility_state'] ?? 'unknown'));
            $entitlement_state = sanitize_html_class((string) ($package_state['entitlement_state'] ?? 'unknown'));

            $classes .= ' gf-package-' . $package_id . '-approval-' . $approval_status;
            $classes .= ' gf-package-' . $package_id . '-compatibility-' . $compatibility_state;
            $classes .= ' gf-package-' . $package_id . '-entitlement-' . $entitlement_state;
        }

        return trim($classes);
    }
    
    public function loadAdminScripts()
    {
        $this->pluginLevelScripts();
        $this->pageSpecificStyles();
        $this->colorStyle();
        $this->freemiusAdminLinkReset();
    }
    
    public function __construct()
    {
        $this->setAll();
        add_action('init', array($this, 'loadAdminScripts'));
        add_action('in_admin_header', array($this, 'printAdminBackgroundBootstrap'), 0);
        add_action('admin_head', array($this, 'printFreemiusAdminPageCss'), 100);
        add_filter('admin_body_class', array($this, 'addPackageStateBodyClasses'));
    }
}
