<?php
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Admin view reads URL state and notices but does not process sensitive actions.
if (!defined('ABSPATH')) exit;

$calliope_sp_tab = isset($_GET['tab']) ? sanitize_key(wp_unslash((string) $_GET['tab'])) : 'dashboard';
$calliope_sp_allowed_tabs = apply_filters('calliope_sp_admin_tabs', ['dashboard', 'publisher', 'history', 'analytics', 'connections', 'logs', 'settings']);
$calliope_sp_allowed_tabs = array_values(array_unique(array_filter(array_map('sanitize_key', is_array($calliope_sp_allowed_tabs) ? $calliope_sp_allowed_tabs : []))));
// Keep core information architecture stable even when Pro extensions add/reorder tabs.
$calliope_sp_preferred_tabs = ['dashboard', 'publisher', 'analytics', 'connections', 'scheduled', 'calendar', 'evergreen', 'history', 'logs', 'settings', 'license', 'account_groups', 'content_variations'];
$calliope_sp_ordered_tabs = [];
foreach ($calliope_sp_preferred_tabs as $calliope_sp_preferred_tab) {
    if (in_array($calliope_sp_preferred_tab, $calliope_sp_allowed_tabs, true)) {
        $calliope_sp_ordered_tabs[] = $calliope_sp_preferred_tab;
    }
}
foreach ($calliope_sp_allowed_tabs as $calliope_sp_extra_tab) {
    if (!in_array($calliope_sp_extra_tab, $calliope_sp_ordered_tabs, true)) {
        $calliope_sp_ordered_tabs[] = $calliope_sp_extra_tab;
    }
}
$calliope_sp_allowed_tabs = $calliope_sp_ordered_tabs;
$calliope_sp_tab = in_array($calliope_sp_tab, $calliope_sp_allowed_tabs, true) ? $calliope_sp_tab : 'dashboard';

// Network tab inside Connections. Extensions may add allowlisted network slugs.
$calliope_sp_base_networks = ['bluesky', 'mastodon', 'tumblr', 'pinterest', 'threads', 'instagram', 'linkedin', 'blogger', 'telegram', 'facebook'];
$calliope_sp_allowed_networks = apply_filters('calliope_sp_connection_networks', $calliope_sp_base_networks);
$calliope_sp_allowed_networks = array_values(array_unique(array_filter(array_map('sanitize_key', is_array($calliope_sp_allowed_networks) ? $calliope_sp_allowed_networks : []))));
$calliope_sp_external_networks = array_values(array_diff($calliope_sp_allowed_networks, $calliope_sp_base_networks));
$calliope_sp_net = isset($_GET['net']) ? sanitize_key(wp_unslash((string) $_GET['net'])) : 'bluesky';
if ($calliope_sp_net === 'youtube_shorts') {
    $calliope_sp_net = 'youtube';
}
$calliope_sp_net = in_array($calliope_sp_net, $calliope_sp_allowed_networks, true) ? $calliope_sp_net : 'bluesky';

$calliope_sp_msg  = isset($_GET['calliope_sp_msg']) ? sanitize_text_field(wp_unslash((string) $_GET['calliope_sp_msg'])) : '';
$calliope_sp_type = isset($_GET['calliope_sp_type']) ? sanitize_key(wp_unslash((string) $_GET['calliope_sp_type'])) : '';

$calliope_sp_status_bsky = [
    'key' => 'not_configured',
    'tone' => 'error',
    'label' => __('Not connected', 'calliope-social-publisher'),
    'message' => __('Enter your Bluesky handle and App Password.', 'calliope-social-publisher'),
    'is_ready' => false,
    'health' => 'unknown',
    'needs_attention' => true,
];
$calliope_sp_bsky_legacy_status = (string) get_option('calliope_sp_bsky_connection_status', '');
$calliope_sp_bsky_has_saved_data = calliope_sp_ui_option_has_value('calliope_sp_bsky_handle')
    || calliope_sp_ui_option_has_value('calliope_sp_bsky_password')
    || calliope_sp_ui_option_has_value('calliope_sp_bsky_validation')
    || ($calliope_sp_bsky_legacy_status !== '' && !in_array($calliope_sp_bsky_legacy_status, ['not_configured', 'not_connected'], true));
if (class_exists('Calliope_SP_Bluesky')) {
    $calliope_sp_bsky_state_object = (new Calliope_SP_Bluesky())->get_connection_state();
    if (!is_wp_error($calliope_sp_bsky_state_object) && $calliope_sp_bsky_state_object instanceof Calliope_SP_Connection_State) {
        $calliope_sp_bsky_state = $calliope_sp_bsky_state_object->to_array();
        $calliope_sp_bsky_labels = [
            'not_configured' => __('Not connected', 'calliope-social-publisher'),
            'configuration_error' => __('Configuration incomplete', 'calliope-social-publisher'),
            'connected_unverified' => __('Verification required', 'calliope-social-publisher'),
            'token_invalid' => __('Connection invalid', 'calliope-social-publisher'),
            'ready_to_publish' => $calliope_sp_bsky_state['health'] === 'degraded'
                ? __('Ready, but needs attention', 'calliope-social-publisher')
                : __('Ready to publish', 'calliope-social-publisher'),
        ];
        $calliope_sp_status_bsky = [
            'key' => (string) $calliope_sp_bsky_state['status'],
            'tone' => (string) $calliope_sp_bsky_state['tone'],
            'label' => $calliope_sp_bsky_labels[$calliope_sp_bsky_state['status']] ?? __('Not connected', 'calliope-social-publisher'),
            'message' => (string) $calliope_sp_bsky_state['message'],
            'is_ready' => !empty($calliope_sp_bsky_state['is_ready']),
            'health' => (string) $calliope_sp_bsky_state['health'],
            'needs_attention' => !empty($calliope_sp_bsky_state['needs_attention']),
        ];
    }
}
$calliope_sp_status_mstdn = [
    'key' => 'not_configured',
    'tone' => 'error',
    'label' => __('Not connected', 'calliope-social-publisher'),
    'message' => __('Enter a public Mastodon server and an access token, or connect with OAuth.', 'calliope-social-publisher'),
    'is_ready' => false,
    'health' => 'unknown',
    'needs_attention' => true,
];
$calliope_sp_mstdn_legacy_status = (string) get_option('calliope_sp_mstdn_connection_status', '');
$calliope_sp_mstdn_has_saved_data = calliope_sp_ui_option_has_value('calliope_sp_mstdn_instance')
    || calliope_sp_ui_option_has_value('calliope_sp_mstdn_token')
    || calliope_sp_ui_option_has_value('calliope_sp_mstdn_client_id')
    || calliope_sp_ui_option_has_value('calliope_sp_mstdn_client_secret')
    || calliope_sp_ui_option_has_value('calliope_sp_mstdn_client_instance')
    || calliope_sp_ui_option_has_value('calliope_sp_mstdn_validation')
    || ($calliope_sp_mstdn_legacy_status !== '' && !in_array($calliope_sp_mstdn_legacy_status, ['not_configured', 'not_connected'], true));
if (class_exists('Calliope_SP_Mastodon')) {
    $calliope_sp_mstdn_state_object = (new Calliope_SP_Mastodon())->get_connection_state();
    if (!is_wp_error($calliope_sp_mstdn_state_object) && $calliope_sp_mstdn_state_object instanceof Calliope_SP_Connection_State) {
        $calliope_sp_mstdn_state = $calliope_sp_mstdn_state_object->to_array();
        $calliope_sp_mstdn_labels = [
            'not_configured' => __('Not connected', 'calliope-social-publisher'),
            'credentials_saved' => __('Server saved', 'calliope-social-publisher'),
            'configuration_error' => __('Configuration incomplete', 'calliope-social-publisher'),
            'connected_unverified' => __('Verification required', 'calliope-social-publisher'),
            'identity_missing' => __('Account identity unavailable', 'calliope-social-publisher'),
            'permission_missing' => __('Publishing permission missing', 'calliope-social-publisher'),
            'token_invalid' => __('Connection invalid', 'calliope-social-publisher'),
            'ready_to_publish' => $calliope_sp_mstdn_state['health'] === 'degraded'
                ? __('Ready, but needs attention', 'calliope-social-publisher')
                : __('Ready to publish', 'calliope-social-publisher'),
        ];
        $calliope_sp_status_mstdn = [
            'key' => (string) $calliope_sp_mstdn_state['status'],
            'tone' => (string) $calliope_sp_mstdn_state['tone'],
            'label' => $calliope_sp_mstdn_labels[$calliope_sp_mstdn_state['status']] ?? __('Not connected', 'calliope-social-publisher'),
            'message' => (string) $calliope_sp_mstdn_state['message'],
            'is_ready' => !empty($calliope_sp_mstdn_state['is_ready']),
            'health' => (string) $calliope_sp_mstdn_state['health'],
            'needs_attention' => !empty($calliope_sp_mstdn_state['needs_attention']),
        ];
    }
}
$calliope_sp_status_tumblr = [
    'key' => 'not_configured',
    'tone' => 'error',
    'label' => __('Not connected', 'calliope-social-publisher'),
    'message' => __('Enter Tumblr application credentials and select a blog.', 'calliope-social-publisher'),
    'is_ready' => false,
    'health' => 'unknown',
    'needs_attention' => true,
];
$calliope_sp_tumblr_legacy_status = (string) get_option('calliope_sp_tumblr_connection_status', '');
$calliope_sp_tumblr_has_saved_data = calliope_sp_ui_option_has_value('calliope_sp_tumblr_consumer_key')
    || calliope_sp_ui_option_has_value('calliope_sp_tumblr_consumer_secret')
    || calliope_sp_ui_option_has_value('calliope_sp_tumblr_token')
    || calliope_sp_ui_option_has_value('calliope_sp_tumblr_token_secret')
    || calliope_sp_ui_option_has_value('calliope_sp_tumblr_blog_identifier')
    || calliope_sp_ui_option_has_value('calliope_sp_tumblr_validation')
    || ($calliope_sp_tumblr_legacy_status !== '' && !in_array($calliope_sp_tumblr_legacy_status, ['not_configured', 'not_connected'], true));
if (class_exists('Calliope_SP_Tumblr')) {
    $calliope_sp_tumblr_state_object = (new Calliope_SP_Tumblr())->get_connection_state();
    if (!is_wp_error($calliope_sp_tumblr_state_object) && $calliope_sp_tumblr_state_object instanceof Calliope_SP_Connection_State) {
        $calliope_sp_tumblr_state = $calliope_sp_tumblr_state_object->to_array();
        $calliope_sp_tumblr_labels = [
            'not_configured' => __('Not connected', 'calliope-social-publisher'),
            'credentials_saved' => __('Application credentials saved', 'calliope-social-publisher'),
            'configuration_error' => __('Configuration incomplete', 'calliope-social-publisher'),
            'connected_unverified' => __('Verification required', 'calliope-social-publisher'),
            'identity_missing' => __('Account identity unavailable', 'calliope-social-publisher'),
            'target_missing' => __('Blog selection required', 'calliope-social-publisher'),
            'permission_missing' => __('Publishing permission missing', 'calliope-social-publisher'),
            'token_invalid' => __('Connection invalid', 'calliope-social-publisher'),
            'ready_to_publish' => $calliope_sp_tumblr_state['health'] === 'degraded'
                ? __('Ready, but needs attention', 'calliope-social-publisher')
                : __('Ready to publish', 'calliope-social-publisher'),
        ];
        $calliope_sp_status_tumblr = [
            'key' => (string) $calliope_sp_tumblr_state['status'],
            'tone' => (string) $calliope_sp_tumblr_state['tone'],
            'label' => $calliope_sp_tumblr_labels[$calliope_sp_tumblr_state['status']] ?? __('Not connected', 'calliope-social-publisher'),
            'message' => (string) $calliope_sp_tumblr_state['message'],
            'is_ready' => !empty($calliope_sp_tumblr_state['is_ready']),
            'health' => (string) $calliope_sp_tumblr_state['health'],
            'needs_attention' => !empty($calliope_sp_tumblr_state['needs_attention']),
        ];
    }
}
$calliope_sp_status_pin = [
    'key' => 'not_configured',
    'tone' => 'error',
    'label' => __('Not connected', 'calliope-social-publisher'),
    'message' => __('Enter Pinterest application credentials and connect an account.', 'calliope-social-publisher'),
    'is_ready' => false,
    'health' => 'unknown',
    'needs_attention' => true,
];
$calliope_sp_pin_legacy_status = (string) get_option('calliope_sp_pinterest_connection_status', '');
$calliope_sp_pin_env_saved = (string) get_option('calliope_sp_pinterest_env', 'production');
$calliope_sp_pin_has_saved_data = calliope_sp_ui_option_has_value('calliope_sp_pinterest_app_id')
    || calliope_sp_ui_option_has_value('calliope_sp_pinterest_app_secret')
    || calliope_sp_ui_option_has_value('calliope_sp_pinterest_token')
    || calliope_sp_ui_option_has_value('calliope_sp_pinterest_refresh_token')
    || calliope_sp_ui_option_has_value('calliope_sp_pinterest_board_id')
    || calliope_sp_ui_option_has_value('calliope_sp_pinterest_board_id_production')
    || calliope_sp_ui_option_has_value('calliope_sp_pinterest_board_id_sandbox')
    || calliope_sp_ui_option_has_value('calliope_sp_pinterest_token_environment')
    || calliope_sp_ui_option_has_value('calliope_sp_pinterest_validation')
    || calliope_sp_ui_option_has_value('calliope_sp_pinterest_access_token_expires_at')
    || calliope_sp_ui_option_has_value('calliope_sp_pinterest_refresh_token_expires_at')
    || calliope_sp_ui_option_has_value('calliope_sp_pinterest_granted_scopes')
    || calliope_sp_ui_option_has_value('calliope_sp_pinterest_auth_method')
    || ($calliope_sp_pin_env_saved !== '' && $calliope_sp_pin_env_saved !== 'production')
    || ($calliope_sp_pin_legacy_status !== '' && !in_array($calliope_sp_pin_legacy_status, ['not_configured', 'not_connected'], true));
if (class_exists('Calliope_SP_Pinterest')) {
    $calliope_sp_pin_state_object = (new Calliope_SP_Pinterest())->get_connection_state();
    if (!is_wp_error($calliope_sp_pin_state_object) && $calliope_sp_pin_state_object instanceof Calliope_SP_Connection_State) {
        $calliope_sp_pin_state = $calliope_sp_pin_state_object->to_array();
        $calliope_sp_pin_labels = [
            'not_configured' => __('Not connected', 'calliope-social-publisher'),
            'credentials_saved' => __('Application credentials saved', 'calliope-social-publisher'),
            'configuration_error' => __('Configuration incomplete', 'calliope-social-publisher'),
            'connected_unverified' => __('Connected', 'calliope-social-publisher'),
            'identity_missing' => __('Account identity unavailable', 'calliope-social-publisher'),
            'target_missing' => __('Board selection required', 'calliope-social-publisher'),
            'permission_missing' => __('Publishing permission missing', 'calliope-social-publisher'),
            'environment_mismatch' => __('Reconnect for selected environment', 'calliope-social-publisher'),
            'publish_access_denied' => __('Publishing access denied', 'calliope-social-publisher'),
            'temporary_error' => __('Verification temporarily unavailable', 'calliope-social-publisher'),
            'token_expired' => __('Access token expired', 'calliope-social-publisher'),
            'token_invalid' => __('Connection invalid', 'calliope-social-publisher'),
            'ready_to_publish' => $calliope_sp_pin_state['health'] === 'degraded'
                ? __('Ready, but needs attention', 'calliope-social-publisher')
                : __('Ready to publish', 'calliope-social-publisher'),
        ];
        $calliope_sp_status_pin = [
            'key' => (string) $calliope_sp_pin_state['status'],
            'tone' => (string) $calliope_sp_pin_state['tone'],
            'label' => $calliope_sp_pin_labels[$calliope_sp_pin_state['status']] ?? __('Not connected', 'calliope-social-publisher'),
            'message' => (string) $calliope_sp_pin_state['message'],
            'is_ready' => !empty($calliope_sp_pin_state['is_ready']),
            'health' => (string) $calliope_sp_pin_state['health'],
            'needs_attention' => !empty($calliope_sp_pin_state['needs_attention']),
        ];
    }
}
if ($calliope_sp_tab === 'connections' && $calliope_sp_net === 'pinterest' && $calliope_sp_msg !== '') {
    $calliope_sp_generic_pinterest_notice = __('Pinterest is connected. Select a board before publishing.', 'calliope-social-publisher');
    if (trim(wp_strip_all_tags((string) $calliope_sp_msg)) === trim(wp_strip_all_tags($calliope_sp_generic_pinterest_notice)) && !empty($calliope_sp_status_pin['message'])) {
        $calliope_sp_msg = '';
    }
}
$calliope_sp_meta_status_from_state = static function ($class_name, $fallback_message) {
    $status = ['key'=>'not_configured','tone'=>'error','label'=>__('Not connected','calliope-social-publisher'),'message'=>$fallback_message,'is_ready'=>false,'health'=>'unknown','needs_attention'=>true];
    if (!class_exists($class_name)) return $status;
    $state=(new $class_name())->get_connection_state();
    if (is_wp_error($state) || !($state instanceof Calliope_SP_Connection_State)) return $status;
    $data=$state->to_array();
    $labels=['not_configured'=>__('Not connected','calliope-social-publisher'),'credentials_saved'=>__('Application credentials saved','calliope-social-publisher'),'configuration_error'=>__('Configuration incomplete','calliope-social-publisher'),'connected_unverified'=>__('Verification required','calliope-social-publisher'),'identity_missing'=>__('Account identity unavailable','calliope-social-publisher'),'target_missing'=>__('Target selection required','calliope-social-publisher'),'permission_missing'=>__('Publishing permission missing','calliope-social-publisher'),'token_expired'=>__('Access token expired','calliope-social-publisher'),'token_invalid'=>__('Connection invalid','calliope-social-publisher'),'ready_to_publish'=>$data['health']==='degraded'?__('Ready, but needs attention','calliope-social-publisher'):__('Ready to publish','calliope-social-publisher')];
    return ['key'=>$data['status'],'tone'=>$data['tone'],'label'=>$labels[$data['status']]??__('Not connected','calliope-social-publisher'),'message'=>$data['message'],'is_ready'=>!empty($data['is_ready']),'health'=>$data['health'],'needs_attention'=>!empty($data['needs_attention'])];
};
$calliope_sp_status_thr=$calliope_sp_meta_status_from_state('Calliope_SP_Threads',__('Connect Threads to publish.','calliope-social-publisher'));
$calliope_sp_status_ig=$calliope_sp_meta_status_from_state('Calliope_SP_Instagram',__('Connect Instagram to publish.','calliope-social-publisher'));
$calliope_sp_c_li     = false;
$calliope_sp_status_blg = [
    'key' => 'not_configured', 'tone' => 'error',
    'label' => __('Not connected', 'calliope-social-publisher'),
    'message' => __('Enter Blogger OAuth application credentials.', 'calliope-social-publisher'),
    'is_ready' => false, 'health' => 'unknown', 'needs_attention' => true,
];
$calliope_sp_blogger_legacy_status = (string) get_option('calliope_sp_blogger_connection_status', '');
$calliope_sp_blogger_has_saved_data = calliope_sp_ui_option_has_value('calliope_sp_blogger_client_id')
    || calliope_sp_ui_option_has_value('calliope_sp_blogger_client_secret')
    || calliope_sp_ui_option_has_value('calliope_sp_blogger_access_token')
    || calliope_sp_ui_option_has_value('calliope_sp_blogger_refresh_token')
    || calliope_sp_ui_option_has_value('calliope_sp_blogger_blog_id')
    || calliope_sp_ui_option_has_value('calliope_sp_blogger_blogs_last')
    || calliope_sp_ui_option_has_value('calliope_sp_blogger_validation')
    || ($calliope_sp_blogger_legacy_status !== '' && !in_array($calliope_sp_blogger_legacy_status, ['not_configured', 'not_connected'], true));
if (class_exists('Calliope_SP_Blogger')) {
    $calliope_sp_blogger_state_object = (new Calliope_SP_Blogger())->get_connection_state();
    if (!is_wp_error($calliope_sp_blogger_state_object) && $calliope_sp_blogger_state_object instanceof Calliope_SP_Connection_State) {
        $calliope_sp_blogger_state = $calliope_sp_blogger_state_object->to_array();
        $calliope_sp_blogger_labels = [
            'not_configured' => __('Not connected', 'calliope-social-publisher'),
            'credentials_saved' => __('Application credentials saved', 'calliope-social-publisher'),
            'configuration_error' => __('Configuration incomplete', 'calliope-social-publisher'),
            'connected_unverified' => __('Verification required', 'calliope-social-publisher'),
            'refresh_required' => __('Reconnect required', 'calliope-social-publisher'),
            'token_expired' => __('Access token expired', 'calliope-social-publisher'),
            'identity_missing' => __('Account identity unavailable', 'calliope-social-publisher'),
            'target_missing' => __('Blog selection required', 'calliope-social-publisher'),
            'permission_missing' => __('Publishing permission missing', 'calliope-social-publisher'),
            'token_invalid' => __('Connection invalid', 'calliope-social-publisher'),
            'ready_to_publish' => $calliope_sp_blogger_state['health'] === 'degraded'
                ? __('Ready, but needs attention', 'calliope-social-publisher')
                : __('Ready to publish', 'calliope-social-publisher'),
        ];
        $calliope_sp_status_blg = [
            'key' => (string) $calliope_sp_blogger_state['status'],
            'tone' => (string) $calliope_sp_blogger_state['tone'],
            'label' => $calliope_sp_blogger_labels[$calliope_sp_blogger_state['status']] ?? __('Not connected', 'calliope-social-publisher'),
            'message' => (string) $calliope_sp_blogger_state['message'],
            'is_ready' => !empty($calliope_sp_blogger_state['is_ready']),
            'health' => (string) $calliope_sp_blogger_state['health'],
            'needs_attention' => !empty($calliope_sp_blogger_state['needs_attention']),
        ];
    }
}
$calliope_sp_status_telegram = [
    'key' => 'not_configured',
    'tone' => 'error',
    'label' => __('Not connected', 'calliope-social-publisher'),
    'message' => __('Enter a Telegram Bot Token and destination.', 'calliope-social-publisher'),
    'is_ready' => false,
    'health' => 'unknown',
    'needs_attention' => true,
];
$calliope_sp_telegram_legacy_status = (string) get_option('calliope_sp_telegram_connection_status', '');
$calliope_sp_telegram_has_saved_data = calliope_sp_ui_option_has_value('calliope_sp_telegram_bot_token')
    || calliope_sp_ui_option_has_value('calliope_sp_telegram_chat_id')
    || calliope_sp_ui_option_has_value('calliope_sp_telegram_message_thread_id')
    || calliope_sp_ui_option_has_value('calliope_sp_telegram_validation')
    || ($calliope_sp_telegram_legacy_status !== '' && !in_array($calliope_sp_telegram_legacy_status, ['not_configured', 'not_connected'], true));
if (class_exists('Calliope_SP_Telegram')) {
    $calliope_sp_telegram_state_object = (new Calliope_SP_Telegram())->get_connection_state();
    if (!is_wp_error($calliope_sp_telegram_state_object) && $calliope_sp_telegram_state_object instanceof Calliope_SP_Connection_State) {
        $calliope_sp_telegram_state = $calliope_sp_telegram_state_object->to_array();
        $calliope_sp_telegram_labels = [
            'not_configured' => __('Not connected', 'calliope-social-publisher'),
            'configuration_error' => __('Configuration incomplete', 'calliope-social-publisher'),
            'connected_unverified' => __('Verification required', 'calliope-social-publisher'),
            'target_missing' => __('Destination unavailable', 'calliope-social-publisher'),
            'permission_missing' => __('Publishing permission missing', 'calliope-social-publisher'),
            'token_invalid' => __('Connection invalid', 'calliope-social-publisher'),
            'ready_to_publish' => $calliope_sp_telegram_state['health'] === 'degraded'
                ? __('Ready, but needs attention', 'calliope-social-publisher')
                : __('Ready to publish', 'calliope-social-publisher'),
        ];
        $calliope_sp_status_telegram = [
            'key' => (string) $calliope_sp_telegram_state['status'],
            'tone' => (string) $calliope_sp_telegram_state['tone'],
            'label' => $calliope_sp_telegram_labels[$calliope_sp_telegram_state['status']] ?? __('Not connected', 'calliope-social-publisher'),
            'message' => (string) $calliope_sp_telegram_state['message'],
            'is_ready' => !empty($calliope_sp_telegram_state['is_ready']),
            'health' => (string) $calliope_sp_telegram_state['health'],
            'needs_attention' => !empty($calliope_sp_telegram_state['needs_attention']),
        ];
    }
}
$calliope_sp_fb_pages_raw = (string) get_option('calliope_sp_fb_pages_last', '');
$calliope_sp_fb_pages = $calliope_sp_fb_pages_raw ? json_decode($calliope_sp_fb_pages_raw, true) : [];
$calliope_sp_fb_selected_page_id = (string) get_option('calliope_sp_fb_page_id', '');
$calliope_sp_status_fb=$calliope_sp_meta_status_from_state('Calliope_SP_Facebook',__('Connect Facebook and select a Page.','calliope-social-publisher'));

$calliope_sp_c_bsky   = !empty($calliope_sp_status_bsky['is_ready']);
$calliope_sp_c_mstdn  = !empty($calliope_sp_status_mstdn['is_ready']);
$calliope_sp_c_tumblr = !empty($calliope_sp_status_tumblr['is_ready']);
$calliope_sp_c_pin    = !empty($calliope_sp_status_pin['is_ready']);
$calliope_sp_c_thr    = !empty($calliope_sp_status_thr['is_ready']);
$calliope_sp_c_ig     = !empty($calliope_sp_status_ig['is_ready']);
$calliope_sp_c_blg    = !empty($calliope_sp_status_blg['is_ready']);
$calliope_sp_c_telegram = !empty($calliope_sp_status_telegram['is_ready']);
$calliope_sp_c_fb     = !empty($calliope_sp_status_fb['is_ready']);

$calliope_sp_li_status = $calliope_sp_meta_status_from_state(
    'Calliope_SP_LinkedIn',
    __('Connect LinkedIn to publish to the authenticated personal profile.', 'calliope-social-publisher')
);
$calliope_sp_c_li = !empty($calliope_sp_li_status['is_ready']);
$calliope_sp_li_member_scope_list = [];
$calliope_sp_li_has_token = calliope_sp_ui_option_has_value('calliope_sp_li_access_token');
if (class_exists('Calliope_SP_LinkedIn') && $calliope_sp_tab === 'connections' && $calliope_sp_net === 'linkedin') {
    $calliope_sp_li_member_scope_list = (new Calliope_SP_LinkedIn())->get_saved_scope_list();

    // Older redirects may leave this expected pre-OAuth condition in the URL.
    // Do not render it as an error while the application credentials are saved
    // and the user still needs to click Connect with LinkedIn.
    $calliope_sp_li_missing_token_notices = [
        'Missing LinkedIn Access Token. Connect with LinkedIn first.',
        __('Missing LinkedIn Access Token. Connect with LinkedIn first.', 'calliope-social-publisher'),
    ];
    if (!$calliope_sp_li_has_token && in_array(trim(wp_strip_all_tags((string) $calliope_sp_msg)), $calliope_sp_li_missing_token_notices, true)) {
        $calliope_sp_msg = '';
        $calliope_sp_type = '';
    }
}

$calliope_sp_logs = get_option('calliope_sp_debug_logs', []);
if (!is_array($calliope_sp_logs)) $calliope_sp_logs = [];

function calliope_sp_ui_option_has_value($option_name) {
    $value = get_option((string) $option_name, '');

    if (is_array($value)) {
        return !empty($value);
    }

    return trim((string) $value) !== '';
}

function calliope_sp_ui_badge($ok) {
    if ($ok) {
        return '<span class="calliope-sp-badge is-ok"><span class="dot"></span>' . esc_html__('Connected', 'calliope-social-publisher') . '</span>';
    }
    return '<span class="calliope-sp-badge is-bad"><span class="dot"></span>' . esc_html__('Not connected', 'calliope-social-publisher') . '</span>';
}

function calliope_sp_ui_network_status($status_key, $has_saved_credentials, $is_ready, $connect_label) {
    if ($is_ready || in_array((string) $status_key, ['connected', 'ready_to_publish'], true)) {
        return [
            'key' => (string) $status_key,
            'tone' => 'success',
            'label' => __('Connected', 'calliope-social-publisher'),
            'message' => '',
            'is_ready' => true,
        ];
    }

    if ((string) $status_key === 'credentials_saved' || ($has_saved_credentials && !$is_ready)) {
        return [
            'key' => 'credentials_saved',
            'tone' => 'warning',
            'label' => __('Credentials saved', 'calliope-social-publisher'),
            'message' => sprintf(
                /* translators: %s: Connection button label. */
                __('Credentials are saved. Click %s to finish the connection.', 'calliope-social-publisher'),
                $connect_label
            ),
            'is_ready' => false,
        ];
    }

    return [
        'key' => 'not_connected',
        'tone' => 'error',
        'label' => __('Not connected', 'calliope-social-publisher'),
        'message' => '',
        'is_ready' => false,
    ];
}

function calliope_sp_ui_status_badge($status) {
    $tone_map = [
        'success' => 'is-ok',
        'warning' => 'is-warn',
        'error' => 'is-bad',
    ];

    $tone = isset($status['tone']) ? (string) $status['tone'] : 'error';
    $label = !empty($status['label']) ? (string) $status['label'] : __('Not connected', 'calliope-social-publisher');
    $class = isset($tone_map[$tone]) ? $tone_map[$tone] : 'is-bad';

    return '<span class="calliope-sp-badge ' . esc_attr($class) . '"><span class="dot"></span>' . esc_html($label) . '</span>';
}


function calliope_sp_ui_disconnect_button($network, $connected) {
    if (!$connected) {
        return '';
    }

    $network = sanitize_key((string) $network);
    $url = wp_nonce_url(
        admin_url('admin-post.php?action=calliope_sp_disconnect_network&network=' . $network),
        'calliope_sp_disconnect_network_' . $network
    );

    return '<a class="button button-link-delete" href="' . esc_url($url) . '" onclick="return confirm(\'' . esc_js(__('Disconnect this network and remove all saved credentials?', 'calliope-social-publisher')) . '\');">' . esc_html__('Disconnect', 'calliope-social-publisher') . '</a>';
}

function calliope_sp_net_tab_class($slug, $active, $connected) {
    $classes = ['calliope-sp-net-tab', 'net-' . sanitize_html_class((string) $slug)];

    if ($active) {
        $classes[] = 'is-active';
    }

    $classes[] = $connected ? 'is-connected' : 'is-disconnected';

    return implode(' ', $classes);
}

function calliope_sp_ui_allowed_html() {
    return [
        'span' => [
            'class' => true,
            'style' => true,
        ],
        'small' => [
            'class' => true,
            'style' => true,
        ],
        'svg'  => [
            'class' => true,
            'viewbox' => true,
            'viewBox' => true,
            'fill' => true,
            'xmlns' => true,
            'aria-label' => true,
        ],
        'defs' => [],
        'lineargradient' => [
            'id' => true,
            'gradientunits' => true,
            'gradienttransform' => true,
            'x1' => true,
            'x2' => true,
            'y1' => true,
            'y2' => true,
        ],
        'linearGradient' => [
            'id' => true,
            'gradientUnits' => true,
            'gradientTransform' => true,
            'x1' => true,
            'x2' => true,
            'y1' => true,
            'y2' => true,
        ],
        'radialgradient' => [
            'id' => true,
            'gradientunits' => true,
            'gradienttransform' => true,
            'cx' => true,
            'cy' => true,
            'fx' => true,
            'fy' => true,
            'r' => true,
        ],
        'radialGradient' => [
            'id' => true,
            'gradientUnits' => true,
            'gradientTransform' => true,
            'cx' => true,
            'cy' => true,
            'fx' => true,
            'fy' => true,
            'r' => true,
        ],
        'stop' => [
            'offset' => true,
            'stop-color' => true,
            'stop-opacity' => true,
        ],
        'g' => [
            'fill' => true,
            'fill-rule' => true,
            'transform' => true,
        ],
        'path' => [
            'class' => true,
            'd' => true,
            'fill' => true,
            'opacity' => true,
            'stroke' => true,
            'stroke-width' => true,
            'stroke-linecap' => true,
            'stroke-linejoin' => true,
            'transform' => true,
        ],
    ];
}


function calliope_sp_ui_notice_allowed_html() {
    return [
        'a' => [
            'href' => true,
            'target' => true,
            'rel' => true,
        ],
        'br' => [],
        'code' => [],
        'strong' => [],
        'b' => [],
        'em' => [],
        'span' => [
            'class' => true,
        ],
    ];
}

function calliope_sp_ui_icon($name) {
    // Simple inline SVG icons (no external fetch)
    switch ($name) {
        case 'bluesky':
            return '<svg class="calliope-sp-net-icon" viewBox="0 0 600 530" xmlns="http://www.w3.org/2000/svg" aria-label="Bluesky"><path d="m135.72 44.03c66.496 49.921 138.02 151.14 164.28 205.46 26.262-54.316 97.782-155.54 164.28-205.46 47.98-36.021 125.72-63.892 125.72 24.795 0 17.712-10.155 148.79-16.111 170.07-20.703 73.984-96.144 92.854-163.25 81.433 117.3 19.964 147.14 86.092 82.697 152.22-122.39 125.59-175.91-31.511-189.63-71.766-2.514-7.3797-3.6904-10.832-3.7077-7.8964-0.0174-2.9357-1.1937 0.51669-3.7077 7.8964-13.714 40.255-67.233 197.36-189.63 71.766-64.444-66.128-34.605-132.26 82.697-152.22-67.108 11.421-142.55-7.4491-163.25-81.433-5.9562-21.282-16.111-152.36-16.111-170.07 0-88.687 77.742-60.816 125.72-24.795z" fill="currentColor"/></svg>';
        case 'mastodon':
            return '<svg class="calliope-sp-net-icon calliope-sp-net-icon--mastodon" viewBox="0 0 480 511.476" xmlns="http://www.w3.org/2000/svg" aria-label="Mastodon"><defs><linearGradient id="calliope-sp-mastodon-gradient" gradientUnits="userSpaceOnUse" x1="235.378" y1=".003" x2="235.378" y2="506.951"><stop offset="0" stop-color="#6364FF"/><stop offset="1" stop-color="#563ACC"/></linearGradient></defs><g fill-rule="nonzero"><path fill="url(#calliope-sp-mastodon-gradient)" d="M478.064 113.237c-7.393-54.954-55.29-98.266-112.071-106.656C356.413 5.163 320.121 0 236.045 0h-.628c-84.1 0-102.141 5.163-111.72 6.581C68.498 14.739 18.088 53.655 5.859 109.261c-5.883 27.385-6.51 57.747-5.416 85.596 1.555 39.939 1.859 79.806 5.487 119.581a562.694 562.694 0 0013.089 78.437c11.625 47.654 58.687 87.313 104.793 103.494a281.073 281.073 0 00153.316 8.09 224.345 224.345 0 0016.577-4.533c12.369-3.928 26.856-8.321 37.506-16.042.146-.107.265-.247.348-.407.086-.161.134-.339.14-.521v-38.543a1.187 1.187 0 00-.119-.491 1.122 1.122 0 00-.773-.604 1.139 1.139 0 00-.503 0 424.932 424.932 0 01-99.491 11.626c-57.664 0-73.171-27.361-77.611-38.752a120.09 120.09 0 01-6.745-30.546 1.123 1.123 0 01.877-1.152c.173-.035.349-.032.518.012a416.876 416.876 0 0097.864 11.623c7.929 0 15.834 0 23.763-.211 33.155-.928 68.103-2.626 100.722-8.997.815-.16 1.63-.3 2.326-.508 51.454-9.883 100.422-40.894 105.397-119.42.185-3.093.651-32.385.651-35.591.022-10.903 3.51-77.343-.511-118.165z"/><path fill="#fff" d="M396.545 174.981v136.53h-54.104V179.002c0-27.896-11.625-42.124-35.272-42.124-25.996 0-39.017 16.833-39.017 50.074v72.531h-53.777v-72.531c0-33.241-13.044-50.074-39.04-50.074-23.507 0-35.248 14.228-35.248 42.124v132.509H86.006v-136.53c0-27.896 7.123-50.059 21.366-66.488 14.695-16.387 33.97-24.803 57.896-24.803 27.691 0 48.617 10.647 62.568 31.917l13.464 22.597 13.484-22.597c13.951-21.27 34.877-31.917 62.521-31.917 23.902 0 43.177 8.416 57.919 24.803 14.231 16.414 21.336 38.577 21.321 66.488z"/></g></svg>';
        case 'tumblr':
            return '<svg class="calliope-sp-net-icon" viewBox="0 0 260 260" xmlns="http://www.w3.org/2000/svg" aria-label="Tumblr"><path d="M210.857,197.545c-1.616-0.872-3.584-0.787-5.119,0.223c-11.62,7.638-23.4,11.511-35.016,11.511c-6.242,0-11.605-1.394-16.416-4.275c-3.27-1.936-6.308-5.321-7.397-8.263c-1.057-2.797-1.045-10.327-1.029-20.748l0.005-63.543h52.795c2.762,0,5-2.239,5-5V62.802c0-2.761-2.238-5-5-5h-52.795V5c0-2.761-2.238-5-5-5h-35.566c-2.528,0-4.658,1.887-4.964,4.397c-1.486,12.229-4.258,22.383-8.247,30.196c-3.89,7.7-9.153,14.401-15.651,19.925c-5.206,4.44-14.118,8.736-26.49,12.769c-2.058,0.671-3.45,2.589-3.45,4.754v35.41c0,2.761,2.238,5,5,5h28.953v82.666c0,12.181,1.292,21.347,3.952,28.026c2.71,6.785,7.521,13.174,14.303,18.993c6.671,5.716,14.79,10.187,24.158,13.298c9.082,2.962,16.315,4.567,28.511,4.567c10.31,0,20.137-1.069,29.213-3.179c8.921-2.082,19.017-5.761,30.008-10.934c1.753-0.825,2.871-2.587,2.871-4.524v-39.417C213.484,200.108,212.476,198.418,210.857,197.545z" fill="currentColor"/></svg>';
        case 'threads':
            // Threads logo: use the exact SVG provided (kept as-is).
            // Coloring is handled via CSS (currentColor) to match the UI.
            return '<svg class="calliope-sp-net-icon calliope-sp-net-icon--threads" aria-label="Threads" viewBox="0 0 192 192" xmlns="http://www.w3.org/2000/svg">'
                . '<path class="x19hqcy" d="M141.537 88.9883C140.71 88.5919 139.87 88.2104 139.019 87.8451C137.537 60.5382 122.616 44.905 97.5619 44.745C97.4484 44.7443 97.3355 44.7443 97.222 44.7443C82.2364 44.7443 69.7731 51.1409 62.102 62.7807L75.881 72.2328C81.6116 63.5383 90.6052 61.6848 97.2286 61.6848C97.3051 61.6848 97.3819 61.6848 97.4576 61.6855C105.707 61.7381 111.932 64.1366 115.961 68.814C118.893 72.2193 120.854 76.925 121.825 82.8638C114.511 81.6207 106.601 81.2385 98.145 81.7233C74.3247 83.0954 59.0111 96.9879 60.0396 116.292C60.5615 126.084 65.4397 134.508 73.775 140.011C80.8224 144.663 89.899 146.938 99.3323 146.423C111.79 145.74 121.563 140.987 128.381 132.296C133.559 125.696 136.834 117.143 138.28 106.366C144.217 109.949 148.617 114.664 151.047 120.332C155.179 129.967 155.42 145.8 142.501 158.708C131.182 170.016 117.576 174.908 97.0135 175.059C74.2042 174.89 56.9538 167.575 45.7381 153.317C35.2355 139.966 29.8077 120.682 29.6052 96C29.8077 71.3178 35.2355 52.0336 45.7381 38.6827C56.9538 24.4249 74.2039 17.11 97.0132 16.9405C119.988 17.1113 137.539 24.4614 149.184 38.788C154.894 45.8136 159.199 54.6488 162.037 64.9503L178.184 60.6422C174.744 47.9622 169.331 37.0357 161.965 27.974C147.036 9.60668 125.202 0.195148 97.0695 0H96.9569C68.8816 0.19447 47.2921 9.6418 32.7883 28.0793C19.8819 44.4864 13.2244 67.3157 13.0007 95.9325L13 96L13.0007 96.0675C13.2244 124.684 19.8819 147.514 32.7883 163.921C47.2921 182.358 68.8816 191.806 96.9569 192H97.0695C122.03 191.827 139.624 185.292 154.118 170.811C173.081 151.866 172.51 128.119 166.26 113.541C161.776 103.087 153.227 94.5962 141.537 88.9883ZM98.4405 129.507C88.0005 130.095 77.1544 125.409 76.6196 115.372C76.2232 107.93 81.9158 99.626 99.0812 98.6368C101.047 98.5234 102.976 98.468 104.871 98.468C111.106 98.468 116.939 99.0737 122.242 100.233C120.264 124.935 108.662 128.946 98.4405 129.507Z"></path>'
                . '</svg>';
        case 'facebook':
            return '<svg class="calliope-sp-net-icon" viewBox="0 0 666.66668 666.66717" xmlns="http://www.w3.org/2000/svg" aria-label="Facebook"><g transform="matrix(1.3333333,0,0,-1.3333333,-133.33333,799.99999)"><g transform="translate(600,350)"><path d="m 0,0 c 0,138.071 -111.929,250 -250,250 -138.071,0 -250,-111.929 -250,-250 0,-117.245 80.715,-215.622 189.606,-242.638 v 166.242 h -51.552 V 0 h 51.552 v 32.919 c 0,85.092 38.508,124.532 122.048,124.532 15.838,0 43.167,-3.105 54.347,-6.211 V 81.986 c -5.901,0.621 -16.149,0.932 -28.882,0.932 -40.993,0 -56.832,-15.528 -56.832,-55.9 V 0 h 81.659 l -14.028,-76.396 h -67.631 V -248.169 C -95.927,-233.218 0,-127.818 0,0" fill="#0866ff"/></g><g transform="translate(447.9175,273.6036)"><path d="M 0,0 14.029,76.396 H -67.63 v 27.019 c 0,40.372 15.838,55.899 56.831,55.899 12.733,0 22.981,-0.31 28.882,-0.931 v 69.253 c -11.18,3.106 -38.509,6.212 -54.347,6.212 -83.539,0 -122.048,-39.441 -122.048,-124.533 V 76.396 h -51.552 V 0 h 51.552 v -166.242 c 19.343,-4.798 39.568,-7.362 60.394,-7.362 10.254,0 20.358,0.632 30.288,1.831 L -67.63,0 Z" fill="#ffffff"/></g></g></svg>';
        case 'pinterest':
            return '<svg class="calliope-sp-net-icon" viewBox="0 0 144 144" xmlns="http://www.w3.org/2000/svg" aria-label="Pinterest"><path d="M71.9,5.4C35.1,5.4,5.3,35.2,5.3,72c0,28.2,17.5,52.3,42.3,62c-0.6-5.3-1.1-13.3,0.2-19.1c1.2-5.2,7.8-33.1,7.8-33.1s-2-4-2-9.9c0-9.3,5.4-16.2,12-16.2c5.7,0,8.4,4.3,8.4,9.4c0,5.7-3.6,14.3-5.5,22.2c-1.6,6.6,3.3,12,9.9,12c11.8,0,20.9-12.5,20.9-30.5c0-15.9-11.5-27.1-27.8-27.1c-18.9,0-30.1,14.2-30.1,28.9c0,5.7,2.2,11.9,5,15.2c0.5,0.7,0.6,1.2,0.5,1.9c-0.5,2.1-1.6,6.6-1.8,7.5c-0.3,1.2-1,1.5-2.2,0.9c-8.3-3.9-13.5-16-13.5-25.8c0-21,15.3-40.3,44-40.3c23.1,0,41,16.5,41,38.4c0,22.9-14.5,41.4-34.5,41.4c-6.7,0-13.1-3.5-15.3-7.6c0,0-3.3,12.7-4.1,15.8c-1.5,5.8-5.6,13-8.3,17.5c6.2,1.9,12.8,3,19.7,3c36.8,0,66.6-29.8,66.6-66.6C138.5,35.2,108.7,5.4,71.9,5.4z" fill="currentColor"/></svg>';
        case 'instagram':
            return '<svg class="calliope-sp-net-icon calliope-sp-net-icon--instagram" viewBox="0 0 264.5833 264.5833" xmlns="http://www.w3.org/2000/svg" aria-label="Instagram">'
                . '<defs>'
                . '<radialGradient id="calliope-sp-instagram-f" cx="158.429" cy="578.088" r="52.3515" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0 -4.03418 4.28018 0 -2332.2273 942.2356)" fx="158.429" fy="578.088"><stop offset="0" stop-color="#fc0"/><stop offset=".1242" stop-color="#fc0"/><stop offset=".5672" stop-color="#fe4a05"/><stop offset=".6942" stop-color="#ff0f3f"/><stop offset="1" stop-color="#fe0657" stop-opacity="0"/></radialGradient>'
                . '<radialGradient id="calliope-sp-instagram-g" gradientUnits="userSpaceOnUse" gradientTransform="matrix(.67441 -1.16203 1.51283 .87801 -814.3657 -47.8354)" cx="172.6149" cy="600.6924" fx="172.6149" fy="600.6924" r="65"><stop offset="0" stop-color="#fc0"/><stop offset="1" stop-color="#fc0" stop-opacity="0"/></radialGradient>'
                . '<radialGradient id="calliope-sp-instagram-h" cx="144.012" cy="51.3367" fx="144.012" fy="51.3367" r="67.081" gradientTransform="matrix(-2.3989 .67549 -.23008 -.81732 464.9957 -26.4035)" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#780cff"/><stop offset="1" stop-color="#820bff" stop-opacity="0"/></radialGradient>'
                . '<radialGradient id="calliope-sp-instagram-e" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-3.10797 .87652 -.6315 -2.23914 1345.6503 1374.1983)" cx="199.7884" cy="628.4379" fx="199.7884" fy="628.4379" r="52.3515"><stop offset="0" stop-color="#ff005f"/><stop offset="1" stop-color="#fc01d8"/></radialGradient>'
                . '</defs>'
                . '<path d="M204.1503 18.1429c-55.2305 0-71.3834.057-74.5232.3175-11.3342.9424-18.387 2.7275-26.0708 6.554-5.9214 2.9413-10.5915 6.3506-15.2005 11.1298-8.3938 8.7157-13.481 19.4383-15.3226 32.1842-.8953 6.1877-1.1558 7.4496-1.2087 39.0558-.0203 10.5354 0 24.4007 0 42.9984 0 55.2008.061 71.3418.3256 74.4764.9157 11.032 2.6453 17.9728 6.3081 25.565 7 14.5329 20.369 25.4428 36.119 29.5137 5.4535 1.4044 11.4767 2.1779 19.2092 2.5442 3.2762.1425 36.6684.2443 70.081.2443 33.4127 0 66.8253-.0407 70.02-.2035 8.9535-.4214 14.1526-1.1195 19.9011-2.6054 15.8517-4.0912 28.9767-14.8383 36.119-29.5748 3.5916-7.409 5.4128-14.6144 6.237-25.0704.179-2.2796.2543-38.6263.2543-74.924 0-36.304-.0814-72.5835-.2605-74.8632-.8343-10.6249-2.6555-17.7692-6.363-25.3207-3.0421-6.1816-6.42-10.798-11.324-15.518-8.752-8.3616-19.4555-13.4502-32.2101-15.2902-6.18-.8936-7.411-1.1582-39.033-1.2131z" fill="url(#calliope-sp-instagram-e)" transform="translate(-71.8155 -18.1429)"/>'
                . '<path d="M204.1503 18.1429c-55.2305 0-71.3834.057-74.5232.3175-11.3342.9424-18.387 2.7275-26.0708 6.554-5.9214 2.9413-10.5915 6.3506-15.2005 11.1298-8.3938 8.7157-13.481 19.4383-15.3226 32.1842-.8953 6.1877-1.1558 7.4496-1.2087 39.0558-.0203 10.5354 0 24.4007 0 42.9984 0 55.2008.061 71.3418.3256 74.4764.9157 11.032 2.6453 17.9728 6.3081 25.565 7 14.5329 20.369 25.4428 36.119 29.5137 5.4535 1.4044 11.4767 2.1779 19.2092 2.5442 3.2762.1425 36.6684.2443 70.081.2443 33.4127 0 66.8253-.0407 70.02-.2035 8.9535-.4214 14.1526-1.1195 19.9011-2.6054 15.8517-4.0912 28.9767-14.8383 36.119-29.5748 3.5916-7.409 5.4128-14.6144 6.237-25.0704.179-2.2796.2543-38.6263.2543-74.924 0-36.304-.0814-72.5835-.2605-74.8632-.8343-10.6249-2.6555-17.7692-6.363-25.3207-3.0421-6.1816-6.42-10.798-11.324-15.518-8.752-8.3616-19.4555-13.4502-32.2101-15.2902-6.18-.8936-7.411-1.1582-39.033-1.2131z" fill="url(#calliope-sp-instagram-f)" transform="translate(-71.8155 -18.1429)"/>'
                . '<path d="M204.1503 18.1429c-55.2305 0-71.3834.057-74.5232.3175-11.3342.9424-18.387 2.7275-26.0708 6.554-5.9214 2.9413-10.5915 6.3506-15.2005 11.1298-8.3938 8.7157-13.481 19.4383-15.3226 32.1842-.8953 6.1877-1.1558 7.4496-1.2087 39.0558-.0203 10.5354 0 24.4007 0 42.9984 0 55.2008.061 71.3418.3256 74.4764.9157 11.032 2.6453 17.9728 6.3081 25.565 7 14.5329 20.369 25.4428 36.119 29.5137 5.4535 1.4044 11.4767 2.1779 19.2092 2.5442 3.2762.1425 36.6684.2443 70.081.2443 33.4127 0 66.8253-.0407 70.02-.2035 8.9535-.4214 14.1526-1.1195 19.9011-2.6054 15.8517-4.0912 28.9767-14.8383 36.119-29.5748 3.5916-7.409 5.4128-14.6144 6.237-25.0704.179-2.2796.2543-38.6263.2543-74.924 0-36.304-.0814-72.5835-.2605-74.8632-.8343-10.6249-2.6555-17.7692-6.363-25.3207-3.0421-6.1816-6.42-10.798-11.324-15.518-8.752-8.3616-19.4555-13.4502-32.2101-15.2902-6.18-.8936-7.411-1.1582-39.033-1.2131z" fill="url(#calliope-sp-instagram-g)" transform="translate(-71.8155 -18.1429)"/>'
                . '<path d="M204.1503 18.1429c-55.2305 0-71.3834.057-74.5232.3175-11.3342.9424-18.387 2.7275-26.0708 6.554-5.9214 2.9413-10.5915 6.3506-15.2005 11.1298-8.3938 8.7157-13.481 19.4383-15.3226 32.1842-.8953 6.1877-1.1558 7.4496-1.2087 39.0558-.0203 10.5354 0 24.4007 0 42.9984 0 55.2008.061 71.3418.3256 74.4764.9157 11.032 2.6453 17.9728 6.3081 25.565 7 14.5329 20.369 25.4428 36.119 29.5137 5.4535 1.4044 11.4767 2.1779 19.2092 2.5442 3.2762.1425 36.6684.2443 70.081.2443 33.4127 0 66.8253-.0407 70.02-.2035 8.9535-.4214 14.1526-1.1195 19.9011-2.6054 15.8517-4.0912 28.9767-14.8383 36.119-29.5748 3.5916-7.409 5.4128-14.6144 6.237-25.0704.179-2.2796.2543-38.6263.2543-74.924 0-36.304-.0814-72.5835-.2605-74.8632-.8343-10.6249-2.6555-17.7692-6.363-25.3207-3.0421-6.1816-6.42-10.798-11.324-15.518-8.752-8.3616-19.4555-13.4502-32.2101-15.2902-6.18-.8936-7.411-1.1582-39.033-1.2131z" fill="url(#calliope-sp-instagram-h)" transform="translate(-71.8155 -18.1429)"/>'
                . '<path d="M132.3452 33.973c-26.7167 0-30.0696.1167-40.5629.5939-10.4727.4792-17.6212 2.136-23.8762 4.567-6.4701 2.5107-11.9586 5.8693-17.4265 11.3352-5.472 5.464-8.8332 10.9483-11.354 17.4116-2.4389 6.2524-4.099 13.3976-4.5703 23.8585-.4693 10.4854-.5923 13.8379-.5923 40.5348 0 26.697.1189 30.0371.5943 40.5225.4817 10.465 2.1397 17.6082 4.5703 23.8585 2.5147 6.4654 5.8758 11.9497 11.3458 17.4136 5.466 5.468 10.9544 8.8349 17.4204 11.3456 6.259 2.4309 13.4097 4.0877 23.8803 4.567 10.4933.477 13.8441.5938 40.5588.5938 26.7188 0 30.0615-.1167 40.5547-.5939 10.4728-.4792 17.6295-2.136 23.8885-4.567 6.4681-2.5106 11.9484-5.8775 17.4143-11.3455 5.472-5.4639 8.8332-10.9482 11.354-17.4115 2.4183-6.2524 4.0784-13.3976 4.5703-23.8585.4713-10.4854.5943-13.8277.5943-40.5246 0-26.697-.123-30.0473-.5943-40.5328-.4919-10.465-2.152-17.6081-4.5703-23.8584-2.5208-6.4654-5.882-11.9498-11.354-17.4137-5.4721-5.468-10.9442-8.8266-17.4204-11.3353-6.2714-2.4309-13.424-4.0877-23.8967-4.5669-10.4933-.4772-13.8339-.5939-40.5588-.5939zm-8.825 17.7147c2.6193-.0041 5.5418 0 8.825 0 26.2659 0 29.379.0942 39.7513.5652 9.5915.4383 14.7971 2.0397 18.2648 3.3852 4.5908 1.7817 7.8638 3.9116 11.3048 7.3521 3.4431 3.4406 5.5745 6.7173 7.3617 11.3046 1.3465 3.461 2.9512 8.6628 3.3877 18.2472.4714 10.3625.5739 13.4754.5739 39.7095 0 26.234-.1025 29.347-.5739 39.7095-.4386 9.5843-2.0412 14.7861-3.3877 18.2471-1.783 4.5874-3.9186 7.8539-7.3617 11.2923-3.443 3.4406-6.712 5.5704-11.3048 7.3521-3.4636 1.3517-8.6733 2.949-18.2648 3.3873-10.3702.471-13.4854.5734-39.7513.5734-26.2679 0-29.381-.1024-39.7513-.5734-9.5914-.4423-14.797-2.0438-18.2668-3.3893-4.5908-1.7817-7.87-3.9116-11.313-7.3521-3.4431-3.4405-5.5745-6.709-7.3617-11.2985-1.3465-3.461-2.9512-8.6628-3.3877-18.2471-.4714-10.3626-.5657-13.4754-.5657-39.7259 0-26.2504.0943-29.347.5657-39.7095.4386-9.5844 2.0412-14.7861 3.3877-18.2512 1.783-4.5874 3.9186-7.8641 7.3617-11.3046 3.443-3.4406 6.7222-5.5704 11.313-7.3562 3.4677-1.3517 8.6754-2.949 18.2668-3.3894 9.075-.4096 12.5919-.5324 30.9264-.553zm61.3363 16.322c-6.5173 0-11.805 5.2776-11.805 11.792 0 6.5125 5.2877 11.7962 11.805 11.7962 6.5172 0 11.8049-5.2837 11.8049-11.7962 0-6.5124-5.2877-11.796-11.805-11.796zm-52.5113 13.7826c-27.8993 0-50.5191 22.6031-50.5191 50.4817 0 27.8786 22.6198 50.4714 50.5191 50.4714s50.511-22.5928 50.511-50.4714c0-27.8786-22.6137-50.4817-50.513-50.4817zm0 17.7147c18.109 0 32.7914 14.6694 32.7914 32.767 0 18.0956-14.6824 32.767-32.7914 32.767-18.111 0-32.7913-14.6714-32.7913-32.767 0-18.0976 14.6803-32.767 32.7913-32.767z" fill="#fff"/>'
                . '</svg>';
        case 'linkedin':
            return '<svg class="calliope-sp-net-icon" viewBox="0 0 72 72" xmlns="http://www.w3.org/2000/svg" aria-label="LinkedIn"><g fill="none" fill-rule="evenodd"><path d="M8,72 L64,72 C68.418278,72 72,68.418278 72,64 L72,8 C72,3.581722 68.418278,-8.11624501e-16 64,0 L8,0 C3.581722,8.11624501e-16 -5.41083001e-16,3.581722 0,8 L0,64 C5.41083001e-16,68.418278 3.581722,72 8,72 Z" fill="#007EBB"/><path d="M62,62 L51.315625,62 L51.315625,43.8021149 C51.315625,38.8127542 49.4197917,36.0245323 45.4707031,36.0245323 C41.1746094,36.0245323 38.9300781,38.9261103 38.9300781,43.8021149 L38.9300781,62 L28.6333333,62 L28.6333333,27.3333333 L38.9300781,27.3333333 L38.9300781,32.0029283 C38.9300781,32.0029283 42.0260417,26.2742151 49.3825521,26.2742151 C56.7356771,26.2742151 62,30.7644705 62,40.051212 L62,62 Z M16.349349,22.7940133 C12.8420573,22.7940133 10,19.9296567 10,16.3970067 C10,12.8643566 12.8420573,10 16.349349,10 C19.8566406,10 22.6970052,12.8643566 22.6970052,16.3970067 C22.6970052,19.9296567 19.8566406,22.7940133 16.349349,22.7940133 Z M11.0325521,62 L21.769401,62 L21.769401,27.3333333 L11.0325521,27.3333333 L11.0325521,62 Z" fill="#FFF"/></g></svg>';
        case 'blogger':
            return '<svg class="calliope-sp-net-icon" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-label="Blogger"><path d="M21.976 24H2.026C.9 24 0 23.1 0 21.976V2.026C0 .9.9 0 2.025 0H22.05C23.1 0 24 .9 24 2.025v19.95C24 23.1 23.1 24 21.976 24zM12 3.975H9c-2.775 0-5.025 2.25-5.025 5.025v6c0 2.774 2.25 5.024 5.025 5.024h6c2.774 0 5.024-2.25 5.024-5.024v-3.975c0-.6-.45-1.05-1.05-1.05H18c-.524 0-.976-.45-.976-.976 0-2.776-2.25-5.026-5.024-5.026zm3.074 12H9c-.525 0-.975-.45-.975-.975s.45-.976.975-.976h6.074c.526 0 .977.45.977.976s-.45.976-.975.976zm-2.55-7.95c.527 0 .976.45.976.975s-.45.975-.975.975h-3.6c-.525 0-.976-.45-.976-.975s.45-.975.975-.975h3.6z" fill="#FF5722"/></svg>';
        case 'telegram':
            return '<svg class="calliope-sp-net-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M21.7 4.1 18.4 19.8c-.2 1-.8 1.3-1.6.8l-5-3.7-2.4 2.3c-.3.3-.5.5-1 .5l.4-5.1 9.3-8.4c.4-.4-.1-.6-.6-.2L6 13.2 1.1 11.7c-1-.3-1-1 .2-1.5L20.4 2.8c.9-.3 1.7.2 1.3 1.3Z" fill="currentColor"/></svg>';
        default:
            return '';
    }
}

function calliope_sp_url_with($args) {
    $base = admin_url('admin.php');
    $q = array_merge([
        'page' => 'calliope-social-publisher',
    ], $args);
    return add_query_arg($q, $base);
}

$calliope_sp_logo_url = CALLIOPE_SP_URL . 'assets/images/social-publisher-logo.svg';
$calliope_sp_dashboard_url = calliope_sp_url_with(['tab' => 'dashboard']);
$calliope_sp_docs_full_url = 'https://pluginswordpress.calliope.com.ar/calliope-social-publisher';
$calliope_sp_docs_url = $calliope_sp_docs_full_url;
$calliope_sp_support_url = 'https://wordpress.org/support/plugin/calliope-social-publisher/';
$calliope_sp_review_url  = 'https://wordpress.org/support/plugin/calliope-social-publisher/reviews/#new-post';
$calliope_sp_suggest_url = 'mailto:suggestions@calliope.com.ar';
$calliope_sp_admin_tab_links = [
    'dashboard' => [
        'url'   => calliope_sp_url_with(['tab' => 'dashboard']),
        'label' => __('Dashboard', 'calliope-social-publisher'),
        'icon'  => 'dashicons-dashboard',
    ],
    'publisher' => [
        'url'   => calliope_sp_url_with(['tab' => 'publisher']),
        'label' => __('Publisher', 'calliope-social-publisher'),
        'icon'  => 'dashicons-edit',
    ],
    'history' => [
        'url'   => calliope_sp_url_with(['tab' => 'history']),
        'label' => __('History', 'calliope-social-publisher'),
        'icon'  => 'dashicons-backup',
    ],
    'analytics' => [
        'url'   => calliope_sp_url_with(['tab' => 'analytics']),
        'label' => __('Analytics', 'calliope-social-publisher'),
        'icon'  => 'dashicons-chart-bar',
    ],
    'connections' => [
        'url'   => calliope_sp_url_with(['tab' => 'connections', 'net' => $calliope_sp_net]),
        'label' => __('Connections', 'calliope-social-publisher'),
        'icon'  => 'dashicons-admin-links',
    ],
    'scheduled' => [
        'url'   => calliope_sp_url_with(['tab' => 'scheduled']),
        'label' => __('Scheduled', 'calliope-social-publisher'),
        'icon'  => '',
    ],
    'calendar' => [
        'url'   => calliope_sp_url_with(['tab' => 'calendar']),
        'label' => __('Calendar', 'calliope-social-publisher'),
        'icon'  => '',
    ],
    'logs' => [
        'url'   => calliope_sp_url_with(['tab' => 'logs']),
        'label' => __('Logs', 'calliope-social-publisher'),
        'icon'  => 'dashicons-list-view',
    ],
    'settings' => [
        'url'   => calliope_sp_url_with(['tab' => 'settings']),
        'label' => __('Settings', 'calliope-social-publisher'),
        'icon'  => 'dashicons-admin-generic',
    ],
    'license' => [
        'url'   => calliope_sp_url_with(['tab' => 'license']),
        'label' => __('License', 'calliope-social-publisher'),
        'icon'  => 'dashicons-lock',
    ],
];
?>

<div class="wrap calliope-sp-wrap">

    <div class="calliope-sp-topbar">
        <div class="calliope-sp-topbar__brand">
            <img src="<?php echo esc_url($calliope_sp_logo_url); ?>" alt="Social Publisher" class="calliope-sp-topbar__logo-clean" />
        </div>
        <div class="calliope-sp-topbar__actions">
            <a class="calliope-sp-topbar__button" href="<?php echo esc_url($calliope_sp_docs_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('Documentation', 'calliope-social-publisher'); ?></a>
            <a class="calliope-sp-topbar__button" href="<?php echo esc_url($calliope_sp_support_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('Support', 'calliope-social-publisher'); ?></a>
            <a class="calliope-sp-topbar__button" href="<?php echo esc_url($calliope_sp_suggest_url); ?>"><?php echo esc_html__('Suggestions', 'calliope-social-publisher'); ?></a>
        </div>
    </div>

    <?php
    // Pro child screens stay routable for backward compatibility, but belong visually
    // to their parent areas instead of consuming primary-navigation tabs.
    $calliope_sp_hidden_primary_tabs = ['account_groups', 'content_variations'];
    $calliope_sp_parent_tab = [
        'account_groups'      => 'connections',
        'content_variations' => 'evergreen',
    ];
    ?>
    <h2 class="nav-tab-wrapper">
        <?php foreach ($calliope_sp_allowed_tabs as $calliope_sp_nav_tab): ?>
            <?php if (in_array($calliope_sp_nav_tab, $calliope_sp_hidden_primary_tabs, true)) { continue; } ?>
            <?php if (!isset($calliope_sp_admin_tab_links[$calliope_sp_nav_tab])): ?>
                <?php do_action('calliope_sp_render_admin_tab_link', $calliope_sp_nav_tab, $calliope_sp_tab); ?>
                <?php continue; ?>
            <?php endif; ?>
            <?php
            $calliope_sp_nav_link = $calliope_sp_admin_tab_links[$calliope_sp_nav_tab];
            $calliope_sp_nav_is_active = $calliope_sp_tab === $calliope_sp_nav_tab
                || (($calliope_sp_parent_tab[$calliope_sp_tab] ?? '') === $calliope_sp_nav_tab);
            ?>
            <a href="<?php echo esc_url($calliope_sp_nav_link['url']); ?>" class="nav-tab <?php echo esc_attr($calliope_sp_nav_is_active ? 'nav-tab-active' : ''); ?>"><?php if ($calliope_sp_nav_link['icon'] !== ''): ?><span class="dashicons <?php echo esc_attr($calliope_sp_nav_link['icon']); ?>"></span><?php endif; ?><?php echo esc_html($calliope_sp_nav_link['label']); ?></a>
        <?php endforeach; ?>
    </h2>

    <?php do_action('calliope_sp_render_context_subnavigation', $calliope_sp_tab); ?>

    <?php if (!empty($calliope_sp_msg)): ?>
        <?php $calliope_sp_notice_type = in_array($calliope_sp_type, ['success', 'warning', 'error'], true) ? $calliope_sp_type : 'error'; ?>
        <div class="notice notice-<?php echo esc_attr($calliope_sp_notice_type); ?> is-dismissible">
            <p><?php echo wp_kses($calliope_sp_msg, calliope_sp_ui_notice_allowed_html()); ?></p>
        </div>
    <?php endif; ?>

    <div class="calliope-sp-panel">

        <?php if ($calliope_sp_tab === 'dashboard'): ?>

            <?php
            $calliope_sp_dashboard_analytics = class_exists('Calliope_SP_History')
                ? Calliope_SP_History::get_basic_analytics(7)
                : ['ready' => false, 'runs' => 0, 'total' => 0, 'success' => 0, 'failed' => 0, 'pending' => 0, 'success_rate' => 0.0, 'networks' => []];
            $calliope_sp_dashboard_activity = class_exists('Calliope_SP_History')
                ? Calliope_SP_History::get_activity_series(7)
                : ['ready' => false, 'points' => [], 'max_value' => 0];
            $calliope_sp_dashboard_recent = class_exists('Calliope_SP_History')
                ? Calliope_SP_History::get_recent_publication_runs(3)
                : [];
            $calliope_sp_dashboard_pro = class_exists('Calliope_SP_Extensions') ? Calliope_SP_Extensions::get_pro_status() : [];

            $calliope_sp_dashboard_connections = [
                'bluesky' => ['label' => 'Bluesky', 'ready' => $calliope_sp_c_bsky, 'configured' => $calliope_sp_bsky_has_saved_data || (string) ($calliope_sp_status_bsky['key'] ?? '') !== 'not_configured', 'status' => $calliope_sp_status_bsky],
                'mastodon' => ['label' => 'Mastodon', 'ready' => $calliope_sp_c_mstdn, 'configured' => $calliope_sp_mstdn_has_saved_data || (string) ($calliope_sp_status_mstdn['key'] ?? '') !== 'not_configured', 'status' => $calliope_sp_status_mstdn],
                'tumblr' => ['label' => 'Tumblr', 'ready' => $calliope_sp_c_tumblr, 'configured' => $calliope_sp_tumblr_has_saved_data || (string) ($calliope_sp_status_tumblr['key'] ?? '') !== 'not_configured', 'status' => $calliope_sp_status_tumblr],
                'pinterest' => ['label' => 'Pinterest', 'ready' => $calliope_sp_c_pin, 'configured' => $calliope_sp_pin_has_saved_data || (string) ($calliope_sp_status_pin['key'] ?? '') !== 'not_configured', 'status' => $calliope_sp_status_pin],
                'threads' => ['label' => 'Threads', 'ready' => $calliope_sp_c_thr, 'configured' => (string) ($calliope_sp_status_thr['key'] ?? '') !== 'not_configured', 'status' => $calliope_sp_status_thr],
                'instagram' => ['label' => 'Instagram', 'ready' => $calliope_sp_c_ig, 'configured' => (string) ($calliope_sp_status_ig['key'] ?? '') !== 'not_configured', 'status' => $calliope_sp_status_ig],
                'linkedin' => ['label' => 'LinkedIn', 'ready' => $calliope_sp_c_li, 'configured' => (string) ($calliope_sp_li_status['key'] ?? '') !== 'not_configured', 'status' => $calliope_sp_li_status],
                'blogger' => ['label' => 'Blogger', 'ready' => $calliope_sp_c_blg, 'configured' => $calliope_sp_blogger_has_saved_data || (string) ($calliope_sp_status_blg['key'] ?? '') !== 'not_configured', 'status' => $calliope_sp_status_blg],
                'telegram' => ['label' => 'Telegram', 'ready' => $calliope_sp_c_telegram, 'configured' => $calliope_sp_telegram_has_saved_data || (string) ($calliope_sp_status_telegram['key'] ?? '') !== 'not_configured', 'status' => $calliope_sp_status_telegram],
                'facebook' => ['label' => 'Facebook', 'ready' => $calliope_sp_c_fb, 'configured' => (string) ($calliope_sp_status_fb['key'] ?? '') !== 'not_configured', 'status' => $calliope_sp_status_fb],
            ];

            $calliope_sp_dashboard_ready_labels = [];
            $calliope_sp_dashboard_attention_labels = [];
            $calliope_sp_dashboard_attention = [];
            $calliope_sp_dashboard_unconfigured_count = 0;
            foreach ($calliope_sp_dashboard_connections as $calliope_sp_dashboard_network => $calliope_sp_dashboard_connection) {
                if (!empty($calliope_sp_dashboard_connection['ready'])) {
                    $calliope_sp_dashboard_ready_labels[$calliope_sp_dashboard_network] = (string) $calliope_sp_dashboard_connection['label'];
                    continue;
                }
                $calliope_sp_dashboard_status = is_array($calliope_sp_dashboard_connection['status'] ?? null) ? $calliope_sp_dashboard_connection['status'] : [];
                if (!empty($calliope_sp_dashboard_connection['configured'])) {
                    $calliope_sp_dashboard_attention_labels[$calliope_sp_dashboard_network] = (string) $calliope_sp_dashboard_connection['label'];
                    $calliope_sp_dashboard_attention[] = [
                        'title' => sprintf(__('%s connection needs attention', 'calliope-social-publisher'), (string) $calliope_sp_dashboard_connection['label']),
                        'message' => sanitize_text_field((string) ($calliope_sp_dashboard_status['message'] ?? __('Review the saved connection before publishing again.', 'calliope-social-publisher'))),
                        'url' => calliope_sp_url_with(['tab' => 'connections', 'net' => $calliope_sp_dashboard_network]),
                        'action' => __('Review connection', 'calliope-social-publisher'),
                    ];
                    continue;
                }
                if (empty($calliope_sp_dashboard_connection['configured'])) {
                    $calliope_sp_dashboard_unconfigured_count++;
                }
            }

            $calliope_sp_dashboard_pro_connection_labels = [
                'discord' => 'Discord',
                'youtube' => 'YouTube',
                'remote_wordpress' => __('Remote WordPress', 'calliope-social-publisher'),
                'custom_webhook' => __('Custom webhook', 'calliope-social-publisher'),
            ];
            if (!empty($calliope_sp_dashboard_pro['active'])) {
                foreach ($calliope_sp_dashboard_pro_connection_labels as $calliope_sp_dashboard_network => $calliope_sp_dashboard_label) {
                    $calliope_sp_dashboard_definition = is_array($calliope_sp_dashboard_pro['connections'][$calliope_sp_dashboard_network] ?? null) ? $calliope_sp_dashboard_pro['connections'][$calliope_sp_dashboard_network] : [];
                    if (!empty($calliope_sp_dashboard_definition['configured'])) {
                        $calliope_sp_dashboard_ready_labels['pro_' . $calliope_sp_dashboard_network] = $calliope_sp_dashboard_label;
                    } else {
                        $calliope_sp_dashboard_unconfigured_count++;
                    }
                }
            }

            $calliope_sp_dashboard_failed = absint($calliope_sp_dashboard_analytics['failed'] ?? 0);
            if ($calliope_sp_dashboard_failed > 0) {
                array_unshift($calliope_sp_dashboard_attention, [
                    'title' => __('Recent publication failures', 'calliope-social-publisher'),
                    'message' => sprintf(__('%d failed destinations in the last 7 days.', 'calliope-social-publisher'), $calliope_sp_dashboard_failed),
                    'url' => calliope_sp_url_with(['tab' => 'history', 'status' => 'failed']),
                    'action' => __('View failures', 'calliope-social-publisher'),
                ]);
            }

            $calliope_sp_dashboard_attention = apply_filters('calliope_sp_dashboard_attention_items', $calliope_sp_dashboard_attention, [
                'analytics' => $calliope_sp_dashboard_analytics,
                'connected_networks' => count($calliope_sp_dashboard_ready_labels),
                'pro_status' => $calliope_sp_dashboard_pro,
            ]);
            $calliope_sp_dashboard_attention = is_array($calliope_sp_dashboard_attention) ? array_slice($calliope_sp_dashboard_attention, 0, 5) : [];

            $calliope_sp_dashboard_operational = apply_filters('calliope_sp_dashboard_operational_context', [
                'schedule' => ['available' => false],
                'automations' => ['available' => false],
            ], [
                'analytics' => $calliope_sp_dashboard_analytics,
                'pro_status' => $calliope_sp_dashboard_pro,
            ]);
            $calliope_sp_dashboard_operational = is_array($calliope_sp_dashboard_operational) ? $calliope_sp_dashboard_operational : [];
            $calliope_sp_dashboard_schedule = is_array($calliope_sp_dashboard_operational['schedule'] ?? null) ? $calliope_sp_dashboard_operational['schedule'] : ['available' => false];
            $calliope_sp_dashboard_automations = is_array($calliope_sp_dashboard_operational['automations'] ?? null) ? $calliope_sp_dashboard_operational['automations'] : ['available' => false];

            $calliope_sp_dashboard_ready_count = count($calliope_sp_dashboard_ready_labels);
            $calliope_sp_dashboard_attention_count = count($calliope_sp_dashboard_attention_labels);
            $calliope_sp_dashboard_most_active = '';
            if (!empty($calliope_sp_dashboard_analytics['networks'][0]['network'])) {
                $calliope_sp_dashboard_most_active = sanitize_key((string) $calliope_sp_dashboard_analytics['networks'][0]['network']);
            }
            $calliope_sp_dashboard_most_active_label = $calliope_sp_dashboard_most_active !== '' && class_exists('Calliope_SP_Publish_Helper')
                ? Calliope_SP_Publish_Helper::get_network_label($calliope_sp_dashboard_most_active)
                : '—';
            $calliope_sp_dashboard_has_attention = !empty($calliope_sp_dashboard_attention);
            $calliope_sp_dashboard_health_class = $calliope_sp_dashboard_has_attention ? 'is-warning' : ($calliope_sp_dashboard_ready_count > 0 ? 'is-healthy' : 'is-neutral');
            $calliope_sp_dashboard_health_title = $calliope_sp_dashboard_has_attention
                ? __('Attention needed', 'calliope-social-publisher')
                : ($calliope_sp_dashboard_ready_count > 0 ? __('Everything looks good', 'calliope-social-publisher') : __('Ready to get started', 'calliope-social-publisher'));
            $calliope_sp_dashboard_health_copy = $calliope_sp_dashboard_has_attention
                ? __('Review the items below before your next publication.', 'calliope-social-publisher')
                : ($calliope_sp_dashboard_ready_count > 0
                    ? __('Your configured destinations are ready and there are no recent delivery failures.', 'calliope-social-publisher')
                    : __('Connect your first destination to start publishing.', 'calliope-social-publisher'));
            $calliope_sp_dashboard_completed = absint($calliope_sp_dashboard_analytics['success'] ?? 0) + absint($calliope_sp_dashboard_analytics['failed'] ?? 0);
            ?>

            <div class="calliope-sp-dashboard">
                <section class="calliope-sp-dashboard-health <?php echo esc_attr($calliope_sp_dashboard_health_class); ?>">
                    <div class="calliope-sp-dashboard-health__icon"><span class="dashicons <?php echo esc_attr($calliope_sp_dashboard_has_attention ? 'dashicons-warning' : ($calliope_sp_dashboard_ready_count > 0 ? 'dashicons-yes-alt' : 'dashicons-controls-play')); ?>"></span></div>
                    <div class="calliope-sp-dashboard-health__body">
                        <span class="calliope-sp-dashboard-eyebrow"><?php echo esc_html__('Dashboard', 'calliope-social-publisher'); ?></span>
                        <h2><?php echo esc_html($calliope_sp_dashboard_health_title); ?></h2>
                        <p><?php echo esc_html($calliope_sp_dashboard_health_copy); ?></p>
                    </div>
                    <div class="calliope-sp-dashboard-health__actions">
                        <a class="button button-primary" href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'publisher'])); ?>"><?php echo esc_html__('Create publication', 'calliope-social-publisher'); ?></a>
                        <?php if (!empty($calliope_sp_dashboard_schedule['available']) && !empty($calliope_sp_dashboard_schedule['url'])): ?>
                            <a class="button" href="<?php echo esc_url((string) $calliope_sp_dashboard_schedule['url']); ?>"><?php echo esc_html__('View scheduling', 'calliope-social-publisher'); ?></a>
                        <?php endif; ?>
                    </div>
                </section>

                <?php if ($calliope_sp_dashboard_has_attention): ?>
                    <section class="calliope-sp-card calliope-sp-dashboard-section calliope-sp-dashboard-attention">
                        <div class="calliope-sp-dashboard-section__head">
                            <div><span class="calliope-sp-dashboard-eyebrow"><?php echo esc_html__('Status', 'calliope-social-publisher'); ?></span><h3><?php echo esc_html__('Needs attention', 'calliope-social-publisher'); ?></h3></div>
                            <span class="calliope-sp-dashboard-count is-warning"><?php echo esc_html(number_format_i18n(count($calliope_sp_dashboard_attention))); ?></span>
                        </div>
                        <div class="calliope-sp-dashboard-attention-list">
                            <?php foreach ($calliope_sp_dashboard_attention as $calliope_sp_dashboard_issue): ?>
                                <article class="calliope-sp-dashboard-attention-item">
                                    <span class="dashicons dashicons-warning"></span>
                                    <div><strong><?php echo esc_html((string) ($calliope_sp_dashboard_issue['title'] ?? '')); ?></strong><p><?php echo esc_html((string) ($calliope_sp_dashboard_issue['message'] ?? '')); ?></p></div>
                                    <?php if (!empty($calliope_sp_dashboard_issue['url'])): ?><a href="<?php echo esc_url((string) $calliope_sp_dashboard_issue['url']); ?>"><?php echo esc_html((string) ($calliope_sp_dashboard_issue['action'] ?? __('Review', 'calliope-social-publisher'))); ?> <span aria-hidden="true">→</span></a><?php endif; ?>
                                </article>
                            <?php endforeach; ?>
                        </div>
                    </section>
                <?php endif; ?>

                <?php if (!empty($calliope_sp_dashboard_schedule['available']) || !empty($calliope_sp_dashboard_automations['available'])): ?>
                    <div class="calliope-sp-dashboard-grid calliope-sp-dashboard-grid--operations">
                        <?php if (!empty($calliope_sp_dashboard_schedule['available'])): ?>
                            <section class="calliope-sp-card calliope-sp-dashboard-section calliope-sp-dashboard-next">
                                <div class="calliope-sp-dashboard-section__head">
                                    <div><span class="calliope-sp-dashboard-eyebrow"><?php echo esc_html__('Scheduled', 'calliope-social-publisher'); ?></span><h3><?php echo esc_html__('Next publication', 'calliope-social-publisher'); ?></h3></div>
                                    <?php if (!empty($calliope_sp_dashboard_schedule['url'])): ?><a href="<?php echo esc_url((string) $calliope_sp_dashboard_schedule['url']); ?>"><?php echo esc_html__('View scheduling', 'calliope-social-publisher'); ?> <span aria-hidden="true">→</span></a><?php endif; ?>
                                </div>
                                <?php $calliope_sp_dashboard_next = is_array($calliope_sp_dashboard_schedule['next'] ?? null) ? $calliope_sp_dashboard_schedule['next'] : []; ?>
                                <?php if ($calliope_sp_dashboard_next): ?>
                                    <div class="calliope-sp-dashboard-next__main">
                                        <span class="dashicons dashicons-calendar-alt"></span>
                                        <div>
                                            <strong><?php echo esc_html(wp_trim_words((string) ($calliope_sp_dashboard_next['title'] ?? __('Scheduled publication', 'calliope-social-publisher')), 14)); ?></strong>
                                            <time><?php echo esc_html((string) ($calliope_sp_dashboard_next['when'] ?? '')); ?></time>
                                            <?php if (!empty($calliope_sp_dashboard_next['meta'])): ?><small><?php echo esc_html((string) $calliope_sp_dashboard_next['meta']); ?></small><?php endif; ?>
                                        </div>
                                    </div>
                                <?php else: ?>
                                    <div class="calliope-sp-dashboard-clear is-neutral"><span class="dashicons dashicons-calendar-alt"></span><div><strong><?php echo esc_html__('No upcoming schedules.', 'calliope-social-publisher'); ?></strong><p><?php echo esc_html__('Scheduled publications will appear here.', 'calliope-social-publisher'); ?></p></div></div>
                                <?php endif; ?>
                                <div class="calliope-sp-dashboard-mini-metrics">
                                    <div><strong><?php echo esc_html(number_format_i18n(absint($calliope_sp_dashboard_schedule['upcoming'] ?? 0))); ?></strong><span><?php echo esc_html__('Upcoming', 'calliope-social-publisher'); ?></span></div>
                                    <div class="<?php echo !empty($calliope_sp_dashboard_schedule['needs_review']) ? 'is-warning' : ''; ?>"><strong><?php echo esc_html(number_format_i18n(absint($calliope_sp_dashboard_schedule['needs_review'] ?? 0))); ?></strong><span><?php echo esc_html__('Needs review', 'calliope-social-publisher'); ?></span></div>
                                    <div class="<?php echo !empty($calliope_sp_dashboard_schedule['waiting_retry']) ? 'is-warning' : ''; ?>"><strong><?php echo esc_html(number_format_i18n(absint($calliope_sp_dashboard_schedule['waiting_retry'] ?? 0))); ?></strong><span><?php echo esc_html__('Waiting retry', 'calliope-social-publisher'); ?></span></div>
                                </div>
                            </section>
                        <?php endif; ?>

                        <?php if (!empty($calliope_sp_dashboard_automations['available'])): ?>
                            <section class="calliope-sp-card calliope-sp-dashboard-section calliope-sp-dashboard-automations">
                                <div class="calliope-sp-dashboard-section__head">
                                    <div><span class="calliope-sp-dashboard-eyebrow"><?php echo esc_html__('Automation', 'calliope-social-publisher'); ?></span><h3><?php echo esc_html__('Evergreen', 'calliope-social-publisher'); ?></h3></div>
                                    <?php if (!empty($calliope_sp_dashboard_automations['url'])): ?><a href="<?php echo esc_url((string) $calliope_sp_dashboard_automations['url']); ?>"><?php echo esc_html__('Manage', 'calliope-social-publisher'); ?> <span aria-hidden="true">→</span></a><?php endif; ?>
                                </div>
                                <div class="calliope-sp-dashboard-automation-count"><strong><?php echo esc_html(number_format_i18n(absint($calliope_sp_dashboard_automations['active_count'] ?? 0))); ?></strong><span><?php echo esc_html__('Active campaigns', 'calliope-social-publisher'); ?></span></div>
                                <?php $calliope_sp_dashboard_automation_items = is_array($calliope_sp_dashboard_automations['items'] ?? null) ? $calliope_sp_dashboard_automations['items'] : []; ?>
                                <?php if ($calliope_sp_dashboard_automation_items): ?>
                                    <div class="calliope-sp-dashboard-automation-list">
                                        <?php foreach ($calliope_sp_dashboard_automation_items as $calliope_sp_dashboard_automation): ?>
                                            <article>
                                                <span class="calliope-sp-dashboard-recent-item__dot"></span>
                                                <div><strong><?php echo esc_html((string) ($calliope_sp_dashboard_automation['name'] ?? '')); ?></strong><span><?php echo esc_html((string) ($calliope_sp_dashboard_automation['meta'] ?? '')); ?></span></div>
                                                <time><?php echo esc_html((string) ($calliope_sp_dashboard_automation['next'] ?? '')); ?></time>
                                            </article>
                                        <?php endforeach; ?>
                                    </div>
                                <?php else: ?>
                                    <div class="calliope-sp-dashboard-clear is-neutral"><span class="dashicons dashicons-controls-repeat"></span><div><strong><?php echo esc_html__('No active Evergreen campaigns.', 'calliope-social-publisher'); ?></strong><p><?php echo esc_html__('Activate a campaign to see its next run here.', 'calliope-social-publisher'); ?></p></div></div>
                                <?php endif; ?>
                            </section>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>

                <section class="calliope-sp-card calliope-sp-dashboard-section calliope-sp-dashboard-activity">
                    <div class="calliope-sp-dashboard-section__head">
                        <div><span class="calliope-sp-dashboard-eyebrow"><?php echo esc_html__('Activity', 'calliope-social-publisher'); ?></span><h3><?php echo esc_html__('Last 7 days', 'calliope-social-publisher'); ?></h3></div>
                        <a href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'analytics'])); ?>"><?php echo esc_html__('View Analytics', 'calliope-social-publisher'); ?> <span aria-hidden="true">→</span></a>
                    </div>
                    <div class="calliope-sp-dashboard-activity__summary">
                        <div><strong><?php echo esc_html(number_format_i18n(absint($calliope_sp_dashboard_analytics['runs'] ?? 0))); ?></strong><span><?php echo esc_html__('Publications', 'calliope-social-publisher'); ?></span></div>
                        <div><strong><?php echo esc_html(number_format_i18n(absint($calliope_sp_dashboard_analytics['total'] ?? 0))); ?></strong><span><?php echo esc_html__('Destinations', 'calliope-social-publisher'); ?></span></div>
                        <div><strong><?php echo $calliope_sp_dashboard_completed > 0 ? esc_html(number_format_i18n((float) ($calliope_sp_dashboard_analytics['success_rate'] ?? 0), 1) . '%') : '—'; ?></strong><span><?php echo esc_html__('Delivery success', 'calliope-social-publisher'); ?></span></div>
                        <div><strong><?php echo esc_html($calliope_sp_dashboard_most_active_label); ?></strong><span><?php echo esc_html__('Most active', 'calliope-social-publisher'); ?></span></div>
                    </div>
                    <?php $calliope_sp_dashboard_max = max(1, absint($calliope_sp_dashboard_activity['max_value'] ?? 0)); ?>
                    <div class="calliope-sp-dashboard-spark" aria-label="<?php echo esc_attr__('Publishing activity for the last 7 days', 'calliope-social-publisher'); ?>">
                        <?php foreach ((array) ($calliope_sp_dashboard_activity['points'] ?? []) as $calliope_sp_dashboard_point): ?>
                            <?php
                            $calliope_sp_dashboard_success = absint($calliope_sp_dashboard_point['success'] ?? 0);
                            $calliope_sp_dashboard_point_failed = absint($calliope_sp_dashboard_point['failed'] ?? 0);
                            $calliope_sp_dashboard_point_total = $calliope_sp_dashboard_success + $calliope_sp_dashboard_point_failed;
                            $calliope_sp_dashboard_height = $calliope_sp_dashboard_point_total > 0 ? max(8, min(100, (int) round(($calliope_sp_dashboard_point_total / $calliope_sp_dashboard_max) * 100))) : 3;
                            $calliope_sp_dashboard_failed_height = $calliope_sp_dashboard_point_total > 0 ? max(0, min(100, (int) round(($calliope_sp_dashboard_point_failed / $calliope_sp_dashboard_point_total) * 100))) : 0;
                            ?>
                            <div class="calliope-sp-dashboard-spark__day" title="<?php echo esc_attr(sprintf('%s · %s %d · %s %d', (string) ($calliope_sp_dashboard_point['label'] ?? ''), __('Successful', 'calliope-social-publisher'), $calliope_sp_dashboard_success, __('Failed', 'calliope-social-publisher'), $calliope_sp_dashboard_point_failed)); ?>">
                                <span class="calliope-sp-dashboard-spark__bar" style="--calliope-sp-bar-height:<?php echo esc_attr((string) $calliope_sp_dashboard_height); ?>%;--calliope-sp-fail-height:<?php echo esc_attr((string) $calliope_sp_dashboard_failed_height); ?>%;"><i></i></span>
                                <small><?php echo esc_html((string) ($calliope_sp_dashboard_point['label'] ?? '')); ?></small>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </section>

                <div class="calliope-sp-dashboard-grid calliope-sp-dashboard-grid--lower">
                    <section class="calliope-sp-card calliope-sp-dashboard-section calliope-sp-dashboard-recent">
                        <div class="calliope-sp-dashboard-section__head"><div><span class="calliope-sp-dashboard-eyebrow"><?php echo esc_html__('History', 'calliope-social-publisher'); ?></span><h3><?php echo esc_html__('Recent activity', 'calliope-social-publisher'); ?></h3></div><a href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'history'])); ?>"><?php echo esc_html__('View History', 'calliope-social-publisher'); ?> <span aria-hidden="true">→</span></a></div>
                        <?php if (empty($calliope_sp_dashboard_recent)): ?>
                            <div class="calliope-sp-dashboard-clear is-neutral"><span class="dashicons dashicons-clock"></span><div><strong><?php echo esc_html__('No publication activity yet.', 'calliope-social-publisher'); ?></strong><p><?php echo esc_html__('Your latest publication runs will appear here.', 'calliope-social-publisher'); ?></p></div></div>
                        <?php else: ?>
                            <div class="calliope-sp-dashboard-recent-list">
                                <?php foreach ($calliope_sp_dashboard_recent as $calliope_sp_dashboard_run): ?>
                                    <?php
                                    $calliope_sp_dashboard_run_failed = absint($calliope_sp_dashboard_run['failed'] ?? 0);
                                    $calliope_sp_dashboard_run_pending = absint($calliope_sp_dashboard_run['pending'] ?? 0);
                                    $calliope_sp_dashboard_run_status = $calliope_sp_dashboard_run_failed > 0 ? 'is-warning' : ($calliope_sp_dashboard_run_pending > 0 ? 'is-pending' : 'is-success');
                                    $calliope_sp_dashboard_run_title = trim((string) ($calliope_sp_dashboard_run['post_title'] ?? ''));
                                    if ($calliope_sp_dashboard_run_title === '') { $calliope_sp_dashboard_run_title = __('Manual publication', 'calliope-social-publisher'); }
                                    $calliope_sp_dashboard_run_timestamp = strtotime((string) ($calliope_sp_dashboard_run['activity_at'] ?? '') . ' UTC');
                                    $calliope_sp_dashboard_run_source = sanitize_key((string) ($calliope_sp_dashboard_run['source'] ?? ''));
                                    if ($calliope_sp_dashboard_run_source === 'evergreen') {
                                        $calliope_sp_dashboard_source_label = __('Evergreen', 'calliope-social-publisher');
                                    } elseif (in_array($calliope_sp_dashboard_run_source, ['pro_schedule', 'schedule', 'scheduled'], true) || !empty($calliope_sp_dashboard_run['schedule_uuid'])) {
                                        $calliope_sp_dashboard_source_label = __('Scheduled', 'calliope-social-publisher');
                                    } else {
                                        $calliope_sp_dashboard_source_label = __('Publisher', 'calliope-social-publisher');
                                    }
                                    $calliope_sp_dashboard_run_summary = sprintf(__('%1$d destinations · %2$d successful · %3$d failed', 'calliope-social-publisher'), absint($calliope_sp_dashboard_run['destinations'] ?? 0), absint($calliope_sp_dashboard_run['success'] ?? 0), $calliope_sp_dashboard_run_failed);
                                    ?>
                                    <article class="calliope-sp-dashboard-recent-item <?php echo esc_attr($calliope_sp_dashboard_run_status); ?>">
                                        <span class="calliope-sp-dashboard-recent-item__dot"></span>
                                        <div class="calliope-sp-dashboard-recent-item__body"><strong><?php echo esc_html(wp_trim_words($calliope_sp_dashboard_run_title, 12)); ?></strong><span><?php echo esc_html($calliope_sp_dashboard_source_label . ' · ' . $calliope_sp_dashboard_run_summary); ?></span></div>
                                        <time><?php echo esc_html($calliope_sp_dashboard_run_timestamp ? wp_date('M j, H:i', $calliope_sp_dashboard_run_timestamp, wp_timezone()) : ''); ?></time>
                                    </article>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </section>

                    <section class="calliope-sp-card calliope-sp-dashboard-section calliope-sp-dashboard-destinations">
                        <div class="calliope-sp-dashboard-section__head"><div><span class="calliope-sp-dashboard-eyebrow"><?php echo esc_html__('Connections', 'calliope-social-publisher'); ?></span><h3><?php echo esc_html__('Destinations', 'calliope-social-publisher'); ?></h3></div><a href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'connections'])); ?>"><?php echo esc_html__('Manage connections', 'calliope-social-publisher'); ?> <span aria-hidden="true">→</span></a></div>
                        <div class="calliope-sp-dashboard-destination-stats">
                            <div class="is-ready"><strong><?php echo esc_html(number_format_i18n($calliope_sp_dashboard_ready_count)); ?></strong><span><?php echo esc_html__('Ready', 'calliope-social-publisher'); ?></span></div>
                            <div class="<?php echo $calliope_sp_dashboard_attention_count > 0 ? 'is-warning' : ''; ?>"><strong><?php echo esc_html(number_format_i18n($calliope_sp_dashboard_attention_count)); ?></strong><span><?php echo esc_html__('Needs attention', 'calliope-social-publisher'); ?></span></div>
                            <div><strong><?php echo esc_html(number_format_i18n($calliope_sp_dashboard_unconfigured_count)); ?></strong><span><?php echo esc_html__('Not configured', 'calliope-social-publisher'); ?></span></div>
                        </div>
                        <?php if ($calliope_sp_dashboard_ready_labels): ?><div class="calliope-sp-dashboard-network-chips"><?php foreach ($calliope_sp_dashboard_ready_labels as $calliope_sp_dashboard_ready_label): ?><span><?php echo esc_html($calliope_sp_dashboard_ready_label); ?></span><?php endforeach; ?></div><?php endif; ?>
                        <?php if ($calliope_sp_dashboard_attention_labels): ?><div class="calliope-sp-dashboard-network-chips is-warning"><?php foreach ($calliope_sp_dashboard_attention_labels as $calliope_sp_dashboard_attention_label): ?><span><?php echo esc_html($calliope_sp_dashboard_attention_label . ' · ' . __('Needs attention', 'calliope-social-publisher')); ?></span><?php endforeach; ?></div><?php endif; ?>
                    </section>
                </div>
            </div>

        <?php elseif ($calliope_sp_tab === 'publisher'): ?>


            <form id="calliope_sp_publish_form" method="post" action="">
                <?php wp_nonce_field('calliope_sp_action_publish', 'calliope_sp_nonce_publish'); ?>
                <input type="hidden" name="calliope_sp_publish" value="1" />
                <input id="calliope_sp_source_post_id" type="hidden" name="calliope_sp_source_post_id" value="" />
                <input id="calliope_sp_ai_used" type="hidden" name="calliope_sp_ai_used" value="0" />
                <div class="calliope-sp-publication-type-layout">
                    <?php do_action('calliope_sp_render_publication_type_selector'); ?>
                </div>

                <div id="calliope-sp-standard-composer" data-calliope-publication-composer="standard">
                <div class="calliope-sp-grid calliope-sp-composer-grid">
                    <div class="calliope-sp-card calliope-sp-content-card">
                        <h3><?php echo esc_html__('Content', 'calliope-social-publisher'); ?></h3>

                        <div class="calliope-sp-field">
                            <label for="calliope_sp_link"><?php echo esc_html__('Link', 'calliope-social-publisher'); ?></label>
                            <input id="calliope_sp_link" type="url" name="calliope_sp_link" placeholder="https://" />
                            <input id="calliope_sp_link_context" type="hidden" name="calliope_sp_link_context" value="" />
                        </div>

                        <div class="calliope-sp-field">
                            <label for="calliope_sp_title"><?php echo esc_html__('Title', 'calliope-social-publisher'); ?></label>
                            <input id="calliope_sp_title" type="text" name="calliope_sp_title" />
                        </div>

                        <div class="calliope-sp-field">
                            <label for="calliope_sp_content"><?php echo esc_html__('Content', 'calliope-social-publisher'); ?></label>
                            <textarea id="calliope_sp_content" name="calliope_sp_content" rows="6"></textarea>
                        </div>

                        <div class="calliope-sp-field">
                            <label for="calliope_sp_hashtags"><?php echo esc_html__('Hashtags', 'calliope-social-publisher'); ?></label>
                            <input id="calliope_sp_hashtags" type="text" name="calliope_sp_hashtags" placeholder="#seo #wordpress" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('You can separate hashtags with spaces, commas, semicolons, or line breaks. They will be normalized automatically.', 'calliope-social-publisher'); ?></div>
                            <div class="calliope-sp-hint" id="calliope_sp_hashtags_preview_hint" style="display:none;"></div>
                        </div>

                        <?php do_action('calliope_sp_render_primary_network_metadata'); ?>

                        <div class="calliope-sp-inline-destinations calliope-sp-destinations-section">
                        <h3><?php echo esc_html__('Destinations', 'calliope-social-publisher'); ?></h3>
                        <div class="calliope-sp-checks">
                            <label><input type="checkbox" name="post_to_bsky" value="1" data-calliope-preview-network="bluesky" <?php checked($calliope_sp_c_bsky); ?> <?php disabled(!$calliope_sp_c_bsky); ?> title="<?php echo esc_attr($calliope_sp_c_bsky ? __('Bluesky is ready to publish.', 'calliope-social-publisher') : __('Verify Bluesky from Connections before publishing.', 'calliope-social-publisher')); ?>" /> <?php echo esc_html__('Bluesky', 'calliope-social-publisher'); ?></label>
                            <label><input type="checkbox" name="post_to_mastodon" value="1" data-calliope-preview-network="mastodon" <?php checked($calliope_sp_c_mstdn); ?> <?php disabled(!$calliope_sp_c_mstdn); ?> title="<?php echo esc_attr($calliope_sp_c_mstdn ? __('Mastodon is ready to publish.', 'calliope-social-publisher') : __('Verify Mastodon from Connections before publishing.', 'calliope-social-publisher')); ?>" /> <?php echo esc_html__('Mastodon', 'calliope-social-publisher'); ?></label>
                            <label><input type="checkbox" name="post_to_tumblr" value="1" data-calliope-preview-network="tumblr" <?php checked($calliope_sp_c_tumblr); ?> <?php disabled(!$calliope_sp_c_tumblr); ?> title="<?php echo esc_attr($calliope_sp_c_tumblr ? __('Tumblr is ready to publish.', 'calliope-social-publisher') : __('Verify Tumblr from Connections before publishing.', 'calliope-social-publisher')); ?>" /> <?php echo esc_html__('Tumblr', 'calliope-social-publisher'); ?></label>
                            <label><input type="checkbox" name="post_to_pinterest" value="1" data-calliope-preview-network="pinterest" <?php checked($calliope_sp_c_pin); ?> <?php disabled(!$calliope_sp_c_pin); ?> title="<?php echo esc_attr($calliope_sp_c_pin ? __('Pinterest is ready to publish.', 'calliope-social-publisher') : __('Verify Pinterest and select a board before publishing.', 'calliope-social-publisher')); ?>" /> <?php echo esc_html__('Pinterest', 'calliope-social-publisher'); ?></label>
                            <label><input type="checkbox" name="post_to_threads" value="1" data-calliope-preview-network="threads" <?php checked($calliope_sp_c_thr); disabled(!$calliope_sp_c_thr); ?> title="<?php echo esc_attr($calliope_sp_c_thr ? __('Threads is ready to publish.','calliope-social-publisher') : __('Verify Threads before publishing.','calliope-social-publisher')); ?>" /> <?php echo esc_html__('Threads', 'calliope-social-publisher'); ?></label>
                            <label><input type="checkbox" name="post_to_instagram" value="1" data-calliope-preview-network="instagram" <?php checked($calliope_sp_c_ig); disabled(!$calliope_sp_c_ig); ?> title="<?php echo esc_attr($calliope_sp_c_ig ? __('Instagram is ready to publish.','calliope-social-publisher') : __('Verify Instagram before publishing.','calliope-social-publisher')); ?>" /> <?php echo esc_html__('Instagram', 'calliope-social-publisher'); ?></label>
                            <label><input type="checkbox" name="post_to_linkedin" value="1" data-calliope-preview-network="linkedin" <?php checked($calliope_sp_c_li); ?> <?php disabled(!$calliope_sp_c_li); ?> title="<?php echo esc_attr($calliope_sp_c_li ? __('LinkedIn is ready to publish.', 'calliope-social-publisher') : __('Verify LinkedIn before publishing.', 'calliope-social-publisher')); ?>" /> <?php echo esc_html__('LinkedIn', 'calliope-social-publisher'); ?></label>
                            <label><input type="checkbox" name="post_to_blogger" value="1" data-calliope-preview-network="blogger" <?php checked($calliope_sp_c_blg); ?> <?php disabled(!$calliope_sp_c_blg); ?> title="<?php echo esc_attr($calliope_sp_c_blg ? __('Blogger is ready to publish.', 'calliope-social-publisher') : __('Verify Blogger and select a blog before publishing.', 'calliope-social-publisher')); ?>" /> <?php echo esc_html__('Blogger', 'calliope-social-publisher'); ?></label>
                            <label><input type="checkbox" name="post_to_telegram" value="1" data-calliope-preview-network="telegram" <?php checked($calliope_sp_c_telegram); ?> <?php disabled(!$calliope_sp_c_telegram); ?> title="<?php echo esc_attr($calliope_sp_c_telegram ? __('Telegram is ready to publish.', 'calliope-social-publisher') : __('Verify Telegram from Connections before publishing.', 'calliope-social-publisher')); ?>" /> <?php echo esc_html__('Telegram', 'calliope-social-publisher'); ?></label>
                            <label><input type="checkbox" name="post_to_facebook" value="1" data-calliope-preview-network="facebook" <?php checked($calliope_sp_c_fb); disabled(!$calliope_sp_c_fb); ?> title="<?php echo esc_attr($calliope_sp_c_fb ? __('Facebook Page is ready to publish.','calliope-social-publisher') : __('Verify Facebook Page before publishing.','calliope-social-publisher')); ?>" /> <?php echo esc_html__('Facebook Page', 'calliope-social-publisher'); ?></label>
                            <?php do_action('calliope_sp_render_external_destinations'); ?>
                        </div>
                        <?php do_action('calliope_sp_render_destination_groups'); ?>
                        <div class="calliope-sp-hint"><?php echo esc_html__('Connect or configure networks from the Connections tab before publishing.', 'calliope-social-publisher'); ?> <a href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'connections'])); ?>"><?php echo esc_html__('Open Connections', 'calliope-social-publisher'); ?></a></div>
                        <section id="calliope-sp-network-specific-options" class="calliope-sp-network-specific-options" hidden aria-labelledby="calliope-sp-network-specific-options-title">
                            <h3 id="calliope-sp-network-specific-options-title"><?php echo esc_html__('Network-specific options', 'calliope-social-publisher'); ?></h3>
                            <?php do_action('calliope_sp_render_external_metadata'); ?>
                        </section>
                        </div>

                    </div>

                    <div class="calliope-sp-card calliope-sp-image-card">
                        <h3><?php echo esc_html__('Media', 'calliope-social-publisher'); ?></h3>
                        <p class="calliope-sp-muted" style="margin-top:0;"><?php echo esc_html__('Choose an image and keep it original or adapt it to a social-friendly format before publishing.', 'calliope-social-publisher'); ?></p>
                        <p class="calliope-sp-hint"><?php echo esc_html__('Original keeps the full image without a forced crop. Crop formats are available when you want a square, portrait, or landscape result.', 'calliope-social-publisher'); ?></p>
                        <?php do_action('calliope_sp_render_pro_media_options'); ?>
                        <div class="calliope-sp-single-image-controls">
                            <div class="calliope-sp-field">
                                <label for="calliope_sp_image_format"><?php echo esc_html__('Image format', 'calliope-social-publisher'); ?></label>
                                <select id="calliope_sp_image_format" name="calliope_sp_image_format">
                                    <option value="original"><?php echo esc_html__('Original', 'calliope-social-publisher'); ?></option>
                                    <option value="square"><?php echo esc_html__('Square 1:1', 'calliope-social-publisher'); ?></option>
                                    <option value="portrait"><?php echo esc_html__('Portrait 4:5', 'calliope-social-publisher'); ?></option>
                                    <option value="landscape"><?php echo esc_html__('Landscape 16:9', 'calliope-social-publisher'); ?></option>
                                </select>
                            </div>
                            <p>
                                <button type="button" class="button" id="btn-up"><?php echo esc_html__('Media Library', 'calliope-social-publisher'); ?></button>
                                <button type="button" class="button button-secondary calliope-sp-dark" id="btn-local"><?php echo esc_html__('From computer', 'calliope-social-publisher'); ?></button>
                                <input type="file" id="file-input" style="display:none;" accept="image/*" />
                            </p>
                            <div id="edit-area" style="display:none;">
                                <div class="cropper-wrapper"><img id="img-crop" src="" alt="" /></div>
                                <div class="calliope-sp-crop-actions"><button type="button" class="button button-primary" id="btn-ok"><?php echo esc_html__('Apply crop', 'calliope-social-publisher'); ?></button></div>
                            </div>
                            <div id="preview" style="display:none; margin-top:10px;">
                                <img id="final-img" src="" alt="" style="max-width:280px;" />
                                <div><button type="button" class="button button-link-delete" id="btn-del" aria-label="<?php echo esc_attr__('Remove selected image', 'calliope-social-publisher'); ?>"><?php echo esc_html__('Remove selected image', 'calliope-social-publisher'); ?></button></div>
                            </div>
                            <input type="hidden" name="calliope_sp_cropped_image_data" id="calliope_sp_data" />
                            <input type="hidden" name="calliope_sp_single_image_attachment_id" id="calliope_sp_single_image_attachment_id" value="" />
                        </div>

                        <div class="calliope-sp-field">
                            <label for="calliope_sp_alt_text"><?php echo esc_html__('Alt text (image)', 'calliope-social-publisher'); ?></label>
                            <input id="calliope_sp_alt_text" type="text" name="calliope_sp_alt_text" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Recommended: describe the image in a single sentence.', 'calliope-social-publisher'); ?></div>
                        </div>
                    </div>
                </div>

                <?php do_action('calliope_sp_render_publisher_full_width_sections'); ?>

                <div class="calliope-sp-composer-section calliope-sp-ai-section">
                    <div class="calliope-sp-card calliope-sp-ai-context-card">
                        <h3><?php echo esc_html__('AI generation', 'calliope-social-publisher'); ?></h3>
                        <p class="calliope-sp-muted" style="margin-top:0;"><?php echo esc_html__('Add an AI prompt or select WordPress content. Gemini can then generate or improve the post using the destinations currently selected.', 'calliope-social-publisher'); ?></p>
                        <p class="calliope-sp-ai-settings-link">
                            <span><?php echo esc_html__('Need AI generation?', 'calliope-social-publisher'); ?></span>
                            <a href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'settings'])); ?>"><?php echo esc_html__('Connect AI', 'calliope-social-publisher'); ?></a>
                        </p>
                        <div class="calliope-sp-field calliope-sp-field--content-search">
                            <label for="calliope_sp_link_search"><?php echo esc_html__('Search post, page or product', 'calliope-social-publisher'); ?></label>
                            <div class="calliope-sp-link-search-row">
                                <input id="calliope_sp_link_search" type="search" placeholder="<?php echo esc_attr__('Search your WordPress content and use it as AI context', 'calliope-social-publisher'); ?>" autocomplete="off" aria-controls="calliope_sp_link_results" aria-expanded="false" aria-haspopup="listbox" />
                                <button type="button" class="button button-secondary" id="calliope_sp_link_search_btn"><?php echo esc_html__('Search', 'calliope-social-publisher'); ?></button>
                            </div>
                            <div class="calliope-sp-hint"><?php echo esc_html__('Select a result to fill the link and give Gemini the product or post context for this publication.', 'calliope-social-publisher'); ?></div>
                            <div class="calliope-sp-link-results" id="calliope_sp_link_results" role="listbox" aria-label="<?php echo esc_attr__('Matching posts, pages and products', 'calliope-social-publisher'); ?>" aria-live="polite" aria-busy="false" hidden></div>
                            <div class="calliope-sp-selected-context" id="calliope_sp_selected_context" data-selected-label="<?php echo esc_attr__('Selected content:', 'calliope-social-publisher'); ?>" aria-live="polite" hidden>
                                <span id="calliope_sp_selected_context_text"></span>
                                <button type="button" class="button-link calliope-sp-change-selection" id="calliope_sp_change_selection"><?php echo esc_html__('Change selection', 'calliope-social-publisher'); ?></button>
                            </div>
                        </div>
                        <div class="calliope-sp-field calliope-sp-field--ai-prompt">
                            <label for="calliope_sp_ai_prompt"><?php echo esc_html__('AI prompt / idea for this publication', 'calliope-social-publisher'); ?></label>
                            <textarea id="calliope_sp_ai_prompt" name="calliope_sp_ai_prompt" rows="4" placeholder="<?php echo esc_attr__('Example: Announce a new blog post about WordPress SEO. Friendly tone, useful for small business owners, invite readers to open the link.', 'calliope-social-publisher'); ?>"></textarea>
                            <div class="calliope-sp-hint"><?php echo esc_html__('AI runs only when you choose one of the generation buttons.', 'calliope-social-publisher'); ?></div>
                        </div>
                        <div class="calliope-sp-ai-field-actions">
                            <button type="button" class="button button-secondary calliope-sp-ai-btn" data-ai-field="title"><?php echo esc_html__('Generate title with AI', 'calliope-social-publisher'); ?></button>
                            <button type="button" class="button button-secondary calliope-sp-ai-btn" data-ai-field="content"><?php echo esc_html__('Generate content with AI', 'calliope-social-publisher'); ?></button>
                            <button type="button" class="button button-secondary calliope-sp-ai-btn" data-ai-field="hashtags"><?php echo esc_html__('Generate hashtags with AI', 'calliope-social-publisher'); ?></button>
                        </div>
                        <div class="calliope-sp-ai-complete">
                            <button type="button" class="button button-primary calliope-sp-ai-btn calliope-sp-ai-complete-btn" id="calliope_sp_ai_complete_btn" data-ai-field="complete" data-default-label="<?php echo esc_attr__('Generate complete post with AI', 'calliope-social-publisher'); ?>" data-loading-label="<?php echo esc_attr__('Generating complete post…', 'calliope-social-publisher'); ?>" aria-describedby="calliope_sp_ai_status"><?php echo esc_html__('Generate complete post with AI', 'calliope-social-publisher'); ?></button>
                        </div>
                        <?php do_action('calliope_sp_render_ai_extensions'); ?>
                        <div class="calliope-sp-ai-status" id="calliope_sp_ai_status" aria-live="polite"></div>
                    </div>
                </div>

                <div class="calliope-sp-composer-section calliope-sp-platform-preview-section" id="calliope-sp-platform-preview-section" hidden>
                    <section class="calliope-sp-card calliope-sp-platform-preview" id="calliope-sp-platform-preview" aria-labelledby="calliope-sp-platform-preview-title">
                        <div class="calliope-sp-platform-preview__head">
                            <div>
                                <h3 id="calliope-sp-platform-preview-title"><?php echo esc_html__('Platform preview', 'calliope-social-publisher'); ?></h3>
                                <p><?php echo esc_html__('Review what each selected destination will receive and catch problems before publishing.', 'calliope-social-publisher'); ?></p>
                            </div>
                            <div class="calliope-sp-platform-preview__actions">
                                <span class="calliope-sp-platform-preview__summary" id="calliope-sp-platform-preview-summary" aria-live="polite"></span>
                                <button type="button" class="button" id="calliope-sp-platform-preview-refresh"><?php echo esc_html__('Refresh preview', 'calliope-social-publisher'); ?></button>
                            </div>
                        </div>
                        <div class="calliope-sp-platform-preview__empty" id="calliope-sp-platform-preview-empty"><?php echo esc_html__('Select at least one destination to see its preview.', 'calliope-social-publisher'); ?></div>
                        <div class="calliope-sp-platform-preview__tabs" id="calliope-sp-platform-preview-tabs" role="tablist" aria-label="<?php echo esc_attr__('Destination previews', 'calliope-social-publisher'); ?>" hidden></div>
                        <div class="calliope-sp-platform-preview__body" id="calliope-sp-platform-preview-body" hidden aria-live="polite"></div>
                        <div class="calliope-sp-final-publish-bar calliope-sp-platform-preview__footer">
                            <div class="calliope-sp-final-publish-bar__status" id="calliope-sp-preview-publish-status" aria-live="polite"></div>
                            <div class="calliope-sp-actions calliope-sp-inline-publish-actions">
                                <?php do_action('calliope_sp_render_publication_timing_controls'); ?>
                                <button type="submit" class="button button-primary button-large" data-publishing-label="<?php echo esc_attr__('Publishing…', 'calliope-social-publisher'); ?>"><?php echo esc_html__('Publish now', 'calliope-social-publisher'); ?></button>
                            </div>
                        </div>
                    </section>
                </div>
                </div><!-- /#calliope-sp-standard-composer -->

                <?php do_action('calliope_sp_render_video_composer'); ?>

            </form>


        <?php elseif ($calliope_sp_tab === 'history'): ?>

            <?php
            $calliope_sp_history_summary = class_exists('Calliope_SP_History')
                ? Calliope_SP_History::get_dashboard_summary()
                : ['ready' => false, 'total' => 0, 'runs' => 0, 'success' => 0, 'failed' => 0, 'pending' => 0, 'last_activity' => ''];
            $calliope_sp_history_network = isset($_GET['history_network']) ? sanitize_key(wp_unslash((string) $_GET['history_network'])) : '';
            $calliope_sp_history_status = isset($_GET['history_status']) ? sanitize_key(wp_unslash((string) $_GET['history_status'])) : '';
            $calliope_sp_history_search = isset($_GET['history_q']) ? sanitize_text_field(wp_unslash((string) $_GET['history_q'])) : '';
            $calliope_sp_history_page_number = isset($_GET['history_page']) ? max(1, absint(wp_unslash((string) $_GET['history_page']))) : 1;
            $calliope_sp_history_data = class_exists('Calliope_SP_History')
                ? Calliope_SP_History::get_history_page([
                    'page' => $calliope_sp_history_page_number,
                    'per_page' => 20,
                    'network' => $calliope_sp_history_network,
                    'status' => $calliope_sp_history_status,
                    'search' => $calliope_sp_history_search,
                ])
                : ['ready' => false, 'items' => [], 'total' => 0, 'page' => 1, 'per_page' => 20, 'total_pages' => 0];
            $calliope_sp_history_networks = class_exists('Calliope_SP_History') ? Calliope_SP_History::get_history_networks() : [];
            $calliope_sp_history_last_activity = '';
            if (!empty($calliope_sp_history_summary['last_activity'])) {
                $calliope_sp_history_timestamp = strtotime((string) $calliope_sp_history_summary['last_activity'] . ' UTC');
                if ($calliope_sp_history_timestamp) {
                    $calliope_sp_history_last_activity = wp_date(get_option('date_format') . ' ' . get_option('time_format'), $calliope_sp_history_timestamp);
                }
            }
            $calliope_sp_history_format_time = static function ($value) {
                $value = trim((string) $value);
                if ($value === '') {
                    return '';
                }
                $timestamp = strtotime($value . ' UTC');
                return $timestamp ? wp_date(get_option('date_format') . ' ' . get_option('time_format'), $timestamp) : '';
            };
            $calliope_sp_history_network_labels = [
                'bluesky' => __('Bluesky', 'calliope-social-publisher'),
                'bsky' => __('Bluesky', 'calliope-social-publisher'),
                'mastodon' => __('Mastodon', 'calliope-social-publisher'),
                'tumblr' => __('Tumblr', 'calliope-social-publisher'),
                'pinterest' => __('Pinterest', 'calliope-social-publisher'),
                'threads' => __('Threads', 'calliope-social-publisher'),
                'instagram' => __('Instagram', 'calliope-social-publisher'),
                'linkedin' => __('LinkedIn', 'calliope-social-publisher'),
                'blogger' => __('Blogger', 'calliope-social-publisher'),
                'telegram' => __('Telegram', 'calliope-social-publisher'),
                'facebook' => __('Facebook', 'calliope-social-publisher'),
                'discord' => __('Discord', 'calliope-social-publisher'),
                'youtube' => __('YouTube', 'calliope-social-publisher'),
                'remote_wordpress' => __('Remote WordPress', 'calliope-social-publisher'),
                'webhook' => __('Custom webhook', 'calliope-social-publisher'),
            ];
            $calliope_sp_history_content_labels = [
                'text' => __('Text', 'calliope-social-publisher'),
                'image' => __('Image', 'calliope-social-publisher'),
                'video' => __('Video', 'calliope-social-publisher'),
                'carousel' => __('Carousel', 'calliope-social-publisher'),
            ];
            $calliope_sp_pro_status = class_exists('Calliope_SP_Extensions') ? Calliope_SP_Extensions::get_pro_status() : [];
            $calliope_sp_pro_purchase_url = class_exists('Calliope_SP_Extensions') ? Calliope_SP_Extensions::get_purchase_url() : 'https://pluginswordpress.calliope.com.ar/calliope-social-publisher/';
            ?>

            <section class="calliope-sp-card calliope-sp-history-browser" aria-label="<?php echo esc_attr__('History records', 'calliope-social-publisher'); ?>">
                <div class="calliope-sp-history-browser__head">
                    <div>
                        <h3><?php echo esc_html__('History records', 'calliope-social-publisher'); ?></h3>
                        <p><?php echo esc_html__('One row represents one destination, so a single publication sent to three networks is easy to audit network by network.', 'calliope-social-publisher'); ?></p>
                        <div class="calliope-sp-history-toolbar">
                            <div class="calliope-sp-history-toolbar__meta">
                                <span class="calliope-sp-history-state <?php echo !empty($calliope_sp_history_summary['ready']) ? 'is-active' : 'is-warning'; ?>"><?php echo !empty($calliope_sp_history_summary['ready']) ? esc_html__('Active', 'calliope-social-publisher') : esc_html__('Needs setup', 'calliope-social-publisher'); ?></span>
                                <span><?php echo esc_html__('Permanent storage is enabled.', 'calliope-social-publisher'); ?></span>
                                <?php if ($calliope_sp_history_last_activity !== ''): ?>
                                    <span><?php echo esc_html(sprintf(__('Last activity: %s', 'calliope-social-publisher'), $calliope_sp_history_last_activity)); ?></span>
                                <?php else: ?>
                                    <span><?php echo esc_html__('Publish something to start building your history.', 'calliope-social-publisher'); ?></span>
                                <?php endif; ?>
                            </div>
                            <?php if (empty($calliope_sp_pro_status['license_active'])): ?>
                                <a class="button calliope-sp-history-inline-pro" href="<?php echo esc_url($calliope_sp_pro_purchase_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('Explore Social Publisher Pro', 'calliope-social-publisher'); ?> <span class="calliope-sp-pro-badge">PRO</span></a>
                            <?php else: ?>
                                <span class="calliope-sp-history-pro-owned"><?php echo esc_html__('Social Publisher Pro is active', 'calliope-social-publisher'); ?></span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <span class="calliope-sp-history-result-count"><?php echo esc_html(sprintf(__('Results: %s', 'calliope-social-publisher'), number_format_i18n((int) $calliope_sp_history_data['total']))); ?></span>
                </div>

                <form method="get" action="<?php echo esc_url(admin_url('admin.php')); ?>" class="calliope-sp-history-filters">
                    <input type="hidden" name="page" value="calliope-social-publisher" />
                    <input type="hidden" name="tab" value="history" />
                    <label class="calliope-sp-history-filter calliope-sp-history-filter--search">
                        <span><?php echo esc_html__('Search history', 'calliope-social-publisher'); ?></span>
                        <input type="search" name="history_q" value="<?php echo esc_attr($calliope_sp_history_search); ?>" placeholder="<?php echo esc_attr__('Post, account, social ID, or error', 'calliope-social-publisher'); ?>" />
                    </label>
                    <label class="calliope-sp-history-filter">
                        <span><?php echo esc_html__('Network', 'calliope-social-publisher'); ?></span>
                        <select name="history_network">
                            <option value=""><?php echo esc_html__('All networks', 'calliope-social-publisher'); ?></option>
                            <?php foreach ($calliope_sp_history_networks as $calliope_sp_history_network_option): ?>
                                <?php $calliope_sp_history_network_option_label = $calliope_sp_history_network_labels[$calliope_sp_history_network_option] ?? ucwords(str_replace(['_', '-'], ' ', $calliope_sp_history_network_option)); ?>
                                <option value="<?php echo esc_attr($calliope_sp_history_network_option); ?>" <?php selected($calliope_sp_history_network, $calliope_sp_history_network_option); ?>><?php echo esc_html($calliope_sp_history_network_option_label); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                    <label class="calliope-sp-history-filter">
                        <span><?php echo esc_html__('Status', 'calliope-social-publisher'); ?></span>
                        <select name="history_status">
                            <option value=""><?php echo esc_html__('All statuses', 'calliope-social-publisher'); ?></option>
                            <option value="success" <?php selected($calliope_sp_history_status, 'success'); ?>><?php echo esc_html__('Successful', 'calliope-social-publisher'); ?></option>
                            <option value="failed" <?php selected($calliope_sp_history_status, 'failed'); ?>><?php echo esc_html__('Failed', 'calliope-social-publisher'); ?></option>
                            <option value="pending" <?php selected($calliope_sp_history_status, 'pending'); ?>><?php echo esc_html__('Pending', 'calliope-social-publisher'); ?></option>
                        </select>
                    </label>
                    <div class="calliope-sp-history-filter-actions">
                        <button class="button button-primary" type="submit"><?php echo esc_html__('Apply filters', 'calliope-social-publisher'); ?></button>
                        <?php if ($calliope_sp_history_search !== '' || $calliope_sp_history_network !== '' || $calliope_sp_history_status !== ''): ?>
                            <a class="button" href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'history'])); ?>"><?php echo esc_html__('Clear filters', 'calliope-social-publisher'); ?></a>
                        <?php endif; ?>
                    </div>
                </form>

                <div class="calliope-sp-history-pro-tools" aria-disabled="true">
                    <div class="calliope-sp-history-pro-tools__title"><span><?php echo esc_html__('Advanced filters', 'calliope-social-publisher'); ?></span><span class="calliope-sp-pro-badge">PRO</span></div>
                    <label><span><?php echo esc_html__('Account', 'calliope-social-publisher'); ?></span><select disabled><option><?php echo esc_html__('All accounts', 'calliope-social-publisher'); ?></option></select></label>
                    <label><span><?php echo esc_html__('Content type', 'calliope-social-publisher'); ?></span><select disabled><option><?php echo esc_html__('All content types', 'calliope-social-publisher'); ?></option></select></label>
                    <label><span><?php echo esc_html__('Custom date range', 'calliope-social-publisher'); ?></span><input type="text" disabled value="<?php echo esc_attr__('From → To', 'calliope-social-publisher'); ?>" /></label>
                    <button class="button" type="button" disabled><?php echo esc_html__('Export CSV', 'calliope-social-publisher'); ?></button>
                </div>

                <?php if (empty($calliope_sp_history_data['ready'])): ?>
                    <div class="calliope-sp-history-empty">
                        <span class="dashicons dashicons-warning"></span>
                        <div><strong><?php echo esc_html__('History storage is not ready.', 'calliope-social-publisher'); ?></strong><p><?php echo esc_html__('Reactivate the plugin or reload this page so Social Publisher can create its history table.', 'calliope-social-publisher'); ?></p></div>
                    </div>
                <?php elseif (empty($calliope_sp_history_data['items'])): ?>
                    <div class="calliope-sp-history-empty">
                        <span class="dashicons dashicons-backup"></span>
                        <div>
                            <strong><?php echo esc_html__('No history records found.', 'calliope-social-publisher'); ?></strong>
                            <p><?php echo esc_html(($calliope_sp_history_search !== '' || $calliope_sp_history_network !== '' || $calliope_sp_history_status !== '') ? __('Try clearing the filters to see more publications.', 'calliope-social-publisher') : __('Publish something from Social Publisher to start building this permanent record.', 'calliope-social-publisher')); ?></p>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="calliope-sp-history-table-wrap">
                        <table class="widefat striped calliope-sp-history-table">
                            <colgroup>
                                <col class="calliope-sp-history-col-publication" />
                                <col class="calliope-sp-history-col-destination" />
                                <col class="calliope-sp-history-col-type" />
                                <col class="calliope-sp-history-col-source" />
                                <col class="calliope-sp-history-col-date" />
                                <col class="calliope-sp-history-col-status" />
                                <col class="calliope-sp-history-col-result" />
                            </colgroup>
                            <thead>
                                <tr>
                                    <th><?php echo esc_html__('Publication', 'calliope-social-publisher'); ?></th>
                                    <th><?php echo esc_html__('Destination', 'calliope-social-publisher'); ?></th>
                                    <th><?php echo esc_html__('Type & AI', 'calliope-social-publisher'); ?></th>
                                    <th><?php echo esc_html__('Source', 'calliope-social-publisher'); ?></th>
                                    <th><?php echo esc_html__('Date', 'calliope-social-publisher'); ?></th>
                                    <th><?php echo esc_html__('Status', 'calliope-social-publisher'); ?></th>
                                    <th><?php echo esc_html__('Result', 'calliope-social-publisher'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($calliope_sp_history_data['items'] as $calliope_sp_history_item): ?>
                                    <?php
                                    $calliope_sp_history_post_id = absint($calliope_sp_history_item['post_id'] ?? 0);
                                    $calliope_sp_history_title = trim((string) ($calliope_sp_history_item['post_title'] ?? ''));
                                    if ($calliope_sp_history_title === '') {
                                        $calliope_sp_history_title = __('Direct social post', 'calliope-social-publisher');
                                    }
                                    $calliope_sp_history_post_url = esc_url((string) ($calliope_sp_history_item['post_url'] ?? ''));
                                    $calliope_sp_history_media_attachment_id = absint($calliope_sp_history_item['media_attachment_id'] ?? 0);
                                    $calliope_sp_history_thumbnail = '';
                                    if ($calliope_sp_history_media_attachment_id > 0) {
                                        $calliope_sp_history_thumbnail_candidate = wp_get_attachment_image_url($calliope_sp_history_media_attachment_id, 'thumbnail');
                                        $calliope_sp_history_thumbnail = is_string($calliope_sp_history_thumbnail_candidate) ? $calliope_sp_history_thumbnail_candidate : '';
                                    } elseif ($calliope_sp_history_post_id > 0) {
                                        // Legacy automatic publications generally used the source post thumbnail.
                                        // For legacy manual rows, do not guess: the exact selected image was not persisted before History schema v3.
                                        $calliope_sp_history_legacy_source = sanitize_key((string) ($calliope_sp_history_item['source'] ?? 'manual'));
                                        $calliope_sp_history_legacy_trigger = sanitize_key((string) ($calliope_sp_history_item['trigger_type'] ?? 'manual'));
                                        if ($calliope_sp_history_legacy_trigger === 'automatic' || in_array($calliope_sp_history_legacy_source, ['gutenberg', 'gutenberg_auto', 'auto_post', 'scheduler', 'scheduled', 'pro_scheduler'], true)) {
                                            $calliope_sp_history_thumbnail_candidate = get_the_post_thumbnail_url($calliope_sp_history_post_id, 'thumbnail');
                                            $calliope_sp_history_thumbnail = is_string($calliope_sp_history_thumbnail_candidate) ? $calliope_sp_history_thumbnail_candidate : '';
                                        }
                                    }
                                    $calliope_sp_history_item_network = sanitize_key((string) ($calliope_sp_history_item['network'] ?? ''));
                                    $calliope_sp_history_network_label = $calliope_sp_history_network_labels[$calliope_sp_history_item_network] ?? ucwords(str_replace(['_', '-'], ' ', $calliope_sp_history_item_network));
                                    $calliope_sp_history_icon_network = $calliope_sp_history_item_network === 'bsky' ? 'bluesky' : $calliope_sp_history_item_network;
                                    $calliope_sp_history_icon_html = calliope_sp_ui_icon($calliope_sp_history_icon_network);
                                    $calliope_sp_history_account = trim((string) ($calliope_sp_history_item['account_label'] ?? ''));
                                    if ($calliope_sp_history_account === '') {
                                        $calliope_sp_history_account = trim((string) ($calliope_sp_history_item['account_id'] ?? ''));
                                    }
                                    $calliope_sp_history_content_type = sanitize_key((string) ($calliope_sp_history_item['content_type'] ?? 'text'));
                                    $calliope_sp_history_content_label = $calliope_sp_history_content_labels[$calliope_sp_history_content_type] ?? __('Text', 'calliope-social-publisher');
                                    $calliope_sp_history_trigger = sanitize_key((string) ($calliope_sp_history_item['trigger_type'] ?? 'manual'));
                                    $calliope_sp_history_source = sanitize_key((string) ($calliope_sp_history_item['source'] ?? 'manual'));
                                    $calliope_sp_history_source_label = $calliope_sp_history_trigger === 'automatic' ? __('Automatic', 'calliope-social-publisher') : __('Manual', 'calliope-social-publisher');
                                    if (in_array($calliope_sp_history_source, ['gutenberg', 'gutenberg_auto', 'auto_post'], true)) {
                                        $calliope_sp_history_source_detail = __('Gutenberg auto-post', 'calliope-social-publisher');
                                    } elseif (in_array($calliope_sp_history_source, ['scheduler', 'scheduled', 'pro_scheduler'], true)) {
                                        $calliope_sp_history_source_detail = __('Scheduler', 'calliope-social-publisher');
                                    } elseif (in_array($calliope_sp_history_source, ['publisher', 'manual'], true)) {
                                        $calliope_sp_history_source_detail = __('Publisher', 'calliope-social-publisher');
                                    } else {
                                        $calliope_sp_history_source_detail = ucwords(str_replace(['_', '-'], ' ', $calliope_sp_history_source));
                                    }
                                    $calliope_sp_history_status_key = sanitize_key((string) ($calliope_sp_history_item['status'] ?? 'pending'));
                                    $calliope_sp_history_outcome = sanitize_key((string) ($calliope_sp_history_item['outcome'] ?? 'pending'));
                                    $calliope_sp_history_status_label = __('Pending', 'calliope-social-publisher');
                                    $calliope_sp_history_status_class = 'is-pending';
                                    if ($calliope_sp_history_status_key === 'failed') {
                                        $calliope_sp_history_status_label = __('Failed', 'calliope-social-publisher');
                                        $calliope_sp_history_status_class = 'is-failed';
                                    } elseif ($calliope_sp_history_status_key === 'success') {
                                        $calliope_sp_history_status_class = 'is-success';
                                        if ($calliope_sp_history_outcome === 'warning') {
                                            $calliope_sp_history_status_label = __('Published with warning', 'calliope-social-publisher');
                                            $calliope_sp_history_status_class = 'is-warning';
                                        } elseif ($calliope_sp_history_outcome === 'needs_review') {
                                            $calliope_sp_history_status_label = __('Needs review', 'calliope-social-publisher');
                                            $calliope_sp_history_status_class = 'is-warning';
                                        } elseif ($calliope_sp_history_outcome === 'skipped') {
                                            $calliope_sp_history_status_label = __('Skipped', 'calliope-social-publisher');
                                            $calliope_sp_history_status_class = 'is-neutral';
                                        } else {
                                            $calliope_sp_history_status_label = __('Published', 'calliope-social-publisher');
                                        }
                                    }
                                    $calliope_sp_history_display_date = $calliope_sp_history_format_time(!empty($calliope_sp_history_item['published_at']) ? $calliope_sp_history_item['published_at'] : $calliope_sp_history_item['created_at']);
                                    $calliope_sp_history_provider_url = esc_url((string) ($calliope_sp_history_item['provider_post_url'] ?? ''));
                                    $calliope_sp_history_provider_id = trim((string) ($calliope_sp_history_item['provider_post_id'] ?? ''));
                                    $calliope_sp_history_error_summary = trim((string) ($calliope_sp_history_item['error_summary'] ?? ''));
                                    $calliope_sp_history_can_retry = class_exists('Calliope_SP_History') && Calliope_SP_History::can_retry($calliope_sp_history_item);
                                    ?>
                                    <tr>
                                        <td class="calliope-sp-history-publication-cell" data-label="<?php echo esc_attr__('Publication', 'calliope-social-publisher'); ?>">
                                            <div class="calliope-sp-history-publication">
                                                <?php if (is_string($calliope_sp_history_thumbnail) && $calliope_sp_history_thumbnail !== ''): ?>
                                                    <img src="<?php echo esc_url($calliope_sp_history_thumbnail); ?>" alt="" loading="lazy" />
                                                <?php else: ?>
                                                    <span class="calliope-sp-history-thumb-placeholder dashicons dashicons-media-document" aria-hidden="true"></span>
                                                <?php endif; ?>
                                                <div>
                                                    <strong><?php echo esc_html($calliope_sp_history_title); ?></strong>
                                                    <?php if ($calliope_sp_history_post_id > 0): ?><span><?php echo esc_html(sprintf(__('WordPress post #%d', 'calliope-social-publisher'), $calliope_sp_history_post_id)); ?></span><?php endif; ?>
                                                    <?php if ($calliope_sp_history_post_url !== ''): ?><a href="<?php echo esc_url($calliope_sp_history_post_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('View source', 'calliope-social-publisher'); ?></a><?php endif; ?>
                                                </div>
                                            </div>
                                        </td>
                                        <td data-label="<?php echo esc_attr__('Destination', 'calliope-social-publisher'); ?>">
                                            <div class="calliope-sp-history-destination">
                                                <span class="calliope-sp-history-network-icon"><?php if ($calliope_sp_history_icon_html !== '') { echo wp_kses($calliope_sp_history_icon_html, calliope_sp_ui_allowed_html()); } else { ?><span class="dashicons dashicons-share" aria-hidden="true"></span><?php } ?></span>
                                                <div><strong><?php echo esc_html($calliope_sp_history_network_label); ?></strong><span><?php echo esc_html($calliope_sp_history_account !== '' ? $calliope_sp_history_account : __('Account not captured', 'calliope-social-publisher')); ?></span></div>
                                            </div>
                                        </td>
                                        <td data-label="<?php echo esc_attr__('Type & AI', 'calliope-social-publisher'); ?>">
                                            <div class="calliope-sp-history-chip-stack">
                                                <span class="calliope-sp-history-chip"><?php echo esc_html($calliope_sp_history_content_label); ?></span>
                                                <span class="calliope-sp-history-chip <?php echo !empty($calliope_sp_history_item['ai_used']) ? 'is-ai' : 'is-muted'; ?>"><?php echo !empty($calliope_sp_history_item['ai_used']) ? esc_html__('AI assisted', 'calliope-social-publisher') : esc_html__('No AI', 'calliope-social-publisher'); ?></span>
                                            </div>
                                        </td>
                                        <td data-label="<?php echo esc_attr__('Source', 'calliope-social-publisher'); ?>"><strong class="calliope-sp-history-source-main"><?php echo esc_html($calliope_sp_history_source_label); ?></strong><span class="calliope-sp-history-source-detail"><?php echo esc_html($calliope_sp_history_source_detail); ?></span></td>
                                        <td data-label="<?php echo esc_attr__('Date', 'calliope-social-publisher'); ?>"><span class="calliope-sp-history-date"><?php echo esc_html($calliope_sp_history_display_date); ?></span></td>
                                        <td data-label="<?php echo esc_attr__('Status', 'calliope-social-publisher'); ?>"><span class="calliope-sp-history-status-badge <?php echo esc_attr($calliope_sp_history_status_class); ?>"><?php echo esc_html($calliope_sp_history_status_label); ?></span></td>
                                        <td class="calliope-sp-history-result-cell" data-label="<?php echo esc_attr__('Result', 'calliope-social-publisher'); ?>">
                                            <?php if ($calliope_sp_history_provider_url !== ''): ?>
                                                <a class="button button-small" href="<?php echo esc_url($calliope_sp_history_provider_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('View social post', 'calliope-social-publisher'); ?></a>
                                            <?php elseif ($calliope_sp_history_status_key === 'failed' && $calliope_sp_history_error_summary !== ''): ?>
                                                <span class="calliope-sp-history-error"><?php echo esc_html($calliope_sp_history_error_summary); ?></span>
                                            <?php elseif ($calliope_sp_history_status_key === 'pending'): ?>
                                                <span class="calliope-sp-history-muted"><?php echo esc_html__('Waiting for provider response', 'calliope-social-publisher'); ?></span>
                                            <?php else: ?>
                                                <span class="calliope-sp-history-muted"><?php echo esc_html__('No public post URL returned', 'calliope-social-publisher'); ?></span>
                                            <?php endif; ?>
                                            <?php if ($calliope_sp_history_can_retry): ?>
                                                <form class="calliope-sp-history-retry-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                                                    <input type="hidden" name="action" value="calliope_sp_retry_history" />
                                                    <input type="hidden" name="history_id" value="<?php echo esc_attr((string) absint($calliope_sp_history_item['id'] ?? 0)); ?>" />
                                                    <?php wp_nonce_field('calliope_sp_retry_history_' . absint($calliope_sp_history_item['id'] ?? 0), 'calliope_sp_retry_nonce'); ?>
                                                    <button type="submit" class="button button-small calliope-sp-history-retry-button" title="<?php echo esc_attr__('Retry only this failed destination', 'calliope-social-publisher'); ?>"><?php echo esc_html__('Retry', 'calliope-social-publisher'); ?></button>
                                                </form>
                                            <?php endif; ?>
                                            <?php do_action('calliope_sp_render_history_result_extensions', $calliope_sp_history_item); ?>
                                            <details class="calliope-sp-history-details">
                                                <summary><?php echo esc_html__('Details', 'calliope-social-publisher'); ?></summary>
                                                <dl>
                                                    <?php if ($calliope_sp_history_provider_id !== ''): ?><div><dt><?php echo esc_html__('Social post ID', 'calliope-social-publisher'); ?></dt><dd><?php echo esc_html($calliope_sp_history_provider_id); ?></dd></div><?php endif; ?>
                                                    <div><dt><?php echo esc_html__('Retries', 'calliope-social-publisher'); ?></dt><dd><?php echo esc_html(number_format_i18n(absint($calliope_sp_history_item['retry_count'] ?? 0))); ?></dd></div>
                                                    <?php if (!empty($calliope_sp_history_item['error_code'])): ?><div><dt><?php echo esc_html__('Error code', 'calliope-social-publisher'); ?></dt><dd><?php echo esc_html((string) $calliope_sp_history_item['error_code']); ?></dd></div><?php endif; ?>
                                                    <div><dt><?php echo esc_html__('Publication ID', 'calliope-social-publisher'); ?></dt><dd><?php echo esc_html((string) ($calliope_sp_history_item['publication_uuid'] ?? '')); ?></dd></div>
                                                    <div><dt><?php echo esc_html__('Created', 'calliope-social-publisher'); ?></dt><dd><?php echo esc_html($calliope_sp_history_format_time($calliope_sp_history_item['created_at'] ?? '')); ?></dd></div>
                                                    <div><dt><?php echo esc_html__('Updated', 'calliope-social-publisher'); ?></dt><dd><?php echo esc_html($calliope_sp_history_format_time($calliope_sp_history_item['updated_at'] ?? '')); ?></dd></div>
                                                </dl>
                                            </details>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <?php if ((int) $calliope_sp_history_data['total_pages'] > 1): ?>
                        <?php
                        $calliope_sp_history_pagination_base = calliope_sp_url_with([
                            'tab' => 'history',
                            'history_q' => $calliope_sp_history_search,
                            'history_network' => $calliope_sp_history_network,
                            'history_status' => $calliope_sp_history_status,
                        ]);
                        $calliope_sp_history_pagination = paginate_links([
                            'base' => add_query_arg('history_page', '%#%', $calliope_sp_history_pagination_base),
                            'format' => '',
                            'current' => max(1, (int) $calliope_sp_history_data['page']),
                            'total' => max(1, (int) $calliope_sp_history_data['total_pages']),
                            'prev_text' => __('Previous', 'calliope-social-publisher'),
                            'next_text' => __('Next', 'calliope-social-publisher'),
                            'type' => 'list',
                        ]);
                        ?>
                        <?php if (is_string($calliope_sp_history_pagination) && $calliope_sp_history_pagination !== ''): ?>
                            <nav class="calliope-sp-history-pagination" aria-label="<?php echo esc_attr__('History pagination', 'calliope-social-publisher'); ?>">
                                <span><?php echo esc_html(sprintf(__('Page %1$d of %2$d', 'calliope-social-publisher'), (int) $calliope_sp_history_data['page'], (int) $calliope_sp_history_data['total_pages'])); ?></span>
                                <?php echo wp_kses_post($calliope_sp_history_pagination); ?>
                            </nav>
                        <?php endif; ?>
                    <?php endif; ?>
                <?php endif; ?>
            </section>


        <?php elseif ($calliope_sp_tab === 'analytics'): ?>

            <?php
            $calliope_sp_analytics_period = isset($_GET['analytics_period']) ? absint(wp_unslash((string) $_GET['analytics_period'])) : 30;
            if (!in_array($calliope_sp_analytics_period, [7, 30, 90], true)) {
                $calliope_sp_analytics_period = 30;
            }
            $calliope_sp_analytics = class_exists('Calliope_SP_History')
                ? Calliope_SP_History::get_basic_analytics($calliope_sp_analytics_period)
                : ['ready' => false, 'days' => $calliope_sp_analytics_period, 'runs' => 0, 'total' => 0, 'success' => 0, 'failed' => 0, 'pending' => 0, 'success_rate' => 0, 'active_networks' => 0, 'networks' => []];
            $calliope_sp_analytics_network_labels = [
                'bluesky' => __('Bluesky', 'calliope-social-publisher'),
                'bsky' => __('Bluesky', 'calliope-social-publisher'),
                'mastodon' => __('Mastodon', 'calliope-social-publisher'),
                'tumblr' => __('Tumblr', 'calliope-social-publisher'),
                'pinterest' => __('Pinterest', 'calliope-social-publisher'),
                'threads' => __('Threads', 'calliope-social-publisher'),
                'instagram' => __('Instagram', 'calliope-social-publisher'),
                'linkedin' => __('LinkedIn', 'calliope-social-publisher'),
                'blogger' => __('Blogger', 'calliope-social-publisher'),
                'telegram' => __('Telegram', 'calliope-social-publisher'),
                'facebook' => __('Facebook', 'calliope-social-publisher'),
                'discord' => __('Discord', 'calliope-social-publisher'),
                'youtube' => __('YouTube', 'calliope-social-publisher'),
                'remote_wordpress' => __('Remote WordPress', 'calliope-social-publisher'),
                'wordpress_remote' => __('Remote WordPress', 'calliope-social-publisher'),
                'webhook' => __('Custom webhook', 'calliope-social-publisher'),
                'custom_webhook' => __('Custom webhook', 'calliope-social-publisher'),
            ];
            $calliope_sp_analytics_period_labels = [
                7 => __('Last 7 days', 'calliope-social-publisher'),
                30 => __('Last 30 days', 'calliope-social-publisher'),
                90 => __('Last 90 days', 'calliope-social-publisher'),
            ];
            $calliope_sp_analytics_pro_status = class_exists('Calliope_SP_Extensions') ? Calliope_SP_Extensions::get_pro_status() : [];
            $calliope_sp_analytics_pro_active = !empty($calliope_sp_analytics_pro_status['license_active']);
            $calliope_sp_analytics_pro_url = class_exists('Calliope_SP_Extensions') ? Calliope_SP_Extensions::get_purchase_url() : 'https://pluginswordpress.calliope.com.ar/calliope-social-publisher/';
            $calliope_sp_analytics_network_filter = isset($_GET['analytics_network']) ? sanitize_key(wp_unslash((string) $_GET['analytics_network'])) : '';
            $calliope_sp_analytics_network_options = [];
            foreach ((array) ($calliope_sp_analytics['networks'] ?? []) as $calliope_sp_network_row) {
                $calliope_sp_network_slug = sanitize_key((string) ($calliope_sp_network_row['network'] ?? ''));
                if ($calliope_sp_network_slug !== '') {
                    $calliope_sp_analytics_network_options[$calliope_sp_network_slug] = $calliope_sp_analytics_network_labels[$calliope_sp_network_slug] ?? ucwords(str_replace(['_', '-'], ' ', $calliope_sp_network_slug));
                }
            }
            if ($calliope_sp_analytics_network_filter !== '' && !isset($calliope_sp_analytics_network_options[$calliope_sp_analytics_network_filter])) {
                $calliope_sp_analytics_network_filter = '';
            }
            $calliope_sp_activity = class_exists('Calliope_SP_History')
                ? Calliope_SP_History::get_activity_series($calliope_sp_analytics_period, $calliope_sp_analytics_network_filter)
                : ['ready' => false, 'days' => $calliope_sp_analytics_period, 'network' => $calliope_sp_analytics_network_filter, 'points' => [], 'max_value' => 0];
            ?>

            <div class="calliope-sp-analytics-free-view" data-calliope-free-analytics>
            <section class="calliope-sp-analytics-head">
                <div>
                    <span class="calliope-sp-history-eyebrow"><?php echo esc_html__('Free analytics', 'calliope-social-publisher'); ?></span>
                    <h3><?php echo esc_html__('Publishing Analytics', 'calliope-social-publisher'); ?></h3>
                    <p><?php echo esc_html__('See how Social Publisher is performing using the permanent publication history stored on your site.', 'calliope-social-publisher'); ?></p>
                </div>
                <div class="calliope-sp-analytics-periods" aria-label="<?php echo esc_attr__('Analytics period', 'calliope-social-publisher'); ?>">
                    <?php foreach ($calliope_sp_analytics_period_labels as $calliope_sp_period_days => $calliope_sp_period_label): ?>
                        <a class="button <?php echo esc_attr($calliope_sp_analytics_period === $calliope_sp_period_days ? 'button-primary' : ''); ?>" href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'analytics', 'analytics_period' => $calliope_sp_period_days, 'analytics_network' => $calliope_sp_analytics_network_filter])); ?>"><?php echo esc_html($calliope_sp_period_label); ?></a>
                    <?php endforeach; ?>
                </div>
            </section>

            <section class="calliope-sp-analytics-metrics" aria-label="<?php echo esc_attr__('Analytics summary', 'calliope-social-publisher'); ?>">
                <article class="calliope-sp-card calliope-sp-analytics-metric"><span><?php echo esc_html__('Publications', 'calliope-social-publisher'); ?></span><strong><?php echo esc_html(number_format_i18n((int) $calliope_sp_analytics['runs'])); ?></strong><small><?php echo esc_html__('Unique publication runs', 'calliope-social-publisher'); ?></small></article>
                <article class="calliope-sp-card calliope-sp-analytics-metric is-success"><span><?php echo esc_html__('Successful', 'calliope-social-publisher'); ?></span><strong><?php echo esc_html(number_format_i18n((int) $calliope_sp_analytics['success'])); ?></strong><small><?php echo esc_html__('Successful destinations', 'calliope-social-publisher'); ?></small></article>
                <article class="calliope-sp-card calliope-sp-analytics-metric is-failed"><span><?php echo esc_html__('Failed', 'calliope-social-publisher'); ?></span><strong><?php echo esc_html(number_format_i18n((int) $calliope_sp_analytics['failed'])); ?></strong><small><?php echo esc_html__('Failed destinations', 'calliope-social-publisher'); ?></small></article>
                <article class="calliope-sp-card calliope-sp-analytics-metric"><span><?php echo esc_html__('Success rate', 'calliope-social-publisher'); ?></span><strong><?php echo esc_html(number_format_i18n((float) $calliope_sp_analytics['success_rate'], 1)); ?>%</strong><small><?php echo esc_html__('Completed destinations only', 'calliope-social-publisher'); ?></small></article>
                <article class="calliope-sp-card calliope-sp-analytics-metric"><span><?php echo esc_html__('Active networks', 'calliope-social-publisher'); ?></span><strong><?php echo esc_html(number_format_i18n((int) $calliope_sp_analytics['active_networks'])); ?></strong><small><?php echo esc_html__('Networks used in this period', 'calliope-social-publisher'); ?></small></article>
            </section>

            <?php
            $calliope_sp_chart_points = (array) ($calliope_sp_activity['points'] ?? []);
            $calliope_sp_chart_width = 1000.0;
            $calliope_sp_chart_height = 250.0;
            $calliope_sp_chart_left = 48.0;
            $calliope_sp_chart_right = 20.0;
            $calliope_sp_chart_top = 18.0;
            $calliope_sp_chart_bottom = 40.0;
            $calliope_sp_chart_plot_width = $calliope_sp_chart_width - $calliope_sp_chart_left - $calliope_sp_chart_right;
            $calliope_sp_chart_plot_height = $calliope_sp_chart_height - $calliope_sp_chart_top - $calliope_sp_chart_bottom;
            $calliope_sp_chart_max = max(1, absint($calliope_sp_activity['max_value'] ?? 0));
            $calliope_sp_chart_count = count($calliope_sp_chart_points);
            $calliope_sp_chart_success_points = [];
            $calliope_sp_chart_failed_points = [];
            $calliope_sp_chart_positions = [];
            foreach ($calliope_sp_chart_points as $calliope_sp_chart_index => $calliope_sp_chart_point) {
                $calliope_sp_chart_x = $calliope_sp_chart_count > 1
                    ? $calliope_sp_chart_left + (($calliope_sp_chart_index / ($calliope_sp_chart_count - 1)) * $calliope_sp_chart_plot_width)
                    : $calliope_sp_chart_left + ($calliope_sp_chart_plot_width / 2);
                $calliope_sp_chart_success = absint($calliope_sp_chart_point['success'] ?? 0);
                $calliope_sp_chart_failed = absint($calliope_sp_chart_point['failed'] ?? 0);
                $calliope_sp_chart_success_y = $calliope_sp_chart_top + $calliope_sp_chart_plot_height - (($calliope_sp_chart_success / $calliope_sp_chart_max) * $calliope_sp_chart_plot_height);
                $calliope_sp_chart_failed_y = $calliope_sp_chart_top + $calliope_sp_chart_plot_height - (($calliope_sp_chart_failed / $calliope_sp_chart_max) * $calliope_sp_chart_plot_height);
                $calliope_sp_chart_success_points[] = number_format($calliope_sp_chart_x, 2, '.', '') . ',' . number_format($calliope_sp_chart_success_y, 2, '.', '');
                $calliope_sp_chart_failed_points[] = number_format($calliope_sp_chart_x, 2, '.', '') . ',' . number_format($calliope_sp_chart_failed_y, 2, '.', '');
                $calliope_sp_chart_positions[] = [
                    'x' => $calliope_sp_chart_x,
                    'success_y' => $calliope_sp_chart_success_y,
                    'failed_y' => $calliope_sp_chart_failed_y,
                    'success' => $calliope_sp_chart_success,
                    'failed' => $calliope_sp_chart_failed,
                    'label' => sanitize_text_field((string) ($calliope_sp_chart_point['label'] ?? '')),
                ];
            }
            $calliope_sp_chart_tick_count = $calliope_sp_chart_max <= 4 ? $calliope_sp_chart_max : 4;
            $calliope_sp_chart_tick_count = max(1, $calliope_sp_chart_tick_count);
            $calliope_sp_chart_label_indexes = [];
            if ($calliope_sp_chart_count > 0) {
                $calliope_sp_chart_label_target = $calliope_sp_analytics_period <= 7 ? min(7, $calliope_sp_chart_count) : 5;
                for ($calliope_sp_chart_label_i = 0; $calliope_sp_chart_label_i < $calliope_sp_chart_label_target; $calliope_sp_chart_label_i++) {
                    $calliope_sp_chart_label_indexes[] = $calliope_sp_chart_label_target > 1
                        ? (int) round(($calliope_sp_chart_label_i / ($calliope_sp_chart_label_target - 1)) * ($calliope_sp_chart_count - 1))
                        : 0;
                }
                $calliope_sp_chart_label_indexes = array_values(array_unique($calliope_sp_chart_label_indexes));
            }
            $calliope_sp_chart_has_activity = false;
            foreach ($calliope_sp_chart_positions as $calliope_sp_chart_position) {
                if ($calliope_sp_chart_position['success'] > 0 || $calliope_sp_chart_position['failed'] > 0) {
                    $calliope_sp_chart_has_activity = true;
                    break;
                }
            }
            ?>
            <section class="calliope-sp-card calliope-sp-analytics-activity-card">
                <div class="calliope-sp-analytics-section-head calliope-sp-analytics-activity-head">
                    <div>
                        <h3><?php echo esc_html__('Activity over time', 'calliope-social-publisher'); ?></h3>
                        <p><?php echo esc_html__('See successful and failed destination results across the selected period.', 'calliope-social-publisher'); ?></p>
                    </div>
                    <div class="calliope-sp-analytics-activity-controls">
                        <form method="get" action="<?php echo esc_url(admin_url('admin.php')); ?>">
                            <input type="hidden" name="page" value="calliope-social-publisher" />
                            <input type="hidden" name="tab" value="analytics" />
                            <input type="hidden" name="analytics_period" value="<?php echo esc_attr((string) $calliope_sp_analytics_period); ?>" />
                            <label>
                                <span><?php echo esc_html__('Network', 'calliope-social-publisher'); ?></span>
                                <select name="analytics_network">
                                    <option value=""><?php echo esc_html__('All networks', 'calliope-social-publisher'); ?></option>
                                    <?php foreach ($calliope_sp_analytics_network_options as $calliope_sp_network_slug => $calliope_sp_network_name): ?>
                                        <option value="<?php echo esc_attr($calliope_sp_network_slug); ?>" <?php selected($calliope_sp_analytics_network_filter, $calliope_sp_network_slug); ?>><?php echo esc_html($calliope_sp_network_name); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </label>
                            <button class="button" type="submit"><?php echo esc_html__('Apply filters', 'calliope-social-publisher'); ?></button>
                        </form>
                        <?php if (!$calliope_sp_analytics_pro_active): ?>
                            <div class="calliope-sp-analytics-pro-controls" aria-label="<?php echo esc_attr__('Advanced analytics', 'calliope-social-publisher'); ?>">
                                <span aria-disabled="true"><?php echo esc_html__('Compare previous period', 'calliope-social-publisher'); ?> <span class="calliope-sp-pro-badge">PRO</span></span>
                                <span aria-disabled="true"><?php echo esc_html__('Custom date range', 'calliope-social-publisher'); ?> <span class="calliope-sp-pro-badge">PRO</span></span>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="calliope-sp-analytics-chart-legend" aria-hidden="true">
                    <span class="is-success"><i></i><?php echo esc_html__('Successful', 'calliope-social-publisher'); ?></span>
                    <span class="is-failed"><i></i><?php echo esc_html__('Failed', 'calliope-social-publisher'); ?></span>
                </div>
                <?php if (empty($calliope_sp_activity['ready'])): ?>
                    <div class="calliope-sp-history-empty"><span class="dashicons dashicons-warning"></span><div><strong><?php echo esc_html__('Analytics is not ready yet.', 'calliope-social-publisher'); ?></strong><p><?php echo esc_html__('Reload the page after Social Publisher creates the permanent History table.', 'calliope-social-publisher'); ?></p></div></div>
                <?php elseif (!$calliope_sp_chart_has_activity): ?>
                    <div class="calliope-sp-history-empty"><span class="dashicons dashicons-chart-line"></span><div><strong><?php echo esc_html__('No publishing activity in this period.', 'calliope-social-publisher'); ?></strong><p><?php echo esc_html__('Publish to at least one social destination to start building these statistics.', 'calliope-social-publisher'); ?></p></div></div>
                <?php else: ?>
                    <div class="calliope-sp-analytics-chart" role="img" aria-label="<?php echo esc_attr__('Daily publishing activity', 'calliope-social-publisher'); ?>">
                        <svg viewBox="0 0 1000 250" preserveAspectRatio="xMidYMid meet" focusable="false" aria-hidden="true">
                            <?php for ($calliope_sp_chart_tick = 0; $calliope_sp_chart_tick <= $calliope_sp_chart_tick_count; $calliope_sp_chart_tick++): ?>
                                <?php
                                $calliope_sp_chart_tick_ratio = $calliope_sp_chart_tick / $calliope_sp_chart_tick_count;
                                $calliope_sp_chart_tick_y = $calliope_sp_chart_top + $calliope_sp_chart_plot_height - ($calliope_sp_chart_tick_ratio * $calliope_sp_chart_plot_height);
                                $calliope_sp_chart_tick_value = (int) round($calliope_sp_chart_tick_ratio * $calliope_sp_chart_max);
                                ?>
                                <line class="calliope-sp-chart-grid" x1="<?php echo esc_attr((string) $calliope_sp_chart_left); ?>" y1="<?php echo esc_attr(number_format($calliope_sp_chart_tick_y, 2, '.', '')); ?>" x2="<?php echo esc_attr((string) ($calliope_sp_chart_width - $calliope_sp_chart_right)); ?>" y2="<?php echo esc_attr(number_format($calliope_sp_chart_tick_y, 2, '.', '')); ?>"></line>
                                <text class="calliope-sp-chart-y-label" x="<?php echo esc_attr((string) ($calliope_sp_chart_left - 10)); ?>" y="<?php echo esc_attr(number_format($calliope_sp_chart_tick_y + 4, 2, '.', '')); ?>" text-anchor="end"><?php echo esc_html((string) $calliope_sp_chart_tick_value); ?></text>
                            <?php endfor; ?>
                            <polyline class="calliope-sp-chart-line is-success" points="<?php echo esc_attr(implode(' ', $calliope_sp_chart_success_points)); ?>"></polyline>
                            <polyline class="calliope-sp-chart-line is-failed" points="<?php echo esc_attr(implode(' ', $calliope_sp_chart_failed_points)); ?>"></polyline>
                            <?php if ($calliope_sp_analytics_period <= 30): ?>
                                <?php foreach ($calliope_sp_chart_positions as $calliope_sp_chart_position): ?>
                                    <circle class="calliope-sp-chart-point is-success" cx="<?php echo esc_attr(number_format((float) $calliope_sp_chart_position['x'], 2, '.', '')); ?>" cy="<?php echo esc_attr(number_format((float) $calliope_sp_chart_position['success_y'], 2, '.', '')); ?>" r="3"><title><?php echo esc_html($calliope_sp_chart_position['label'] . ' — ' . __('Successful', 'calliope-social-publisher') . ': ' . number_format_i18n((int) $calliope_sp_chart_position['success'])); ?></title></circle>
                                    <circle class="calliope-sp-chart-point is-failed" cx="<?php echo esc_attr(number_format((float) $calliope_sp_chart_position['x'], 2, '.', '')); ?>" cy="<?php echo esc_attr(number_format((float) $calliope_sp_chart_position['failed_y'], 2, '.', '')); ?>" r="3"><title><?php echo esc_html($calliope_sp_chart_position['label'] . ' — ' . __('Failed', 'calliope-social-publisher') . ': ' . number_format_i18n((int) $calliope_sp_chart_position['failed'])); ?></title></circle>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            <?php foreach ($calliope_sp_chart_label_indexes as $calliope_sp_chart_label_index): ?>
                                <?php if (!isset($calliope_sp_chart_positions[$calliope_sp_chart_label_index])) { continue; } $calliope_sp_chart_label_position = $calliope_sp_chart_positions[$calliope_sp_chart_label_index]; ?>
                                <text class="calliope-sp-chart-x-label" x="<?php echo esc_attr(number_format((float) $calliope_sp_chart_label_position['x'], 2, '.', '')); ?>" y="<?php echo esc_attr((string) ($calliope_sp_chart_height - 12)); ?>" text-anchor="middle"><?php echo esc_html($calliope_sp_chart_label_position['label']); ?></text>
                            <?php endforeach; ?>
                        </svg>
                    </div>
                <?php endif; ?>
            </section>

            <section class="calliope-sp-card calliope-sp-analytics-table-card">
                <div class="calliope-sp-analytics-section-head">
                    <div><h3><?php echo esc_html__('Performance by network', 'calliope-social-publisher'); ?></h3><p><?php echo esc_html__('Compare publishing volume and delivery reliability across your connected destinations.', 'calliope-social-publisher'); ?></p></div>
                    <span class="calliope-sp-history-result-count"><?php echo esc_html($calliope_sp_analytics_period_labels[$calliope_sp_analytics_period]); ?></span>
                </div>
                <?php if (empty($calliope_sp_analytics['ready'])): ?>
                    <div class="calliope-sp-history-empty"><span class="dashicons dashicons-warning"></span><div><strong><?php echo esc_html__('Analytics is not ready yet.', 'calliope-social-publisher'); ?></strong><p><?php echo esc_html__('Reload the page after Social Publisher creates the permanent History table.', 'calliope-social-publisher'); ?></p></div></div>
                <?php elseif (empty($calliope_sp_analytics['networks'])): ?>
                    <div class="calliope-sp-history-empty"><span class="dashicons dashicons-chart-bar"></span><div><strong><?php echo esc_html__('No analytics data yet.', 'calliope-social-publisher'); ?></strong><p><?php echo esc_html__('Publish to at least one social destination to start building these statistics.', 'calliope-social-publisher'); ?></p></div></div>
                <?php else: ?>
                    <div class="calliope-sp-analytics-table-wrap">
                        <table class="widefat striped calliope-sp-analytics-table">
                            <thead><tr><th><?php echo esc_html__('Network', 'calliope-social-publisher'); ?></th><th><?php echo esc_html__('Publications', 'calliope-social-publisher'); ?></th><th><?php echo esc_html__('Published', 'calliope-social-publisher'); ?></th><th><?php echo esc_html__('Failed', 'calliope-social-publisher'); ?></th><th><?php echo esc_html__('Pending', 'calliope-social-publisher'); ?></th><th><?php echo esc_html__('Success rate', 'calliope-social-publisher'); ?></th></tr></thead>
                            <tbody>
                            <?php foreach ((array) $calliope_sp_analytics['networks'] as $calliope_sp_network_row): ?>
                                <?php $calliope_sp_analytics_network = sanitize_key((string) ($calliope_sp_network_row['network'] ?? '')); $calliope_sp_analytics_network_label = $calliope_sp_analytics_network_labels[$calliope_sp_analytics_network] ?? ucwords(str_replace(['_', '-'], ' ', $calliope_sp_analytics_network)); ?>
                                <tr>
                                    <td data-label="<?php echo esc_attr__('Network', 'calliope-social-publisher'); ?>"><strong><?php echo esc_html($calliope_sp_analytics_network_label); ?></strong></td>
                                    <td data-label="<?php echo esc_attr__('Publications', 'calliope-social-publisher'); ?>"><?php echo esc_html(number_format_i18n((int) ($calliope_sp_network_row['runs'] ?? 0))); ?></td>
                                    <td data-label="<?php echo esc_attr__('Published', 'calliope-social-publisher'); ?>"><?php echo esc_html(number_format_i18n((int) ($calliope_sp_network_row['success'] ?? 0))); ?></td>
                                    <td data-label="<?php echo esc_attr__('Failed', 'calliope-social-publisher'); ?>"><?php echo esc_html(number_format_i18n((int) ($calliope_sp_network_row['failed'] ?? 0))); ?></td>
                                    <td data-label="<?php echo esc_attr__('Pending', 'calliope-social-publisher'); ?>"><?php echo esc_html(number_format_i18n((int) ($calliope_sp_network_row['pending'] ?? 0))); ?></td>
                                    <td data-label="<?php echo esc_attr__('Success rate', 'calliope-social-publisher'); ?>"><strong><?php echo esc_html(number_format_i18n((float) ($calliope_sp_network_row['success_rate'] ?? 0), 1)); ?>%</strong></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </section>
            </div>

            <?php if ($calliope_sp_analytics_pro_active): ?>
                <section class="calliope-sp-analytics-pro calliope-sp-analytics-pro--mount" data-calliope-pro-analytics-mount></section>
            <?php else: ?>
                <section class="calliope-sp-card calliope-sp-analytics-pro" aria-disabled="true">
                    <div class="calliope-sp-analytics-pro__head"><div><span class="calliope-sp-history-eyebrow"><?php echo esc_html__('Advanced analytics', 'calliope-social-publisher'); ?></span><h3><?php echo esc_html__('Go deeper with Social Publisher Pro', 'calliope-social-publisher'); ?> <span class="calliope-sp-pro-badge">PRO</span></h3></div><a class="button calliope-sp-history-pro-cta" href="<?php echo esc_url($calliope_sp_analytics_pro_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('Explore Social Publisher Pro', 'calliope-social-publisher'); ?></a></div>
                    <div class="calliope-sp-analytics-pro-grid">
                        <div><strong><?php echo esc_html__('Period comparison', 'calliope-social-publisher'); ?></strong><span><?php echo esc_html__('Compare results with the previous period and see percentage trends.', 'calliope-social-publisher'); ?></span></div>
                        <div><strong><?php echo esc_html__('Advanced filters', 'calliope-social-publisher'); ?></strong><span><?php echo esc_html__('Filter by account, content type, source, AI usage, and custom dates.', 'calliope-social-publisher'); ?></span></div>
                        <div><strong><?php echo esc_html__('Social performance', 'calliope-social-publisher'); ?></strong><span><?php echo esc_html__('Add reach, impressions, engagement, clicks, and content performance when APIs allow it.', 'calliope-social-publisher'); ?></span></div>
                    </div>
                </section>
            <?php endif; ?>

        <?php elseif ($calliope_sp_tab === 'settings'): ?>

            <?php
            $calliope_sp_saved_gemini_key = trim((string) get_option('calliope_sp_gemini_api_key', ''));
            $calliope_sp_ai_key_saved = $calliope_sp_saved_gemini_key !== '';
            $calliope_sp_ai_key_mask = $calliope_sp_ai_key_saved ? $this->mask_secret_for_display($calliope_sp_saved_gemini_key) : '';
            $calliope_sp_gemini_model = $this->sanitize_gemini_model_setting(get_option('calliope_sp_gemini_model', 'gemini-3.1-flash-lite'));
            $calliope_sp_gemini_models = $this->get_gemini_model_choices();
            $calliope_sp_generation_language = $this->get_generation_language_code();
            $calliope_sp_generation_languages = $this->get_generation_language_choices();
            $calliope_sp_cleanup_enabled = (bool) get_option('calliope_sp_cleanup_on_delete', false);
            $calliope_sp_history_retry_enabled = class_exists('Calliope_SP_History') ? Calliope_SP_History::is_retry_enabled() : get_option('calliope_sp_history_retry_enabled', '1') !== '0';
            $calliope_sp_social_templates_enabled = class_exists('Calliope_SP_Social_Templates') ? Calliope_SP_Social_Templates::is_enabled() : get_option('calliope_sp_social_templates_enabled', '0') === '1';
            $calliope_sp_social_templates = class_exists('Calliope_SP_Social_Templates') ? Calliope_SP_Social_Templates::get_templates() : [];
            $calliope_sp_social_template_networks = class_exists('Calliope_SP_Social_Templates') ? Calliope_SP_Social_Templates::network_labels() : [];
            $calliope_sp_social_template_smart_tags = class_exists('Calliope_SP_Social_Templates') ? Calliope_SP_Social_Templates::smart_tags() : [];
            $calliope_sp_social_template_group_labels = class_exists('Calliope_SP_Social_Templates') ? Calliope_SP_Social_Templates::smart_tag_group_labels() : [];
            $calliope_sp_social_template_defaults = class_exists('Calliope_SP_Social_Templates') ? Calliope_SP_Social_Templates::defaults() : [];
            $calliope_sp_templates_pro_url = class_exists('Calliope_SP_Extensions') ? Calliope_SP_Extensions::get_purchase_url() : 'https://pluginswordpress.calliope.com.ar/calliope-social-publisher/';
            $calliope_sp_tracking_enabled = class_exists('Calliope_SP_Tracking') ? Calliope_SP_Tracking::is_enabled() : get_option('calliope_sp_tracking_enabled', '0') === '1';
            $calliope_sp_short_links_enabled = class_exists('Calliope_SP_Short_Link_Service') ? Calliope_SP_Short_Link_Service::is_enabled() : get_option('calliope_sp_short_links_enabled', '1') !== '0';
            $calliope_sp_tracking_settings = class_exists('Calliope_SP_Tracking') ? Calliope_SP_Tracking::get_settings() : ['utm_source' => '{network}', 'utm_medium' => 'social', 'utm_campaign' => 'wordpress'];
            $calliope_sp_tracking_networks = class_exists('Calliope_SP_Platform_Preview') ? Calliope_SP_Platform_Preview::network_labels() : $calliope_sp_social_template_networks;
            $calliope_sp_tracking_pro_url = class_exists('Calliope_SP_Extensions') ? Calliope_SP_Extensions::get_purchase_url() : 'https://pluginswordpress.calliope.com.ar/calliope-social-publisher/';
            $calliope_sp_failure_alerts_enabled = class_exists('Calliope_SP_Failure_Alerts') ? Calliope_SP_Failure_Alerts::is_enabled() : get_option('calliope_sp_failure_alerts_enabled', '0') === '1';
            $calliope_sp_failure_alert_email = class_exists('Calliope_SP_Failure_Alerts') ? Calliope_SP_Failure_Alerts::get_recipient() : sanitize_email((string) get_option('calliope_sp_failure_alert_email', get_option('admin_email', '')));
            ?>

            <div class="calliope-sp-settings-grid">
                <div class="calliope-sp-card calliope-sp-settings-hero calliope-sp-settings-wide">
                    <div>
                        <span class="calliope-sp-doc-eyebrow"><?php echo esc_html__('Plugin controls', 'calliope-social-publisher'); ?></span>
                        <h3><?php echo esc_html__('Settings', 'calliope-social-publisher'); ?></h3>
                        <p><?php echo esc_html__('Configure the options that affect the whole plugin. Network credentials stay inside Connections, while this screen keeps AI generation, History retry controls and data cleanup settings in one predictable place.', 'calliope-social-publisher'); ?></p>
                    </div>
                    <div class="calliope-sp-settings-hero__actions">
                        <a class="button" href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'connections', 'net' => $calliope_sp_net])); ?>"><?php echo esc_html__('Open Connections', 'calliope-social-publisher'); ?></a>
                        <a class="button" href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'history'])); ?>"><?php echo esc_html__('History', 'calliope-social-publisher'); ?></a>
                        <a class="button" href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'logs'])); ?>"><?php echo esc_html__('View Logs', 'calliope-social-publisher'); ?></a>
                    </div>
                </div>

                <div class="calliope-sp-card calliope-sp-settings-card calliope-sp-settings-card--ai">
                    <div class="calliope-sp-settings-card__head">
                        <div>
                            <h3><?php echo esc_html__('AI assistant', 'calliope-social-publisher'); ?></h3>
                            <p><?php echo esc_html__('Connect Gemini to generate post titles, captions and hashtags directly from the Publisher screen.', 'calliope-social-publisher'); ?></p>
                        </div>
                        <span class="calliope-sp-settings-status <?php echo esc_attr($calliope_sp_ai_key_saved ? 'is-ok' : 'is-warn'); ?>"><?php echo esc_html($calliope_sp_ai_key_saved ? __('AI connected', 'calliope-social-publisher') : __('AI not connected', 'calliope-social-publisher')); ?></span>
                    </div>

                    <div class="calliope-sp-settings-summary">
                        <div>
                            <strong><?php echo esc_html__('Required', 'calliope-social-publisher'); ?></strong>
                            <span><?php echo esc_html__('Gemini API key', 'calliope-social-publisher'); ?></span>
                        </div>
                        <div>
                            <strong><?php echo esc_html__('Model', 'calliope-social-publisher'); ?></strong>
                            <span><?php echo esc_html((string) ($calliope_sp_gemini_models[$calliope_sp_gemini_model] ?? $calliope_sp_gemini_model)); ?></span>
                        </div>
                        <div>
                            <strong><?php echo esc_html__('Language', 'calliope-social-publisher'); ?></strong>
                            <span><?php echo esc_html((string) ($calliope_sp_generation_languages[$calliope_sp_generation_language] ?? $calliope_sp_generation_language)); ?></span>
                        </div>
                    </div>

                    <form class="calliope-sp-settings-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <input type="hidden" name="action" value="calliope_sp_save_ai_settings" />
                        <?php wp_nonce_field('calliope_sp_save_ai_settings_action', 'calliope_sp_save_ai_settings_nonce'); ?>

                        <div class="calliope-sp-field">
                            <label for="calliope_sp_gemini_api_key"><?php echo esc_html__('Gemini API key', 'calliope-social-publisher'); ?></label>
                            <input id="calliope_sp_gemini_api_key" name="calliope_sp_gemini_api_key" type="password" placeholder="<?php echo esc_attr($calliope_sp_ai_key_saved ? __('Saved key — paste a new one only if you want to replace it', 'calliope-social-publisher') : __('Paste your Gemini API key from Google AI Studio', 'calliope-social-publisher')); ?>" autocomplete="off" />
                            <?php if ($calliope_sp_ai_key_saved): ?>
                                <div class="calliope-sp-secret-preview">
                                    <strong><?php echo esc_html__('Saved key', 'calliope-social-publisher'); ?>:</strong>
                                    <code><?php echo esc_html($calliope_sp_ai_key_mask); ?></code>
                                </div>
                            <?php endif; ?>
                            <div class="calliope-sp-hint"><?php echo esc_html__('This AI composer is included in the free plugin version and uses only the Social Publisher key saved here. Leave empty to keep the saved key.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <?php if ($calliope_sp_ai_key_saved): ?>
                            <label class="calliope-sp-inline-check calliope-sp-settings-clear-key">
                                <input type="checkbox" name="calliope_sp_clear_gemini_api_key" value="1" />
                                <span><?php echo esc_html__('Remove the saved Social Publisher Gemini key', 'calliope-social-publisher'); ?></span>
                            </label>
                        <?php endif; ?>

                        <div class="calliope-sp-settings-form-grid">
                        <div class="calliope-sp-field">
                            <label for="calliope_sp_gemini_model"><?php echo esc_html__('AI model', 'calliope-social-publisher'); ?></label>
                            <select id="calliope_sp_gemini_model" name="calliope_sp_gemini_model">
                                <?php foreach ($calliope_sp_gemini_models as $calliope_sp_model_key => $calliope_sp_model_label): ?>
                                    <option value="<?php echo esc_attr($calliope_sp_model_key); ?>" <?php selected($calliope_sp_gemini_model, $calliope_sp_model_key); ?>><?php echo esc_html($calliope_sp_model_label); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <div class="calliope-sp-hint"><?php echo esc_html__('Choose the Gemini model used by the title, content and hashtag generator.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label for="calliope_sp_generation_language"><?php echo esc_html__('Generation language', 'calliope-social-publisher'); ?></label>
                            <select id="calliope_sp_generation_language" name="calliope_sp_generation_language">
                                <?php foreach ($calliope_sp_generation_languages as $calliope_sp_lang_code => $calliope_sp_lang_name): ?>
                                    <option value="<?php echo esc_attr($calliope_sp_lang_code); ?>" <?php selected($calliope_sp_generation_language, $calliope_sp_lang_code); ?>><?php echo esc_html($calliope_sp_lang_name); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <div class="calliope-sp-hint"><?php echo esc_html__('Choose the default language for AI generated social titles, captions and hashtags.', 'calliope-social-publisher'); ?></div>
                        </div>
                        </div>

                        <div class="calliope-sp-actions calliope-sp-settings-actions">
                            <button class="button button-primary" type="submit"><?php echo esc_html__('Save AI settings', 'calliope-social-publisher'); ?></button>
                            <a class="button" href="https://aistudio.google.com/app/apikey" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('Get a Gemini API key', 'calliope-social-publisher'); ?></a>
                        </div>
                    </form>
                </div>

                <div class="calliope-sp-card calliope-sp-settings-card calliope-sp-settings-card--templates">
                    <div class="calliope-sp-settings-card__head">
                        <div>
                            <h3><?php echo esc_html__('Social Templates', 'calliope-social-publisher'); ?></h3>
                            <p><?php echo esc_html__('Create one reusable publishing template for each Free network.', 'calliope-social-publisher'); ?></p>
                        </div>
                        <span class="calliope-sp-settings-status <?php echo esc_attr($calliope_sp_social_templates_enabled ? 'is-ok' : 'is-neutral'); ?>"><?php echo esc_html($calliope_sp_social_templates_enabled ? __('Templates enabled', 'calliope-social-publisher') : __('Templates disabled', 'calliope-social-publisher')); ?></span>
                    </div>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="calliope-sp-settings-form calliope-sp-template-settings-form">
                        <input type="hidden" name="action" value="calliope_sp_save_social_templates" />
                        <?php wp_nonce_field('calliope_sp_save_social_templates_action', 'calliope_sp_save_social_templates_nonce'); ?>

                        <label class="calliope-sp-inline-check">
                            <input type="checkbox" name="calliope_sp_social_templates_enabled" value="1" <?php checked($calliope_sp_social_templates_enabled); ?> />
                            <span><?php echo esc_html__('Enable Social Templates for publishing.', 'calliope-social-publisher'); ?></span>
                        </label>
                        <p class="calliope-sp-muted"><?php echo esc_html__('When enabled, each selected network uses its own saved template. Leave this disabled to keep the current Publisher formatting unchanged.', 'calliope-social-publisher'); ?></p>

                        <div class="calliope-sp-template-workspace" data-calliope-template-editor
                             data-default-label="<?php echo esc_attr__('Default', 'calliope-social-publisher'); ?>"
                             data-custom-label="<?php echo esc_attr__('Customized', 'calliope-social-publisher'); ?>"
                             data-reset-message="<?php echo esc_attr__('Default template restored.', 'calliope-social-publisher'); ?>"
                             data-copy-message="<?php echo esc_attr__('Template copied to all Free networks.', 'calliope-social-publisher'); ?>"
                             data-copy-confirm="<?php echo esc_attr__('Copy this template to every Free network? This replaces the other template texts in this form.', 'calliope-social-publisher'); ?>">

                            <div class="calliope-sp-template-picker-block">
                                <div class="calliope-sp-template-section-title">
                                    <div>
                                        <strong><?php echo esc_html__('Choose a network', 'calliope-social-publisher'); ?></strong>
                                        <span><?php echo esc_html__('Edit one network at a time. Your changes remain in the form when you switch networks.', 'calliope-social-publisher'); ?></span>
                                    </div>
                                </div>
                                <div class="calliope-sp-template-network-picker" role="tablist" aria-label="<?php echo esc_attr__('Template network', 'calliope-social-publisher'); ?>">
                                    <?php $calliope_sp_template_first_network = true; ?>
                                    <?php foreach ($calliope_sp_social_template_networks as $calliope_sp_template_network => $calliope_sp_template_label): ?>
                                        <button type="button"
                                                class="calliope-sp-template-network-button<?php echo esc_attr($calliope_sp_template_first_network ? ' is-active' : ''); ?>"
                                                role="tab"
                                                aria-selected="<?php echo esc_attr($calliope_sp_template_first_network ? 'true' : 'false'); ?>"
                                                data-template-network="<?php echo esc_attr($calliope_sp_template_network); ?>">
                                            <span class="calliope-sp-template-network-button__icon"><?php echo wp_kses(calliope_sp_ui_icon($calliope_sp_template_network), calliope_sp_ui_allowed_html()); ?></span>
                                            <span><?php echo esc_html($calliope_sp_template_label); ?></span>
                                        </button>
                                        <?php $calliope_sp_template_first_network = false; ?>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <div class="calliope-sp-smart-tags" aria-label="<?php echo esc_attr__('Smart Tags', 'calliope-social-publisher'); ?>">
                                <div class="calliope-sp-template-section-title">
                                    <div>
                                        <strong><?php echo esc_html__('Smart Tags', 'calliope-social-publisher'); ?></strong>
                                        <span><?php echo esc_html__('Click a Smart Tag to insert it at the cursor in the active template.', 'calliope-social-publisher'); ?></span>
                                    </div>
                                </div>
                                <?php foreach ($calliope_sp_social_template_group_labels as $calliope_sp_tag_group => $calliope_sp_tag_group_label): ?>
                                    <?php
                                    $calliope_sp_group_tags = array_filter($calliope_sp_social_template_smart_tags, static function ($definition) use ($calliope_sp_tag_group) {
                                        return is_array($definition) && (($definition['group'] ?? '') === $calliope_sp_tag_group);
                                    });
                                    if ($calliope_sp_group_tags === []) { continue; }
                                    ?>
                                    <div class="calliope-sp-smart-tag-group">
                                        <span class="calliope-sp-smart-tag-group__label"><?php echo esc_html($calliope_sp_tag_group_label); ?></span>
                                        <div class="calliope-sp-smart-tag-list">
                                            <?php foreach ($calliope_sp_group_tags as $calliope_sp_template_token => $calliope_sp_tag_definition): ?>
                                                <button type="button" class="calliope-sp-smart-tag"
                                                        data-template-token="<?php echo esc_attr($calliope_sp_template_token); ?>"
                                                        title="<?php echo esc_attr((string) ($calliope_sp_tag_definition['description'] ?? '')); ?>">
                                                    <code><?php echo esc_html($calliope_sp_template_token); ?></code>
                                                    <span><?php echo esc_html((string) ($calliope_sp_tag_definition['label'] ?? $calliope_sp_template_token)); ?></span>
                                                </button>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                                <p class="calliope-sp-template-safety-note"><?php echo esc_html__('Mistyped Smart Tags are removed before publishing so raw placeholders are never sent to a social network.', 'calliope-social-publisher'); ?></p>
                            </div>

                            <div class="calliope-sp-template-editors">
                                <?php $calliope_sp_template_first_panel = true; ?>
                                <?php foreach ($calliope_sp_social_template_networks as $calliope_sp_template_network => $calliope_sp_template_label): ?>
                                    <?php
                                    $calliope_sp_template_value = (string) ($calliope_sp_social_templates[$calliope_sp_template_network] ?? '');
                                    $calliope_sp_template_default = (string) ($calliope_sp_social_template_defaults[$calliope_sp_template_network] ?? '');
                                    $calliope_sp_template_is_default = $calliope_sp_template_value === $calliope_sp_template_default;
                                    ?>
                                    <section class="calliope-sp-template-editor-panel<?php echo esc_attr($calliope_sp_template_first_panel ? ' is-active' : ''); ?>"
                                             data-template-panel="<?php echo esc_attr($calliope_sp_template_network); ?>"
                                             data-default-template="<?php echo esc_attr($calliope_sp_template_default); ?>"
                                             <?php if (!$calliope_sp_template_first_panel) : ?>hidden<?php endif; ?>>
                                        <div class="calliope-sp-template-editor-head">
                                            <div class="calliope-sp-template-editor-network">
                                                <?php echo wp_kses(calliope_sp_ui_icon($calliope_sp_template_network), calliope_sp_ui_allowed_html()); ?>
                                                <div><strong><?php echo esc_html($calliope_sp_template_label); ?></strong><span><?php echo esc_html__('1 Free template', 'calliope-social-publisher'); ?></span></div>
                                            </div>
                                            <span class="calliope-sp-template-editor-state<?php echo esc_attr($calliope_sp_template_is_default ? ' is-default' : ' is-custom'); ?>" data-template-state><?php echo esc_html($calliope_sp_template_is_default ? __('Default', 'calliope-social-publisher') : __('Customized', 'calliope-social-publisher')); ?></span>
                                        </div>
                                        <textarea name="calliope_sp_social_templates[<?php echo esc_attr($calliope_sp_template_network); ?>]"
                                                  rows="8" maxlength="4000" spellcheck="false" autocomplete="off" autocapitalize="off"
                                                  data-template-textarea="<?php echo esc_attr($calliope_sp_template_network); ?>"><?php echo esc_textarea($calliope_sp_template_value); ?></textarea>
                                        <div class="calliope-sp-template-editor-footer">
                                            <span class="calliope-sp-template-char-count" data-template-count>0 / 4000</span>
                                            <div class="calliope-sp-template-editor-actions">
                                                <button type="button" class="button button-small" data-template-reset><?php echo esc_html__('Restore default', 'calliope-social-publisher'); ?></button>
                                                <button type="button" class="button button-small" data-template-copy-all><?php echo esc_html__('Copy to all networks', 'calliope-social-publisher'); ?></button>
                                            </div>
                                        </div>
                                    </section>
                                    <?php $calliope_sp_template_first_panel = false; ?>
                                <?php endforeach; ?>
                            </div>
                            <div class="calliope-sp-template-editor-notice" data-template-editor-notice role="status" aria-live="polite"></div>
                        </div>

                        <?php if (has_action('calliope_sp_render_advanced_templates')): ?>
                            <?php do_action('calliope_sp_render_advanced_templates'); ?>
                        <?php else: ?>
                            <div class="calliope-sp-template-pro-teaser" aria-disabled="true">
                                <div><strong><?php echo esc_html__('Multiple templates per network', 'calliope-social-publisher'); ?> <span class="calliope-sp-pro-badge">PRO</span> <span class="calliope-sp-template-roadmap"><?php echo esc_html__('Pro roadmap', 'calliope-social-publisher'); ?></span></strong><span><?php echo esc_html__('Create reusable templates for blog posts, products, tutorials, promotions, and more.', 'calliope-social-publisher'); ?></span></div>
                                <a class="button" href="<?php echo esc_url($calliope_sp_templates_pro_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('Explore Social Publisher Pro', 'calliope-social-publisher'); ?></a>
                            </div>
                        <?php endif; ?>

                        <div class="calliope-sp-actions calliope-sp-settings-actions">
                            <button class="button button-primary" type="submit"><?php echo esc_html__('Save Social Templates', 'calliope-social-publisher'); ?></button>
                        </div>
                    </form>
                </div>

                <div class="calliope-sp-card calliope-sp-settings-card calliope-sp-settings-card--tracking calliope-sp-settings-wide" data-calliope-tracking-settings>
                    <div class="calliope-sp-settings-card__head">
                        <div>
                            <h3><?php echo esc_html__('Tracking', 'calliope-social-publisher'); ?></h3>
                            <p><?php echo esc_html__('Add UTM parameters automatically to publication links so traffic can be attributed to each social destination.', 'calliope-social-publisher'); ?></p>
                        </div>
                        <span class="calliope-sp-settings-status <?php echo esc_attr($calliope_sp_tracking_enabled ? 'is-ok' : 'is-neutral'); ?>"><?php echo esc_html($calliope_sp_tracking_enabled ? __('Tracking enabled', 'calliope-social-publisher') : __('Tracking disabled', 'calliope-social-publisher')); ?></span>
                    </div>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="calliope-sp-settings-form">
                        <input type="hidden" name="action" value="calliope_sp_save_tracking_settings" />
                        <?php wp_nonce_field('calliope_sp_save_tracking_settings_action', 'calliope_sp_save_tracking_settings_nonce'); ?>

                        <label class="calliope-sp-inline-check">
                            <input type="checkbox" name="calliope_sp_tracking_enabled" value="1" <?php checked($calliope_sp_tracking_enabled); ?> />
                            <span><?php echo esc_html__('Enable automatic UTM tracking for publication links.', 'calliope-social-publisher'); ?></span>
                        </label>

                        <div class="calliope-sp-short-links-setting">
                            <div>
                                <strong><?php echo esc_html__('Short Links', 'calliope-social-publisher'); ?></strong>
                                <p><?php echo esc_html__('Replace long tracked URLs with short links from your own domain.', 'calliope-social-publisher'); ?></p>
                            </div>
                            <label class="calliope-sp-inline-check calliope-sp-short-links-toggle">
                                <input type="checkbox" name="calliope_sp_short_links_enabled" value="1" <?php checked($calliope_sp_short_links_enabled); ?> />
                                <span><?php echo esc_html__('Use built-in short links', 'calliope-social-publisher'); ?></span>
                            </label>
                            <small><?php echo esc_html__('Short links are generated automatically when publishing or scheduling.', 'calliope-social-publisher'); ?></small>
                        </div>

                        <div class="calliope-sp-tracking-grid">
                            <div class="calliope-sp-field">
                                <div class="calliope-sp-field-head">
                                    <label for="calliope_sp_utm_source"><?php echo esc_html__('UTM source', 'calliope-social-publisher'); ?> <code>utm_source</code></label>
                                    <button type="button" class="button button-small calliope-sp-tracking-token" data-tracking-token="{network}" data-tracking-target="calliope_sp_utm_source">{network}</button>
                                </div>
                                <input id="calliope_sp_utm_source" name="calliope_sp_tracking_settings[utm_source]" type="text" maxlength="160" value="<?php echo esc_attr((string) ($calliope_sp_tracking_settings['utm_source'] ?? '{network}')); ?>" autocomplete="off" spellcheck="false" />
                                <div class="calliope-sp-hint"><?php echo esc_html__('Use {network} to insert the destination automatically, such as linkedin or facebook.', 'calliope-social-publisher'); ?></div>
                            </div>
                            <div class="calliope-sp-field">
                                <div class="calliope-sp-field-head">
                                    <label for="calliope_sp_utm_medium"><?php echo esc_html__('UTM medium', 'calliope-social-publisher'); ?> <code>utm_medium</code></label>
                                    <button type="button" class="button button-small calliope-sp-tracking-token" data-tracking-token="{network}" data-tracking-target="calliope_sp_utm_medium">{network}</button>
                                </div>
                                <input id="calliope_sp_utm_medium" name="calliope_sp_tracking_settings[utm_medium]" type="text" maxlength="160" value="<?php echo esc_attr((string) ($calliope_sp_tracking_settings['utm_medium'] ?? 'social')); ?>" autocomplete="off" spellcheck="false" />
                                <div class="calliope-sp-hint"><?php echo esc_html__('A common value is social.', 'calliope-social-publisher'); ?></div>
                            </div>
                            <div class="calliope-sp-field">
                                <div class="calliope-sp-field-head">
                                    <label for="calliope_sp_utm_campaign"><?php echo esc_html__('UTM campaign', 'calliope-social-publisher'); ?> <code>utm_campaign</code></label>
                                    <button type="button" class="button button-small calliope-sp-tracking-token" data-tracking-token="{network}" data-tracking-target="calliope_sp_utm_campaign">{network}</button>
                                </div>
                                <input id="calliope_sp_utm_campaign" name="calliope_sp_tracking_settings[utm_campaign]" type="text" maxlength="160" value="<?php echo esc_attr((string) ($calliope_sp_tracking_settings['utm_campaign'] ?? 'wordpress')); ?>" autocomplete="off" spellcheck="false" />
                                <div class="calliope-sp-hint"><?php echo esc_html__('Use a stable campaign name, for example wordpress, blog, or launch.', 'calliope-social-publisher'); ?></div>
                            </div>
                        </div>

                        <div class="calliope-sp-tracking-preview">
                            <div class="calliope-sp-tracking-preview__head">
                                <div><strong><?php echo esc_html__('Tracked URL preview', 'calliope-social-publisher'); ?></strong><span><?php echo esc_html__('See how the same link changes for a selected destination before saving.', 'calliope-social-publisher'); ?></span></div>
                                <label><span><?php echo esc_html__('Preview network', 'calliope-social-publisher'); ?></span>
                                    <select data-tracking-preview-network>
                                        <?php foreach ($calliope_sp_tracking_networks as $calliope_sp_tracking_network => $calliope_sp_tracking_label): ?>
                                            <option value="<?php echo esc_attr($calliope_sp_tracking_network); ?>" <?php selected($calliope_sp_tracking_network, 'linkedin'); ?>><?php echo esc_html($calliope_sp_tracking_label); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </label>
                            </div>
                            <code data-tracking-example-url>https://example.com/post?utm_source=linkedin&amp;utm_medium=social&amp;utm_campaign=wordpress</code>
                            <p><?php echo esc_html__('Existing parameters are preserved, and existing UTM values with the same name are replaced instead of duplicated.', 'calliope-social-publisher'); ?></p>
                        </div>

                        <div class="calliope-sp-ga4-help">
                            <div>
                                <strong><?php echo esc_html__('View social traffic in Google Analytics', 'calliope-social-publisher'); ?></strong>
                                <p><?php echo esc_html__('Social Publisher adds UTM parameters to tracked links so Google Analytics can identify the network that sent the visit.', 'calliope-social-publisher'); ?></p>
                            </div>
                            <div class="calliope-sp-ga4-help__path">
                                <span><?php echo esc_html__('In GA4 open:', 'calliope-social-publisher'); ?></span>
                                <strong><?php echo esc_html__('Reports → Acquisition → Traffic acquisition', 'calliope-social-publisher'); ?></strong>
                            </div>
                            <div class="calliope-sp-ga4-help__dimensions">
                                <div><span><?php echo esc_html__('Session source / medium', 'calliope-social-publisher'); ?></span><code data-ga4-source-medium>linkedin / social</code></div>
                                <div><span><?php echo esc_html__('Session campaign', 'calliope-social-publisher'); ?></span><code data-ga4-campaign>wordpress</code></div>
                            </div>
                            <p class="calliope-sp-ga4-help__note"><?php echo esc_html__('Traffic acquisition shows the source of sessions. User acquisition can be used to see where new users were first acquired.', 'calliope-social-publisher'); ?></p>
                        </div>

                        <div class="calliope-sp-template-pro-teaser calliope-sp-tracking-pro-teaser" aria-disabled="true">
                            <div><strong><?php echo esc_html__('Advanced UTM rules', 'calliope-social-publisher'); ?> <span class="calliope-sp-pro-badge">PRO</span></strong><span><?php echo esc_html__('Use different UTM values by network, campaign, or Social Template with Social Publisher Pro.', 'calliope-social-publisher'); ?></span></div>
                            <a class="button" href="<?php echo esc_url($calliope_sp_tracking_pro_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('Explore Social Publisher Pro', 'calliope-social-publisher'); ?></a>
                        </div>

                        <div class="calliope-sp-actions calliope-sp-settings-actions">
                            <button class="button button-primary" type="submit"><?php echo esc_html__('Save Tracking settings', 'calliope-social-publisher'); ?></button>
                        </div>
                    </form>
                </div>

                <div class="calliope-sp-card calliope-sp-settings-card calliope-sp-settings-wide calliope-sp-settings-card--alerts">
                    <div class="calliope-sp-settings-card__head calliope-sp-alerts-head">
                        <div><h3><?php echo esc_html__('Failure alerts', 'calliope-social-publisher'); ?></h3><p><?php echo esc_html__('Receive an email only when at least one destination fails. Successful publications never send notification emails.', 'calliope-social-publisher'); ?></p></div>
                        <span class="calliope-sp-settings-status <?php echo esc_attr($calliope_sp_failure_alerts_enabled ? 'is-ok' : 'is-neutral'); ?>"><?php echo esc_html($calliope_sp_failure_alerts_enabled ? __('Alerts enabled', 'calliope-social-publisher') : __('Alerts disabled', 'calliope-social-publisher')); ?></span>
                    </div>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="calliope-sp-settings-form calliope-sp-alerts-form">
                        <input type="hidden" name="action" value="calliope_sp_save_failure_alert_settings" />
                        <?php wp_nonce_field('calliope_sp_save_failure_alert_settings_action', 'calliope_sp_save_failure_alert_settings_nonce'); ?>

                        <div class="calliope-sp-alerts-controls">
                            <label class="calliope-sp-alert-toggle">
                                <input class="calliope-sp-alert-toggle__input" type="checkbox" name="calliope_sp_failure_alerts_enabled" value="1" <?php checked($calliope_sp_failure_alerts_enabled); ?> />
                                <span class="calliope-sp-alert-toggle__switch" aria-hidden="true"><span></span></span>
                                <span class="calliope-sp-alert-toggle__copy"><strong><?php echo esc_html__('Notify me when a publication fails', 'calliope-social-publisher'); ?></strong></span>
                            </label>

                            <div class="calliope-sp-alert-email">
                                <div class="calliope-sp-field">
                                    <label for="calliope_sp_failure_alert_email"><?php echo esc_html__('Notification email', 'calliope-social-publisher'); ?></label>
                                    <input id="calliope_sp_failure_alert_email" name="calliope_sp_failure_alert_email" type="email" value="<?php echo esc_attr($calliope_sp_failure_alert_email); ?>" autocomplete="email" />
                                    <div class="calliope-sp-hint"><?php echo esc_html(sprintf(__('Leave empty to use the WordPress administration email: %s', 'calliope-social-publisher'), sanitize_email((string) get_option('admin_email', '')))); ?></div>
                                </div>
                            </div>
                        </div>

                        <div class="calliope-sp-alerts-footer">
                            <p class="calliope-sp-muted"><?php echo esc_html__('One email is sent per publication, even if several destinations fail. No email is sent when every destination succeeds.', 'calliope-social-publisher'); ?></p>
                            <div class="calliope-sp-actions calliope-sp-settings-actions"><button class="button button-primary" type="submit"><?php echo esc_html__('Save alert settings', 'calliope-social-publisher'); ?></button></div>
                        </div>
                    </form>
                </div>

                <div class="calliope-sp-card calliope-sp-settings-card calliope-sp-settings-card--maintenance">
                    <div class="calliope-sp-settings-subsection calliope-sp-settings-subsection--first">
                        <div class="calliope-sp-settings-card__head">
                            <div>
                                <h3><?php echo esc_html__('History & retry', 'calliope-social-publisher'); ?></h3>
                                <p><?php echo esc_html__('Control whether failed destinations can be manually retried from Publication History.', 'calliope-social-publisher'); ?></p>
                            </div>
                            <span class="calliope-sp-settings-status <?php echo esc_attr($calliope_sp_history_retry_enabled ? 'is-ok' : 'is-neutral'); ?>"><?php echo esc_html($calliope_sp_history_retry_enabled ? __('Retry enabled', 'calliope-social-publisher') : __('Retry disabled', 'calliope-social-publisher')); ?></span>
                        </div>
                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="calliope-sp-settings-form">
                            <input type="hidden" name="action" value="calliope_sp_save_history_settings" />
                            <?php wp_nonce_field('calliope_sp_save_history_settings_action', 'calliope_sp_save_history_settings_nonce'); ?>
                            <label class="calliope-sp-inline-check">
                                <input type="checkbox" name="calliope_sp_history_retry_enabled" value="1" <?php checked($calliope_sp_history_retry_enabled); ?> />
                                <span><?php echo esc_html__('Enable manual Retry for failed destinations in History.', 'calliope-social-publisher'); ?></span>
                            </label>
                            <p class="calliope-sp-muted"><?php echo esc_html__('When enabled, Social Publisher securely keeps the publication snapshot needed to retry only the failed destination. When disabled, Retry buttons are hidden and stored retry snapshots are removed.', 'calliope-social-publisher'); ?></p>
                            <div class="calliope-sp-actions calliope-sp-settings-actions">
                                <button class="button button-primary" type="submit"><?php echo esc_html__('Save History settings', 'calliope-social-publisher'); ?></button>
                            </div>
                        </form>
                    </div>

                    <div class="calliope-sp-settings-subsection">
                        <div class="calliope-sp-settings-card__head">
                            <div>
                                <h3><?php echo esc_html__('Uninstall and data cleanup', 'calliope-social-publisher'); ?></h3>
                                <p><?php echo esc_html__('Choose what happens to Social Publisher data when the plugin is deleted from WordPress.', 'calliope-social-publisher'); ?></p>
                            </div>
                            <span class="calliope-sp-settings-status <?php echo esc_attr($calliope_sp_cleanup_enabled ? 'is-warn' : 'is-neutral'); ?>"><?php echo esc_html($calliope_sp_cleanup_enabled ? __('Cleanup enabled', 'calliope-social-publisher') : __('Data preserved', 'calliope-social-publisher')); ?></span>
                        </div>
                        <div class="calliope-sp-settings-note">
                            <strong><?php echo esc_html__('Default behavior', 'calliope-social-publisher'); ?></strong>
                            <span><?php echo esc_html__('Deleting the plugin keeps saved connections, AI settings, logs and cached account data unless cleanup is enabled below.', 'calliope-social-publisher'); ?></span>
                        </div>
                        <p class="calliope-sp-muted"><?php echo esc_html__('Disconnecting a network only removes that network credentials. To delete the plugin itself, first deactivate Social Publisher from the WordPress Plugins screen, then click Delete.', 'calliope-social-publisher'); ?></p>
                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="calliope-sp-settings-form">
                            <input type="hidden" name="action" value="calliope_sp_save_cleanup_settings" />
                            <?php wp_nonce_field('calliope_sp_save_cleanup_settings_action', 'calliope_sp_save_cleanup_settings_nonce'); ?>
                            <label class="calliope-sp-inline-check">
                                <input type="checkbox" name="calliope_sp_cleanup_on_delete" value="1" <?php checked($calliope_sp_cleanup_enabled); ?> />
                                <span><?php echo esc_html__('Delete Social Publisher data when the plugin is deleted (tokens, settings, logs, cached boards/pages/blogs, and temporary Social Publisher upload files).', 'calliope-social-publisher'); ?></span>
                            </label>
                            <div class="calliope-sp-actions calliope-sp-settings-actions">
                                <button class="button button-primary" type="submit"><?php echo esc_html__('Save uninstall setting', 'calliope-social-publisher'); ?></button>
                            </div>
                        </form>
                    </div>
                </div>

                <?php /** Generic extension point for Pro settings cards. */ ?>
                <?php do_action('calliope_sp_render_external_settings_sections'); ?>

            </div>

        <?php elseif ($calliope_sp_tab === 'connections'): ?>
            <?php do_action('calliope_sp_render_pro_connection_cards'); ?>
            <div class="calliope-sp-net-tabs">
                <a class="<?php echo esc_attr(calliope_sp_net_tab_class('bluesky', $calliope_sp_net === 'bluesky', $calliope_sp_c_bsky)); ?>" href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'connections', 'net' => 'bluesky'])); ?>"><?php echo wp_kses(calliope_sp_ui_icon('bluesky'), calliope_sp_ui_allowed_html()); ?><?php echo esc_html__('Bluesky', 'calliope-social-publisher'); ?></a>
                <a class="<?php echo esc_attr(calliope_sp_net_tab_class('mastodon', $calliope_sp_net === 'mastodon', $calliope_sp_c_mstdn)); ?>" href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'connections', 'net' => 'mastodon'])); ?>"><?php echo wp_kses(calliope_sp_ui_icon('mastodon'), calliope_sp_ui_allowed_html()); ?><?php echo esc_html__('Mastodon', 'calliope-social-publisher'); ?></a>
                <a class="<?php echo esc_attr(calliope_sp_net_tab_class('tumblr', $calliope_sp_net === 'tumblr', $calliope_sp_c_tumblr)); ?>" href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'connections', 'net' => 'tumblr'])); ?>"><?php echo wp_kses(calliope_sp_ui_icon('tumblr'), calliope_sp_ui_allowed_html()); ?><?php echo esc_html__('Tumblr', 'calliope-social-publisher'); ?></a>
                <a class="<?php echo esc_attr(calliope_sp_net_tab_class('pinterest', $calliope_sp_net === 'pinterest', $calliope_sp_c_pin)); ?>" href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'connections', 'net' => 'pinterest'])); ?>"><?php echo wp_kses(calliope_sp_ui_icon('pinterest'), calliope_sp_ui_allowed_html()); ?><?php echo esc_html__('Pinterest', 'calliope-social-publisher'); ?></a>
                <a class="<?php echo esc_attr(calliope_sp_net_tab_class('threads', $calliope_sp_net === 'threads', $calliope_sp_c_thr)); ?>" href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'connections', 'net' => 'threads'])); ?>"><?php echo wp_kses(calliope_sp_ui_icon('threads'), calliope_sp_ui_allowed_html()); ?><?php echo esc_html__('Threads', 'calliope-social-publisher'); ?></a>
                <a class="<?php echo esc_attr(calliope_sp_net_tab_class('instagram', $calliope_sp_net === 'instagram', $calliope_sp_c_ig)); ?>" href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'connections', 'net' => 'instagram'])); ?>"><?php echo wp_kses(calliope_sp_ui_icon('instagram'), calliope_sp_ui_allowed_html()); ?><?php echo esc_html__('Instagram', 'calliope-social-publisher'); ?></a>
                <a class="<?php echo esc_attr(calliope_sp_net_tab_class('linkedin', $calliope_sp_net === 'linkedin', $calliope_sp_c_li)); ?>" href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'connections', 'net' => 'linkedin'])); ?>"><?php echo wp_kses(calliope_sp_ui_icon('linkedin'), calliope_sp_ui_allowed_html()); ?><?php echo esc_html__('LinkedIn', 'calliope-social-publisher'); ?></a>
                <a class="<?php echo esc_attr(calliope_sp_net_tab_class('blogger', $calliope_sp_net === 'blogger', $calliope_sp_c_blg)); ?>" href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'connections', 'net' => 'blogger'])); ?>"><?php echo wp_kses(calliope_sp_ui_icon('blogger'), calliope_sp_ui_allowed_html()); ?><?php echo esc_html__('Blogger', 'calliope-social-publisher'); ?></a>
                <a class="<?php echo esc_attr(calliope_sp_net_tab_class('telegram', $calliope_sp_net === 'telegram', $calliope_sp_c_telegram)); ?>" href="<?php echo esc_url(calliope_sp_url_with(['tab' => 'connections', 'net' => 'telegram'])); ?>"><?php echo wp_kses(calliope_sp_ui_icon('telegram'), calliope_sp_ui_allowed_html()); ?><?php echo esc_html__('Telegram', 'calliope-social-publisher'); ?></a>
                <a class="<?php echo esc_attr(calliope_sp_net_tab_class('facebook', $calliope_sp_net === 'facebook', $calliope_sp_c_fb)); ?>" href="<?php echo esc_url(add_query_arg(['tab' => 'connections', 'net' => 'facebook'])); ?>"><?php echo wp_kses(calliope_sp_ui_icon('facebook'), calliope_sp_ui_allowed_html()); ?><?php echo esc_html__('Facebook', 'calliope-social-publisher'); ?></a>
                <?php do_action('calliope_sp_render_external_connection_tabs', $calliope_sp_net); ?>
            </div>

            <div class="calliope-sp-divider"></div>

            <?php if ($calliope_sp_net === 'bluesky'): ?>
                <div class="calliope-sp-card">
                    <h3><?php echo esc_html__('Bluesky', 'calliope-social-publisher'); ?></h3>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <input type="hidden" name="action" value="calliope_sp_test_bluesky" />
                        <?php wp_nonce_field('calliope_sp_test_bluesky_action', 'calliope_sp_test_bluesky_nonce'); ?>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Handle', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_bsky_handle" type="text" value="<?php echo esc_attr(get_option('calliope_sp_bsky_handle')); ?>" />
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('App password (not your main password)', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_bsky_password" type="password" placeholder="***" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Leave this empty to keep the saved app password.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-actions">
                            <span><strong><?php echo esc_html__('Status', 'calliope-social-publisher'); ?>:</strong> <?php echo wp_kses(calliope_sp_ui_status_badge($calliope_sp_status_bsky), calliope_sp_ui_allowed_html()); ?></span>
                            <?php echo wp_kses(calliope_sp_ui_disconnect_button('bluesky', $calliope_sp_bsky_has_saved_data), ['a' => ['class' => true, 'href' => true, 'onclick' => true]]); ?>
                            <?php if (!empty($calliope_sp_status_bsky['message'])) : ?>
                                <div class="calliope-sp-hint"><?php echo esc_html($calliope_sp_status_bsky['message']); ?></div>
                            <?php endif; ?>
                        </div>

                        <div class="calliope-sp-actions">
                            <button class="button button-primary"><?php echo esc_html__('Save and test', 'calliope-social-publisher'); ?></button>
                        </div>

                        <div class="calliope-sp-howto calliope-sp-howto--below">
                            <b><?php echo esc_html__('Quick guide (Bluesky)', 'calliope-social-publisher'); ?></b>
                            <ol class="calliope-sp-steps calliope-sp-steps--compact">
                                <li><?php echo esc_html__('Create or sign in to your Bluesky account at https://bsky.app/.', 'calliope-social-publisher'); ?></li>
                                <li><?php echo esc_html__('Go to Settings > Privacy and Security > App Passwords and create a new app password for Social Publisher.', 'calliope-social-publisher'); ?></li>
                                <li><?php echo esc_html__('Important: this app password is NOT your regular account password. Do not paste your main password here.', 'calliope-social-publisher'); ?></li>
                                <li><?php echo esc_html__('Paste your handle above, for example yourname.bsky.social, and paste the new app password in the password field.', 'calliope-social-publisher'); ?></li>
                                <li><?php echo esc_html__('Click Save and test. When it works, the status will change to Ready to publish.', 'calliope-social-publisher'); ?></li>
                            </ol>
                        </div>
                    </form>
                </div>

            <?php elseif ($calliope_sp_net === 'mastodon'): ?>
                <div class="calliope-sp-card">
                    <h3><?php echo esc_html__('Mastodon', 'calliope-social-publisher'); ?></h3>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin-top:14px;">
                        <input type="hidden" name="action" value="calliope_sp_save_mastodon_settings" />
                        <?php wp_nonce_field('calliope_sp_save_mastodon_settings_action', 'calliope_sp_save_mastodon_settings_nonce'); ?>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Mastodon server', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_mstdn_instance" type="text" value="<?php echo esc_attr(get_option('calliope_sp_mstdn_instance')); ?>" placeholder="mastodon.social" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Example: if your Mastodon address is @name@mastodon.social, type only mastodon.social here.', 'calliope-social-publisher'); ?></div>
                            <div class="calliope-sp-hint"><?php echo esc_html__('If your address is @name@fosstodon.org, type only fosstodon.org.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Manual token (optional)', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_mstdn_token" type="password" placeholder="***" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Use this only if you prefer the manual method. It is not your Mastodon password.', 'calliope-social-publisher'); ?></div>
                            <div class="calliope-sp-hint"><?php echo esc_html__('Leave this empty to keep the saved token.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-actions">
                            <span><strong><?php echo esc_html__('Status', 'calliope-social-publisher'); ?>:</strong> <?php echo wp_kses(calliope_sp_ui_status_badge($calliope_sp_status_mstdn), calliope_sp_ui_allowed_html()); ?></span>
                            <?php echo wp_kses(calliope_sp_ui_disconnect_button('mastodon', $calliope_sp_mstdn_has_saved_data), ['a' => ['class' => true, 'href' => true, 'onclick' => true]]); ?>
                        </div>
                        <?php if (!empty($calliope_sp_status_mstdn['message'])): ?>
                            <p class="calliope-sp-muted"><?php echo esc_html($calliope_sp_status_mstdn['message']); ?></p>
                        <?php endif; ?>

                        <div class="calliope-sp-actions">
                            <button class="button button-primary"><?php echo esc_html__('Save and test', 'calliope-social-publisher'); ?></button>
                            <a class="button button-link-delete" href="<?php echo esc_url( wp_nonce_url( admin_url('admin-post.php?action=calliope_sp_mastodon_clear_tokens'), 'calliope_sp_mastodon_clear_tokens_action' ) ); ?>" onclick="return confirm('<?php echo esc_js(__('Delete saved Mastodon credentials?', 'calliope-social-publisher')); ?>');"><?php echo esc_html__('Clear tokens', 'calliope-social-publisher'); ?></a>
                        </div>
                    </form>

                    <div class="calliope-sp-howto calliope-sp-howto--below">
                        <b><?php echo esc_html__('Step 2: Connect with Mastodon', 'calliope-social-publisher'); ?></b>
                        <p class="calliope-sp-muted" style="margin:8px 0 0;"><?php echo esc_html__('First save the server above. Then click the button below, authorize access in Mastodon, and return here.', 'calliope-social-publisher'); ?></p>
                        <div class="calliope-sp-actions" style="margin-top:12px;">
                            <a class="button button-secondary calliope-sp-dark" href="<?php echo esc_url( wp_nonce_url( admin_url('admin-post.php?action=calliope_sp_mastodon_oauth_start'), 'calliope_sp_mastodon_oauth_start_action' ) ); ?>"><?php echo esc_html__('Connect with Mastodon', 'calliope-social-publisher'); ?></a>
                        </div>
                    </div>

                    <div class="calliope-sp-howto calliope-sp-howto--below">
                        <b><?php echo esc_html__('Quick guide (Mastodon)', 'calliope-social-publisher'); ?></b>
                        <ol class="calliope-sp-steps calliope-sp-steps--compact">
                            <li><?php echo esc_html__('Create or sign in to your Mastodon account on your own server, for example mastodon.social.', 'calliope-social-publisher'); ?></li>
                            <li><?php echo esc_html__('In Mastodon server, enter only the server. Example: if your account is @name@mastodon.social, enter only mastodon.social here.', 'calliope-social-publisher'); ?></li>
                            <li><?php echo esc_html__('First click Save settings.', 'calliope-social-publisher'); ?></li>
                            <li><?php echo esc_html__('Then click Connect with Mastodon and authorize access on the permissions screen.', 'calliope-social-publisher'); ?></li>
                            <li><?php echo esc_html__('When you return to WordPress, the connection will be ready to publish.', 'calliope-social-publisher'); ?></li>
                            <li><?php echo esc_html__('Use the manual method only if you really need it: create an app on your Mastodon server, use urn:ietf:wg:oauth:2.0:oob only if the server asks for a Redirect URI, and enable read:accounts, write:statuses, and write:media.', 'calliope-social-publisher'); ?></li>
                        </ol>
                    </div>
                </div>

            <?php elseif ($calliope_sp_net === 'tumblr'): ?>
                <?php
                $calliope_sp_tumblr_saved_blog = trim((string) get_option('calliope_sp_tumblr_blog_identifier', ''));
                $calliope_sp_tumblr_blog_input = $calliope_sp_tumblr_saved_blog;
                $calliope_sp_tumblr_uses_subdomain_input = $calliope_sp_tumblr_saved_blog === '';
                if (preg_match('/^([a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?)\.tumblr\.com$/i', $calliope_sp_tumblr_saved_blog, $calliope_sp_tumblr_blog_match)) {
                    $calliope_sp_tumblr_blog_input = $calliope_sp_tumblr_blog_match[1];
                    $calliope_sp_tumblr_uses_subdomain_input = true;
                } elseif (preg_match('/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/i', $calliope_sp_tumblr_saved_blog)) {
                    $calliope_sp_tumblr_uses_subdomain_input = true;
                }
                ?>
                <div class="calliope-sp-card">
                    <h3><?php echo esc_html__('Tumblr', 'calliope-social-publisher'); ?></h3>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin-top:14px;">
                        <input type="hidden" name="action" value="calliope_sp_save_tumblr_settings" />
                        <?php wp_nonce_field('calliope_sp_save_tumblr_settings_action', 'calliope_sp_save_tumblr_settings_nonce'); ?>

                        <div class="calliope-sp-field">
                            <label for="calliope-sp-tumblr-blog-identifier"><?php echo esc_html__('Blog identifier', 'calliope-social-publisher'); ?></label>
                            <?php if ($calliope_sp_tumblr_uses_subdomain_input): ?>
                                <div class="calliope-sp-input-suffix">
                                    <input id="calliope-sp-tumblr-blog-identifier" name="calliope_sp_tumblr_blog_identifier" type="text" value="<?php echo esc_attr($calliope_sp_tumblr_blog_input); ?>" placeholder="yourblog" maxlength="64" autocapitalize="none" spellcheck="false" aria-describedby="calliope-sp-tumblr-blog-hint" />
                                    <span class="calliope-sp-input-suffix__text" aria-hidden="true">.tumblr.com</span>
                                </div>
                            <?php else: ?>
                                <input id="calliope-sp-tumblr-blog-identifier" name="calliope_sp_tumblr_blog_identifier" type="text" value="<?php echo esc_attr($calliope_sp_tumblr_blog_input); ?>" placeholder="yourblog.tumblr.com" autocapitalize="none" spellcheck="false" aria-describedby="calliope-sp-tumblr-blog-hint" />
                            <?php endif; ?>
                            <div id="calliope-sp-tumblr-blog-hint" class="calliope-sp-hint"><?php echo esc_html__('Enter only the blog name. The .tumblr.com ending is added automatically.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Consumer Key', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_tumblr_consumer_key" type="text" value="<?php echo esc_attr(get_option('calliope_sp_tumblr_consumer_key')); ?>" />
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Consumer Secret', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_tumblr_consumer_secret" type="password" placeholder="***" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Leave this empty to keep the saved consumer secret.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-hint calliope-sp-hint-box"><?php echo esc_html__('Tumblr stores Token and Token Secret automatically after you click Connect with Tumblr. You do not need to fill them manually.', 'calliope-social-publisher'); ?></div>

                        <div class="calliope-sp-actions">
                            <span><strong><?php echo esc_html__('Status', 'calliope-social-publisher'); ?>:</strong> <?php echo wp_kses(calliope_sp_ui_status_badge($calliope_sp_status_tumblr), calliope_sp_ui_allowed_html()); ?></span>
                            <?php echo wp_kses(calliope_sp_ui_disconnect_button('tumblr', $calliope_sp_tumblr_has_saved_data), ['a' => ['class' => true, 'href' => true, 'onclick' => true]]); ?>
                        </div>
                        <?php if (!empty($calliope_sp_status_tumblr['message'])): ?>
                            <p class="calliope-sp-muted" style="margin:10px 0 0;"><?php echo esc_html($calliope_sp_status_tumblr['message']); ?></p>
                        <?php endif; ?>

                        <div class="calliope-sp-actions">
                            <button class="button button-primary"><?php echo esc_html__('Save and test', 'calliope-social-publisher'); ?></button>
                        </div>
                    </form>

                    <div class="calliope-sp-howto calliope-sp-howto--below">
                        <b><?php echo esc_html__('Step 2: Connect with Tumblr', 'calliope-social-publisher'); ?></b>
                        <p class="calliope-sp-muted" style="margin:8px 0 0;"><?php echo esc_html__('After you click the button below, Tumblr will open a permissions screen. Click Allow to finish the connection.', 'calliope-social-publisher'); ?></p>
                        <div class="calliope-sp-actions" style="margin-top:12px;">
                            <a class="button button-secondary calliope-sp-dark" href="<?php echo esc_url( wp_nonce_url( admin_url('admin-post.php?action=calliope_sp_tumblr_oauth_start'), 'calliope_sp_tumblr_oauth_start_action' ) ); ?>"><?php echo esc_html__('Connect with Tumblr', 'calliope-social-publisher'); ?></a>
                            <a class="button button-link-delete" href="<?php echo esc_url( wp_nonce_url( admin_url('admin-post.php?action=calliope_sp_tumblr_clear_tokens'), 'calliope_sp_tumblr_clear_tokens_action' ) ); ?>" onclick="return confirm('<?php echo esc_js(__('Delete saved Tumblr tokens?', 'calliope-social-publisher')); ?>');"><?php echo esc_html__('Clear tokens', 'calliope-social-publisher'); ?></a>
                        </div>
                    </div>

                    <div class="calliope-sp-howto calliope-sp-howto--below">
                        <b><?php echo esc_html__('Quick guide (Tumblr)', 'calliope-social-publisher'); ?></b>
                        <ol class="calliope-sp-steps calliope-sp-steps--compact">
                            <li><?php echo esc_html__('Create or sign in to your Tumblr account.', 'calliope-social-publisher'); ?></li>
                            <li><?php echo esc_html__('Open https://www.tumblr.com/oauth/register and create your app.', 'calliope-social-publisher'); ?></li>
                            <li><?php echo esc_html__('Complete the required fields: Application Name, Website, Description, and Admin Contact Email.', 'calliope-social-publisher'); ?></li>
                            <li><?php echo esc_html__('For Callback URL and OAuth Redirect URL, use this exact address:', 'calliope-social-publisher'); ?><br><code><?php echo esc_html( admin_url('admin-post.php?action=calliope_sp_tumblr_oauth_callback') ); ?></code></li>
                            <li><?php echo esc_html__('If Tumblr asks for icons in several sizes, upload the requested PNG files and finish creating the app.', 'calliope-social-publisher'); ?></li>
                            <li><?php echo esc_html__('Copy the Consumer Key and Consumer Secret and paste them into this plugin.', 'calliope-social-publisher'); ?></li>
                            <li><?php echo esc_html__('In Blog identifier, enter only the blog name that appears before .tumblr.com.', 'calliope-social-publisher'); ?></li>
                            <li><?php echo esc_html__('Click Save settings, then Connect with Tumblr, and finally Allow on the permissions screen.', 'calliope-social-publisher'); ?></li>
                        </ol>
                    </div>
                </div>

            <?php elseif ($calliope_sp_net === 'threads'): ?>
                <div class="calliope-sp-card">
                    <h3><?php echo esc_html__('Threads', 'calliope-social-publisher'); ?></h3>

                    <div class="calliope-sp-actions" style="margin-top:0;">
                        <span style="margin-left:auto;"><?php echo wp_kses(calliope_sp_ui_status_badge($calliope_sp_status_thr), calliope_sp_ui_allowed_html()); ?></span>
                        <?php echo wp_kses(calliope_sp_ui_disconnect_button('threads', $calliope_sp_c_thr), ['a' => ['class' => true, 'href' => true, 'onclick' => true]]); ?>
                    </div>
                    <?php if (!empty($calliope_sp_status_thr['message'])): ?>
                        <div class="calliope-sp-hint" style="margin-top:8px;"><?php echo esc_html($calliope_sp_status_thr['message']); ?></div>
                    <?php endif; ?>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin-top:14px;">
                        <input type="hidden" name="action" value="calliope_sp_test_threads" />
                        <?php wp_nonce_field('calliope_sp_test_threads_action', 'calliope_sp_test_threads_nonce'); ?>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Threads App ID', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_threads_client_id" type="text" placeholder="Example: 2529..." value="<?php echo esc_attr(get_option('calliope_sp_threads_client_id')); ?>" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Use the dedicated Threads App ID, not the generic Meta App ID.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Threads App Secret', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_threads_client_secret" type="password" placeholder="***" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Leave this empty to keep the saved secret.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-actions">
                            <button class="button button-primary calliope-sp-cta" type="submit"><?php echo esc_html__('Save and test', 'calliope-social-publisher'); ?></button>
                            <a class="button button-secondary calliope-sp-dark" href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=calliope_sp_threads_oauth_start'), 'calliope_sp_threads_oauth_start_action')); ?>"><?php echo esc_html__('Connect with Threads', 'calliope-social-publisher'); ?></a>
                            <a class="button" href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=calliope_sp_test_meta_media_url&calliope_sp_meta_media_network=threads'), 'calliope_sp_test_meta_media_url_action')); ?>"><?php echo esc_html__('Test Meta media URL', 'calliope-social-publisher'); ?></a>
                            <a class="button button-link-delete" href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=calliope_sp_threads_clear_tokens'), 'calliope_sp_threads_clear_tokens_action')); ?>"><?php echo esc_html__('Clear tokens', 'calliope-social-publisher'); ?></a>
                        </div>

                        <div class="calliope-sp-howto calliope-sp-howto--below">
                            <b><?php echo esc_html__('Quick guide (Threads)', 'calliope-social-publisher'); ?></b>
                            <div class="calliope-sp-muted" style="margin-top:6px;">
                                <?php echo wp_kses(__('1) Open <code>https://developers.facebook.com/</code> and create an app for Threads.<br>2) Choose the correct <b>Business Portfolio</b>. If the portfolio is wrong, the connection often fails later.<br>3) Add the <b>Threads API</b> product and enable <b>threads_basic</b> and <b>threads_content_publish</b>.<br>4) In the basic app settings, add a valid <b>Privacy Policy</b> and move the app to <b>Live</b> when Meta requires it.<br>5) In the login settings, add this exact redirect URI:', 'calliope-social-publisher'), calliope_sp_ui_notice_allowed_html()); ?> <code><?php echo esc_html(admin_url('admin-post.php')); ?></code><br>
                                <span class="calliope-sp-hint"><?php echo wp_kses(__('In Meta, use this same URL in Redirect Callback URL, Deauthorize Callback URL, and Delete Callback URL. Threads often refuses to save the form if any of those fields are empty or different.', 'calliope-social-publisher'), calliope_sp_ui_notice_allowed_html()); ?></span><br>
                                <?php echo wp_kses(__('6) Paste the <b>Threads App ID</b> and <b>Threads App Secret</b> here, then click <b>Save and test</b>.<br>7) Add your account as a <b>Threads Tester</b> and accept the invitation at <code>https://www.threads.com/settings/website_permissions</code>.<br>8) Then click <b>Connect with Threads</b>, authorize access, and when you return to WordPress the connection should be ready.', 'calliope-social-publisher'), calliope_sp_ui_notice_allowed_html()); ?>
                            </div>
                        </div>
                    </form>
                </div>

            <?php elseif ($calliope_sp_net === 'instagram'): ?>
                <div class="calliope-sp-card">
                    <h3><?php echo esc_html__('Instagram', 'calliope-social-publisher'); ?></h3>

                    <div class="calliope-sp-actions" style="margin-top:0;">
                        <a class="button button-link-delete" href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=calliope_sp_instagram_clear_tokens'), 'calliope_sp_instagram_clear_tokens_action')); ?>" onclick="return confirm('<?php echo esc_js(__('Clear saved Instagram tokens?', 'calliope-social-publisher')); ?>');"><?php echo esc_html__('Clear tokens', 'calliope-social-publisher'); ?></a>
                        <span style="margin-left:auto;"><?php echo wp_kses(calliope_sp_ui_status_badge($calliope_sp_status_ig), calliope_sp_ui_allowed_html()); ?></span>
                        <?php echo wp_kses(calliope_sp_ui_disconnect_button('instagram', $calliope_sp_c_ig), ['a' => ['class' => true, 'href' => true, 'onclick' => true]]); ?>
                    </div>
                    <?php if (!empty($calliope_sp_status_ig['message'])): ?>
                        <div class="calliope-sp-hint" style="margin-top:8px;"><?php echo esc_html($calliope_sp_status_ig['message']); ?></div>
                    <?php endif; ?>
                    <div class="calliope-sp-hint" style="margin-top:8px;">
                        <?php echo esc_html__('Instagram feed posts only accept image ratios from 4:5 portrait to 1.91:1 landscape. If an image is outside that range, the plugin prepares a centered compatible crop for Instagram automatically.', 'calliope-social-publisher'); ?>
                    </div>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin-top:14px;">
                        <input type="hidden" name="action" value="calliope_sp_test_instagram" />
                        <?php wp_nonce_field('calliope_sp_test_instagram_action', 'calliope_sp_test_instagram_nonce'); ?>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('App ID', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_ig_app_id" type="text" value="<?php echo esc_attr(get_option('calliope_sp_ig_app_id')); ?>" />
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('App Secret', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_ig_app_secret" type="password" placeholder="***" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Leave this empty to keep the saved secret.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Redirect URI', 'calliope-social-publisher'); ?></label>
                            <?php
                            $calliope_sp_ig_redirect_uri = $this->get_instagram_redirect_uri();
                            $calliope_sp_ig_legacy_redirect_uri = admin_url('admin-post.php?action=calliope_sp_instagram_callback');
                            ?>
                            <input type="text" readonly value="<?php echo esc_attr($calliope_sp_ig_redirect_uri); ?>" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Paste this exact URL into the OAuth redirect URI field for Instagram Login / Business Login in Meta Developers.', 'calliope-social-publisher'); ?></div>
                            <div class="calliope-sp-hint" style="margin-top:6px;"><?php echo esc_html__('It must match exactly, including https/http, trailing slash, and every query parameter if the URL contains any.', 'calliope-social-publisher'); ?></div>
                            <?php if ($calliope_sp_ig_redirect_uri !== $calliope_sp_ig_legacy_redirect_uri) : ?>
                                <div class="calliope-sp-hint" style="margin-top:6px;"><?php echo esc_html__('Legacy callback previously used by older installs:', 'calliope-social-publisher'); ?> <code><?php echo esc_html($calliope_sp_ig_legacy_redirect_uri); ?></code></div>
                            <?php endif; ?>
                        </div>

                        <div class="calliope-sp-actions">
                            <button class="button button-primary calliope-sp-cta" type="submit"><?php echo esc_html__('Save and test', 'calliope-social-publisher'); ?></button>
                            <a class="button button-secondary calliope-sp-dark" href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=calliope_sp_instagram_oauth_start'), 'calliope_sp_instagram_oauth_start_action')); ?>"><?php echo esc_html__('Connect with Instagram', 'calliope-social-publisher'); ?></a>
                            <a class="button" href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=calliope_sp_test_meta_media_url&calliope_sp_meta_media_network=instagram'), 'calliope_sp_test_meta_media_url_action')); ?>"><?php echo esc_html__('Test Meta media URL', 'calliope-social-publisher'); ?></a>
                        </div>

                        <div class="calliope-sp-howto calliope-sp-howto--below">
                            <b><?php echo esc_html__('Quick guide (Instagram)', 'calliope-social-publisher'); ?></b>
                            <div class="calliope-sp-muted" style="margin-top:6px;">
                                <?php echo wp_kses(__('1) Open <code>https://developers.facebook.com/</code> and create an app.<br>2) Choose the <b>Other</b> use case, set the app type to <b>Business</b>, and select the correct <b>Business Portfolio</b>.<br>3) Add the <b>Instagram</b> or <b>Instagram Login</b> product, depending on how Meta shows it in your panel.<br>4) In <b>Business login settings</b> or Instagram Login settings, add this exact redirect URI:', 'calliope-social-publisher'), calliope_sp_ui_notice_allowed_html()); ?> <code><?php echo esc_html($calliope_sp_ig_redirect_uri); ?></code><br>
                                <?php echo wp_kses(__('5) Add a valid <b>Privacy Policy</b> in the app settings and move the app to <b>Live</b> when Meta requires it.<br>6) Add your account as an <b>Instagram Tester</b> and accept the invitation at <code>https://www.instagram.com/accounts/manage_access</code>.<br>7) Paste the <b>App ID</b> and <b>App Secret</b> here, click <b>Save and test</b>, and only then click <b>Connect with Instagram</b>.<br>8) If Meta shows <code>Invalid redirect_uri</code>, it usually means the callback is entered in the wrong place or does not match exactly. Check the real OAuth redirect field and copy the URL shown above exactly.', 'calliope-social-publisher'), calliope_sp_ui_notice_allowed_html()); ?>
                            </div>
                        </div>
                    </form>
                </div>

            <?php elseif ($calliope_sp_net === 'linkedin'): ?>
                <div class="calliope-sp-card">
                    <h3><?php echo esc_html__('LinkedIn', 'calliope-social-publisher'); ?></h3>

                    <div class="calliope-sp-actions" style="margin-top:0;">
                        <a class="button button-link-delete" href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=calliope_sp_linkedin_clear_tokens'), 'calliope_sp_linkedin_clear_tokens_action')); ?>" onclick="return confirm('<?php echo esc_js(__('Disconnect this network and remove all saved credentials?', 'calliope-social-publisher')); ?>');"><?php echo esc_html__('Clear tokens', 'calliope-social-publisher'); ?></a>
                        <span style="margin-left:auto;"><?php echo wp_kses(calliope_sp_ui_status_badge($calliope_sp_li_status), calliope_sp_ui_allowed_html()); ?></span>
                    </div>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin-top:14px;">
                        <input type="hidden" name="action" value="calliope_sp_test_linkedin" />
                        <?php wp_nonce_field('calliope_sp_test_linkedin_action', 'calliope_sp_test_linkedin_nonce'); ?>

                        <div class="calliope-sp-help" style="margin-bottom:14px;">
                            <strong><?php echo esc_html__('Personal profile only', 'calliope-social-publisher'); ?></strong><br>
                            <?php echo esc_html__("LinkedIn Free publishes only to the authenticated member's personal profile. Company Pages are not supported.", 'calliope-social-publisher'); ?>
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Client ID', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_li_client_id" type="text" value="<?php echo esc_attr(get_option('calliope_sp_li_client_id')); ?>" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Copy this from LinkedIn Developers > Auth. This is not the App ID from the approval email.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Client Secret', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_li_client_secret" type="password" placeholder="***" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Copy this from LinkedIn Developers > Auth. Leave this empty to keep the saved secret.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Redirect URI', 'calliope-social-publisher'); ?></label>
                            <input type="text" readonly value="<?php echo esc_attr(rest_url('calliope-social-publisher/v1/linkedin/callback')); ?>" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Paste this exact URL into LinkedIn Developers > Auth > Authorized redirect URLs.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Access token (optional)', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_li_access_token" type="password" placeholder="***" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Usually this is not needed. Connect with LinkedIn stores the token automatically.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Profile author ID (optional)', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_li_person_id" type="text" value="<?php echo esc_attr(get_option('calliope_sp_li_person_id')); ?>" placeholder="urn:li:person:ABC123..." />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Recommended: save your credentials, click Connect with LinkedIn, and then click Use connected profile so the plugin fills this automatically.', 'calliope-social-publisher'); ?></div>
                            <div class="calliope-sp-hint"><?php echo esc_html__('Paste a full Person URN here only if LinkedIn does not let the plugin detect it automatically.', 'calliope-social-publisher'); ?></div>
                            <div class="calliope-sp-hint"><?php echo esc_html__('Do not paste a company page ID, company page URL, Client ID, App ID, or approval email number here.', 'calliope-social-publisher'); ?></div>
                            <?php if (!empty($calliope_sp_li_member_scope_list)): ?>
                                <div class="calliope-sp-hint"><?php echo esc_html__('Connection scopes:', 'calliope-social-publisher'); ?> <code><?php echo esc_html(implode(', ', $calliope_sp_li_member_scope_list)); ?></code></div>
                            <?php endif; ?>
                        </div>

                        <p><strong><?php echo esc_html__('Status', 'calliope-social-publisher'); ?>:</strong> <?php echo wp_kses(calliope_sp_ui_status_badge($calliope_sp_li_status), calliope_sp_ui_allowed_html()); ?></p>
                        <?php if (!empty($calliope_sp_li_status['message'])): ?>
                            <div class="calliope-sp-hint"><?php echo esc_html($calliope_sp_li_status['message']); ?></div>
                        <?php endif; ?>

                        <div class="calliope-sp-actions">
                            <button class="button button-primary calliope-sp-cta" type="submit"><?php echo esc_html__('Save and test', 'calliope-social-publisher'); ?></button>
                            <a class="button button-secondary calliope-sp-dark" href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=calliope_sp_linkedin_oauth_start'), 'calliope_sp_linkedin_oauth_start_action')); ?>"><?php echo esc_html__('Connect with LinkedIn', 'calliope-social-publisher'); ?></a>
                            <?php if ($calliope_sp_li_has_token): ?>
                                <a class="button button-secondary" href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=calliope_sp_linkedin_detect_profile_target'), 'calliope_sp_linkedin_detect_profile_target_action')); ?>"><?php echo esc_html__('Use connected profile', 'calliope-social-publisher'); ?></a>
                            <?php endif; ?>
                        </div>
                        <div class="calliope-sp-hint" style="margin-top:10px;"><?php echo esc_html__("LinkedIn Free publishes only to the authenticated member's personal profile.", 'calliope-social-publisher'); ?></div>
                        <?php if ($calliope_sp_li_has_token): ?>
                            <div class="calliope-sp-hint"><?php echo esc_html__('Use connected profile tries to detect the member profile author ID from the current LinkedIn token.', 'calliope-social-publisher'); ?></div>
                        <?php endif; ?>

                        <div class="calliope-sp-howto calliope-sp-howto--below">
                            <b><?php echo esc_html__('Quick guide (LinkedIn)', 'calliope-social-publisher'); ?></b>
                            <div class="calliope-sp-muted" style="margin-top:6px;">
                                1) <a href="https://developer.linkedin.com/" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('Open LinkedIn Developers', 'calliope-social-publisher'); ?></a> and create your app.<br>
                                2) <?php echo esc_html__('Open the Auth section, copy the Client ID and Client Secret, and paste them into this plugin.', 'calliope-social-publisher'); ?><br>
                                3) <?php echo esc_html__('Copy the Redirect URI shown above and paste that exact same URL into LinkedIn Developers > Auth > Authorized redirect URLs.', 'calliope-social-publisher'); ?><br>
                                4) <?php echo esc_html__('First click Save and test so Social Publisher saves the credentials.', 'calliope-social-publisher'); ?><br>
                                5) <?php echo esc_html__('Then click Connect with LinkedIn and approve access in LinkedIn.', 'calliope-social-publisher'); ?><br>
                                6) <?php echo esc_html__('When LinkedIn returns you to WordPress, click Use connected profile so the plugin can automatically fill the author ID for your personal profile.', 'calliope-social-publisher'); ?><br>
                                7) <?php echo esc_html__('If automatic detection fails, manually paste a complete Person URN into the Profile author ID field.', 'calliope-social-publisher'); ?><br>
                                8) <?php echo esc_html__('Important: this LinkedIn connection is only for personal profiles. It does not publish to company pages or business pages from this plugin.', 'calliope-social-publisher'); ?><br>
                                <span class="calliope-sp-hint"><?php echo esc_html__('In this version, LinkedIn supports text, links, and images on personal profiles.', 'calliope-social-publisher'); ?></span>
                            </div>
                        </div>
                    </form>
                </div>

            <?php elseif ($calliope_sp_net === 'blogger'): ?>
                <?php $calliope_sp_blogs = get_option('calliope_sp_blogger_blogs_last', []); if (!is_array($calliope_sp_blogs)) $calliope_sp_blogs = []; ?>
                <div class="calliope-sp-card">
                    <h3><?php echo esc_html__('Blogger', 'calliope-social-publisher'); ?></h3>

                    <div class="calliope-sp-actions" style="margin-top:0;">
                        <a class="button button-link-delete" href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=calliope_sp_blogger_clear_tokens'), 'calliope_sp_blogger_clear_tokens_action')); ?>" onclick="return confirm('<?php echo esc_js(__('Clear saved Blogger tokens?', 'calliope-social-publisher')); ?>');"><?php echo esc_html__('Clear tokens', 'calliope-social-publisher'); ?></a>
                        <span style="margin-left:auto;"><?php echo wp_kses(calliope_sp_ui_status_badge($calliope_sp_status_blg), calliope_sp_ui_allowed_html()); ?></span>
                        <?php echo wp_kses(calliope_sp_ui_disconnect_button('blogger', $calliope_sp_blogger_has_saved_data), ['a' => ['class' => true, 'href' => true, 'onclick' => true]]); ?>
                    </div>
                    <?php if (!empty($calliope_sp_status_blg['message'])): ?>
                        <div class="calliope-sp-hint" style="margin-top:8px;"><?php echo esc_html($calliope_sp_status_blg['message']); ?></div>
                    <?php endif; ?>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin-top:14px;">
                        <input type="hidden" name="action" value="calliope_sp_test_blogger" />
                        <?php wp_nonce_field('calliope_sp_test_blogger_action', 'calliope_sp_test_blogger_nonce'); ?>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Google OAuth Client ID', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_blogger_client_id" type="text" value="<?php echo esc_attr(get_option('calliope_sp_blogger_client_id')); ?>" />
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Google OAuth Client Secret', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_blogger_client_secret" type="password" placeholder="***" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Leave this empty to keep the saved secret.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Redirect URI', 'calliope-social-publisher'); ?></label>
                            <input type="text" readonly value="<?php echo esc_attr(rest_url('calliope-social-publisher/v1/blogger/callback')); ?>" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Paste this into Google Cloud > OAuth consent / Credentials > Authorized redirect URIs.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Blog destination', 'calliope-social-publisher'); ?></label>
                            <select name="calliope_sp_blogger_blog_id">
                                <?php
                                $calliope_sp_selected_blog = (string) get_option('calliope_sp_blogger_blog_id', '');
                                $calliope_sp_cached_blog_ids = [];
                                echo '<option value=""' . selected($calliope_sp_selected_blog, '', false) . '>' . esc_html__('Select a Blogger blog', 'calliope-social-publisher') . '</option>';
                                foreach ($calliope_sp_blogs as $calliope_sp_item) {
                                    $blog_id   = (string) ($calliope_sp_item['id'] ?? '');
                                    $calliope_sp_blog_name = (string) ($calliope_sp_item['name'] ?? $blog_id);
                                    $calliope_sp_blog_url  = (string) ($calliope_sp_item['url'] ?? '');
                                    if ($blog_id === '') continue;
                                    $calliope_sp_cached_blog_ids[$blog_id] = true;
                                    ?>
                                    <option value="<?php echo esc_attr($blog_id); ?>" <?php selected($calliope_sp_selected_blog, $blog_id); ?>>
                                        <?php echo esc_html($calliope_sp_blog_name); ?><?php echo $calliope_sp_blog_url !== '' ? esc_html(' - ' . $calliope_sp_blog_url) : ''; ?>
                                    </option>
                                    <?php
                                }
                                if ($calliope_sp_selected_blog !== '' && !isset($calliope_sp_cached_blog_ids[$calliope_sp_selected_blog])) {
                                    echo '<option value="' . esc_attr($calliope_sp_selected_blog) . '" selected>' . esc_html(sprintf(__('Saved Blog ID: %s', 'calliope-social-publisher'), $calliope_sp_selected_blog)) . '</option>';
                                }
                                ?>
                            </select>
                            <div class="calliope-sp-hint"><?php echo esc_html__('Social Publisher loads the blogs automatically after OAuth. If Google does not return the list, use the manual field below.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label for="calliope-sp-blogger-manual-blog-id"><?php echo esc_html__('Manual Blog ID', 'calliope-social-publisher'); ?></label>
                            <input id="calliope-sp-blogger-manual-blog-id" type="text" name="calliope_sp_blogger_manual_blog_id" value="" autocomplete="off" spellcheck="false" placeholder="1234567890123456789" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Optional fallback: paste the numeric Blog ID or the Blogger dashboard URL, for example https://www.blogger.com/blog/posts/1234567890. A manual value overrides the dropdown when you save.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <p><strong><?php echo esc_html__('Status', 'calliope-social-publisher'); ?>:</strong> <?php echo wp_kses(calliope_sp_ui_status_badge($calliope_sp_status_blg), calliope_sp_ui_allowed_html()); ?></p>
                        <?php if (!empty($calliope_sp_status_blg['message'])): ?>
                            <div class="calliope-sp-hint"><?php echo esc_html($calliope_sp_status_blg['message']); ?></div>
                        <?php endif; ?>

                        <div class="calliope-sp-actions">
                            <button class="button button-primary calliope-sp-cta" type="submit"><?php echo esc_html__('Save and test', 'calliope-social-publisher'); ?></button>
                            <a class="button button-secondary calliope-sp-dark" href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=calliope_sp_blogger_oauth_start'), 'calliope_sp_blogger_oauth_start_action')); ?>"><?php echo esc_html__('Connect with Blogger', 'calliope-social-publisher'); ?></a>
                        </div>

                        <div class="calliope-sp-howto calliope-sp-howto--below">
                            <?php
                            $calliope_sp_blogger_console_url = 'https://console.cloud.google.com/';
                            $calliope_sp_blogger_redirect_uri = rest_url('calliope-social-publisher/v1/blogger/callback');
                            $calliope_sp_blogger_guide_allowed = [
                                'a' => [
                                    'href'   => true,
                                    'target' => true,
                                    'rel'    => true,
                                ],
                                'b' => [],
                            ];
                            ?>
                            <b><?php echo esc_html__('Quick guide (Blogger)', 'calliope-social-publisher'); ?></b>
                            <div class="calliope-sp-muted" style="margin-top:6px;">
                                <ol class="calliope-sp-guide-list">
                                    <li><?php /* translators: %s: Google Cloud Console URL. */ echo wp_kses(sprintf(__('Open <a href="%s" target="_blank" rel="noopener noreferrer">Google Cloud Console</a>.', 'calliope-social-publisher'), esc_url($calliope_sp_blogger_console_url)), $calliope_sp_blogger_guide_allowed); ?></li>
                                    <li><?php echo wp_kses(__('Create a project if needed, then go to <b>APIs &amp; Services &rarr; Library</b>, search for <b>Blogger API</b>, and enable it.', 'calliope-social-publisher'), $calliope_sp_blogger_guide_allowed); ?></li>
                                    <li><?php echo wp_kses(__('Go to <b>APIs &amp; Services &rarr; OAuth consent screen</b> and complete the consent screen step by step.', 'calliope-social-publisher'), $calliope_sp_blogger_guide_allowed); ?></li>
                                    <li><?php echo wp_kses(__('Create an <b>OAuth Client ID</b> with application type <b>Web application</b>.', 'calliope-social-publisher'), $calliope_sp_blogger_guide_allowed); ?></li>
                                    <li><?php echo esc_html__('Add this exact authorized redirect URI:', 'calliope-social-publisher'); ?><br><code><?php echo esc_html($calliope_sp_blogger_redirect_uri); ?></code></li>
                                    <li><?php echo wp_kses(__('Copy the <b>Client ID</b> and <b>Client Secret</b> from Google and paste them into this plugin.', 'calliope-social-publisher'), $calliope_sp_blogger_guide_allowed); ?></li>
                                    <li><?php echo wp_kses(__('If Google requires it for your case, move the app to <b>External</b> / production before connecting.', 'calliope-social-publisher'), $calliope_sp_blogger_guide_allowed); ?></li>
                                    <li><?php echo wp_kses(__('First click <b>Save and test</b>. This only saves the credentials. Then click <b>Connect with Blogger</b> and allow access to the Google account.', 'calliope-social-publisher'), $calliope_sp_blogger_guide_allowed); ?></li>
                                    <li><?php echo wp_kses(__('If the blog list is still empty, verify that <b>Blogger API</b> is enabled in the same Google project. You can also paste the Blog ID or Blogger dashboard URL into <b>Manual Blog ID</b> and click <b>Save and test</b>.', 'calliope-social-publisher'), $calliope_sp_blogger_guide_allowed); ?></li>
                                    <li><?php echo wp_kses(__('If Google returns exactly one blog, Social Publisher selects it automatically. If you have more than one, choose the correct <b>Blog destination</b> and save again.', 'calliope-social-publisher'), $calliope_sp_blogger_guide_allowed); ?></li>
                                </ol>
                                <span class="calliope-sp-hint"><?php echo esc_html__('In this version, Blogger supports text, links, and images inside the content.', 'calliope-social-publisher'); ?></span>
                            </div>
                        </div>
                    </form>
                </div>

            <?php elseif ($calliope_sp_net === 'pinterest'): ?>
                <?php
                $calliope_sp_pin_env = get_option('calliope_sp_pinterest_env', 'production');
                $calliope_sp_pin_client = class_exists('Calliope_SP_Pinterest') ? new Calliope_SP_Pinterest() : null;
                $calliope_sp_pin_board = $calliope_sp_pin_client ? $calliope_sp_pin_client->get_board_id_for_environment($calliope_sp_pin_env) : get_option('calliope_sp_pinterest_board_id', '');
                $calliope_sp_pin_boards = $calliope_sp_pin_client ? $calliope_sp_pin_client->get_boards_for_environment($calliope_sp_pin_env) : get_option('calliope_sp_pinterest_boards_last', []);
                $calliope_sp_pin_boards = is_array($calliope_sp_pin_boards) ? array_values(array_filter($calliope_sp_pin_boards, static function ($item) {
                    return is_array($item) && !empty($item['id']);
                })) : [];
                $calliope_sp_pin_board_ids = array_values(array_filter(array_map(static function ($item) {
                    return isset($item['id']) && is_scalar($item['id']) ? (string) $item['id'] : '';
                }, $calliope_sp_pin_boards)));
                $calliope_sp_pin_board_available = $calliope_sp_pin_board !== '' && in_array((string) $calliope_sp_pin_board, $calliope_sp_pin_board_ids, true);
                $calliope_sp_pin_connect_label = $calliope_sp_pin_env === 'sandbox' ? __('Connect Pinterest — Sandbox', 'calliope-social-publisher') : __('Connect Pinterest — Production', 'calliope-social-publisher');
                ?>
                <div class="calliope-sp-card">
                    <h3><?php echo esc_html__('Pinterest', 'calliope-social-publisher'); ?></h3>

                    <div class="calliope-sp-actions" style="margin-top:0;">
                        <a class="button button-link-delete" href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=calliope_sp_pinterest_clear_tokens'), 'calliope_sp_pinterest_clear_tokens_action')); ?>" onclick="return confirm('<?php echo esc_js(__('Clear saved Pinterest tokens?', 'calliope-social-publisher')); ?>');"><?php echo esc_html__('Clear tokens', 'calliope-social-publisher'); ?></a>
                        <span style="margin-left:auto;"><?php echo wp_kses(calliope_sp_ui_status_badge($calliope_sp_status_pin), calliope_sp_ui_allowed_html()); ?></span>
                        <?php echo wp_kses(calliope_sp_ui_disconnect_button('pinterest', $calliope_sp_pin_has_saved_data), ['a' => ['class' => true, 'href' => true, 'onclick' => true]]); ?>
                    </div>
                    <?php if (!empty($calliope_sp_status_pin['message'])): ?>
                        <div class="calliope-sp-hint" style="margin-top:8px;"><?php echo esc_html($calliope_sp_status_pin['message']); ?></div>
                    <?php endif; ?>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin-top:14px;">
                        <input type="hidden" name="action" value="calliope_sp_test_pinterest" />
                        <?php wp_nonce_field('calliope_sp_test_pinterest_action', 'calliope_sp_test_pinterest_nonce'); ?>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Environment', 'calliope-social-publisher'); ?></label>
                            <select id="calliope_sp_pinterest_env" name="calliope_sp_pinterest_env" data-saved-environment="<?php echo esc_attr($calliope_sp_pin_env); ?>">
                                <option value="production" <?php selected($calliope_sp_pin_env, 'production'); ?>><?php echo esc_html__('Production (api.pinterest.com)', 'calliope-social-publisher'); ?></option>
                                <option value="sandbox" <?php selected($calliope_sp_pin_env, 'sandbox'); ?>><?php echo esc_html__('Sandbox (api-sandbox.pinterest.com)', 'calliope-social-publisher'); ?></option>
                            </select>
                            <div class="calliope-sp-hint"><?php echo esc_html($calliope_sp_pin_env === 'sandbox' ? __('Use Sandbox for Trial testing. Sandbox Pins and boards are separate from Production.', 'calliope-social-publisher') : __('Use Production only when the Pinterest application has the required Production access.', 'calliope-social-publisher')); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('App ID', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_pinterest_app_id" type="text" value="<?php echo esc_attr(get_option('calliope_sp_pinterest_app_id')); ?>" />
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('App Secret', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_pinterest_app_secret" type="password" placeholder="***" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Leave this empty to keep the saved secret.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Token', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_pinterest_token" type="password" placeholder="***" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('If you use Connect with Pinterest, the plugin stores the token automatically. Leave this empty to keep the saved token.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Pinterest board', 'calliope-social-publisher'); ?></label>
                            <?php if (!empty($calliope_sp_pin_boards)) : ?>
                                <select name="calliope_sp_pinterest_board_id">
                                    <option value=""><?php echo esc_html__('Select a board', 'calliope-social-publisher'); ?></option>
                                    <?php foreach ($calliope_sp_pin_boards as $calliope_sp_item) : ?>
                                        <?php
                                        $calliope_sp_item_id = isset($calliope_sp_item['id']) && is_scalar($calliope_sp_item['id']) ? (string) $calliope_sp_item['id'] : '';
                                        if ($calliope_sp_item_id === '') continue;
                                        $calliope_sp_item_name = isset($calliope_sp_item['name']) && is_scalar($calliope_sp_item['name']) && trim((string) $calliope_sp_item['name']) !== ''
                                            ? trim((string) $calliope_sp_item['name'])
                                            : __('(no name)', 'calliope-social-publisher');
                                        ?>
                                        <option value="<?php echo esc_attr($calliope_sp_item_id); ?>" <?php selected($calliope_sp_pin_board_available ? $calliope_sp_pin_board : '', $calliope_sp_item_id); ?>><?php echo esc_html($calliope_sp_item_name . ' — ' . $calliope_sp_item_id); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <?php if ($calliope_sp_pin_board !== '' && !$calliope_sp_pin_board_available) : ?>
                                    <div class="calliope-sp-hint calliope-sp-pinterest-board-warning"><strong><?php echo esc_html__('The previously selected board is no longer available for this Pinterest connection.', 'calliope-social-publisher'); ?></strong> <?php echo esc_html__('Choose an available board and save again.', 'calliope-social-publisher'); ?></div>
                                <?php else : ?>
                                    <div class="calliope-sp-hint"><?php echo esc_html__('Choose the board where Social Publisher should create Pins.', 'calliope-social-publisher'); ?></div>
                                <?php endif; ?>
                                <details class="calliope-sp-howto" style="margin-top:10px;">
                                    <summary><?php echo esc_html__('Advanced: enter a Board ID manually', 'calliope-social-publisher'); ?></summary>
                                    <div class="calliope-sp-field" style="margin-top:10px;">
                                        <input name="calliope_sp_pinterest_board_id_manual" type="text" value="" placeholder="<?php echo esc_attr($calliope_sp_pin_board); ?>" />
                                        <div class="calliope-sp-hint"><?php echo esc_html__('Use this only when Pinterest does not return the board in the available boards list. A manual value overrides the selector above.', 'calliope-social-publisher'); ?></div>
                                    </div>
                                </details>
                            <?php else : ?>
                                <input name="calliope_sp_pinterest_board_id" type="text" value="<?php echo esc_attr($calliope_sp_pin_board); ?>" />
                                <div class="calliope-sp-hint"><?php echo esc_html__('Load your available boards to choose by name instead of copying an ID.', 'calliope-social-publisher'); ?></div>
                            <?php endif; ?>
                        </div>

                        <div class="calliope-sp-actions">
                            <a class="button" href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=calliope_sp_pinterest_detect_board'), 'calliope_sp_pinterest_detect_board_action')); ?>"><?php echo esc_html__('Load available boards', 'calliope-social-publisher'); ?></a>
                        </div>

                        <div class="calliope-sp-actions">
                            <button class="button button-primary"><?php echo esc_html__('Save and test', 'calliope-social-publisher'); ?></button>
                            <a id="calliope_sp_pinterest_connect" class="button button-secondary calliope-sp-dark" href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=calliope_sp_pinterest_oauth_start'), 'calliope_sp_pinterest_oauth_start_action')); ?>" data-production-label="<?php echo esc_attr__('Connect Pinterest — Production', 'calliope-social-publisher'); ?>" data-sandbox-label="<?php echo esc_attr__('Connect Pinterest — Sandbox', 'calliope-social-publisher'); ?>" data-unsaved-label="<?php echo esc_attr__('Save settings before connecting', 'calliope-social-publisher'); ?>"><?php echo esc_html($calliope_sp_pin_connect_label); ?></a>
                            <span id="calliope_sp_pinterest_environment_notice" class="calliope-sp-hint" hidden><?php echo esc_html__('Save the selected Pinterest environment before starting OAuth.', 'calliope-social-publisher'); ?></span>
                        </div>

                        <div class="calliope-sp-howto calliope-sp-howto--below">
                            <b><?php echo esc_html__('Quick guide (Pinterest)', 'calliope-social-publisher'); ?></b>
                            <div class="calliope-sp-muted" style="margin-top:6px;">
                                <?php echo wp_kses(__('1) A <b>Pinterest business account</b> is required. If you use a personal account, convert it to a business account before creating the app at <code>https://developers.pinterest.com/apps</code>. Complete all required fields, including your website and privacy policy.<br>2) Add this exact redirect URI in your Pinterest app:', 'calliope-social-publisher'), calliope_sp_ui_notice_allowed_html()); ?> <code><?php echo esc_html(admin_url('admin-post.php')); ?></code><br>
                                <span class="calliope-sp-hint"><?php echo esc_html__('Pinterest does not accept query parameters in the redirect URI. Social Publisher resolves the callback using the OAuth state.', 'calliope-social-publisher'); ?></span><br>
                                <?php echo wp_kses(__('3) Paste the <b>App ID</b> and <b>App Secret</b> here, then click <b>Save and test</b> first.<br>4) If your app is still pending or under review, wait for approval by email before trying to publish.<br>5) Then click <b>Load available boards</b>, copy the Board ID you want, save and test it, and then use <b>Connect with Pinterest</b> to complete the connection.<br>6) To publish in production, your app needs <b>Standard access active</b>. Without standard access, publishing may fail even if login works.<br>7) If you recently enabled permissions or changed the environment, reconnect Pinterest to generate a new token.', 'calliope-social-publisher'), calliope_sp_ui_notice_allowed_html()); ?>
                            </div>
                        </div>

                        <p class="calliope-sp-hint" style="margin-top:12px;"><?php echo esc_html__('Scopes used:', 'calliope-social-publisher'); ?> <code>pins:read pins:write boards:read boards:write user_accounts:read</code></p>
                    </form>
                </div>


            <?php elseif ($calliope_sp_net === 'telegram'): ?>
                <div class="calliope-sp-card">
                    <h3><?php echo esc_html__('Telegram', 'calliope-social-publisher'); ?></h3>

                    <div class="calliope-sp-row">
                        <div class="calliope-sp-hint"><?php echo esc_html__('Publish posts to a Telegram group, supergroup, channel, or topic using a Telegram bot.', 'calliope-social-publisher'); ?></div>
                        <span style="margin-left:auto;"><?php echo wp_kses(calliope_sp_ui_status_badge($calliope_sp_status_telegram), calliope_sp_ui_allowed_html()); ?></span>
                        <?php echo wp_kses(calliope_sp_ui_disconnect_button('telegram', $calliope_sp_telegram_has_saved_data), ['a' => ['class' => true, 'href' => true, 'onclick' => true]]); ?>
                    </div>
                    <?php if (!empty($calliope_sp_status_telegram['message'])): ?>
                        <div class="calliope-sp-hint" style="margin-top:8px;"><?php echo esc_html($calliope_sp_status_telegram['message']); ?></div>
                    <?php endif; ?>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin-top:14px;">
                        <input type="hidden" name="action" value="calliope_sp_test_telegram" />
                        <?php wp_nonce_field('calliope_sp_test_telegram_action', 'calliope_sp_test_telegram_nonce'); ?>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Bot Token', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_telegram_bot_token" type="password" placeholder="123456789:ABC..." />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Create the bot with BotFather and paste the Bot Token here. Leave this empty to keep the saved token.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Group / Channel ID', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_telegram_chat_id" type="text" value="<?php echo esc_attr(get_option('calliope_sp_telegram_chat_id')); ?>" placeholder="@yourchannel or -1001234567890" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('For public channels or groups, you can use @username. For private channels or groups, use the numeric chat ID.', 'calliope-social-publisher'); ?></div>
                            <div class="calliope-sp-hint"><?php echo esc_html__('Public t.me links like https://t.me/yourchannel are normalized automatically to @yourchannel.', 'calliope-social-publisher'); ?></div>
                            <div class="calliope-sp-hint"><strong><?php echo esc_html__('Do not paste the Bot ID here. The destination must be the channel or group itself; private channel/supergroup IDs usually start with -100.', 'calliope-social-publisher'); ?></strong></div>
                            <?php
                            $calliope_sp_telegram_saved_token = (string) get_option('calliope_sp_telegram_bot_token', '');
                            $calliope_sp_telegram_saved_chat = (string) get_option('calliope_sp_telegram_chat_id', '');
                            $calliope_sp_telegram_self_target = class_exists('Calliope_SP_Telegram')
                                && (new Calliope_SP_Telegram())->destination_is_bot_identity($calliope_sp_telegram_saved_chat, $calliope_sp_telegram_saved_token);
                            ?>
                            <?php if ($calliope_sp_telegram_self_target): ?>
                                <div class="notice notice-error inline" style="margin:10px 0 0;"><p><?php echo esc_html__('The saved Telegram destination is the Bot ID, so Telegram will reject publication. Replace it with the channel or group @username, t.me link, or numeric chat ID.', 'calliope-social-publisher'); ?></p></div>
                            <?php endif; ?>
                        </div>


                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Topic ID (optional)', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_telegram_message_thread_id" type="number" min="0" step="1" value="<?php echo esc_attr((string) get_option('calliope_sp_telegram_message_thread_id', '0')); ?>" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Only use this if your Telegram group has forum topics and you want posts sent to a specific topic.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-actions">
                            <button class="button button-primary calliope-sp-cta" type="submit"><?php echo esc_html__('Save and test', 'calliope-social-publisher'); ?></button>
                        </div>

                        <div class="calliope-sp-howto calliope-sp-howto--below">
                            <b><?php echo esc_html__('Quick guide (Telegram)', 'calliope-social-publisher'); ?></b>
                            <ol class="calliope-sp-steps calliope-sp-steps--compact">
                                <li><?php echo esc_html__('Open Telegram and search for BotFather.', 'calliope-social-publisher'); ?></li>
                                <li><?php echo esc_html__('Create a new bot with /newbot and copy the Bot Token.', 'calliope-social-publisher'); ?></li>
                                <li><?php echo esc_html__('Add the bot to your group or channel. For channels, make it an administrator so it can publish.', 'calliope-social-publisher'); ?></li>
                                <li><?php echo esc_html__('Paste the Bot Token and the actual Group / Channel destination here, then click Save and test. Never use the bot user ID as the destination.', 'calliope-social-publisher'); ?></li>
                                <li><?php echo esc_html__('If the destination is public, use @yourchannel. If it is private, use the numeric chat ID, usually starting with -100 for supergroups/channels.', 'calliope-social-publisher'); ?></li>
                                <li><?php echo esc_html__('Publishing supports text, link, hashtags, and one image. If the post has an image, Telegram receives it as a photo with the message as caption.', 'calliope-social-publisher'); ?></li>
                            </ol>
                        </div>
                    </form>
                </div>

            <?php elseif ($calliope_sp_net === 'facebook'): ?>
                <div class="calliope-sp-card">
                    <h3><?php echo esc_html__('Facebook', 'calliope-social-publisher'); ?></h3>

                    <div class="calliope-sp-row">
                        <div class="calliope-sp-hint"><?php echo esc_html__('Automatic publishing to a Facebook Page with text, image, and link support.', 'calliope-social-publisher'); ?></div>
                        <span style="margin-left:auto;"><?php echo wp_kses(calliope_sp_ui_status_badge($calliope_sp_status_fb), calliope_sp_ui_allowed_html()); ?></span>
                        <?php echo wp_kses(calliope_sp_ui_disconnect_button('facebook', $calliope_sp_c_fb), ['a' => ['class' => true, 'href' => true, 'onclick' => true]]); ?>
                    </div>
                    <?php if (!empty($calliope_sp_status_fb['message'])): ?>
                        <div class="calliope-sp-hint" style="margin-top:8px;"><?php echo esc_html($calliope_sp_status_fb['message']); ?></div>
                    <?php endif; ?>

                    <?php if (!empty($calliope_sp_status_fb['is_ready'])): ?>
                        <div class="calliope-sp-hint" style="margin-top:10px;">
                            <?php echo esc_html__('Facebook may allow the Page connection but still block publishing until the connected account completes a security or identity confirmation. If publishing fails with an identity confirmation message, open the Facebook mobile app with the connected account and follow the instructions to confirm your account or phone.', 'calliope-social-publisher'); ?>
                        </div>
                    <?php endif; ?>

                    <?php
                    $calliope_sp_fb_dbg_raw = (string) get_option('calliope_sp_fb_last_oauth_debug');
                    $calliope_sp_fb_dbg = $calliope_sp_fb_dbg_raw ? json_decode($calliope_sp_fb_dbg_raw, true) : null;
                    if (is_array($calliope_sp_fb_dbg)):
                        $calliope_sp_step = (string) ($calliope_sp_fb_dbg['step'] ?? '');
                        $calliope_sp_ts = !empty($calliope_sp_fb_dbg['ts']) ? date_i18n('Y-m-d H:i:s', (int) $calliope_sp_fb_dbg['ts']) : '';
                        ?>
                        <div class="calliope-sp-hint" style="margin-top:10px;">
                            <b><?php echo esc_html__('Last OAuth attempt:', 'calliope-social-publisher'); ?></b> <?php echo esc_html($calliope_sp_step); ?><?php echo $calliope_sp_ts ? ' - ' . esc_html($calliope_sp_ts) : ''; ?>
                            <span style="display:block;opacity:.8;"><?php echo esc_html__('If it remains not connected, check the Logs tab for callback and token details.', 'calliope-social-publisher'); ?></span>
                        </div>
                    <?php endif; ?>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin-top:14px;">
                        <input type="hidden" name="action" value="calliope_sp_test_facebook" />
                        <?php wp_nonce_field('calliope_sp_test_facebook_action', 'calliope_sp_test_facebook_nonce'); ?>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Facebook App ID', 'calliope-social-publisher'); ?></label>
                            <input type="text" name="calliope_sp_fb_app_id" value="<?php echo esc_attr(get_option('calliope_sp_fb_app_id')); ?>" />
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Facebook App Secret', 'calliope-social-publisher'); ?></label>
                            <input name="calliope_sp_fb_app_secret" type="password" placeholder="***" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Leave this empty to keep the saved secret.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Facebook Login for Business Config ID (optional)', 'calliope-social-publisher'); ?></label>
                            <input type="text" name="calliope_sp_fb_config_id" value="<?php echo esc_attr(get_option('calliope_sp_fb_config_id')); ?>" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Leave empty when Meta does not provide Login Configurations. Social Publisher will use classic Facebook Page OAuth.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Redirect URI', 'calliope-social-publisher'); ?></label>
                            <?php $calliope_sp_fb_redirect_uri = rest_url('calliope-social-publisher/v1/facebook/callback'); ?>
                            <input type="text" readonly value="<?php echo esc_attr($calliope_sp_fb_redirect_uri); ?>" />
                            <div class="calliope-sp-hint"><?php echo esc_html__('Paste this into Meta Developers > Facebook Login > Settings > Valid OAuth Redirect URIs.', 'calliope-social-publisher'); ?></div>
                        </div>

                        <div class="calliope-sp-field">
                            <label><?php echo esc_html__('Page destination', 'calliope-social-publisher'); ?></label>
                            <?php
                            $calliope_sp_pages_raw = (string) get_option('calliope_sp_fb_pages_last');
                            $pages = $calliope_sp_pages_raw ? json_decode($calliope_sp_pages_raw, true) : [];
                            $calliope_sp_sel = (string) get_option('calliope_sp_fb_page_id');
                            ?>
                            <select name="calliope_sp_fb_page_id">
                                <option value=""><?php echo esc_html__('Auto-detect', 'calliope-social-publisher'); ?></option>
                                <?php if (is_array($pages)) : foreach ($pages as $calliope_sp_page_item) : ?>
                                    <?php $calliope_sp_pid = (string) ($calliope_sp_page_item['id'] ?? ''); $calliope_sp_pname = (string) ($calliope_sp_page_item['name'] ?? $calliope_sp_pid); ?>
                                    <option value="<?php echo esc_attr($calliope_sp_pid); ?>" <?php selected($calliope_sp_sel, $calliope_sp_pid); ?>><?php echo esc_html($calliope_sp_pname); ?></option>
                                <?php endforeach; endif; ?>
                            </select>
                            <div class="calliope-sp-hint"><?php echo esc_html__('Refresh this screen after connecting if the page list does not appear immediately.', 'calliope-social-publisher'); ?></div>
                            <div class="calliope-sp-hint"><strong><?php echo esc_html__('Social Publisher obtains the Facebook Page token automatically. You never need to copy or paste an access token manually.', 'calliope-social-publisher'); ?></strong></div>
                        </div>

                        <div class="calliope-sp-actions">
                            <button class="button button-primary" type="submit"><?php echo esc_html__('Save', 'calliope-social-publisher'); ?></button>
                        </div>
                    </form>

                    <div class="calliope-sp-divider"></div>

                    <div class="calliope-sp-actions">
                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="display:inline-block;margin-right:8px;">
                            <input type="hidden" name="action" value="calliope_sp_facebook_oauth_start" />
                            <?php wp_nonce_field('calliope_sp_fb_oauth_start_action', 'calliope_sp_fb_oauth_start_nonce'); ?>
                            <button class="button button-secondary" type="submit"><?php echo esc_html__('Connect Facebook', 'calliope-social-publisher'); ?></button>
                        </form>

                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="display:inline-block;margin-right:8px;">
                            <input type="hidden" name="action" value="calliope_sp_diagnose_facebook" />
                            <?php wp_nonce_field('calliope_sp_diagnose_facebook_action', 'calliope_sp_diagnose_facebook_nonce'); ?>
                            <button class="button button-secondary" type="submit"><?php echo esc_html__('Run diagnostics', 'calliope-social-publisher'); ?></button>
                        </form>

                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="display:inline-block;">
                            <input type="hidden" name="action" value="calliope_sp_facebook_clear_tokens" />
                            <?php wp_nonce_field('calliope_sp_fb_clear_action', 'calliope_sp_fb_clear_nonce'); ?>
                            <button class="button" type="submit"><?php echo esc_html__('Clear tokens', 'calliope-social-publisher'); ?></button>
                        </form>
                    </div>

                    <div class="calliope-sp-divider"></div>


                    <div class="calliope-sp-howto calliope-sp-howto--below">
                        <div class="calliope-sp-hint">
                            <?php echo esc_html__('The Config ID is optional. Use it only when your Meta app has a Facebook Login for Business configuration; otherwise leave it empty and connect with the classic Facebook Page permissions.', 'calliope-social-publisher'); ?>
                        </div>

                        <div class="calliope-sp-hint" style="margin-top:12px;">
                            <b><?php echo esc_html__('Quick guide (Facebook)', 'calliope-social-publisher'); ?></b><br>
                            <?php
                            echo wp_kses(
                                sprintf(
                                    /* translators: %s: Meta Developers URL. */
                                    __('1) Open <a href="%s" target="_blank" rel="noreferrer">Meta Developers</a> and create an app.<br>2) Choose the <b>Manage all aspects of your Page</b> use case and select the correct <b>Business Portfolio</b>. If the portfolio is wrong, the page list may come back empty.<br>3) In <b>Facebook Login &gt; Settings</b>, add the <b>Valid OAuth Redirect URI</b> shown above.<br>4) In the login settings or use case settings, enable page permissions such as <code>pages_show_list</code>, <code>pages_manage_metadata</code>, <code>pages_manage_posts</code>, and <code>pages_read_engagement</code> when available.<br>5) Add a valid <b>Privacy Policy</b> in the basic settings and publish the app when Meta requires it.<br>6) Paste the <b>App ID</b> and <b>App Secret</b> here, click <b>Save</b>, and only then click <b>Connect Facebook</b>.<br>7) During the Meta permissions screen, choose the correct Page and approve access.<br>8) If no Pages appear, review the Page roles, assigned business portfolio, and selected permissions before trying again.', 'calliope-social-publisher'),
                                    esc_url('https://developers.facebook.com/')
                                ),
                                calliope_sp_ui_notice_allowed_html()
                            );
                            ?>
                        </div>
                    </div>
                </div>

            <?php elseif (in_array($calliope_sp_net, $calliope_sp_external_networks, true)): ?>
                <?php do_action('calliope_sp_render_external_connection_panel', $calliope_sp_net); ?>
            <?php endif; ?>

        <?php elseif (in_array($calliope_sp_tab, array_diff($calliope_sp_allowed_tabs, ['dashboard', 'publisher', 'history', 'analytics', 'connections', 'settings', 'logs']), true)): ?>
            <?php do_action('calliope_sp_render_external_admin_page', $calliope_sp_tab); ?>
        <?php else: ?>

            <div class="calliope-sp-card">
                <h3><?php echo esc_html__('Logs', 'calliope-social-publisher'); ?></h3>
                <p class="calliope-sp-muted"><?php echo esc_html__('Up to 200 events are stored. You can clear them at any time.', 'calliope-social-publisher'); ?></p>

                <div class="calliope-sp-actions calliope-sp-log-actions" style="margin-bottom:12px;">
                    <button type="button" class="button" id="calliope-sp-copy-logs"><?php echo esc_html__('Copy logs', 'calliope-social-publisher'); ?></button>
                    <button type="button" class="button" id="calliope-sp-export-logs"><?php echo esc_html__('Export logs', 'calliope-social-publisher'); ?></button>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <input type="hidden" name="action" value="calliope_sp_clear_logs" />
                        <?php wp_nonce_field('calliope_sp_clear_logs_action', 'calliope_sp_clear_logs_nonce'); ?>
                        <button class="button"><?php echo esc_html__('Clear logs', 'calliope-social-publisher'); ?></button>
                    </form>
                </div>

                <?php if (empty($calliope_sp_logs)): ?>
                    <p><em><?php echo esc_html__('No logs yet.', 'calliope-social-publisher'); ?></em></p>
                <?php else: ?>
                    <table class="widefat striped">
                        <thead>
                            <tr>
                                <th><?php echo esc_html__('Date', 'calliope-social-publisher'); ?></th>
                                <th><?php echo esc_html__('Network', 'calliope-social-publisher'); ?></th>
                                <th><?php echo esc_html__('Status', 'calliope-social-publisher'); ?></th>
                                <th><?php echo esc_html__('Message', 'calliope-social-publisher'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($calliope_sp_logs as $calliope_sp_row): ?>
                            <tr>
                                <td><?php echo esc_html($calliope_sp_row['date'] ?? ''); ?></td>
                                <td><?php echo esc_html($calliope_sp_row['network'] ?? ''); ?></td>
                                <td><?php echo esc_html($calliope_sp_row['status'] ?? ''); ?></td>
                                <td><?php echo esc_html($calliope_sp_row['message'] ?? ''); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
                <?php
                $calliope_sp_log_lines = [];
                foreach ($calliope_sp_logs as $calliope_sp_export_row) {
                    $calliope_sp_log_lines[] = implode("\t", [
                        (string) ($calliope_sp_export_row['date'] ?? ''),
                        (string) ($calliope_sp_export_row['network'] ?? ''),
                        (string) ($calliope_sp_export_row['status'] ?? ''),
                        (string) ($calliope_sp_export_row['message'] ?? ''),
                    ]);
                }
                $calliope_sp_log_export = implode("\n", $calliope_sp_log_lines);
                ?>
                <textarea id="calliope-sp-log-export-data" hidden><?php echo esc_textarea($calliope_sp_log_export); ?></textarea>
                <script>
                (function(){
                    var source=document.getElementById('calliope-sp-log-export-data');
                    var copy=document.getElementById('calliope-sp-copy-logs');
                    var exportButton=document.getElementById('calliope-sp-export-logs');
                    if(!source){return;}
                    function text(){return source.value||'';}
                    if(copy){copy.addEventListener('click',function(){
                        var done=function(){var original=copy.textContent;copy.textContent='<?php echo esc_js(__('Copied', 'calliope-social-publisher')); ?>';setTimeout(function(){copy.textContent=original;},1400);};
                        if(navigator.clipboard&&window.isSecureContext){navigator.clipboard.writeText(text()).then(done);return;}
                        source.hidden=false;source.select();document.execCommand('copy');source.hidden=true;done();
                    });}
                    if(exportButton){exportButton.addEventListener('click',function(){
                        var blob=new Blob([text()],{type:'text/plain;charset=utf-8'});
                        var url=URL.createObjectURL(blob);var a=document.createElement('a');
                        a.href=url;a.download='calliope-social-publisher-logs-'+new Date().toISOString().slice(0,10)+'.txt';
                        document.body.appendChild(a);a.click();a.remove();setTimeout(function(){URL.revokeObjectURL(url);},1000);
                    });}
                })();
                </script>
            </div>

        <?php endif; ?>

    </div>

    <div class="calliope-sp-review-box">
        <div class="calliope-sp-review-box__text">
            <strong><?php echo esc_html__('Enjoying Social Publisher?', 'calliope-social-publisher'); ?></strong>
            <span><?php echo esc_html__('A ⭐⭐⭐⭐⭐ review helps the plugin grow and keeps improvements coming.', 'calliope-social-publisher'); ?></span>
        </div>
        <div class="calliope-sp-review-box__actions">
            <a class="calliope-sp-review-box__button" href="<?php echo esc_url($calliope_sp_review_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('Leave a review', 'calliope-social-publisher'); ?></a>
        </div>
    </div>
</div>
