<?php

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

class SEO_Fury_Tickets
{
    private static $instance = null;

    private $api_url = 'https://api.seo-fury.com/api/v1';

    public static function get_instance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct()
    {
        add_action('wp_ajax_seo_fury_get_tickets', array($this, 'ajax_get_tickets'));
        add_action('wp_ajax_seo_fury_get_ticket', array($this, 'ajax_get_ticket'));
        add_action('wp_ajax_seo_fury_create_ticket', array($this, 'ajax_create_ticket'));
        add_action('wp_ajax_seo_fury_reply_ticket', array($this, 'ajax_reply_ticket'));
        add_action('wp_ajax_seo_fury_close_ticket', array($this, 'ajax_close_ticket'));
        add_action('wp_ajax_seo_fury_faq_feedback', array($this, 'ajax_faq_feedback'));
    }

    /**
     * Make API request with auth token
     */
    private function api_request($endpoint, $method = 'GET', $data = array())
    {
        $url = $this->api_url . $endpoint;

        $args = array(
            'method'  => $method,
            'timeout' => 30,
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
        );

        if ($method !== 'GET' && !empty($data)) {
            $args['body'] = json_encode($data);
        }

        $token = $this->get_token();
        if ($token) {
            $args['headers']['Authorization'] = 'Bearer ' . $token;
        }

        $response = wp_remote_request($url, $args);

        if (is_wp_error($response)) {
            return array('success' => false, 'message' => $response->get_error_message());
        }

        $body = wp_remote_retrieve_body($response);
        $code = wp_remote_retrieve_response_code($response);
        $result = json_decode($body, true);

        if (!$result) {
            return array('success' => false, 'message' => 'Invalid API response (HTTP ' . $code . ')');
        }

        // Token expired / unauthorized / deactivated — re-activate license to
        // obtain a fresh JWT, then retry the original request once.
        if ($this->is_token_error($code, $result)) {
            $fresh_token = $this->reactivate_for_token();
            if (!empty($fresh_token)) {
                $args['headers']['Authorization'] = 'Bearer ' . $fresh_token;
                $retry = wp_remote_request($url, $args);
                if (!is_wp_error($retry)) {
                    $retry_body = wp_remote_retrieve_body($retry);
                    $retry_result = json_decode($retry_body, true);
                    if ($retry_result) {
                        return $retry_result;
                    }
                }
            }
        }

        return $result;
    }

    /**
     * Check if an API response indicates an auth / token problem.
     */
    private function is_token_error($code, $result)
    {
        if ($code === 401 || $code === 403) {
            return true;
        }

        if (!is_array($result)) {
            return false;
        }

        // Collect all possible message fields (top-level and nested).
        $candidates = array();
        if (isset($result['message']) && is_string($result['message'])) {
            $candidates[] = strtolower($result['message']);
        }
        if (isset($result['error']) && is_string($result['error'])) {
            $candidates[] = strtolower($result['error']);
        }
        if (isset($result['data']['message']) && is_string($result['data']['message'])) {
            $candidates[] = strtolower($result['data']['message']);
        }
        if (isset($result['data']['error']) && is_string($result['data']['error'])) {
            $candidates[] = strtolower($result['data']['error']);
        }

        if (empty($candidates)) {
            return false;
        }

        $keywords = array('token', 'unauthorized', 'expired', 'jwt', 'deactivated', 'unauthenticated', 'not authorized');
        foreach ($candidates as $msg) {
            foreach ($keywords as $kw) {
                if (strpos($msg, $kw) !== false) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Re-activate the stored license key directly (no Bearer header) to obtain
     * a fresh JWT token. This is self-contained — does not depend on the PRO
     * addon being present.
     *
     * @return string Fresh JWT token or empty string on failure.
     */
    private function reactivate_for_token()
    {
        $license_key = $this->get_license_key();
        if (empty($license_key)) {
            return '';
        }

        $domain = wp_parse_url(home_url(), PHP_URL_HOST);
        $domain = preg_replace('/^www\./', '', $domain);

        $activate_data = array(
            'licenseKey' => $license_key,
            'domain'     => $domain,
            'siteUrl'    => site_url(),
            'homeUrl'    => home_url(),
            'phpVersion' => PHP_VERSION,
            'wpVersion'  => get_bloginfo('version'),
        );

        // Send WITHOUT any Bearer header — authenticate purely by licenseKey.
        $response = wp_remote_post($this->api_url . '/plugin/activate', array(
            'timeout' => 30,
            'headers' => array('Content-Type' => 'application/json'),
            'body'    => wp_json_encode($activate_data),
        ));

        if (is_wp_error($response)) {
            // Store debug info for the calling code.
            $this->_refresh_debug = 'wp_error: ' . $response->get_error_message();
            return '';
        }

        $raw_body = wp_remote_retrieve_body($response);
        $http_code = wp_remote_retrieve_response_code($response);
        $body = json_decode($raw_body, true);

        if (empty($body['success'])) {
            $err = isset($body['message']) ? $body['message'] : (isset($body['error']) ? $body['error'] : 'unknown');
            $this->_refresh_debug = 'activate_failed(HTTP ' . $http_code . '): ' . $err;
            return '';
        }

        $token = '';
        if (!empty($body['data']['token'])) {
            $token = $body['data']['token'];
        } elseif (!empty($body['token'])) {
            $token = $body['token'];
        }

        if (!empty($token)) {
            $salt = 'seo_fury_2025';
            $option_token = '_sf_' . substr(md5($salt . 'token'), 0, 8);
            update_option($option_token, $token);
            $this->_refresh_debug = 'token_refreshed';
        } else {
            $this->_refresh_debug = 'activate_ok_but_no_token';
        }

        return $token;
    }

    /**
     * Check if user has a license (even free)
     */
    private function has_license()
    {
        $salt = 'seo_fury_2025';
        $option_key = '_sf_' . substr(md5($salt . 'key'), 0, 8);
        $key = get_option($option_key, '');
        return !empty($key);
    }

    /**
     * Get license key
     */
    private function get_license_key()
    {
        $salt = 'seo_fury_2025';
        $option_key = '_sf_' . substr(md5($salt . 'key'), 0, 8);
        return get_option($option_key, '');
    }

    /**
     * Get stored auth token
     */
    private function get_token()
    {
        $salt = 'seo_fury_2025';
        $option_token = '_sf_' . substr(md5($salt . 'token'), 0, 8);
        return get_option($option_token, '');
    }

    /**
     * Collect system/environment info to attach to ticket
     */
    private function get_system_info()
    {
        global $wpdb;

        // Active plugins
        $active_plugins = get_option('active_plugins', array());
        $plugins_list = array();
        foreach ($active_plugins as $plugin_file) {
            $plugin_data = get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin_file, false, false);
            if (!empty($plugin_data['Name'])) {
                $plugins_list[] = $plugin_data['Name'] . ' ' . $plugin_data['Version'];
            }
        }

        // Theme
        $theme = wp_get_theme();

        // SEO Fury plan
        $salt = 'seo_fury_2025';
        $plan_key = '_sf_' . substr(md5($salt . 'plan'), 0, 8);
        $plan = get_option($plan_key, 'free');

        $info = array(
            'domain'          => home_url(),
            'wp_version'      => get_bloginfo('version'),
            'php_version'     => phpversion(),
            'mysql_version'   => $wpdb->db_version(),
            'server_software' => isset($_SERVER['SERVER_SOFTWARE']) ? sanitize_text_field($_SERVER['SERVER_SOFTWARE']) : 'Unknown',
            'plugin_version'  => defined('SEO_FURY_VERSION') ? SEO_FURY_VERSION : 'Unknown',
            'license_key'     => $this->mask_license($this->get_license_key()),
            'plan'            => $plan,
            'theme'           => $theme->get('Name') . ' ' . $theme->get('Version'),
            'active_plugins'  => $plugins_list,
            'multisite'       => is_multisite() ? 'Yes' : 'No',
            'memory_limit'    => WP_MEMORY_LIMIT,
            'locale'          => get_locale(),
        );

        return $info;
    }

    /**
     * Mask license key for security (show first 4 and last 4 chars)
     */
    private function mask_license($key)
    {
        if (strlen($key) <= 8) {
            return $key;
        }
        return substr($key, 0, 4) . str_repeat('*', strlen($key) - 8) . substr($key, -4);
    }

    /**
     * Format system info as readable text for ticket
     */
    private function format_system_info($info)
    {
        $lines = array();
        $lines[] = '--- System Info ---';
        $lines[] = 'Domain: ' . $info['domain'];
        $lines[] = 'WordPress: ' . $info['wp_version'];
        $lines[] = 'PHP: ' . $info['php_version'];
        $lines[] = 'MySQL: ' . $info['mysql_version'];
        $lines[] = 'Server: ' . $info['server_software'];
        $lines[] = 'SEO Fury: ' . $info['plugin_version'] . ' (' . $info['plan'] . ')';
        $lines[] = 'License: ' . $info['license_key'];
        $lines[] = 'Theme: ' . $info['theme'];
        $lines[] = 'Multisite: ' . $info['multisite'];
        $lines[] = 'Memory Limit: ' . $info['memory_limit'];
        $lines[] = 'Locale: ' . $info['locale'];
        $lines[] = 'Active Plugins (' . count($info['active_plugins']) . '):';
        foreach ($info['active_plugins'] as $p) {
            $lines[] = '  - ' . $p;
        }
        $lines[] = '---';
        return implode("\n", $lines);
    }

    /**
     * AJAX: Get user's tickets list
     */
    public function ajax_get_tickets()
    {
        check_ajax_referer('seo_fury_tickets_nonce', 'nonce');

        if (!$this->has_license()) {
            wp_send_json_error(array('message' => __('A license is required to access support.', 'seo-fury')));
        }

        $page = isset($_POST['page']) ? absint($_POST['page']) : 1;
        $result = $this->api_request('/user/tickets?page=' . $page);

        if (!empty($result['success']) && isset($result['data'])) {
            wp_send_json_success($result['data']);
        } else {
            $msg = '';
            if (isset($result['message'])) {
                $msg = $result['message'];
            } elseif (isset($result['error'])) {
                $msg = $result['error'];
            } else {
                $msg = __('Failed to load tickets. Please check your license.', 'seo-fury');
            }
            wp_send_json_error(array('message' => $msg));
        }
    }

    /**
     * AJAX: Get single ticket with messages
     */
    public function ajax_get_ticket()
    {
        check_ajax_referer('seo_fury_tickets_nonce', 'nonce');

        $ticket_id = isset($_POST['ticket_id']) ? sanitize_text_field($_POST['ticket_id']) : '';

        if (empty($ticket_id)) {
            wp_send_json_error(array('message' => __('Ticket ID is required.', 'seo-fury')));
        }

        $result = $this->api_request('/user/tickets/' . $ticket_id);

        if (!empty($result['success']) && isset($result['data'])) {
            wp_send_json_success($result['data']);
        } else {
            $msg = isset($result['message']) ? $result['message'] : (isset($result['error']) ? $result['error'] : __('Failed to load ticket', 'seo-fury'));
            wp_send_json_error(array('message' => $msg));
        }
    }

    /**
     * AJAX: Create a new ticket
     */
    public function ajax_create_ticket()
    {
        check_ajax_referer('seo_fury_tickets_nonce', 'nonce');

        if (!$this->has_license()) {
            wp_send_json_error(array('message' => __('A license is required to create tickets.', 'seo-fury')));
        }

        $subject = isset($_POST['subject']) ? sanitize_text_field($_POST['subject']) : '';
        $message = isset($_POST['message']) ? sanitize_textarea_field($_POST['message']) : '';

        if (empty($subject) || empty($message)) {
            wp_send_json_error(array('message' => __('Subject and message are required.', 'seo-fury')));
        }

        // Collect and append system info
        $system_info = $this->get_system_info();
        $system_text = $this->format_system_info($system_info);
        $full_message = $message . "\n\n" . $system_text;

        $result = $this->api_request('/user/tickets', 'POST', array(
            'subject'    => $subject,
            'message'    => $full_message,
            'source'     => 'plugin',
            'locale'     => substr(get_locale(), 0, 2),
            'systemInfo' => $system_info,
        ));

        if (!empty($result['success']) && isset($result['data'])) {
            wp_send_json_success($result['data']);
        } else {
            $msg = isset($result['message']) ? $result['message'] : (isset($result['error']) ? $result['error'] : __('Failed to create ticket', 'seo-fury'));
            wp_send_json_error(array('message' => $msg));
        }
    }

    /**
     * AJAX: Reply to a ticket
     */
    public function ajax_reply_ticket()
    {
        check_ajax_referer('seo_fury_tickets_nonce', 'nonce');

        $ticket_id = isset($_POST['ticket_id']) ? sanitize_text_field($_POST['ticket_id']) : '';
        $message = isset($_POST['message']) ? sanitize_textarea_field($_POST['message']) : '';

        if (empty($ticket_id) || empty($message)) {
            wp_send_json_error(array('message' => __('Ticket ID and message are required.', 'seo-fury')));
        }

        $result = $this->api_request('/user/tickets/' . $ticket_id . '/reply', 'POST', array(
            'message' => $message,
        ));

        if (!empty($result['success'])) {
            wp_send_json_success(isset($result['data']) ? $result['data'] : array());
        } else {
            $msg = isset($result['message']) ? $result['message'] : (isset($result['error']) ? $result['error'] : __('Failed to send reply', 'seo-fury'));
            wp_send_json_error(array('message' => $msg));
        }
    }

    /**
     * AJAX: Close a ticket
     */
    public function ajax_close_ticket()
    {
        check_ajax_referer('seo_fury_tickets_nonce', 'nonce');

        $ticket_id = isset($_POST['ticket_id']) ? sanitize_text_field($_POST['ticket_id']) : '';

        if (empty($ticket_id)) {
            wp_send_json_error(array('message' => __('Ticket ID is required.', 'seo-fury')));
        }

        $result = $this->api_request('/user/tickets/' . $ticket_id . '/close', 'POST');

        if (!empty($result['success'])) {
            wp_send_json_success(isset($result['data']) ? $result['data'] : array());
        } else {
            $msg = isset($result['message']) ? $result['message'] : (isset($result['error']) ? $result['error'] : __('Failed to close ticket', 'seo-fury'));
            wp_send_json_error(array('message' => $msg));
        }
    }

    /**
     * AJAX: FAQ feedback (helpful or not)
     */
    public function ajax_faq_feedback()
    {
        check_ajax_referer('seo_fury_tickets_nonce', 'nonce');

        $ticket_id = isset($_POST['ticket_id']) ? sanitize_text_field($_POST['ticket_id']) : '';
        $helpful = isset($_POST['helpful']) ? (bool)$_POST['helpful'] : false;
        $faq_id = isset($_POST['faq_id']) ? sanitize_text_field($_POST['faq_id']) : '';

        $result = $this->api_request('/user/tickets/' . $ticket_id . '/faq-feedback', 'POST', array(
            'helpful' => $helpful,
            'faqId'   => $faq_id,
        ));

        if (!empty($result['success'])) {
            wp_send_json_success(isset($result['data']) ? $result['data'] : array());
        } else {
            $msg = isset($result['message']) ? $result['message'] : __('Failed to submit feedback', 'seo-fury');
            wp_send_json_error(array('message' => $msg));
        }
    }

    /**
     * Render support tab content
     */
    public function render_support_tab()
    {
        $has_license = $this->has_license();
        ?>
        <div id="seo-fury-support-wrap">
            <?php if (!$has_license): ?>
                <div class="sf-support-lock">
                    <div class="sf-support-lock-icon">
                        <span class="dashicons dashicons-admin-users"></span>
                    </div>
                    <h3><?php esc_html_e('Account Required', 'seo-fury'); ?></h3>
                    <p><?php esc_html_e('Support is available for registered users. Create a free account or purchase a PRO license to get access to tickets.', 'seo-fury'); ?></p>
                    <p style="margin-top:4px;font-size:13px;color:var(--sf-gray-400,#94A3B8);"><?php esc_html_e('Free registration takes less than a minute. After registration, activate your license key in the License tab.', 'seo-fury'); ?></p>
                    <div style="display:flex;gap:10px;justify-content:center;margin-top:16px;">
                        <a href="https://dashboard.seo-fury.com/register" target="_blank" class="sf-support-btn sf-support-btn-primary">
                            <?php esc_html_e('Create Free Account', 'seo-fury'); ?>
                        </a>
                        <a href="?page=seo-fury&tab=license" class="sf-support-btn sf-support-btn-ghost">
                            <?php esc_html_e('I Have a Key', 'seo-fury'); ?>
                        </a>
                    </div>
                </div>
            <?php else: ?>
                <!-- Header -->
                <div class="sf-support-header">
                    <div>
                        <h3 class="sf-support-title"><?php esc_html_e('Support', 'seo-fury'); ?></h3>
                        <p class="sf-support-subtitle"><?php esc_html_e('Create tickets or browse FAQ articles for quick answers.', 'seo-fury'); ?></p>
                    </div>
                    <button type="button" class="sf-support-btn sf-support-btn-primary" id="sf-create-ticket-btn">
                        <span class="dashicons dashicons-plus-alt2"></span>
                        <?php esc_html_e('New Ticket', 'seo-fury'); ?>
                    </button>
                </div>

                <!-- Create ticket form (hidden by default) -->
                <div id="sf-create-ticket-form" class="sf-support-section" style="display:none;">
                    <div class="sf-support-card sf-support-card-accent">
                        <h4 class="sf-support-card-title">
                            <span class="dashicons dashicons-edit"></span>
                            <?php esc_html_e('Create Support Ticket', 'seo-fury'); ?>
                        </h4>
                        <div class="sf-support-form-group">
                            <label for="sf-ticket-subject"><?php esc_html_e('Subject', 'seo-fury'); ?></label>
                            <input type="text" id="sf-ticket-subject" placeholder="<?php esc_attr_e('Briefly describe your issue', 'seo-fury'); ?>">
                        </div>
                        <div class="sf-support-form-group">
                            <label for="sf-ticket-message"><?php esc_html_e('Message', 'seo-fury'); ?></label>
                            <textarea id="sf-ticket-message" rows="5" placeholder="<?php esc_attr_e('Describe your issue in detail...', 'seo-fury'); ?>"></textarea>
                        </div>
                        <div class="sf-support-form-info">
                            <span class="dashicons dashicons-info"></span>
                            <?php esc_html_e('System information (WP version, PHP, plugins, etc.) will be automatically attached to help us diagnose faster.', 'seo-fury'); ?>
                        </div>
                        <div class="sf-support-form-actions">
                            <button type="button" class="sf-support-btn sf-support-btn-primary" id="sf-submit-ticket">
                                <span class="dashicons dashicons-yes-alt"></span>
                                <?php esc_html_e('Submit Ticket', 'seo-fury'); ?>
                            </button>
                            <button type="button" class="sf-support-btn sf-support-btn-ghost" id="sf-cancel-ticket">
                                <?php esc_html_e('Cancel', 'seo-fury'); ?>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- FAQ suggestions (hidden by default) -->
                <div id="sf-faq-suggestions" class="sf-support-section" style="display:none;">
                    <div class="sf-support-card sf-support-card-faq">
                        <h4 class="sf-support-card-title">
                            <span class="dashicons dashicons-lightbulb"></span>
                            <?php esc_html_e('We found articles that might help', 'seo-fury'); ?>
                        </h4>
                        <div id="sf-faq-list"></div>
                        <div class="sf-support-faq-footer">
                            <p><?php esc_html_e('None of these helped?', 'seo-fury'); ?></p>
                            <button type="button" class="sf-support-btn sf-support-btn-primary" id="sf-escalate-ticket">
                                <span class="dashicons dashicons-sos"></span>
                                <?php esc_html_e('Send to Support Team', 'seo-fury'); ?>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Toast notification -->
                <div id="sf-support-toast" class="sf-support-toast" style="display:none;"></div>

                <!-- Tickets list -->
                <div id="sf-tickets-list">
                    <div class="sf-support-loading">
                        <div class="sf-support-spinner"></div>
                        <span><?php esc_html_e('Loading tickets...', 'seo-fury'); ?></span>
                    </div>
                </div>

                <!-- Ticket detail (hidden by default) -->
                <div id="sf-ticket-detail" style="display:none;"></div>
            <?php endif; ?>
        </div>

        <style>
            /* ========== Support Tab Styles ========== */
            #seo-fury-support-wrap {
                font-family: var(--sf-font, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif);
            }

            /* Lock screen */
            .sf-support-lock {
                text-align: center;
                padding: 60px 24px;
            }
            .sf-support-lock-icon {
                width: 64px;
                height: 64px;
                border-radius: 50%;
                background: var(--sf-gray-100, #F1F5F9);
                display: flex;
                align-items: center;
                justify-content: center;
                margin: 0 auto 20px;
            }
            .sf-support-lock-icon .dashicons {
                font-size: 28px;
                width: 28px;
                height: 28px;
                color: var(--sf-gray-400, #94A3B8);
            }
            .sf-support-lock h3 {
                font-size: 18px;
                font-weight: 600;
                color: var(--sf-dark, #0F172A);
                margin: 0 0 8px;
            }
            .sf-support-lock p {
                color: var(--sf-gray-500, #64748B);
                margin: 0 0 20px;
                font-size: 14px;
            }

            /* Header */
            .sf-support-header {
                display: flex;
                justify-content: space-between;
                align-items: flex-start;
                margin-bottom: 20px;
                flex-wrap: wrap;
                gap: 12px;
            }
            .sf-support-title {
                font-size: 18px;
                font-weight: 700;
                color: var(--sf-dark, #0F172A);
                margin: 0 0 4px;
            }
            .sf-support-subtitle {
                font-size: 13px;
                color: var(--sf-gray-500, #64748B);
                margin: 0;
            }

            /* Buttons */
            .sf-support-btn {
                display: inline-flex;
                align-items: center;
                gap: 6px;
                padding: 8px 16px;
                border-radius: var(--sf-radius-xs, 6px);
                font-size: 13px;
                font-weight: 600;
                cursor: pointer;
                border: none;
                transition: var(--sf-transition, all 0.2s);
                line-height: 1.4;
                text-decoration: none;
            }
            .sf-support-btn .dashicons {
                font-size: 16px;
                width: 16px;
                height: 16px;
                line-height: 16px;
            }
            .sf-support-btn-primary {
                background: var(--sf-primary, #4F46E5);
                color: #fff;
            }
            .sf-support-btn-primary:hover {
                background: var(--sf-primary-dark, #4338CA);
                color: #fff;
            }
            .sf-support-btn-primary:disabled {
                opacity: 0.6;
                cursor: not-allowed;
            }
            .sf-support-btn-ghost {
                background: transparent;
                color: var(--sf-gray-500, #64748B);
                border: 1px solid var(--sf-gray-300, #CBD5E1);
            }
            .sf-support-btn-ghost:hover {
                background: var(--sf-gray-50, #F8FAFC);
                color: var(--sf-gray-700, #334155);
            }
            .sf-support-btn-success {
                background: var(--sf-success, #10B981);
                color: #fff;
            }
            .sf-support-btn-success:hover {
                background: #059669;
                color: #fff;
            }
            .sf-support-btn-danger {
                background: transparent;
                color: var(--sf-danger, #EF4444);
                border: 1px solid var(--sf-danger, #EF4444);
            }
            .sf-support-btn-danger:hover {
                background: var(--sf-danger-light, #FEF2F2);
            }
            .sf-support-btn-sm {
                padding: 5px 10px;
                font-size: 12px;
            }

            /* Cards */
            .sf-support-card {
                background: var(--sf-white, #fff);
                border: 1px solid var(--sf-gray-200, #E2E8F0);
                border-radius: var(--sf-radius-sm, 8px);
                padding: 20px;
                margin-bottom: 16px;
            }
            .sf-support-card-accent {
                border-left: 4px solid var(--sf-primary, #4F46E5);
            }
            .sf-support-card-faq {
                border-left: 4px solid var(--sf-success, #10B981);
            }
            .sf-support-card-title {
                display: flex;
                align-items: center;
                gap: 8px;
                font-size: 15px;
                font-weight: 600;
                color: var(--sf-dark, #0F172A);
                margin: 0 0 16px;
            }
            .sf-support-card-title .dashicons {
                color: var(--sf-primary, #4F46E5);
                font-size: 18px;
                width: 18px;
                height: 18px;
            }

            /* Form */
            .sf-support-form-group {
                margin-bottom: 14px;
            }
            .sf-support-form-group label {
                display: block;
                font-size: 13px;
                font-weight: 600;
                color: var(--sf-gray-700, #334155);
                margin-bottom: 5px;
            }
            .sf-support-form-group input,
            .sf-support-form-group textarea {
                width: 100%;
                padding: 9px 12px;
                border: 1px solid var(--sf-gray-300, #CBD5E1);
                border-radius: var(--sf-radius-xs, 6px);
                font-size: 14px;
                color: var(--sf-dark, #0F172A);
                background: var(--sf-white, #fff);
                transition: border-color 0.15s;
                font-family: inherit;
                box-sizing: border-box;
            }
            .sf-support-form-group input:focus,
            .sf-support-form-group textarea:focus {
                border-color: var(--sf-primary, #4F46E5);
                outline: none;
                box-shadow: 0 0 0 3px rgba(79,70,229,0.1);
            }
            .sf-support-form-info {
                display: flex;
                align-items: flex-start;
                gap: 6px;
                font-size: 12px;
                color: var(--sf-gray-500, #64748B);
                background: var(--sf-gray-50, #F8FAFC);
                padding: 10px 12px;
                border-radius: var(--sf-radius-xs, 6px);
                margin-bottom: 14px;
                line-height: 1.5;
            }
            .sf-support-form-info .dashicons {
                font-size: 15px;
                width: 15px;
                height: 15px;
                margin-top: 1px;
                color: var(--sf-primary, #4F46E5);
                flex-shrink: 0;
            }
            .sf-support-form-actions {
                display: flex;
                gap: 8px;
            }

            /* FAQ items */
            .sf-faq-item {
                background: var(--sf-gray-50, #F8FAFC);
                border: 1px solid var(--sf-gray-200, #E2E8F0);
                border-radius: var(--sf-radius-xs, 6px);
                padding: 14px;
                margin-bottom: 10px;
                transition: border-color 0.15s;
            }
            .sf-faq-item:hover {
                border-color: var(--sf-gray-300, #CBD5E1);
            }
            .sf-faq-item h5 {
                font-size: 14px;
                font-weight: 600;
                color: var(--sf-dark, #0F172A);
                margin: 0 0 6px;
            }
            .sf-faq-item p {
                font-size: 13px;
                color: var(--sf-gray-500, #64748B);
                margin: 0 0 10px;
                line-height: 1.5;
            }
            .sf-support-faq-footer {
                border-top: 1px solid var(--sf-gray-200, #E2E8F0);
                margin-top: 16px;
                padding-top: 16px;
                text-align: center;
            }
            .sf-support-faq-footer p {
                font-size: 13px;
                color: var(--sf-gray-500, #64748B);
                margin: 0 0 10px;
            }

            /* Toast */
            .sf-support-toast {
                position: fixed;
                bottom: 24px;
                right: 24px;
                background: var(--sf-dark, #0F172A);
                color: #fff;
                padding: 12px 20px;
                border-radius: var(--sf-radius-sm, 8px);
                font-size: 13px;
                font-weight: 500;
                z-index: 999999;
                box-shadow: var(--sf-shadow-lg);
                transition: opacity 0.3s, transform 0.3s;
                max-width: 400px;
            }
            .sf-support-toast.sf-toast-error {
                background: var(--sf-danger, #EF4444);
            }
            .sf-support-toast.sf-toast-success {
                background: var(--sf-success, #10B981);
            }

            /* Loading */
            .sf-support-loading {
                text-align: center;
                padding: 40px 20px;
                color: var(--sf-gray-400, #94A3B8);
                font-size: 13px;
            }
            .sf-support-spinner {
                width: 24px;
                height: 24px;
                border: 3px solid var(--sf-gray-200, #E2E8F0);
                border-top-color: var(--sf-primary, #4F46E5);
                border-radius: 50%;
                animation: sf-spin 0.6s linear infinite;
                margin: 0 auto 10px;
            }
            @keyframes sf-spin {
                to { transform: rotate(360deg); }
            }

            /* Tickets table */
            .sf-tickets-table {
                width: 100%;
                border-collapse: separate;
                border-spacing: 0;
                font-size: 13px;
            }
            .sf-tickets-table th {
                background: var(--sf-gray-50, #F8FAFC);
                color: var(--sf-gray-500, #64748B);
                font-weight: 600;
                font-size: 11px;
                text-transform: uppercase;
                letter-spacing: 0.05em;
                padding: 10px 14px;
                text-align: left;
                border-bottom: 1px solid var(--sf-gray-200, #E2E8F0);
            }
            .sf-tickets-table td {
                padding: 12px 14px;
                border-bottom: 1px solid var(--sf-gray-100, #F1F5F9);
                color: var(--sf-gray-700, #334155);
            }
            .sf-tickets-table tr:hover td {
                background: var(--sf-primary-light, #EEF2FF);
                cursor: pointer;
            }
            .sf-tickets-table .sf-ticket-subject {
                font-weight: 600;
                color: var(--sf-dark, #0F172A);
            }

            /* Status badge */
            .sf-status-badge {
                display: inline-block;
                padding: 3px 10px;
                border-radius: 20px;
                font-size: 11px;
                font-weight: 600;
                line-height: 1.5;
            }
            .sf-status-open {
                background: var(--sf-warning-light, #FFFBEB);
                color: #92400E;
            }
            .sf-status-awaiting_reply {
                background: #DBEAFE;
                color: #1E40AF;
            }
            .sf-status-resolved {
                background: var(--sf-success-light, #ECFDF5);
                color: #065F46;
            }
            .sf-status-closed {
                background: var(--sf-gray-100, #F1F5F9);
                color: var(--sf-gray-500, #64748B);
            }

            /* Empty state */
            .sf-support-empty {
                text-align: center;
                padding: 48px 24px;
            }
            .sf-support-empty-icon {
                width: 56px;
                height: 56px;
                border-radius: 50%;
                background: var(--sf-primary-light, #EEF2FF);
                display: flex;
                align-items: center;
                justify-content: center;
                margin: 0 auto 16px;
            }
            .sf-support-empty-icon .dashicons {
                font-size: 24px;
                width: 24px;
                height: 24px;
                color: var(--sf-primary, #4F46E5);
            }
            .sf-support-empty h4 {
                font-size: 15px;
                color: var(--sf-dark, #0F172A);
                margin: 0 0 6px;
            }
            .sf-support-empty p {
                font-size: 13px;
                color: var(--sf-gray-500, #64748B);
                margin: 0;
            }

            /* Ticket Detail */
            .sf-ticket-detail-header {
                display: flex;
                justify-content: space-between;
                align-items: flex-start;
                flex-wrap: wrap;
                gap: 12px;
                margin-bottom: 16px;
            }
            .sf-ticket-detail-subject {
                font-size: 17px;
                font-weight: 700;
                color: var(--sf-dark, #0F172A);
                margin: 0 0 6px;
            }
            .sf-ticket-detail-meta {
                font-size: 12px;
                color: var(--sf-gray-500, #64748B);
            }
            .sf-ticket-messages {
                max-height: 400px;
                overflow-y: auto;
                padding: 16px 0;
                border-top: 1px solid var(--sf-gray-200, #E2E8F0);
                border-bottom: 1px solid var(--sf-gray-200, #E2E8F0);
            }
            .sf-msg-bubble {
                max-width: 75%;
                padding: 10px 14px;
                border-radius: 12px;
                margin-bottom: 10px;
                font-size: 13px;
                line-height: 1.55;
            }
            .sf-msg-user {
                background: var(--sf-gray-100, #F1F5F9);
                border: 1px solid var(--sf-gray-200, #E2E8F0);
                margin-right: auto;
            }
            .sf-msg-admin {
                background: var(--sf-primary-light, #EEF2FF);
                border: 1px solid #C7D2FE;
                margin-left: auto;
            }
            .sf-msg-system {
                background: var(--sf-warning-light, #FFFBEB);
                border: 1px solid #FDE68A;
                margin-right: auto;
            }
            .sf-msg-sender {
                font-size: 11px;
                font-weight: 600;
                color: var(--sf-gray-500, #64748B);
                margin-bottom: 3px;
            }
            .sf-msg-text {
                white-space: pre-wrap;
                word-wrap: break-word;
            }
            .sf-msg-time {
                font-size: 10px;
                color: var(--sf-gray-400, #94A3B8);
                margin-top: 4px;
                text-align: right;
            }

            /* Reply area */
            .sf-ticket-reply-area {
                padding-top: 16px;
            }
            .sf-ticket-reply-area textarea {
                width: 100%;
                padding: 10px 12px;
                border: 1px solid var(--sf-gray-300, #CBD5E1);
                border-radius: var(--sf-radius-xs, 6px);
                font-size: 13px;
                font-family: inherit;
                resize: vertical;
                box-sizing: border-box;
                margin-bottom: 10px;
            }
            .sf-ticket-reply-area textarea:focus {
                border-color: var(--sf-primary, #4F46E5);
                outline: none;
                box-shadow: 0 0 0 3px rgba(79,70,229,0.1);
            }
            .sf-ticket-reply-actions {
                display: flex;
                gap: 8px;
            }
        </style>
        <?php
    }
}
