<?php

namespace Calio\Admin;

use Calio\Core\GoogleCalendarOAuthManager;
use Calio\Support\DashboardWidgetCatalog;
use Calio\Support\Settings;
use Calio\Support\ExtensionCatalog;
use Calio\Support\ProAccess;
use Calio\Support\WidgetCatalog;

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

/**
 * Renders the Calio dashboard and delegates sanitization to the Settings API.
 */
class AdminPage
{
    private const PAGE_ID = CALIO_MENU_SLUG;

    /**
     * @var array<string, array{label: string, icon: string}>
     */
    private array $tabs = [
        'calio_overview' => [
            'label' => 'Overview',
            'icon' => 'dashicons-dashboard',
        ],
        'calio_addon_active_modules' => [
            'label' => 'Core Widgets',
            'icon' => 'dashicons-screenoptions',
        ],
        'calio_addon_third_party_widget' => [
            'label' => '3rd Party Widgets',
            'icon' => 'dashicons-admin-plugins',
        ],
        'calio_addon_dashboard_widgets' => [
            'label' => 'Dashboard Widgets',
            'icon' => 'dashicons-chart-area',
        ],
        'calio_addon_elementor_extend' => [
            'label' => 'Extensions',
            'icon' => 'dashicons-admin-tools',
        ],
        'calio_addon_api_settings' => [
            'label' => 'API Settings',
            'icon' => 'dashicons-cloud',
        ],
        'calio_addon_other_settings' => [
            'label' => 'Other Settings',
            'icon' => 'dashicons-admin-settings',
        ],
        'calio_addon_license_settings' => [
            'label' => 'License',
            'icon' => 'dashicons-lock',
        ],
    ];

    public function __construct()
    {
        add_action('admin_menu', [$this, 'register_menu'], 58);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_init', [$this, 'register_freemius_license_ajax'], 20);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
    }

    /**
     * Keeps Freemius modal license activation usable from Calio's custom dashboard.
     *
     * Freemius does not register the activation AJAX handler for a free plugin
     * that has a separate premium version. Calio intentionally surfaces the
     * activation modal in the free dashboard, so the handler must be registered
     * for the separate admin-ajax.php request as well.
     */
    public function register_freemius_license_ajax(): void
    {
        static $registered = false;

        if ($registered) {
            return;
        }

        $freemiusSdk = $this->freemius_sdk();
        if (!is_object($freemiusSdk) || !method_exists($freemiusSdk, 'add_ajax_action')) {
            return;
        }

        if (method_exists($freemiusSdk, 'has_paid_plan') && !$freemiusSdk->has_paid_plan()) {
            return;
        }

        if (method_exists($freemiusSdk, '_activate_license_ajax_action')) {
            $freemiusSdk->add_ajax_action('activate_license', [$freemiusSdk, '_activate_license_ajax_action']);
            $registered = true;
        }

        if (method_exists($freemiusSdk, '_resend_license_key_ajax_action')) {
            $freemiusSdk->add_ajax_action('resend_license_key', [$freemiusSdk, '_resend_license_key_ajax_action']);
        }
    }

    /**
     * @return object|null
     */
    private function freemius_sdk()
    {
        if (function_exists('calio_pro_fs')) {
            $candidate = calio_pro_fs();
            if (is_object($candidate)) {
                return $candidate;
            }
        }

        if (function_exists('calio_fs')) {
            $candidate = calio_fs();
            if (is_object($candidate)) {
                return $candidate;
            }
        }

        if (function_exists('cal_fs')) {
            $candidate = cal_fs();
            if (is_object($candidate)) {
                return $candidate;
            }
        }

        return null;
    }

    public function register_settings(): void
    {
        register_setting(
            'calio_addon_active_modules',
            Settings::OPTION_CORE_WIDGETS,
            [
                'type' => 'array',
                'sanitize_callback' => [Settings::class, 'sanitize_core_widget_map'],
                'default' => [],
            ]
        );

        register_setting(
            'calio_addon_elementor_extend',
            Settings::OPTION_EXTENSIONS,
            [
                'type' => 'array',
                'sanitize_callback' => [Settings::class, 'sanitize_extension_map'],
                'default' => [],
            ]
        );

        register_setting(
            'calio_addon_dashboard_widgets',
            Settings::OPTION_DASHBOARD_WIDGETS,
            [
                'type' => 'array',
                'sanitize_callback' => [Settings::class, 'sanitize_dashboard_widget_map'],
                'default' => [],
            ]
        );

        register_setting(
            'calio_addon_api_settings',
            Settings::OPTION_API_SETTINGS,
            [
                'type' => 'array',
                'sanitize_callback' => [Settings::class, 'sanitize_api_settings'],
                'default' => [],
            ]
        );

        register_setting(
            'calio_addon_other_settings',
            Settings::OPTION_OTHER_SETTINGS,
            [
                'type' => 'array',
                'sanitize_callback' => [Settings::class, 'sanitize_other_settings'],
                'default' => [],
            ]
        );
    }

    public function register_menu(): void
    {
        add_menu_page(
            esc_html__('Calio Dashboard', 'calio-addon'),
            esc_html__('Calio', 'calio-addon'),
            'manage_options',
            self::PAGE_ID,
            [$this, 'render_page'],
            $this->menu_icon_url(),
            58
        );

        foreach ($this->tabs as $tabId => $tab) {
            add_submenu_page(
                self::PAGE_ID,
                esc_html__('Calio', 'calio-addon'),
                esc_html($tab['label']),
                'manage_options',
                self::PAGE_ID . '#' . $tabId,
                [$this, 'render_page']
            );
        }
    }

    private function menu_icon_url(): string
    {
        return set_url_scheme(CALIO_URL . 'assets/admin/calio-menu-icon.svg');
    }

    public function enqueue_assets(string $hookSuffix): void
    {
        if ($hookSuffix !== 'toplevel_page_' . self::PAGE_ID) {
            return;
        }

        wp_enqueue_style('calio-admin-ui');
        wp_enqueue_script('calio-admin-ui');
    }

    public function render_page(): void
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        $coreMap = Settings::core_widget_map();
        $dashboardWidgetMap = Settings::dashboard_widget_map();
        $dashboardWidgets = DashboardWidgetCatalog::all();
        $apiSettings = get_option(Settings::OPTION_API_SETTINGS, []);
        $otherSettings = Settings::other_settings();
        $extensions = ExtensionCatalog::all();
        $extension_map = Settings::extension_map();

        if (!is_array($apiSettings)) {
            $apiSettings = [];
        }

        $googleConnected = GoogleCalendarOAuthManager::is_connected();
        $googleConfigured = GoogleCalendarOAuthManager::has_client_credentials();
        $googleRedirectUri = GoogleCalendarOAuthManager::redirect_uri();
        $googleCalendars = GoogleCalendarOAuthManager::cached_calendars();
        $googleConnectedEmail = sanitize_email((string) ($apiSettings['google_calendar_connected_email'] ?? ''));
        $googleConnectedName = sanitize_text_field((string) ($apiSettings['google_calendar_connected_name'] ?? ''));
        $googleConnectedCalendar = sanitize_text_field((string) ($apiSettings['google_calendar_connected_calendar'] ?? ''));
        $googleConnectedCalendarId = sanitize_text_field((string) ($apiSettings['google_calendar_connected_calendar_id'] ?? ''));
        $googleConnectedAt = (int) ($apiSettings['google_calendar_connected_at'] ?? 0);
        $googleTokenExpiresAt = (int) ($apiSettings['google_calendar_token_expires_at'] ?? 0);
        $googleLastError = sanitize_text_field((string) ($apiSettings['google_calendar_last_error'] ?? ''));
        // Read-only admin notice flag added after OAuth redirects.
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $googleNoticeCode = isset($_GET['calio_google_status']) ? sanitize_key((string) wp_unslash($_GET['calio_google_status'])) : '';
        $googleNoticeMessage = '';
        $googleNoticeClass = 'is-active';
        if ($googleNoticeCode === 'tested') {
            $googleNoticeMessage = __('Google Calendar connection looks healthy. Tokens refreshed and calendars loaded successfully.', 'calio-addon');
        } elseif ($googleNoticeCode === 'refreshed') {
            $googleNoticeMessage = __('Google calendar cache was refreshed successfully.', 'calio-addon');
        } elseif ($googleNoticeCode === 'warning') {
            $googleNoticeMessage = __('Google Calendar responded, but the returned data needs attention. Review the cached calendars and permissions below.', 'calio-addon');
            $googleNoticeClass = 'is-warning';
        } elseif ($googleNoticeCode === 'error') {
            $googleNoticeMessage = __('Google Calendar action did not complete cleanly. Check the error note in the connection card below.', 'calio-addon');
            $googleNoticeClass = 'is-inactive';
        }
        $googleAccountLabel = trim($googleConnectedName . ($googleConnectedEmail !== '' ? ' - ' . $googleConnectedEmail : ''));
        $googleConnectedAtLabel = $googleConnectedAt > 0
            ? wp_date(get_option('date_format') . ' ' . get_option('time_format'), $googleConnectedAt)
            : esc_html__('Not connected yet', 'calio-addon');
        $googleExpiryLabel = $googleTokenExpiresAt > 0
            ? wp_date(get_option('date_format') . ' ' . get_option('time_format'), $googleTokenExpiresAt)
            : esc_html__('Refresh on demand', 'calio-addon');

        $allWidgets = WidgetCatalog::all();
        $totalWidgets = 0;
        $activeWidgets = 0;
        $disabledWidgets = 0;
        $freeWidgets = 0;
        $proWidgets = 0;
        $lockedWidgets = 0;
        $thirdPartyTotalWidgets = 0;
        $thirdPartyActiveWidgets = 0;
        $thirdPartyDisabledWidgets = 0;
        $thirdPartyFreeWidgets = 0;
        $thirdPartyProWidgets = 0;
        $thirdPartyLockedWidgets = 0;
        $coreWidgets = [];
        $thirdPartyWidgets = [];
        $totalDashboardWidgets = count($dashboardWidgets);
        $activeDashboardWidgets = count(array_filter($dashboardWidgetMap));
        $disabledDashboardWidgets = $totalDashboardWidgets - $activeDashboardWidgets;
        $totalExtensions = count($extensions);
        $activeExtensions = count(array_filter($extension_map));
        $disabledExtensions = $totalExtensions - $activeExtensions;
        $proExtensions = 0;
        $lockedExtensions = 0;
        $proUnlocked = ProAccess::is_pro_unlocked();
        $proPluginActive = ProAccess::is_pro_plugin_active();
        $proCompatible = ProAccess::is_free_version_compatible();
        $requiredFreeVersion = ProAccess::required_free_version();
        $proCtaUrl = ProAccess::upgrade_url();
        $upgradePlansUrl = ProAccess::upgrade_url();
        $licenseActivationUrl = ProAccess::activation_url();
        $licenseAccountUrl = ProAccess::account_url();
        $freemiusSdk = $this->freemius_sdk();

        $licenseTriggerClass = '';
        $licenseDialogAvailable = is_object($freemiusSdk) && method_exists($freemiusSdk, '_add_license_activation_dialog_box');
        if (is_object($freemiusSdk) && method_exists($freemiusSdk, 'get_unique_affix')) {
            $affix = trim((string) $freemiusSdk->get_unique_affix());
            if ($affix !== '') {
                $licenseTriggerClass = sanitize_html_class($affix);
            }
        }

        $proLockReason = ProAccess::lock_reason();
        $proCtaLabel = esc_html__('Unlock Pro', 'calio-addon');
        if ($proLockReason === 'pro_inactive') {
            $proCtaLabel = esc_html__('Install Pro', 'calio-addon');
        } elseif ($proLockReason === 'free_outdated') {
            $proCtaLabel = esc_html__('Update Free', 'calio-addon');
        } elseif ($proLockReason === 'license_inactive') {
            $proCtaLabel = esc_html__('Activate License', 'calio-addon');
            if ($licenseActivationUrl !== '') {
                $proCtaUrl = $licenseActivationUrl;
            }
        }
        $licenseStateLabel = esc_html__('License Required', 'calio-addon');
        $licenseStateClass = 'is-inactive';
        if ($proUnlocked) {
            $licenseStateLabel = esc_html__('Licensed', 'calio-addon');
            $licenseStateClass = 'is-active';
        } elseif ($proLockReason === 'pro_inactive') {
            $licenseStateLabel = esc_html__('Pro Missing', 'calio-addon');
        } elseif ($proLockReason === 'free_outdated') {
            $licenseStateLabel = esc_html__('Update Required', 'calio-addon');
        }
        $licenseStateNote = esc_html__('Premium widgets are available and can be enabled from Core Widgets and 3rd Party Widgets.', 'calio-addon');
        if ($proLockReason === 'pro_inactive') {
            $licenseStateNote = esc_html__('Install and activate Calio Pro to unlock premium widgets in Core Widgets and 3rd Party Widgets tabs.', 'calio-addon');
        } elseif ($proLockReason === 'free_outdated') {
            $licenseStateNote = esc_html__('Update the free plugin first. Premium widgets stay locked until version compatibility is met.', 'calio-addon');
        } elseif ($proLockReason === 'license_inactive') {
            $licenseStateNote = esc_html__('Activate your license in Freemius to unlock premium widgets.', 'calio-addon');
        }
        $licensePrimaryLabel = $proUnlocked ? esc_html__('Manage License', 'calio-addon') : esc_html__('Activate License', 'calio-addon');
        $licensePrimaryUrl = $licenseActivationUrl !== '' ? $licenseActivationUrl : $proCtaUrl;
        // Freemius license activation is modal-driven; direct URLs can collapse back to the dashboard tab router.
        $useLicenseDialogTrigger = $licenseDialogAvailable && $proLockReason === 'license_inactive';
        $licenseAjaxAction = '';
        $licenseAjaxSecurity = '';
        $licenseModuleId = '';
        if (is_object($freemiusSdk)) {
            if (method_exists($freemiusSdk, 'get_ajax_action')) {
                $licenseAjaxAction = (string) $freemiusSdk->get_ajax_action('activate_license');
            }

            if (method_exists($freemiusSdk, 'get_ajax_security')) {
                $licenseAjaxSecurity = (string) $freemiusSdk->get_ajax_security('activate_license');
            }

            if (method_exists($freemiusSdk, 'get_id')) {
                $licenseModuleId = (string) $freemiusSdk->get_id();
            }
        }
        $canInlineLicenseActivation = $proLockReason === 'license_inactive' && $licenseAjaxAction !== '' && $licenseAjaxSecurity !== '';
        if ($upgradePlansUrl === '') {
            $upgradePlansUrl = $proCtaUrl;
        }
        $upgradeAreaHeading = $proUnlocked ? esc_html__('Plan & Billing', 'calio-addon') : esc_html__('Plans & Pricing', 'calio-addon');
        $upgradeAreaNote = $proUnlocked
            ? esc_html__('Need more sites or seats? Manage billing and plan upgrades from here.', 'calio-addon')
            : esc_html__('Compare plans and unlock all premium widgets without leaving the Calio dashboard flow.', 'calio-addon');
        $upgradeAreaCta = $proUnlocked ? esc_html__('Manage Plan', 'calio-addon') : esc_html__('View Upgrade Plans', 'calio-addon');
        $phaseLabel = 'Phase 02';
        $categories = [];
        $categoryStats = [];
        $wpVersion = (string) get_bloginfo('version');
        $phpVersion = PHP_VERSION;
        $elementorVersion = defined('ELEMENTOR_VERSION') ? (string) ELEMENTOR_VERSION : esc_html__('Not detected', 'calio-addon');
        $pluginVersion = defined('CALIO_VERSION') ? CALIO_VERSION : '1.01';
        $requirements = [
            [
                'label' => esc_html__('WordPress', 'calio-addon'),
                'current' => $wpVersion,
                'required' => '6.7+',
                'ok' => version_compare($wpVersion, '6.7', '>='),
            ],
            [
                'label' => esc_html__('PHP', 'calio-addon'),
                'current' => $phpVersion,
                'required' => '8.2+',
                'ok' => version_compare($phpVersion, '8.2', '>='),
            ],
            [
                'label' => esc_html__('Elementor', 'calio-addon'),
                'current' => $elementorVersion,
                'required' => '3.20+',
                'ok' => defined('ELEMENTOR_VERSION') && version_compare((string) ELEMENTOR_VERSION, '3.20.0', '>='),
            ],
        ];

        $maskSecret = static function (string $secret): string {
            $secret = trim($secret);
            if ($secret === '') {
                return '-';
            }

            $length = strlen($secret);
            if ($length <= 8) {
                return str_repeat('*', $length);
            }

            return substr($secret, 0, 4) . str_repeat('*', max(4, $length - 7)) . substr($secret, -3);
        };

        $fsUser = null;
        $fsSite = null;
        $fsLicense = null;

        if (is_object($freemiusSdk)) {
            if (method_exists($freemiusSdk, 'get_user')) {
                $candidate = $freemiusSdk->get_user();
                if (is_object($candidate)) {
                    $fsUser = $candidate;
                }
            }

            if (method_exists($freemiusSdk, 'get_site')) {
                $candidate = $freemiusSdk->get_site();
                if (is_object($candidate)) {
                    $fsSite = $candidate;
                }
            }

            if (method_exists($freemiusSdk, '_get_license')) {
                $candidate = $freemiusSdk->_get_license();
                if (is_object($candidate)) {
                    $fsLicense = $candidate;
                }
            }
        }

        $accountConnectionState = is_object($freemiusSdk) ? __('Connected', 'calio-addon') : __('Not Connected', 'calio-addon');
        $accountConnectionClass = is_object($freemiusSdk) ? 'is-active' : 'is-inactive';
        $accountName = '-';
        $accountEmail = '-';
        $accountUserId = '-';
        $accountPluginName = __('Calio Addon', 'calio-addon');
        $accountPluginId = '-';
        $accountSiteId = '-';
        $accountVersion = 'v' . $pluginVersion;
        $accountPlan = __('No Active Plan', 'calio-addon');
        $accountPlanStateClass = 'is-inactive';
        $accountLicenseKey = __('Not Activated', 'calio-addon');
        $accountLicenseExpires = '-';
        $accountLicenseState = __('Inactive', 'calio-addon');
        $accountLicenseStateClass = 'is-inactive';
        $accountExpiryStateClass = 'is-inactive';
        $licenseCountdownLabel = __('No Active License', 'calio-addon');
        $licenseCountdownClass = 'is-inactive';
        $canDeactivateLicense = false;
        $deactivateLicenseUrl = '';
        $deactivateBlogId = '';
        $deactivateInstallId = '';
        $currentTimestamp = (int) current_time('timestamp');

        if (is_object($fsUser)) {
            if (method_exists($fsUser, 'get_name')) {
                $accountName = trim((string) $fsUser->get_name());
            }

            if ($accountName === '' || $accountName === '-') {
                $first = isset($fsUser->first) ? trim((string) $fsUser->first) : '';
                $last = isset($fsUser->last) ? trim((string) $fsUser->last) : '';
                $accountName = trim($first . ' ' . $last);
            }

            $accountEmail = isset($fsUser->email) ? trim((string) $fsUser->email) : '-';
            $accountUserId = isset($fsUser->id) && (string) $fsUser->id !== '' ? (string) $fsUser->id : '-';
        }

        if ($accountName === '') {
            $accountName = '-';
        }
        if ($accountEmail === '') {
            $accountEmail = '-';
        }

        if (is_object($freemiusSdk)) {
            if (method_exists($freemiusSdk, 'get_plugin_title')) {
                $value = trim((string) $freemiusSdk->get_plugin_title());
                if ($value !== '') {
                    $accountPluginName = $value;
                }
            } elseif (method_exists($freemiusSdk, 'get_plugin_name')) {
                $value = trim((string) $freemiusSdk->get_plugin_name());
                if ($value !== '') {
                    $accountPluginName = $value;
                }
            }

            if (method_exists($freemiusSdk, 'get_id')) {
                $value = (string) $freemiusSdk->get_id();
                if ($value !== '') {
                    $accountPluginId = $value;
                }
            }

            if (method_exists($freemiusSdk, 'get_plugin_version')) {
                $value = trim((string) $freemiusSdk->get_plugin_version());
                if ($value !== '') {
                    $accountVersion = $value;
                }
            }

            if (method_exists($freemiusSdk, 'get_plan_title')) {
                $value = trim((string) $freemiusSdk->get_plan_title());
                if ($value !== '' && strpos($value, 'PLAN_') !== 0) {
                    $accountPlan = $value;
                    $accountPlanStateClass = 'is-active';
                }
            }
        }

        if (is_object($fsSite)) {
            if (isset($fsSite->id) && (string) $fsSite->id !== '') {
                $accountSiteId = (string) $fsSite->id;
            } elseif (isset($fsSite->site_id) && (string) $fsSite->site_id !== '') {
                $accountSiteId = (string) $fsSite->site_id;
            }
        }

        if (is_object($fsLicense)) {
            $rawKey = isset($fsLicense->secret_key) ? (string) $fsLicense->secret_key : '';
            if ($rawKey !== '') {
                $accountLicenseKey = $maskSecret($rawKey);
            }

            $isExpired = method_exists($fsLicense, 'is_expired') ? (bool) $fsLicense->is_expired() : false;
            $isActive = method_exists($fsLicense, 'is_active') ? (bool) $fsLicense->is_active() : true;
            $accountLicenseState = (!$isActive || $isExpired) ? __('Inactive', 'calio-addon') : __('Active', 'calio-addon');
            $accountLicenseStateClass = (!$isActive || $isExpired) ? 'is-inactive' : 'is-active';

            if (method_exists($fsLicense, 'is_lifetime') && $fsLicense->is_lifetime()) {
                $accountLicenseExpires = __('Lifetime', 'calio-addon');
                $accountExpiryStateClass = 'is-active';
                $licenseCountdownLabel = __('Lifetime License', 'calio-addon');
                $licenseCountdownClass = 'is-active';
            } elseif (isset($fsLicense->expiration) && is_string($fsLicense->expiration) && trim($fsLicense->expiration) !== '') {
                $timestamp = strtotime($fsLicense->expiration);
                if (is_int($timestamp) && $timestamp > 0) {
                    $accountLicenseExpires = wp_date((string) get_option('date_format'), $timestamp);

                    $daysDiff = (int) ceil(($timestamp - $currentTimestamp) / DAY_IN_SECONDS);
                    if ($daysDiff > 7) {
                        $accountExpiryStateClass = 'is-active';
                    } elseif ($daysDiff > 0) {
                        $accountExpiryStateClass = 'is-warning';
                    } else {
                        $accountExpiryStateClass = 'is-inactive';
                    }

                    if ($daysDiff > 0) {
                        $licenseCountdownLabel = sprintf(
                            /* translators: %d: number of days remaining before license expiration. */
                            _n('%d day left', '%d days left', $daysDiff, 'calio-addon'),
                            $daysDiff
                        );
                        $licenseCountdownClass = $daysDiff > 7 ? 'is-active' : 'is-warning';
                    } else {
                        $licenseCountdownLabel = __('Expired', 'calio-addon');
                        $licenseCountdownClass = 'is-inactive';
                    }
                } else {
                    $accountLicenseExpires = trim($fsLicense->expiration);
                    $accountExpiryStateClass = 'is-warning';
                    $licenseCountdownLabel = __('Expiry Date Unavailable', 'calio-addon');
                    $licenseCountdownClass = 'is-warning';
                }
            }

            if (is_object($freemiusSdk) && method_exists($freemiusSdk, '_get_admin_page_url')) {
                $deactivateLicenseUrl = (string) $freemiusSdk->_get_admin_page_url('account');
                if (is_object($fsSite)) {
                    if (isset($fsSite->blog_id) && (string) $fsSite->blog_id !== '') {
                        $deactivateBlogId = (string) $fsSite->blog_id;
                    }

                    if (isset($fsSite->id) && (string) $fsSite->id !== '') {
                        $deactivateInstallId = (string) $fsSite->id;
                    }
                }

                $canDeactivateLicense = $deactivateLicenseUrl !== '';
            }
        }

        $accountRows = [
            ['label' => __('Name', 'calio-addon'), 'value' => $accountName, 'value_class' => ''],
            ['label' => __('Email', 'calio-addon'), 'value' => $accountEmail, 'value_class' => ''],
            ['label' => __('User ID', 'calio-addon'), 'value' => $accountUserId, 'value_class' => ''],
            ['label' => __('Plugin', 'calio-addon'), 'value' => $accountPluginName, 'value_class' => ''],
            ['label' => __('Plugin ID', 'calio-addon'), 'value' => $accountPluginId, 'value_class' => ''],
            ['label' => __('Site ID', 'calio-addon'), 'value' => $accountSiteId, 'value_class' => ''],
            ['label' => __('Version', 'calio-addon'), 'value' => $accountVersion, 'value_class' => ''],
            ['label' => __('Plan', 'calio-addon'), 'value' => $accountPlan, 'value_class' => 'is-pill ' . $accountPlanStateClass],
            ['label' => __('License State', 'calio-addon'), 'value' => $accountLicenseState, 'value_class' => 'is-pill ' . $accountLicenseStateClass],
            ['label' => __('License Key', 'calio-addon'), 'value' => $accountLicenseKey, 'value_class' => ''],
            ['label' => __('Expires', 'calio-addon'), 'value' => $accountLicenseExpires, 'value_class' => 'is-pill ' . $accountExpiryStateClass],
        ];

        foreach ($extensions as $extension) {
            $tier = strtolower((string) ($extension['tier'] ?? 'free'));
            if ($tier === 'pro') {
                $proExtensions++;
            }
            if (ProAccess::is_extension_locked($extension)) {
                $lockedExtensions++;
            }
        }

        foreach ($allWidgets as $slug => $widget) {
            $panel = strtolower(trim((string) ($widget['panel'] ?? '')));
            $categoryLabel = trim((string) ($widget['category'] ?? 'Content'));
            $isThirdPartyPanel = in_array($panel, ['third_party', 'third-party', '3rd_party', '3rd-party'], true);
            $isThirdPartyCategory = strtolower($categoryLabel) === '3rd party';
            $isThirdParty = $isThirdPartyPanel || $isThirdPartyCategory;

            $tier = strtolower((string) ($widget['tier'] ?? 'free'));
            if (!in_array($tier, ['free', 'pro'], true)) {
                $tier = 'free';
            }

            $isLocked = $tier === 'pro' && !$proUnlocked;
            $enabled = !$isLocked && !empty($coreMap[$slug]);

            if ($isThirdParty) {
                $thirdPartyWidgets[$slug] = $widget;
                $thirdPartyTotalWidgets++;

                if ($tier === 'pro') {
                    $thirdPartyProWidgets++;
                } else {
                    $thirdPartyFreeWidgets++;
                }

                if ($isLocked) {
                    $thirdPartyLockedWidgets++;
                }

                if ($enabled) {
                    $thirdPartyActiveWidgets++;
                } else {
                    $thirdPartyDisabledWidgets++;
                }

                continue;
            }

            $coreWidgets[$slug] = $widget;
            $totalWidgets++;

            if ($tier === 'pro') {
                $proWidgets++;
            } else {
                $freeWidgets++;
            }

            if ($isLocked) {
                $lockedWidgets++;
            }

            if ($enabled) {
                $activeWidgets++;
            } else {
                $disabledWidgets++;
            }

            $category = $categoryLabel;
            $categories[$category] = true;

            if (!isset($categoryStats[$category])) {
                $categoryStats[$category] = [
                    'total' => 0,
                    'active' => 0,
                ];
            }

            $categoryStats[$category]['total']++;

            if ($enabled) {
                $categoryStats[$category]['active']++;
            }
        }

        $categories = array_keys($categories);
        sort($categories);
        ?>
        <div class="wrap element-pack-dashboard calio-admin-page">
            <h1 class="calio-admin-notice-anchor"></h1>

            <div class="calio-admin-shell">
            <header class="calio-admin-header">
                <div class="calio-admin-header-brand">
                    <img src="<?php echo esc_url(CALIO_URL . 'assets/admin/calio-menu-icon.svg'); ?>" alt="<?php echo esc_attr__('Calio mark', 'calio-addon'); ?>" />
                    <div class="calio-admin-header-copy">
                        <strong><?php echo esc_html__('Calio', 'calio-addon'); ?></strong>
                        <span><?php echo esc_html__('Elementor Addon Dashboard', 'calio-addon'); ?></span>
                    </div>
                </div>

                <div class="calio-admin-header-actions">
                    <span class="calio-placeholder-label"><?php echo esc_html('v' . $pluginVersion); ?></span>
                    <a class="calio-admin-header-link" href="<?php echo esc_url(admin_url('post-new.php?post_type=page')); ?>">
                        <?php echo esc_html__('Create New Page', 'calio-addon'); ?>
                    </a>
                </div>
            </header>

            <div class="calio-admin-frame">
            <aside class="calio-admin-sidebar">
                <div class="calio-sidebar-panel">
                    <div class="calio-sidebar-panel-brand">
                        <img src="<?php echo esc_url(CALIO_URL . 'assets/admin/calio-menu-icon.svg'); ?>" alt="<?php echo esc_attr__('Calio mark', 'calio-addon'); ?>" />
                        <div class="calio-sidebar-panel-copy">
                            <strong><?php echo esc_html__('Calio', 'calio-addon'); ?></strong>
                            <span><?php echo esc_html__('Control Sections', 'calio-addon'); ?></span>
                        </div>
                    </div>
                    <div class="calio-sidebar-panel-meta">
                        <span class="calio-placeholder-label"><?php echo esc_html__('Dashboard', 'calio-addon'); ?></span>
                        <span class="calio-placeholder-label"><?php echo esc_html('v' . $pluginVersion); ?></span>
                    </div>
                </div>

                <nav class="calio-tab-nav" id="calio-tabs" aria-label="Calio settings tabs">
                    <?php foreach ($this->tabs as $tabId => $tab) : ?>
                        <a href="#<?php echo esc_attr($tabId); ?>" class="calio-tab-link" data-tab="<?php echo esc_attr($tabId); ?>">
                            <span class="calio-tab-icon dashicons <?php echo esc_attr($tab['icon']); ?>" aria-hidden="true"></span>
                            <span class="calio-tab-label"><?php echo esc_html($tab['label']); ?></span>
                        </a>
                    <?php endforeach; ?>
                </nav>
            </aside>

            <div class="calio-admin-content">
            <section id="calio_overview" class="calio-tab-panel">
                <div class="calio-hero calio-hero-overview">
                    <div class="calio-hero-banner">
                        <img src="<?php echo esc_url(CALIO_URL . 'assets/admin/calio-dashboard-banner.svg'); ?>" alt="<?php echo esc_attr__('Calio dashboard banner', 'calio-addon'); ?>" />
                    </div>

                    <div class="calio-hero-summary">
                        <div class="calio-hero-copy">
                            <span class="calio-kicker"><?php echo esc_html__('Calio Control Center', 'calio-addon'); ?></span>
                            <p><?php echo esc_html__('General health, requirements and module totals live here so the control tabs can stay focused on actual runtime settings.', 'calio-addon'); ?></p>
                        </div>

                        <div class="calio-hero-meta">
                            <div class="calio-hero-brand-chips">
                                <span class="calio-placeholder-label"><?php echo esc_html__('Widgets', 'calio-addon'); ?>: <?php echo esc_html((string) $totalWidgets); ?></span>
                                <span class="calio-placeholder-label"><?php echo esc_html__('Extensions', 'calio-addon'); ?>: <?php echo esc_html((string) $totalExtensions); ?></span>
                                <span class="calio-placeholder-label"><?php echo esc_html(!empty($otherSettings['load_assets_globally']) ? __('Global Assets', 'calio-addon') : __('Conditional Assets', 'calio-addon')); ?></span>
                                <span class="calio-placeholder-label"><?php echo esc_html($phaseLabel); ?></span>
                            </div>

                            <div class="calio-quickstart-actions">
                                <a class="calio-quick-action" href="#calio_addon_active_modules"><?php echo esc_html__('Open Widgets', 'calio-addon'); ?></a>
                                <a class="calio-quick-action" href="#calio_addon_elementor_extend"><?php echo esc_html__('Open Extensions', 'calio-addon'); ?></a>
                                <a class="calio-quick-action" href="#calio_addon_api_settings"><?php echo esc_html__('Open API', 'calio-addon'); ?></a>
                            </div>
                        </div>

                        <div class="calio-hero-stats calio-hero-stats-compact">
                            <div class="calio-stat-card calio-stat-card-primary">
                                <span class="calio-stat-label"><?php echo esc_html__('Active Widgets', 'calio-addon'); ?></span>
                                <strong class="calio-stat-value" data-active-count><?php echo esc_html((string) $activeWidgets); ?></strong>
                                <span class="calio-stat-note"><?php echo esc_html__('ready in Elementor', 'calio-addon'); ?></span>
                            </div>
                            <div class="calio-stat-card">
                                <span class="calio-stat-label"><?php echo esc_html__('Disabled Widgets', 'calio-addon'); ?></span>
                                <strong class="calio-stat-value" data-disabled-count><?php echo esc_html((string) $disabledWidgets); ?></strong>
                                <span class="calio-stat-note"><?php echo esc_html__('available when needed', 'calio-addon'); ?></span>
                            </div>
                            <div class="calio-stat-card">
                                <span class="calio-stat-label"><?php echo esc_html__('Active Extensions', 'calio-addon'); ?></span>
                                <strong class="calio-stat-value"><?php echo esc_html((string) $activeExtensions); ?></strong>
                                <span class="calio-stat-note"><?php echo esc_html__('utility layers enabled', 'calio-addon'); ?></span>
                            </div>
                            <div class="calio-stat-card">
                                <span class="calio-stat-label"><?php echo esc_html__('Plugin Version', 'calio-addon'); ?></span>
                                <strong class="calio-stat-value calio-stat-value-small"><?php echo esc_html('v' . $pluginVersion); ?></strong>
                                <span class="calio-stat-note"><?php echo esc_html__('current local build', 'calio-addon'); ?></span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="calio-overview-shell">
                    <div class="calio-overview-main">
                        <div class="calio-surface">
                            <div class="calio-surface-head">
                                <div>
                                    <h2><?php echo esc_html__('System Requirements', 'calio-addon'); ?></h2>
                                    <p class="calio-section-note"><?php echo esc_html__('Live environment checks stay here instead of crowding the widget manager.', 'calio-addon'); ?></p>
                                </div>
                            </div>
                            <div class="calio-requirements-grid">
                                <?php foreach ($requirements as $requirement) : ?>
                                    <article class="calio-requirement-card <?php echo esc_attr($requirement['ok'] ? 'is-ok' : 'is-risk'); ?>">
                                        <span class="calio-requirement-label"><?php echo esc_html($requirement['label']); ?></span>
                                        <strong class="calio-requirement-current"><?php echo esc_html($requirement['current']); ?></strong>
                                        <span class="calio-requirement-required"><?php echo esc_html__('Required:', 'calio-addon'); ?> <?php echo esc_html($requirement['required']); ?></span>
                                        <span class="calio-requirement-state"><?php echo esc_html($requirement['ok'] ? __('Ready', 'calio-addon') : __('Needs attention', 'calio-addon')); ?></span>
                                    </article>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <div class="calio-overview-strip">
                            <article class="calio-overview-mini">
                                <span class="calio-insight-label"><?php echo esc_html__('Widget Coverage', 'calio-addon'); ?></span>
                                <strong><?php echo esc_html((string) $activeWidgets); ?> / <?php echo esc_html((string) $totalWidgets); ?></strong>
                                <p><?php echo esc_html__('widgets enabled right now', 'calio-addon'); ?></p>
                            </article>
                            <article class="calio-overview-mini">
                                <span class="calio-insight-label"><?php echo esc_html__('Asset Mode', 'calio-addon'); ?></span>
                                <strong><?php echo esc_html(!empty($otherSettings['load_assets_globally']) ? __('Global', 'calio-addon') : __('Conditional', 'calio-addon')); ?></strong>
                                <p><?php echo esc_html(!empty($otherSettings['load_assets_globally']) ? __('simple delivery path', 'calio-addon') : __('lean runtime loading', 'calio-addon')); ?></p>
                            </article>
                            <article class="calio-overview-mini">
                                <span class="calio-insight-label"><?php echo esc_html__('Reminder', 'calio-addon'); ?></span>
                                <strong><?php echo esc_html__('Save after edits', 'calio-addon'); ?></strong>
                                <p><?php echo esc_html__('switches preview instantly but save persists them', 'calio-addon'); ?></p>
                            </article>
                        </div>
                    </div>

                    <aside class="calio-overview-side">
                        <div class="calio-surface">
                            <div class="calio-surface-head">
                                <div>
                                    <h2><?php echo esc_html__('Widget Categories', 'calio-addon'); ?></h2>
                                    <p class="calio-section-note"><?php echo esc_html__('A quick snapshot of how your widget mix is distributed right now.', 'calio-addon'); ?></p>
                                </div>
                            </div>
                            <div class="calio-overview-grid">
                                <?php foreach ($categories as $category) : ?>
                                    <article class="calio-overview-card is-static">
                                        <span class="calio-overview-label"><?php echo esc_html($category); ?></span>
                                        <strong class="calio-overview-value"><?php echo esc_html((string) $categoryStats[$category]['active']); ?></strong>
                                        <span class="calio-overview-note"><?php echo esc_html((string) $categoryStats[$category]['total']); ?> <?php echo esc_html__('total widgets', 'calio-addon'); ?></span>
                                    </article>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </aside>
                </div>
            </section>

            <section id="calio_addon_active_modules" class="calio-tab-panel">
                <div class="calio-surface">
                    <div class="calio-module-toolbar">
                        <div class="calio-module-toolbar-left">
                            <div>
                            <h2><?php echo esc_html__('Core Widgets', 'calio-addon'); ?></h2>
                                <p class="calio-section-note"><?php echo esc_html__('Disable the widgets you are not using so Elementor only loads the parts you actually need.', 'calio-addon'); ?></p>
                            </div>

                            <div class="calio-module-pills" id="calio-state-filters">
                                <button type="button" class="calio-filter-pill calio-module-pill is-active" data-filter-type="state" data-filter-value="all">
                                    <span><?php echo esc_html__('All', 'calio-addon'); ?></span>
                                    <strong data-total-count><?php echo esc_html((string) $totalWidgets); ?></strong>
                                </button>
                                <button type="button" class="calio-filter-pill calio-module-pill" data-filter-type="state" data-filter-value="active">
                                    <span><?php echo esc_html__('Active', 'calio-addon'); ?></span>
                                    <strong data-active-count><?php echo esc_html((string) $activeWidgets); ?></strong>
                                </button>
                                <button type="button" class="calio-filter-pill calio-module-pill" data-filter-type="state" data-filter-value="disabled">
                                    <span><?php echo esc_html__('Disabled', 'calio-addon'); ?></span>
                                    <strong data-disabled-count><?php echo esc_html((string) $disabledWidgets); ?></strong>
                                </button>
                                <button type="button" class="calio-filter-pill calio-module-pill is-active" data-filter-type="tier" data-filter-value="all">
                                    <span><?php echo esc_html__('All Tiers', 'calio-addon'); ?></span>
                                    <strong data-total-count><?php echo esc_html((string) $totalWidgets); ?></strong>
                                </button>
                                <button type="button" class="calio-filter-pill calio-module-pill" data-filter-type="tier" data-filter-value="free">
                                    <span><?php echo esc_html__('Free', 'calio-addon'); ?></span>
                                    <strong data-free-count><?php echo esc_html((string) $freeWidgets); ?></strong>
                                </button>
                                <button type="button" class="calio-filter-pill calio-module-pill" data-filter-type="tier" data-filter-value="pro">
                                    <span><?php echo esc_html__('Pro', 'calio-addon'); ?></span>
                                    <strong data-pro-count><?php echo esc_html((string) $proWidgets); ?></strong>
                                </button>
                                <span class="calio-module-pill calio-module-pill-static">
                                    <span><?php echo esc_html__('Locked', 'calio-addon'); ?></span>
                                    <strong data-locked-count><?php echo esc_html((string) $lockedWidgets); ?></strong>
                                </span>
                                <a href="#calio_addon_elementor_extend" class="calio-module-pill calio-module-pill-static calio-module-pill-link">
                                    <span><?php echo esc_html__('Extensions', 'calio-addon'); ?></span>
                                    <strong><?php echo esc_html((string) $activeExtensions); ?></strong>
                                </a>
                            </div>
                        </div>

                        <div class="calio-module-toolbar-right">
                            <div class="calio-toolbar-actions">
                            <input id="calio-widget-search" type="search" placeholder="<?php echo esc_attr__('Search widget, category or keyword...', 'calio-addon'); ?>" />
                            <button type="button" class="button" id="calio-clear-search"><?php echo esc_html__('Clear Search', 'calio-addon'); ?></button>
                            <button type="button" class="button" id="calio-enable-all"><?php echo esc_html__('Enable All', 'calio-addon'); ?></button>
                            <button type="button" class="button" id="calio-disable-all"><?php echo esc_html__('Disable All', 'calio-addon'); ?></button>
                            </div>
                        </div>
                    </div>

                    <div class="calio-filter-bar calio-filter-bar-compact" aria-label="<?php echo esc_attr__('Widget filters', 'calio-addon'); ?>">
                        <span class="calio-filter-label"><?php echo esc_html__('Filter By', 'calio-addon'); ?></span>
                        <div class="calio-filter-group" id="calio-category-filters">
                            <button type="button" class="calio-filter-pill is-active" data-filter-type="category" data-filter-value="all"><?php echo esc_html__('All Categories', 'calio-addon'); ?></button>
                            <?php foreach ($categories as $category) : ?>
                                <button type="button" class="calio-filter-pill" data-filter-type="category" data-filter-value="<?php echo esc_attr(strtolower($category)); ?>"><?php echo esc_html($category); ?></button>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <div class="calio-module-summary">
                        <span class="calio-results-note"><strong data-visible-count><?php echo esc_html((string) $totalWidgets); ?></strong> <?php echo esc_html__('widgets visible', 'calio-addon'); ?></span>
                        <span class="calio-results-note" data-filter-summary><?php echo esc_html__('Showing all categories, all tiers, all states.', 'calio-addon'); ?></span>
                    </div>

                    <form method="post" action="options.php" id="calio-core-form">
                        <?php settings_fields('calio_addon_active_modules'); ?>

                        <div class="calio-widget-grid" id="calio-widget-grid">
                            <?php foreach ($coreWidgets as $slug => $widget) : ?>
                                <?php
                                $tier = strtolower((string) ($widget['tier'] ?? 'free'));
                                if (!in_array($tier, ['free', 'pro'], true)) {
                                    $tier = 'free';
                                }

                                $isLocked = $tier === 'pro' && !$proUnlocked;
                                $enabled = !$isLocked && !empty($coreMap[$slug]);
                                $cardClasses = 'calio-widget-card' . ($isLocked ? ' is-locked' : '');
                                $tierLabel = $tier === 'pro' ? esc_html__('Pro', 'calio-addon') : esc_html__('Free', 'calio-addon');
                                ?>
                                <article class="<?php echo esc_attr($cardClasses); ?>" data-widget-item data-title="<?php echo esc_attr(strtolower($widget['title'])); ?>" data-keywords="<?php echo esc_attr(strtolower(trim(((string) $widget['keywords']) . ' ' . $tier))); ?>" data-category="<?php echo esc_attr(strtolower($widget['category'])); ?>" data-tier="<?php echo esc_attr($tier); ?>" data-locked="<?php echo esc_attr($isLocked ? '1' : '0'); ?>" data-enabled="<?php echo esc_attr($enabled ? '1' : '0'); ?>">
                                    <div class="calio-widget-status-bar"></div>
                                    <div class="calio-widget-head">
                                        <div class="calio-widget-head-main">
                                            <div class="calio-widget-title-row">
                                                <h3><?php echo esc_html($widget['title']); ?></h3>
                                                <?php if ($tier === 'pro') : ?>
                                                    <span class="calio-lock-badge<?php echo esc_attr($isLocked ? '' : ' is-unlocked'); ?>"><?php echo esc_html__('Pro', 'calio-addon'); ?></span>
                                                <?php endif; ?>
                                            </div>
                                            <span class="calio-focus-pill"><?php echo esc_html($widget['focus']); ?></span>
                                            <p class="calio-widget-summary"><?php echo esc_html($widget['summary']); ?></p>
                                            <?php if ($isLocked) : ?>
                                                <p class="calio-widget-lock-note"><?php echo esc_html__('Premium plugin required. Install and activate Pro to unlock this widget.', 'calio-addon'); ?></p>
                                            <?php endif; ?>
                                        </div>
                                        <div class="calio-widget-head-side">
                                            <?php if ($isLocked) : ?>
                                                <input type="hidden" name="<?php echo esc_attr(Settings::OPTION_CORE_WIDGETS . '[' . $slug . ']'); ?>" value="0" />
                                                <div class="calio-lock-actions">
                                                    <span class="calio-lock-chip"><span class="dashicons dashicons-lock" aria-hidden="true"></span><?php echo esc_html__('Locked', 'calio-addon'); ?></span>
                                                    <?php if ($useLicenseDialogTrigger) : ?>
                                                        <a href="#calio_addon_license_settings"
                                                           class="calio-lock-link"><?php echo esc_html($proCtaLabel); ?></a>
                                                    <?php else : ?>
                                                        <a href="<?php echo esc_url($proCtaUrl); ?>" class="calio-lock-link"><?php echo esc_html($proCtaLabel); ?></a>
                                                    <?php endif; ?>
                                                </div>
                                            <?php else : ?>
                                                <?php $this->render_toggle_control(Settings::OPTION_CORE_WIDGETS . '[' . $slug . ']', $enabled, (string) $widget['title'], true); ?>
                                            <?php endif; ?>
                                        </div>
                                    </div>

                                    <div class="calio-widget-meta">
                                        <span class="calio-widget-slug"><?php echo esc_html($slug); ?></span>
                                        <span class="calio-meta-chip"><?php echo esc_html($widget['category']); ?></span>
                                        <span class="calio-meta-chip calio-meta-chip-tier <?php echo esc_attr($tier === 'pro' ? 'is-pro' : 'is-free'); ?>"><?php echo esc_html($tierLabel); ?></span>
                                        <?php if ($isLocked) : ?>
                                            <span class="calio-meta-chip calio-meta-chip-locked"><?php echo esc_html__('Locked', 'calio-addon'); ?></span>
                                        <?php endif; ?>
                                    </div>
                                </article>
                            <?php endforeach; ?>
                        </div>
                        <div class="calio-empty-state" id="calio-widget-empty-state" hidden>
                            <span class="calio-placeholder-label"><?php echo esc_html__('No Results', 'calio-addon'); ?></span>
                            <p><?php echo esc_html__('No widgets match the current search and filter combination. Try clearing filters or search terms.', 'calio-addon'); ?></p>
                        </div>

                        <div class="calio-form-footer">
                            <span class="calio-form-status" data-form-status><?php echo esc_html__('No unsaved changes yet.', 'calio-addon'); ?></span>
                            <?php submit_button(__('Save Core Widgets', 'calio-addon'), 'primary calio-save-btn'); ?>
                        </div>
                    </form>
                </div>
            </section>

            <section id="calio_addon_third_party_widget" class="calio-tab-panel">
                <div class="calio-surface">
                    <div class="calio-module-toolbar">
                        <div class="calio-module-toolbar-left">
                            <div>
                                <h2><?php echo esc_html__('3rd Party Widgets', 'calio-addon'); ?></h2>
                                <p class="calio-section-note"><?php echo esc_html__('External platform widgets stay here so Core Widgets stays focused on first-party modules.', 'calio-addon'); ?></p>
                            </div>

                            <div class="calio-module-pills">
                                <span class="calio-module-pill calio-module-pill-static">
                                    <span><?php echo esc_html__('Total', 'calio-addon'); ?></span>
                                    <strong><?php echo esc_html((string) $thirdPartyTotalWidgets); ?></strong>
                                </span>
                                <span class="calio-module-pill calio-module-pill-static">
                                    <span><?php echo esc_html__('Active', 'calio-addon'); ?></span>
                                    <strong><?php echo esc_html((string) $thirdPartyActiveWidgets); ?></strong>
                                </span>
                                <span class="calio-module-pill calio-module-pill-static">
                                    <span><?php echo esc_html__('Disabled', 'calio-addon'); ?></span>
                                    <strong><?php echo esc_html((string) $thirdPartyDisabledWidgets); ?></strong>
                                </span>
                                <span class="calio-module-pill calio-module-pill-static">
                                    <span><?php echo esc_html__('Free', 'calio-addon'); ?></span>
                                    <strong><?php echo esc_html((string) $thirdPartyFreeWidgets); ?></strong>
                                </span>
                                <span class="calio-module-pill calio-module-pill-static">
                                    <span><?php echo esc_html__('Pro', 'calio-addon'); ?></span>
                                    <strong><?php echo esc_html((string) $thirdPartyProWidgets); ?></strong>
                                </span>
                                <span class="calio-module-pill calio-module-pill-static">
                                    <span><?php echo esc_html__('Locked', 'calio-addon'); ?></span>
                                    <strong><?php echo esc_html((string) $thirdPartyLockedWidgets); ?></strong>
                                </span>
                            </div>
                        </div>
                    </div>

                    <form method="post" action="options.php">
                        <?php settings_fields('calio_addon_active_modules'); ?>

                        <div class="calio-widget-grid">
                            <?php if ($thirdPartyWidgets === []) : ?>
                                <article class="calio-widget-card calio-widget-card-single" data-enabled="0">
                                    <div class="calio-widget-head">
                                        <div class="calio-widget-head-main">
                                            <h3><?php echo esc_html__('No 3rd Party Widgets Yet', 'calio-addon'); ?></h3>
                                            <p class="calio-widget-summary"><?php echo esc_html__('As third-party modules are added (Instagram, WooCommerce, etc.), they will appear here with separate toggles.', 'calio-addon'); ?></p>
                                        </div>
                                    </div>
                                </article>
                            <?php else : ?>
                                <?php foreach ($thirdPartyWidgets as $slug => $widget) : ?>
                                    <?php
                                    $tier = strtolower((string) ($widget['tier'] ?? 'free'));
                                    if (!in_array($tier, ['free', 'pro'], true)) {
                                        $tier = 'free';
                                    }

                                    $isLocked = $tier === 'pro' && !$proUnlocked;
                                    $enabled = !$isLocked && !empty($coreMap[$slug]);
                                    $cardClasses = 'calio-widget-card' . ($isLocked ? ' is-locked' : '');
                                    $tierLabel = $tier === 'pro' ? esc_html__('Pro', 'calio-addon') : esc_html__('Free', 'calio-addon');
                                    ?>
                                    <article class="<?php echo esc_attr($cardClasses); ?>" data-enabled="<?php echo esc_attr($enabled ? '1' : '0'); ?>">
                                        <div class="calio-widget-status-bar"></div>
                                        <div class="calio-widget-head">
                                            <div class="calio-widget-head-main">
                                                <div class="calio-widget-title-row">
                                                    <h3><?php echo esc_html($widget['title']); ?></h3>
                                                    <?php if ($tier === 'pro') : ?>
                                                        <span class="calio-lock-badge<?php echo esc_attr($isLocked ? '' : ' is-unlocked'); ?>"><?php echo esc_html__('Pro', 'calio-addon'); ?></span>
                                                    <?php endif; ?>
                                                </div>
                                                <span class="calio-focus-pill"><?php echo esc_html($widget['focus']); ?></span>
                                                <p class="calio-widget-summary"><?php echo esc_html($widget['summary']); ?></p>
                                                <?php if ($isLocked) : ?>
                                                    <p class="calio-widget-lock-note"><?php echo esc_html__('Premium plugin required. Install and activate Pro to unlock this widget.', 'calio-addon'); ?></p>
                                                <?php endif; ?>
                                            </div>
                                            <div class="calio-widget-head-side">
                                                <?php if ($isLocked) : ?>
                                                    <input type="hidden" name="<?php echo esc_attr(Settings::OPTION_CORE_WIDGETS . '[' . $slug . ']'); ?>" value="0" />
                                                    <div class="calio-lock-actions">
                                                        <span class="calio-lock-chip"><span class="dashicons dashicons-lock" aria-hidden="true"></span><?php echo esc_html__('Locked', 'calio-addon'); ?></span>
                                                        <?php if ($useLicenseDialogTrigger) : ?>
                                                            <a href="#calio_addon_license_settings" class="calio-lock-link"><?php echo esc_html($proCtaLabel); ?></a>
                                                        <?php elseif ($licensePrimaryUrl !== '') : ?>
                                                            <a href="<?php echo esc_url($licensePrimaryUrl); ?>" class="calio-lock-link"><?php echo esc_html($proCtaLabel); ?></a>
                                                        <?php endif; ?>
                                                    </div>
                                                <?php else : ?>
                                                    <?php $this->render_toggle_control(Settings::OPTION_CORE_WIDGETS . '[' . $slug . ']', $enabled, (string) $widget['title'], true); ?>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <div class="calio-widget-meta">
                                            <span class="calio-widget-slug"><?php echo esc_html($slug); ?></span>
                                            <span class="calio-meta-chip"><?php echo esc_html($widget['category']); ?></span>
                                            <span class="calio-meta-chip calio-meta-chip-tier <?php echo esc_attr($tier === 'pro' ? 'is-pro' : 'is-free'); ?>"><?php echo esc_html($tierLabel); ?></span>
                                            <?php if ($isLocked) : ?>
                                                <span class="calio-meta-chip calio-meta-chip-locked"><?php echo esc_html__('Locked', 'calio-addon'); ?></span>
                                            <?php endif; ?>
                                        </div>
                                    </article>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>

                        <div class="calio-form-footer">
                            <span class="calio-form-status" data-form-status><?php echo esc_html__('No unsaved changes yet.', 'calio-addon'); ?></span>
                            <?php submit_button(__('Save 3rd Party Widgets', 'calio-addon'), 'primary calio-save-btn'); ?>
                        </div>
                    </form>
                </div>
            </section>

            <section id="calio_addon_dashboard_widgets" class="calio-tab-panel">
                <div class="calio-surface">
                    <div class="calio-module-toolbar">
                        <div class="calio-module-toolbar-left">
                            <div>
                                <h2><?php echo esc_html__('Dashboard Widgets', 'calio-addon'); ?></h2>
                                <p class="calio-section-note"><?php echo esc_html__('Choose which Calio monitoring and status cards appear on the main WordPress Dashboard.', 'calio-addon'); ?></p>
                            </div>

                            <div class="calio-module-pills">
                                <span class="calio-module-pill calio-module-pill-static">
                                    <span><?php echo esc_html__('Total', 'calio-addon'); ?></span>
                                    <strong><?php echo esc_html((string) $totalDashboardWidgets); ?></strong>
                                </span>
                                <span class="calio-module-pill calio-module-pill-static">
                                    <span><?php echo esc_html__('Active', 'calio-addon'); ?></span>
                                    <strong><?php echo esc_html((string) $activeDashboardWidgets); ?></strong>
                                </span>
                                <span class="calio-module-pill calio-module-pill-static">
                                    <span><?php echo esc_html__('Disabled', 'calio-addon'); ?></span>
                                    <strong><?php echo esc_html((string) $disabledDashboardWidgets); ?></strong>
                                </span>
                            </div>
                        </div>
                    </div>

                    <form method="post" action="options.php">
                        <?php settings_fields('calio_addon_dashboard_widgets'); ?>

                        <div class="calio-widget-grid">
                            <?php foreach ($dashboardWidgets as $slug => $dashboardWidget) : ?>
                                <?php
                                $enabled = !empty($dashboardWidgetMap[$slug]);
                                $requiresWooCommerce = !empty($dashboardWidget['requires_woocommerce']);
                                $requirementMet = !$requiresWooCommerce || class_exists('WooCommerce');
                                ?>
                                <article class="calio-widget-card<?php echo esc_attr($requirementMet ? '' : ' is-requirement-missing'); ?>" data-enabled="<?php echo esc_attr($enabled ? '1' : '0'); ?>">
                                    <div class="calio-widget-status-bar"></div>
                                    <div class="calio-widget-head">
                                        <div class="calio-widget-head-main">
                                            <div class="calio-widget-title-row">
                                                <h3><?php echo esc_html($dashboardWidget['title']); ?></h3>
                                                <span class="calio-lock-badge is-unlocked"><?php echo esc_html__('Dashboard', 'calio-addon'); ?></span>
                                            </div>
                                            <span class="calio-focus-pill"><?php echo esc_html($dashboardWidget['focus']); ?></span>
                                            <p class="calio-widget-summary"><?php echo esc_html($dashboardWidget['summary']); ?></p>
                                            <?php if (!$requirementMet) : ?>
                                                <p class="calio-widget-lock-note"><?php echo esc_html__('WooCommerce must be installed and active before this dashboard module can load store data.', 'calio-addon'); ?></p>
                                            <?php endif; ?>
                                        </div>
                                        <div class="calio-widget-head-side">
                                            <?php $this->render_toggle_control(Settings::OPTION_DASHBOARD_WIDGETS . '[' . $slug . ']', $enabled, (string) $dashboardWidget['title'], true); ?>
                                        </div>
                                    </div>
                                    <div class="calio-widget-meta">
                                        <span class="calio-widget-slug"><?php echo esc_html($slug); ?></span>
                                        <span class="calio-meta-chip"><?php echo esc_html($dashboardWidget['requirement']); ?></span>
                                        <span class="calio-meta-chip calio-meta-chip-tier is-free"><?php echo esc_html__('Free', 'calio-addon'); ?></span>
                                    </div>
                                </article>
                            <?php endforeach; ?>
                        </div>

                        <div class="calio-form-footer">
                            <span class="calio-form-status" data-form-status><?php echo esc_html__('No unsaved changes yet.', 'calio-addon'); ?></span>
                            <?php submit_button(__('Save Dashboard Widgets', 'calio-addon'), 'primary calio-save-btn'); ?>
                        </div>
                    </form>
                </div>
            </section>

            <section id="calio_addon_elementor_extend" class="calio-tab-panel">
                <div class="calio-surface">
                    <div class="calio-module-toolbar">
                        <div class="calio-module-toolbar-left">
                            <div>
                                <h2><?php echo esc_html__('Extensions', 'calio-addon'); ?></h2>
                                <p class="calio-section-note"><?php echo esc_html__('Utility extensions stay isolated from widgets so you can keep motion and interaction helpers lean.', 'calio-addon'); ?></p>
                            </div>

                            <div class="calio-module-pills">
                                <span class="calio-module-pill calio-module-pill-static">
                                    <span><?php echo esc_html__('Total', 'calio-addon'); ?></span>
                                    <strong><?php echo esc_html((string) $totalExtensions); ?></strong>
                                </span>
                                <span class="calio-module-pill calio-module-pill-static">
                                    <span><?php echo esc_html__('Active', 'calio-addon'); ?></span>
                                    <strong><?php echo esc_html((string) $activeExtensions); ?></strong>
                                </span>
                                <span class="calio-module-pill calio-module-pill-static">
                                    <span><?php echo esc_html__('Disabled', 'calio-addon'); ?></span>
                                    <strong><?php echo esc_html((string) $disabledExtensions); ?></strong>
                                </span>
                                <span class="calio-module-pill calio-module-pill-static">
                                    <span><?php echo esc_html__('Pro', 'calio-addon'); ?></span>
                                    <strong><?php echo esc_html((string) $proExtensions); ?></strong>
                                </span>
                                <span class="calio-module-pill calio-module-pill-static">
                                    <span><?php echo esc_html__('Locked', 'calio-addon'); ?></span>
                                    <strong><?php echo esc_html((string) $lockedExtensions); ?></strong>
                                </span>
                            </div>
                        </div>
                    </div>

                    <form method="post" action="options.php">
                        <?php settings_fields('calio_addon_elementor_extend'); ?>
                        <div class="calio-widget-grid">
                            <?php foreach ($extensions as $slug => $extension) : ?>
                                <?php $enabled = !empty($extension_map[$slug]); ?>
                                <?php
                                $tier = strtolower((string) ($extension['tier'] ?? 'free'));
                                $tierLabel = $tier === 'pro' ? __('Pro', 'calio-addon') : __('Free', 'calio-addon');
                                $isLocked = ProAccess::is_extension_locked($extension);
                                ?>
                                <article class="calio-widget-card" data-enabled="<?php echo esc_attr($enabled ? '1' : '0'); ?>" data-locked="<?php echo esc_attr($isLocked ? '1' : '0'); ?>">
                                    <div class="calio-widget-status-bar"></div>
                                    <div class="calio-widget-head">
                                        <div class="calio-widget-head-main">
                                            <div class="calio-widget-title-row">
                                                <h3><?php echo esc_html((string) $extension['title']); ?></h3>
                                            </div>
                                            <span class="calio-focus-pill"><?php echo esc_html((string) $extension['focus']); ?></span>
                                            <p class="calio-widget-summary"><?php echo esc_html((string) $extension['summary']); ?></p>
                                        </div>
                                        <div class="calio-widget-head-side">
                                            <?php if ($isLocked) : ?>
                                                <input type="hidden" name="<?php echo esc_attr(Settings::OPTION_EXTENSIONS . '[' . $slug . ']'); ?>" value="0" />
                                                <div class="calio-lock-actions">
                                                    <span class="calio-lock-chip"><span class="dashicons dashicons-lock" aria-hidden="true"></span><?php echo esc_html__('Locked', 'calio-addon'); ?></span>
                                                    <?php if ($useLicenseDialogTrigger) : ?>
                                                        <a href="#calio_addon_license_settings" class="calio-lock-link"><?php echo esc_html($proCtaLabel); ?></a>
                                                    <?php elseif ($licensePrimaryUrl !== '') : ?>
                                                        <a href="<?php echo esc_url($licensePrimaryUrl); ?>" class="calio-lock-link"><?php echo esc_html($proCtaLabel); ?></a>
                                                    <?php endif; ?>
                                                </div>
                                            <?php else : ?>
                                                <?php $this->render_toggle_control(Settings::OPTION_EXTENSIONS . '[' . $slug . ']', $enabled, (string) $extension['title'], true); ?>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="calio-widget-meta">
                                        <span class="calio-widget-slug"><?php echo esc_html($slug); ?></span>
                                        <span class="calio-meta-chip calio-meta-chip-tier <?php echo esc_attr($tier === 'pro' ? 'is-pro' : 'is-free'); ?>"><?php echo esc_html($tierLabel); ?></span>
                                        <?php if ($isLocked) : ?>
                                            <span class="calio-meta-chip calio-meta-chip-locked"><?php echo esc_html__('Locked', 'calio-addon'); ?></span>
                                        <?php endif; ?>
                                    </div>
                                </article>
                            <?php endforeach; ?>
                        </div>
                        <div class="calio-form-footer">
                            <span class="calio-form-status" data-form-status><?php echo esc_html__('No unsaved changes yet.', 'calio-addon'); ?></span>
                            <?php submit_button(__('Save Extensions', 'calio-addon'), 'primary calio-save-btn'); ?>
                        </div>
                    </form>
                </div>
            </section>

            <section id="calio_addon_api_settings" class="calio-tab-panel">
                <div class="calio-surface">
                    <div class="calio-section-toolbar">
                        <div>
                            <h2><?php echo esc_html__('API Settings', 'calio-addon'); ?></h2>
                            <p class="calio-section-note"><?php echo esc_html__('Keep shared provider credentials here so widgets can reuse one stable connection. Google Calendar OAuth now lives here and feeds Calendar Pro without per-widget secrets.', 'calio-addon'); ?></p>
                        </div>
                        <div class="calio-section-pills">
                            <span class="calio-build-pill"><?php echo esc_html__('5 fields', 'calio-addon'); ?></span>
                            <span class="calio-build-pill"><?php echo esc_html__('Local-first', 'calio-addon'); ?></span>
                            <span class="calio-build-pill"><?php echo esc_html($googleConnected ? __('Google Connected', 'calio-addon') : __('Google Ready', 'calio-addon')); ?></span>
                        </div>
                    </div>
                    <?php if ($googleNoticeMessage !== '') : ?>
                        <div class="calio-module-summary">
                            <span class="calio-placeholder-label calio-status-label <?php echo esc_attr($googleNoticeClass); ?>"><?php echo esc_html__('Google Status', 'calio-addon'); ?></span>
                            <span class="calio-results-note"><?php echo esc_html($googleNoticeMessage); ?></span>
                        </div>
                    <?php endif; ?>
                    <form method="post" action="options.php" class="calio-form-grid">
                        <?php settings_fields('calio_addon_api_settings'); ?>
                        <div class="calio-setting-card-grid">
                            <article class="calio-setting-card">
                                <span class="calio-setting-card-kicker"><?php echo esc_html__('Provider', 'calio-addon'); ?></span>
                                <span class="calio-placeholder-label"><?php echo esc_html__('Maps', 'calio-addon'); ?></span>
                                <label>
                                    <span><?php echo esc_html__('Maps API Key', 'calio-addon'); ?></span>
                                    <input
                                        id="calio-maps-api-key"
                                        type="text"
                                        name="<?php echo esc_attr(Settings::OPTION_API_SETTINGS . '[maps_api_key]'); ?>"
                                        value="<?php echo esc_attr((string) ($apiSettings['maps_api_key'] ?? '')); ?>"
                                    />
                                </label>
                                <p class="calio-subtle-note"><?php echo esc_html__('Use this only for widgets or features that actually need map rendering or geolocation providers.', 'calio-addon'); ?></p>
                            </article>
                            <article class="calio-setting-card">
                                <span class="calio-setting-card-kicker"><?php echo esc_html__('Endpoint', 'calio-addon'); ?></span>
                                <span class="calio-placeholder-label"><?php echo esc_html__('Custom Service', 'calio-addon'); ?></span>
                                <label>
                                    <span><?php echo esc_html__('Custom API Endpoint', 'calio-addon'); ?></span>
                                    <input
                                        id="calio-custom-endpoint"
                                        type="url"
                                        name="<?php echo esc_attr(Settings::OPTION_API_SETTINGS . '[custom_endpoint]'); ?>"
                                        value="<?php echo esc_attr((string) ($apiSettings['custom_endpoint'] ?? '')); ?>"
                                    />
                                </label>
                                <p class="calio-subtle-note"><?php echo esc_html__('Keep this empty unless a custom integration or internal service is part of the project.', 'calio-addon'); ?></p>
                            </article>
                            <article class="calio-setting-card">
                                <span class="calio-setting-card-kicker"><?php echo esc_html__('Provider', 'calio-addon'); ?></span>
                                <span class="calio-placeholder-label"><?php echo esc_html__('Google Calendar Public API', 'calio-addon'); ?></span>
                                <label>
                                    <span><?php echo esc_html__('Google Calendar API Key', 'calio-addon'); ?></span>
                                    <input
                                        id="calio-google-calendar-api-key"
                                        type="text"
                                        name="<?php echo esc_attr(Settings::OPTION_API_SETTINGS . '[google_calendar_api_key]'); ?>"
                                        value="<?php echo esc_attr((string) ($apiSettings['google_calendar_api_key'] ?? '')); ?>"
                                    />
                                </label>
                                <p class="calio-subtle-note"><?php echo esc_html__('Optional fallback for public calendars. OAuth sources do not need this field once the account is connected.', 'calio-addon'); ?></p>
                            </article>
                            <article class="calio-setting-card">
                                <span class="calio-setting-card-kicker"><?php echo esc_html__('OAuth', 'calio-addon'); ?></span>
                                <span class="calio-placeholder-label"><?php echo esc_html__('Google Calendar Access', 'calio-addon'); ?></span>
                                <label>
                                    <span><?php echo esc_html__('Google Client ID', 'calio-addon'); ?></span>
                                    <input
                                        id="calio-google-calendar-client-id"
                                        type="text"
                                        name="<?php echo esc_attr(Settings::OPTION_API_SETTINGS . '[google_calendar_client_id]'); ?>"
                                        value="<?php echo esc_attr((string) ($apiSettings['google_calendar_client_id'] ?? '')); ?>"
                                    />
                                </label>
                                <label>
                                    <span><?php echo esc_html__('Google Client Secret', 'calio-addon'); ?></span>
                                    <input
                                        id="calio-google-calendar-client-secret"
                                        type="password"
                                        autocomplete="new-password"
                                        name="<?php echo esc_attr(Settings::OPTION_API_SETTINGS . '[google_calendar_client_secret]'); ?>"
                                        value="<?php echo esc_attr((string) ($apiSettings['google_calendar_client_secret'] ?? '')); ?>"
                                    />
                                </label>
                                <label>
                                    <span><?php echo esc_html__('OAuth Redirect URI', 'calio-addon'); ?></span>
                                    <input
                                        id="calio-google-calendar-redirect-uri"
                                        type="text"
                                        readonly
                                        value="<?php echo esc_attr($googleRedirectUri); ?>"
                                    />
                                </label>
                                <p class="calio-subtle-note"><?php echo esc_html__('Add this exact redirect URI to your Google OAuth client. Save the credentials first, then connect the account from the card below.', 'calio-addon'); ?></p>
                            </article>
                        </div>
                        <div class="calio-form-footer">
                            <span class="calio-form-status" data-form-status><?php echo esc_html__('No unsaved changes yet.', 'calio-addon'); ?></span>
                            <?php submit_button(__('Save API Settings', 'calio-addon'), 'primary calio-save-btn'); ?>
                        </div>
                    </form>
                    <div class="calio-setting-card-grid">
                        <article class="calio-setting-card">
                            <span class="calio-setting-card-kicker"><?php echo esc_html__('Connection', 'calio-addon'); ?></span>
                            <span class="calio-placeholder-label"><?php echo esc_html__('Google Calendar OAuth', 'calio-addon'); ?></span>
                            <div class="calio-license-flags">
                                <span class="calio-placeholder-label calio-status-label <?php echo esc_attr($googleConfigured ? 'is-active' : 'is-inactive'); ?>">
                                    <?php echo esc_html($googleConfigured ? __('Client configured', 'calio-addon') : __('Client missing', 'calio-addon')); ?>
                                </span>
                                <span class="calio-placeholder-label calio-status-label <?php echo esc_attr($googleConnected ? 'is-active' : 'is-inactive'); ?>">
                                    <?php echo esc_html($googleConnected ? __('OAuth connected', 'calio-addon') : __('Not connected', 'calio-addon')); ?>
                                </span>
                            </div>
                            <div class="calio-license-account-grid">
                                <div class="calio-license-account-item">
                                    <span class="calio-license-account-label"><?php echo esc_html__('Account', 'calio-addon'); ?></span>
                                    <strong class="calio-license-account-value"><?php echo esc_html($googleAccountLabel !== '' ? $googleAccountLabel : __('Not connected yet', 'calio-addon')); ?></strong>
                                </div>
                                <div class="calio-license-account-item">
                                    <span class="calio-license-account-label"><?php echo esc_html__('Primary Calendar', 'calio-addon'); ?></span>
                                    <strong class="calio-license-account-value"><?php echo esc_html($googleConnectedCalendar !== '' ? $googleConnectedCalendar : __('Pending connection', 'calio-addon')); ?></strong>
                                </div>
                                <div class="calio-license-account-item">
                                    <span class="calio-license-account-label"><?php echo esc_html__('Connected At', 'calio-addon'); ?></span>
                                    <strong class="calio-license-account-value"><?php echo esc_html($googleConnectedAtLabel); ?></strong>
                                </div>
                                <div class="calio-license-account-item">
                                    <span class="calio-license-account-label"><?php echo esc_html__('Token State', 'calio-addon'); ?></span>
                                    <strong class="calio-license-account-value"><?php echo esc_html($googleExpiryLabel); ?></strong>
                                </div>
                            </div>
                            <?php if ($googleLastError !== '') : ?>
                                <p class="calio-subtle-note" style="color:#b91c1c;"><?php echo esc_html($googleLastError); ?></p>
                            <?php endif; ?>
                            <div class="calio-quickstart-actions">
                                <form method="post" action="<?php echo esc_url(GoogleCalendarOAuthManager::start_url()); ?>" class="calio-inline-action-form">
                                    <?php wp_nonce_field('calio_google_oauth_start'); ?>
                                    <button type="submit" class="calio-quick-action calio-quick-action-primary" <?php disabled(!$googleConfigured); ?>>
                                        <?php echo esc_html($googleConnected ? __('Reconnect Google Calendar', 'calio-addon') : __('Connect Google Calendar', 'calio-addon')); ?>
                                    </button>
                                </form>
                                <?php if ($googleConnected) : ?>
                                    <form method="post" action="<?php echo esc_url(GoogleCalendarOAuthManager::test_url()); ?>" class="calio-inline-action-form">
                                        <?php wp_nonce_field('calio_google_oauth_test'); ?>
                                        <button type="submit" class="calio-quick-action"><?php echo esc_html__('Test Connection', 'calio-addon'); ?></button>
                                    </form>
                                    <form method="post" action="<?php echo esc_url(GoogleCalendarOAuthManager::refresh_url()); ?>" class="calio-inline-action-form">
                                        <?php wp_nonce_field('calio_google_oauth_refresh'); ?>
                                        <button type="submit" class="calio-quick-action"><?php echo esc_html__('Refresh Calendars', 'calio-addon'); ?></button>
                                    </form>
                                <?php endif; ?>
                                <?php if ($googleConnected) : ?>
                                    <form method="post" action="<?php echo esc_url(GoogleCalendarOAuthManager::disconnect_url()); ?>" class="calio-inline-action-form">
                                        <?php wp_nonce_field('calio_google_oauth_disconnect'); ?>
                                        <button type="submit" class="calio-quick-action"><?php echo esc_html__('Disconnect', 'calio-addon'); ?></button>
                                    </form>
                                <?php endif; ?>
                            </div>
                            <p class="calio-subtle-note"><?php echo esc_html__('Calendar Pro OAuth sources reuse this connection. Public Google feeds can still use the shared API key above if you prefer key-based access.', 'calio-addon'); ?></p>
                        </article>
                        <article class="calio-setting-card">
                            <span class="calio-setting-card-kicker"><?php echo esc_html__('Calendar Cache', 'calio-addon'); ?></span>
                            <span class="calio-placeholder-label"><?php echo esc_html__('Available Calendars', 'calio-addon'); ?></span>
                            <?php if ($googleCalendars) : ?>
                                <div class="calio-license-account-grid">
                                    <?php foreach ($googleCalendars as $calendarItem) : ?>
                                        <div class="calio-license-account-item">
                                            <span class="calio-license-account-label">
                                                <?php echo esc_html(!empty($calendarItem['primary']) ? __('Primary', 'calio-addon') : __('Calendar', 'calio-addon')); ?>
                                            </span>
                                            <strong class="calio-license-account-value"><?php echo esc_html($calendarItem['summary']); ?></strong>
                                            <span class="calio-widget-slug"><?php echo esc_html($calendarItem['id']); ?></span>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php else : ?>
                                <p class="calio-subtle-note"><?php echo esc_html__('Connect Google Calendar once and Calio will cache the calendars here for quick reuse in Calendar Pro sources.', 'calio-addon'); ?></p>
                            <?php endif; ?>
                            <?php if ($googleConnectedCalendarId !== '') : ?>
                                <p class="calio-subtle-note"><?php echo esc_html__('Connected calendar ID', 'calio-addon'); ?>: <code><?php echo esc_html($googleConnectedCalendarId); ?></code></p>
                            <?php endif; ?>
                        </article>
                    </div>
                </div>
            </section>

            <section id="calio_addon_other_settings" class="calio-tab-panel">
                <div class="calio-surface">
                    <div class="calio-section-toolbar">
                        <div>
                            <h2><?php echo esc_html__('Other Settings', 'calio-addon'); ?></h2>
                            <p class="calio-section-note"><?php echo esc_html__('Global runtime switches live here, including asset delivery strategy and Smooth Scroll tuning.', 'calio-addon'); ?></p>
                        </div>
                        <div class="calio-section-pills">
                            <span class="calio-build-pill"><?php echo esc_html__('Performance', 'calio-addon'); ?></span>
                        </div>
                    </div>
                    <form method="post" action="options.php">
                        <?php settings_fields('calio_addon_other_settings'); ?>

                        <div class="calio-module-summary">
                            <span class="calio-results-note"><strong><?php echo esc_html(!empty($otherSettings['load_assets_globally']) ? __('Global', 'calio-addon') : __('Conditional', 'calio-addon')); ?></strong> <?php echo esc_html__('asset loading mode', 'calio-addon'); ?></span>
                            <span class="calio-results-note"><strong><?php echo esc_html(Settings::is_extension_enabled('smooth_scroll') ? __('Enabled', 'calio-addon') : __('Disabled', 'calio-addon')); ?></strong> <?php echo esc_html__('smooth scroll extension', 'calio-addon'); ?></span>
                        </div>

                        <div class="calio-setting-card-grid">
                            <article class="calio-widget-card calio-widget-card-single" data-enabled="<?php echo esc_attr(!empty($otherSettings['load_assets_globally']) ? '1' : '0'); ?>">
                                <div class="calio-widget-status-bar"></div>
                                <div class="calio-widget-head">
                                    <div>
                                        <div class="calio-widget-title-row">
                                            <h3><?php echo esc_html__('Load Assets Globally', 'calio-addon'); ?></h3>
                                        </div>
                                        <span class="calio-focus-pill"><?php echo esc_html__('Performance', 'calio-addon'); ?></span>
                                        <p class="calio-widget-summary"><?php echo esc_html__('Enable only if you prefer simpler delivery over per-widget conditional loading.', 'calio-addon'); ?></p>
                                    </div>
                                </div>

                                <div class="calio-widget-meta">
                                    <span class="calio-widget-slug">frontend</span>
                                </div>

                                <div class="calio-widget-footer">
                                    <div class="calio-widget-state-copy">
                                        <span class="calio-widget-state-label"><?php echo esc_html__('State', 'calio-addon'); ?></span>
                                        <strong data-state-text><?php echo esc_html(!empty($otherSettings['load_assets_globally']) ? __('Active', 'calio-addon') : __('Disabled', 'calio-addon')); ?></strong>
                                    </div>
                                    <?php $this->render_toggle_control(Settings::OPTION_OTHER_SETTINGS . '[load_assets_globally]', !empty($otherSettings['load_assets_globally']), esc_html__('Load Assets Globally', 'calio-addon')); ?>
                                </div>
                            </article>

                            <article class="calio-setting-card">
                                <span class="calio-setting-card-kicker"><?php echo esc_html__('Smooth Scroll', 'calio-addon'); ?></span>
                                <span class="calio-placeholder-label"><?php echo esc_html__('Smooth scroll runtime', 'calio-addon'); ?></span>
                                <label>
                                    <span><?php echo esc_html__('Smooth Amount (Desktop)', 'calio-addon'); ?></span>
                                    <input
                                        type="number"
                                        min="0.1"
                                        max="4"
                                        step="0.05"
                                        name="<?php echo esc_attr(Settings::OPTION_OTHER_SETTINGS . '[smooth_scroll_smooth]'); ?>"
                                        value="<?php echo esc_attr((string) (float) ($otherSettings['smooth_scroll_smooth'] ?? 1.15)); ?>"
                                    />
                                </label>
                                <p class="calio-subtle-note"><?php echo esc_html__('Desktop smoothing strength. 1.0 feels natural, higher values feel more cinematic but heavier.', 'calio-addon'); ?></p>
                                <label>
                                    <span><?php echo esc_html__('Smooth Amount (Touch)', 'calio-addon'); ?></span>
                                    <input
                                        type="number"
                                        min="0"
                                        max="2"
                                        step="0.05"
                                        name="<?php echo esc_attr(Settings::OPTION_OTHER_SETTINGS . '[smooth_scroll_touch]'); ?>"
                                        value="<?php echo esc_attr((string) (float) ($otherSettings['smooth_scroll_touch'] ?? 0.08)); ?>"
                                    />
                                </label>
                                <p class="calio-subtle-note"><?php echo esc_html__('Touch smoothing strength. Keep this low to avoid lag on mobile devices.', 'calio-addon'); ?></p>

                                <div class="calio-license-account-grid">
                                    <div class="calio-license-account-item">
                                        <span class="calio-license-account-label"><?php echo esc_html__('Enable Effects', 'calio-addon'); ?></span>
                                        <p class="calio-subtle-note"><?php echo esc_html__('Allows ScrollSmoother effects/parallax data attributes to animate with smoothing.', 'calio-addon'); ?></p>
                                        <?php $this->render_toggle_control(Settings::OPTION_OTHER_SETTINGS . '[smooth_scroll_effects]', !empty($otherSettings['smooth_scroll_effects']), esc_html__('Enable Effects', 'calio-addon')); ?>
                                    </div>
                                    <div class="calio-license-account-item">
                                        <span class="calio-license-account-label"><?php echo esc_html__('Normalize Scroll', 'calio-addon'); ?></span>
                                        <p class="calio-subtle-note"><?php echo esc_html__('Normalizes wheel/trackpad behavior across browsers for more consistent scrolling.', 'calio-addon'); ?></p>
                                        <?php $this->render_toggle_control(Settings::OPTION_OTHER_SETTINGS . '[smooth_scroll_normalize_scroll]', !empty($otherSettings['smooth_scroll_normalize_scroll']), esc_html__('Normalize Scroll', 'calio-addon')); ?>
                                    </div>
                                    <div class="calio-license-account-item">
                                        <span class="calio-license-account-label"><?php echo esc_html__('Ignore Mobile Resize', 'calio-addon'); ?></span>
                                        <p class="calio-subtle-note"><?php echo esc_html__('Prevents frequent mobile viewport resize refresh jumps (address bar open/close).', 'calio-addon'); ?></p>
                                        <?php $this->render_toggle_control(Settings::OPTION_OTHER_SETTINGS . '[smooth_scroll_ignore_mobile_resize]', !empty($otherSettings['smooth_scroll_ignore_mobile_resize']), esc_html__('Ignore Mobile Resize', 'calio-addon')); ?>
                                    </div>
                                </div>
                                <p class="calio-subtle-note"><?php echo esc_html__('These values apply globally once the Smooth Scroll extension is enabled from the Extensions tab.', 'calio-addon'); ?></p>
                            </article>
                        </div>

                        <div class="calio-form-footer">
                            <span class="calio-form-status" data-form-status><?php echo esc_html__('No unsaved changes yet.', 'calio-addon'); ?></span>
                            <?php submit_button(__('Save Other Settings', 'calio-addon'), 'primary calio-save-btn'); ?>
                        </div>
                    </form>
                </div>
            </section>

            <section id="calio_addon_license_settings" class="calio-tab-panel">
                <div class="calio-surface">
                    <div class="calio-section-toolbar">
                        <div>
                            <h2><?php echo esc_html__('License', 'calio-addon'); ?></h2>
                            <p class="calio-section-note"><?php echo esc_html__('Freemius plan and activation state is tracked here. Premium widgets in Core Widgets follow this state in real-time.', 'calio-addon'); ?></p>
                        </div>
                        <div class="calio-section-pills">
                            <span class="calio-build-pill"><?php echo esc_html__('Pro Plugin', 'calio-addon'); ?>: <?php echo esc_html($proPluginActive ? __('Active', 'calio-addon') : __('Inactive', 'calio-addon')); ?></span>
                            <span class="calio-build-pill"><?php echo esc_html__('Compatibility', 'calio-addon'); ?>: <?php echo esc_html($proCompatible ? __('Ready', 'calio-addon') : __('Update Required', 'calio-addon')); ?></span>
                        </div>
                    </div>
                    <div class="calio-license-shell">
                        <article class="calio-dashboard-card calio-dashboard-card-highlight calio-license-summary-card">
                            <span class="calio-dashboard-label"><?php echo esc_html__('Premium Access', 'calio-addon'); ?></span>
                            <strong class="calio-dashboard-value calio-dashboard-value-small calio-license-status <?php echo esc_attr($licenseStateClass); ?>"><?php echo esc_html($licenseStateLabel); ?></strong>
                            <p><?php echo esc_html($licenseStateNote); ?></p>
                            <div class="calio-license-flags">
                                <span class="calio-placeholder-label"><?php echo esc_html__('Required Free', 'calio-addon'); ?>: <?php echo esc_html($requiredFreeVersion !== '' ? $requiredFreeVersion : __('None', 'calio-addon')); ?></span>
                                <span class="calio-placeholder-label calio-status-label <?php echo esc_attr($accountLicenseStateClass); ?>"><?php echo esc_html__('License', 'calio-addon'); ?>: <?php echo esc_html($accountLicenseState); ?></span>
                                <span class="calio-placeholder-label calio-status-label <?php echo esc_attr($licenseCountdownClass); ?>"><?php echo esc_html($licenseCountdownLabel); ?></span>
                            </div>
                            <?php if ($upgradePlansUrl !== '') : ?>
                                <div class="calio-license-upgrade-callout">
                                    <div class="calio-license-upgrade-copy">
                                        <span class="calio-license-upgrade-kicker"><?php echo esc_html__('Premium', 'calio-addon'); ?></span>
                                        <strong><?php echo esc_html($upgradeAreaHeading); ?></strong>
                                        <p><?php echo esc_html($upgradeAreaNote); ?></p>
                                    </div>
                                    <a href="<?php echo esc_url($upgradePlansUrl); ?>" class="calio-quick-action calio-quick-action-primary"><?php echo esc_html($upgradeAreaCta); ?></a>
                                </div>
                            <?php endif; ?>
                            <div class="calio-quickstart-actions">
                                <?php if (!$proUnlocked && ($licenseDialogAvailable || $canInlineLicenseActivation)) : ?>
                                    <button type="button"
                                            class="calio-quick-action calio-quick-action-primary<?php echo esc_attr($licenseDialogAvailable ? ' activate-license-trigger ' . $licenseTriggerClass : ''); ?>"
                                            data-calio-license-modal-trigger="1"
                                            data-calio-license-fallback="#calio-inline-license-activation">
                                        <?php echo esc_html($licensePrimaryLabel); ?>
                                    </button>
                                <?php elseif ($licensePrimaryUrl !== '') : ?>
                                    <a href="<?php echo esc_url($licensePrimaryUrl); ?>" class="calio-quick-action"><?php echo esc_html($licensePrimaryLabel); ?></a>
                                <?php endif; ?>
                                <?php if ($canDeactivateLicense) : ?>
                                    <form action="<?php echo esc_url($deactivateLicenseUrl); ?>" method="post" class="calio-inline-action-form">
                                        <input type="hidden" name="fs_action" value="deactivate_license" />
                                        <?php wp_nonce_field(trim('deactivate_license:' . $deactivateBlogId . ':' . $deactivateInstallId, ':')); ?>
                                        <input type="hidden" name="install_id" value="<?php echo esc_attr($deactivateInstallId); ?>" />
                                        <input type="hidden" name="blog_id" value="<?php echo esc_attr($deactivateBlogId); ?>" />
                                        <button type="button"
                                                class="calio-quick-action fs-deactivate-license"
                                                data-calio-confirm-submit="<?php echo esc_attr__('Deactivate the active license on this site?', 'calio-addon'); ?>"><?php echo esc_html__('Deactivate License', 'calio-addon'); ?></button>
                                    </form>
                                <?php endif; ?>
                                <?php if ($licenseAccountUrl !== '' && $licenseAccountUrl !== $licensePrimaryUrl) : ?>
                                    <a href="<?php echo esc_url($licenseAccountUrl); ?>" class="calio-quick-action">
                                        <?php echo esc_html__('Open Account', 'calio-addon'); ?>
                                    </a>
                                <?php endif; ?>
                                <a href="#calio_addon_active_modules" class="calio-quick-action"><?php echo esc_html__('Back to Core Widgets', 'calio-addon'); ?></a>
                            </div>
                            <?php if ($canInlineLicenseActivation) : ?>
                                <form id="calio-inline-license-activation"
                                      class="calio-license-activation-form"
                                      action="<?php echo esc_url(admin_url('admin-ajax.php')); ?>"
                                      method="post"
                                      data-calio-license-activation>
                                    <label for="calio-license-key"><?php echo esc_html__('License Key', 'calio-addon'); ?></label>
                                    <div class="calio-license-activation-row">
                                        <input id="calio-license-key"
                                               type="password"
                                               name="license_key"
                                               class="regular-text"
                                               autocomplete="off"
                                               placeholder="<?php echo esc_attr__('Paste your Freemius license key', 'calio-addon'); ?>" />
                                        <button type="submit" class="calio-quick-action calio-quick-action-primary">
                                            <?php echo esc_html__('Activate License', 'calio-addon'); ?>
                                        </button>
                                    </div>
                                    <input type="hidden" name="action" value="<?php echo esc_attr($licenseAjaxAction); ?>" />
                                    <input type="hidden" name="security" value="<?php echo esc_attr($licenseAjaxSecurity); ?>" />
                                    <?php if ($licenseModuleId !== '') : ?>
                                        <input type="hidden" name="module_id" value="<?php echo esc_attr($licenseModuleId); ?>" />
                                    <?php endif; ?>
                                    <p class="calio-license-activation-message calio-subtle-note" data-calio-license-message>
                                        <?php echo esc_html__('Activation happens here without leaving the Calio dashboard.', 'calio-addon'); ?>
                                    </p>
                                </form>
                            <?php endif; ?>
                        </article>
                        <article class="calio-setting-card calio-license-account-card">
                            <div class="calio-license-account-head">
                                <span class="calio-setting-card-kicker"><?php echo esc_html__('Account Snapshot', 'calio-addon'); ?></span>
                                <span class="calio-placeholder-label calio-status-label <?php echo esc_attr($accountConnectionClass); ?>"><?php echo esc_html($accountConnectionState); ?></span>
                            </div>
                            <div class="calio-license-account-grid">
                                <?php foreach ($accountRows as $row) : ?>
                                    <?php
                                    $valueClass = 'calio-license-account-value';
                                    if (!empty($row['value_class'])) {
                                        $valueClass .= ' ' . $row['value_class'];
                                    }
                                    ?>
                                    <div class="calio-license-account-item">
                                        <span class="calio-license-account-label"><?php echo esc_html($row['label']); ?></span>
                                        <strong class="<?php echo esc_attr($valueClass); ?>"><?php echo esc_html((string) $row['value']); ?></strong>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <p class="calio-subtle-note"><?php echo esc_html__('For billing, ownership transfer, and advanced actions use Open Account.', 'calio-addon'); ?></p>
                        </article>
                    </div>
                </div>
            </section>
            </div>
            </div>
            </div>
        </div>
        <?php

        if ($licenseDialogAvailable && is_object($freemiusSdk) && method_exists($freemiusSdk, '_add_license_activation_dialog_box')) {
            $freemiusSdk->_add_license_activation_dialog_box();
        }
    }

    private function render_toggle_control(string $name, bool $enabled, string $label, bool $compact = false): void
    {
        ?>
        <div class="calio-switch-wrap<?php echo esc_attr($compact ? ' is-compact' : ''); ?>">
            <input type="hidden" name="<?php echo esc_attr($name); ?>" value="0" />
            <label class="calio-switch" aria-label="<?php echo esc_attr($label); ?>">
                <input class="calio-switch-input" type="checkbox" name="<?php echo esc_attr($name); ?>" value="1" <?php checked($enabled); ?> />
                <span class="calio-switch-track">
                    <span class="calio-switch-thumb"></span>
                </span>
                <span class="calio-switch-copy">
                    <span class="calio-switch-copy-on"><?php echo esc_html__('Active', 'calio-addon'); ?></span>
                    <span class="calio-switch-copy-off"><?php echo esc_html__('Disabled', 'calio-addon'); ?></span>
                </span>
            </label>
        </div>
        <?php
    }
}
