<?php

declare(strict_types=1);

namespace FleekDash\Admin;

// Load debug helpers (procedural functions require file load, not class use)
if (!function_exists('fleekdash_log_error')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

/**
 * Builds localization data for FleekDash admin scripts.
 *
 * @package FleekDash\Admin
 */
class AssetsLocalizationBuilder
{
    /**
     * Build user info array for localization.
     *
     * @param object $user_info WP_User instance
     * @return array
     */
    public function buildUserInfoArray(object $user_info): array
    {
        return array(
            'id' => $user_info->ID,
            'username' => $user_info->user_login,
            'avatar' => get_avatar_url($user_info->ID),
            'name' => $user_info->display_name,
            'display_name' => $user_info->display_name,
            'email' => $user_info->user_email,
            'role' => $user_info->roles[0] ?? '',
            'first_name' => \get_user_meta($user_info->ID, 'first_name', true) ?: '',
            'last_name' => \get_user_meta($user_info->ID, 'last_name', true) ?: '',
            'nickname' => \get_user_meta($user_info->ID, 'nickname', true) ?: '',
            'description' => \get_user_meta($user_info->ID, 'description', true) ?: '',
        );
    }

    /**
     * Build appearance settings array from options.
     *
     * @return array
     */
    public function buildAppearanceSettings(): array
    {
        return array(
            'logo' => \get_option('_fleekdash_logo', ''),
            'dark_logo' => \get_option('_fleekdash_dark_logo', ''),
            'use_dark_logo' => (bool) \get_option('_fleekdash_use_dark_logo', false),
            'auto_invert_logo_dark_mode' => (bool) \get_option('_fleekdash_auto_invert_logo_dark_mode', true),
            'favicon' => \get_option('_fleekdash_favicon', ''),
            'primary_color' => \get_option('_fleekdash_primary_color', '#3858e9'),
            'secondary_color' => \get_option('_fleekdash_secondary_color', '#64748b'),
            'accent_color' => \get_option('_fleekdash_accent_color', '#f59e0b'),
            'sidebar_width' => \get_option('_fleekdash_sidebar_width', '280'),
            'enable_animations' => \get_option('_fleekdash_enable_animations', true),
            'enable_shadows' => \get_option('_fleekdash_enable_shadows', true),
            'enable_rounded_corners' => \get_option('_fleekdash_enable_rounded_corners', true),
            'brand_name' => \get_option('_fleekdash_brand_name', ''),
        );
    }

    /**
     * Build the full localization data array.
     *
     * @return array
     */
    public function buildLocalizationData(
        array $admin_menu,
        array $toolbar_data,
        object $user_info,
        array $active_integrations,
        array $discovered_integrations,
        array $debug_status,
    ): array {
        $api_url = function_exists('get_rest_url') ? \call_user_func('get_rest_url', null, 'fleekdash/v1') : '';
        $site_logo_url = function_exists('get_site_icon_url') ? \call_user_func('get_site_icon_url') : '';
        $site_url = function_exists('home_url') ? \home_url() : '';
        $admin_url = function_exists('admin_url') ? \admin_url() : '';
        if (function_exists('wp_login_url')) {
            $wp_login_url = \wp_login_url();
        } elseif (function_exists('site_url')) {
            $wp_login_url = \site_url('wp-login.php');
        } else {
            $wp_login_url = '';
        }

        return array(
            'developer' => 'Fleek',
            'pluginVersion' => FLEEKDASH_VERSION,
            'isAdmin' => \current_user_can('manage_options'),
            'apiUrl' => $api_url,
            'pluginUrl' => FLEEKDASH_PLUGIN_URL,
            'mediaFolderSidebarJs' => \FleekDash\Libs\Assets\getJsUrl('media-folder-sidebar'),
            'mediaFolderSidebarCss' => \FleekDash\Libs\Assets\getCssUrl('media-folder-sidebar'),
            'siteUrl' => $site_url,
            'userInfo' => $this->buildUserInfoArray($user_info),
            'nonce' => \wp_create_nonce('wp_rest'),
            'adminUrl' => $admin_url,
            'wpLoginUrl' => $wp_login_url,
            'debug' => $debug_status['debug'],
            'debugStatus' => $debug_status,
            'adminMenu' => $admin_menu,
            'adminToolbar' => $toolbar_data,
            'siteLogo' => $site_logo_url,
            'siteTitle' => \get_bloginfo('name'),
            'activeIntegrations' => $active_integrations,
            'discoveredIntegrations' => $discovered_integrations,
            'appearanceSettings' => $this->buildAppearanceSettings(),
            'iframeBuiltinTaxonomies' => $this->getIframeBuiltinTaxonomyNames(),
            'iframeBuiltinPostTypes' => $this->getIframeBuiltinPostTypeNames(),
        );
    }

    /**
     * Taxonomies WordPress marks as _builtin (category, post_tag, …) for edit-tags.php iframe mode.
     *
     * @return list<string>
     */
    public function getIframeBuiltinTaxonomyNames(): array
    {
        if (!function_exists('get_taxonomies')) {
            return [];
        }

        $names = get_taxonomies(['_builtin' => true], 'names');

        return is_array($names) ? array_values($names) : [];
    }

    /**
     * Post types WordPress marks as _builtin for edit-tags.php when post_type= is present.
     *
     * @return list<string>
     */
    public function getIframeBuiltinPostTypeNames(): array
    {
        if (!function_exists('get_post_types')) {
            return [];
        }

        $names = get_post_types(['_builtin' => true], 'names');

        return is_array($names) ? array_values($names) : [];
    }

    /**
     * Format integrations from IntegrationManager for frontend.
     *
     * @return array
     */
    public function formatIntegrationsForFrontend(): array
    {
        $formatted = [
            'plugin' => [],
            'theme' => [],
            'api' => [],
            'app' => [],
            'example' => [],
        ];

        try {
            $manager = \FleekDash\Core\IntegrationManager::getInstance();
            $current_active = $manager->getAll();
        } catch (\Exception $e) {
            fleekdash_log_error('FleekDash: Error getting integrations: ' . $e->getMessage());
            return $formatted;
        }

        if (empty($current_active)) {
            return $formatted;
        }

        foreach (['plugin', 'theme', 'api', 'app'] as $category) {
            if (!isset($current_active[$category])) {
                continue;
            }
            foreach ($current_active[$category] as $integration) {
                if (is_array($integration) && isset($integration['id'])) {
                    $formatted[$category][] = $integration['id'];
                } elseif (is_string($integration)) {
                    $formatted[$category][] = $integration;
                }
            }
        }

        return $formatted;
    }

    /**
     * Build debug and integrations inline script HTML.
     *
     * @return string
     */
    public function buildDebugIntegrationsScript(
        array $debug_status,
        string $site_url,
        string $api_url,
        string $site_logo_url,
    ): string {
        $formatted = $this->formatIntegrationsForFrontend();
        $debug_val = ($debug_status['debug'] ?? false) ? 'true' : 'false';
        $debug_log = ($debug_status['wp_debug_log'] ?? false) ? 'true' : 'false';
        $debug_disp = ($debug_status['wp_debug_display'] ?? false) ? 'true' : 'false';

        $nonce = \wp_create_nonce('wp_rest');
        $is_admin = \current_user_can('manage_options') ? 'true' : 'false';
        $siteUrlJs = \esc_js($site_url ?: '');
        $apiUrlJs = \esc_js($api_url ?: '');
        $siteIconJs = \esc_url($site_logo_url ?: '');

        return '<script>
            window.fleekDashActiveIntegrations = ' . json_encode($formatted) . ';
            window.FleekDash = window.FleekDash || {};
            window.FleekDash.activeIntegrations = ' . json_encode($formatted) . ';
            window.FleekDash.nonce = "' . $nonce . '";
            window.FleekDash.isAdmin = ' . $is_admin . ';
            window.FleekDash.wordPressData = window.FleekDash.wordPressData || {};
            window.FleekDash.wordPressData.debug = ' . $debug_val . ';
            window.FleekDash.wordPressData.debug_log = ' . $debug_log . ';
            window.FleekDash.wordPressData.debug_display = ' . $debug_disp . ';
            window.FleekDash.wordPressData.debugStatus = ' . json_encode($debug_status) . ';
            window.FleekDash.wordPressData.siteUrl = "' . $siteUrlJs . '";
            window.FleekDash.wordPressData.adminUrl = "' . \admin_url() . '";
            window.FleekDash.wordPressData.apiUrl = "' . $apiUrlJs . '";
            window.FleekDash.wordPressData.siteName = "' . \esc_js(\get_bloginfo('name')) . '";
            window.FleekDash.wordPressData.siteIcon = "' . $siteIconJs . '";
            window.FleekDash.debug = ' . $debug_val . ';
            window.FleekDash.debugStatus = ' . json_encode($debug_status) . ';
            var metaTag = document.createElement("meta");
            metaTag.name = "wp-debug";
            metaTag.content = ' . $debug_val . ';
            document.head.appendChild(metaTag);
        </script>';
    }

    /**
     * Inject debug/integrations inline script once per request.
     *
     * @param array $debug_status
     * @param array $cached_data Localization data (contains apiUrl, siteLogo, etc.)
     */
    public function injectDebugScriptOnce(array $debug_status, array $cached_data): void
    {
        static $script_injected = false;

        if ($script_injected) {
            return;
        }

        $site_url = function_exists('get_site_url') ? \call_user_func('get_site_url') : '';
        $api_url = $cached_data['apiUrl'] ?? '';
        $site_logo_url = $cached_data['siteLogo'] ?? '';

        \add_action('admin_enqueue_scripts', function () use ($debug_status, $site_url, $api_url, $site_logo_url) {
            echo $this->buildDebugIntegrationsScript($debug_status, $site_url, $api_url, $site_logo_url);
        }, 10);

        $script_injected = true;
    }
}
