<?php

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

class List2Play_Servers_Widget extends WP_Widget {
    
    private $api;
    private $renderer;
    
    public function __construct() {
        parent::__construct(
            'list2play_servers_widget',
            __('List2Play Servers', 'list2play-servers'),
            [
                'description' => __('Display List2Play game servers in your sidebar or widget areas.', 'list2play-servers'),
            ]
        );
        
        // Create API and renderer instances
        $this->api = new List2Play_Servers_API();
        $this->renderer = new List2Play_Servers_Renderer($this->api);
    }
    
    /**
     * Output widget content
     */
    public function widget($args, $instance) {
        // WordPress widget args are already escaped by WordPress core
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo $args['before_widget'];
        
        $title = !empty($instance['title']) ? $instance['title'] : __('Game Servers', 'list2play-servers');
        if (!empty($title)) {
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo $args['before_title'] . esc_html(apply_filters('widget_title', $title)) . $args['after_title'];
        }
        
        // Get widget settings
        $per_page = !empty($instance['per_page']) ? absint($instance['per_page']) : 5;
        $game_type = !empty($instance['game_type']) ? sanitize_text_field($instance['game_type']) : '';
        $country = !empty($instance['country']) ? strtoupper(sanitize_text_field($instance['country'])) : '';
        $status = !empty($instance['status']) ? sanitize_text_field($instance['status']) : '';
        $sort = !empty($instance['sort']) ? sanitize_text_field($instance['sort']) : 'votes';
        $direction = !empty($instance['direction']) ? sanitize_text_field($instance['direction']) : 'desc';
        $single_server_id = !empty($instance['single_server_id']) ? absint($instance['single_server_id']) : 0;
        
        // Prepare API arguments
        $api_args = [];
        
        // If single server ID is specified, show only that server
        if (!empty($single_server_id)) {
            $server_response = $this->api->get_server($single_server_id);
            if (isset($server_response['error'])) {
                echo '<p class="list2play-error">' . esc_html($server_response['message'] ?? __('Server not found.', 'list2play-servers')) . '</p>';
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                echo $args['after_widget'];
                return;
            }
            
            // Get display options from widget instance or fallback to admin defaults
            // Use isset() to check if value is set in instance (even if '0'), otherwise use admin defaults
            $display_options = [
                'show_hostname' => isset($instance['show_hostname']) ? ($instance['show_hostname'] === '1') : (get_option('list2play_show_hostname', '1') === '1'),
                'show_status' => isset($instance['show_status']) ? ($instance['show_status'] === '1') : (get_option('list2play_show_status', '1') === '1'),
                'show_address' => isset($instance['show_address']) ? ($instance['show_address'] === '1') : (get_option('list2play_show_address', '1') === '1'),
                'show_game' => isset($instance['show_game']) ? ($instance['show_game'] === '1') : (get_option('list2play_show_game', '1') === '1'),
                'show_region' => isset($instance['show_region']) ? ($instance['show_region'] === '1') : (get_option('list2play_show_region', '1') === '1'),
                'show_players' => isset($instance['show_players']) ? ($instance['show_players'] === '1') : (get_option('list2play_show_players', '1') === '1'),
                'show_map' => isset($instance['show_map']) ? ($instance['show_map'] === '1') : (get_option('list2play_show_map', '1') === '1'),
                'show_votes' => isset($instance['show_votes']) ? ($instance['show_votes'] === '1') : (get_option('list2play_show_votes', '1') === '1'),
                'show_chart' => isset($instance['show_chart']) ? ($instance['show_chart'] === '1') : false,
            ];
            
            $show_stats = isset($instance['show_stats']) ? ($instance['show_stats'] === '1') : (get_option('list2play_show_stats', '1') === '1');
            $show_votes = isset($instance['show_votes']) ? ($instance['show_votes'] === '1') : (get_option('list2play_show_votes', '1') === '1');
            $show_vote_button = isset($instance['show_vote_button']) ? ($instance['show_vote_button'] === '1') : (get_option('list2play_show_vote_button', '1') === '1');
            
            // Renderer output is already escaped
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo $this->renderer->render_server_list([$server_response], [
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Boolean parameter, not output
                'show_stats' => $show_stats,
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Boolean parameter, not output
                'show_votes' => $show_votes,
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Boolean parameter, not output
                'show_vote_button' => $show_vote_button,
                'style_preset' => !empty($instance['style_preset']) ? sanitize_key($instance['style_preset']) : 'default',
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Array parameter, not output
                'display_options' => $display_options,
                'pagination' => null,
            ]);
            
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo $args['after_widget'];
            return;
        }
        
        // Widget always uses selected servers from admin settings
        // Get selected server IDs from admin settings
        $selected_ids = get_option('list2play_selected_server_ids', []);
        
        // Always use selected server IDs if available
        if (!empty($selected_ids) && is_array($selected_ids)) {
            $api_args['server_ids'] = $selected_ids;
        } else {
            // Fallback to user servers if no selection
            $api_args['user_servers_only'] = true;
        }
        
        if (!empty($game_type)) {
            $api_args['game_type'] = $game_type;
        }
        
        if (!empty($country)) {
            $api_args['country'] = $country;
        }
        
        if (!empty($status) && in_array($status, ['online', 'offline'], true)) {
            $api_args['status'] = $status;
        }
        
        if (!empty($sort)) {
            $api_args['sort'] = $sort;
        }
        
        if (!empty($direction) && in_array($direction, ['asc', 'desc'], true)) {
            $api_args['direction'] = $direction;
        }
        
        $api_args['per_page'] = $per_page;
        
        // Get display options from widget instance or fallback to admin defaults
        // Use isset() to check if value is set in instance (even if '0'), otherwise use admin defaults
        $display_options = [
            'show_hostname' => isset($instance['show_hostname']) ? ($instance['show_hostname'] === '1') : (get_option('list2play_show_hostname', '1') === '1'),
            'show_status' => isset($instance['show_status']) ? ($instance['show_status'] === '1') : (get_option('list2play_show_status', '1') === '1'),
            'show_address' => isset($instance['show_address']) ? ($instance['show_address'] === '1') : (get_option('list2play_show_address', '1') === '1'),
            'show_game' => isset($instance['show_game']) ? ($instance['show_game'] === '1') : (get_option('list2play_show_game', '1') === '1'),
            'show_region' => isset($instance['show_region']) ? ($instance['show_region'] === '1') : (get_option('list2play_show_region', '1') === '1'),
            'show_players' => isset($instance['show_players']) ? ($instance['show_players'] === '1') : (get_option('list2play_show_players', '1') === '1'),
            'show_map' => isset($instance['show_map']) ? ($instance['show_map'] === '1') : (get_option('list2play_show_map', '1') === '1'),
            'show_votes' => isset($instance['show_votes']) ? ($instance['show_votes'] === '1') : (get_option('list2play_show_votes', '1') === '1'),
            'show_chart' => isset($instance['show_chart']) ? ($instance['show_chart'] === '1') : false,
        ];
        
        // Get show_stats, show_votes, show_vote_button from widget instance or admin defaults
        $show_stats = isset($instance['show_stats']) ? ($instance['show_stats'] === '1') : (get_option('list2play_show_stats', '1') === '1');
        $show_votes = isset($instance['show_votes']) ? ($instance['show_votes'] === '1') : (get_option('list2play_show_votes', '1') === '1');
        $show_vote_button = isset($instance['show_vote_button']) ? ($instance['show_vote_button'] === '1') : (get_option('list2play_show_vote_button', '1') === '1');
        
        // Get servers - handle selected IDs like shortcode does
        $has_selected_ids = !empty($selected_ids) && is_array($selected_ids);
        
        if ($has_selected_ids) {
            // Get all selected servers first
            $all_servers_args = $api_args;
            $all_servers_args['per_page'] = 1000;
            
            $all_response = $this->api->get_servers($all_servers_args);
            
            $all_servers = $all_response['data'] ?? [];
            
            // Check for missing servers and fetch them individually
            if ($has_selected_ids) {
                $returned_ids = array_map(function($server) {
                    return $server['id'] ?? 0;
                }, $all_servers);
                
                $missing_ids = array_diff($selected_ids, $returned_ids);
                
                foreach ($missing_ids as $server_id) {
                    $server_response = $this->api->get_server($server_id);
                    if (!isset($server_response['error']) && isset($server_response['id'])) {
                        $all_servers[] = $server_response;
                    }
                }
            }
            
            // Apply filters
            if (!empty($game_type)) {
                $all_servers = array_filter($all_servers, function($server) use ($game_type) {
                    return isset($server['game_type']['slug']) && $server['game_type']['slug'] === $game_type;
                });
            }
            
            if (!empty($country)) {
                $all_servers = array_filter($all_servers, function($server) use ($country) {
                    return isset($server['country']) && strtoupper($server['country']) === $country;
                });
            }
            
            if (!empty($status)) {
                $all_servers = array_filter($all_servers, function($server) use ($status) {
                    return isset($server['status']) && $server['status'] === $status;
                });
            }
            
            // Sort
            if (!empty($sort)) {
                usort($all_servers, function($a, $b) use ($sort, $direction) {
                    $val_a = 0;
                    $val_b = 0;
                    
                    if ($sort === 'votes') {
                        $val_a = $a['votes'] ?? 0;
                        $val_b = $b['votes'] ?? 0;
                    } elseif ($sort === 'activity') {
                        $val_a = strtotime($a['last_queried_at'] ?? '1970-01-01');
                        $val_b = strtotime($b['last_queried_at'] ?? '1970-01-01');
                    }
                    
                    return $direction === 'desc' ? $val_b - $val_a : $val_a - $val_b;
                });
            }
            
            // Limit to per_page
            $servers = array_slice($all_servers, 0, $per_page);
            $response = ['data' => $servers];
        } else {
            // Fallback: use API directly
            $api_args['per_page'] = $per_page;
            $response = $this->api->get_servers($api_args);
        }
        
        if (isset($response['error'])) {
            echo '<p class="list2play-error">' . esc_html($response['message'] ?? __('Failed to load servers.', 'list2play-servers')) . '</p>';
        } elseif (!empty($response['data'])) {
            // Renderer output is already escaped
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo $this->renderer->render_server_list($response['data'], [
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Boolean parameter, not output
                'show_stats' => $show_stats,
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Boolean parameter, not output
                'show_votes' => $show_votes,
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Boolean parameter, not output
                'show_vote_button' => $show_vote_button,
                'style_preset' => !empty($instance['style_preset']) ? sanitize_key($instance['style_preset']) : 'default',
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Array parameter, not output
                'display_options' => $display_options,
                'pagination' => null, // No pagination in widgets
            ]);
        } else {
            echo '<p class="list2play-empty">' . esc_html__('No servers found. Please select servers in plugin settings.', 'list2play-servers') . '</p>';
        }
        
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo $args['after_widget'];
    }
    
    /**
     * Output widget settings form
     */
    public function form($instance) {
        $global_style_preset = sanitize_key((string) get_option('list2play_default_style_preset', 'default'));
        if ($global_style_preset === '') {
            $global_style_preset = 'default';
        }
        $title = !empty($instance['title']) ? $instance['title'] : '';
        $per_page = !empty($instance['per_page']) ? absint($instance['per_page']) : 5;
        $game_type = !empty($instance['game_type']) ? $instance['game_type'] : '';
        $country = !empty($instance['country']) ? $instance['country'] : '';
        $status = !empty($instance['status']) ? $instance['status'] : '';
        $sort = !empty($instance['sort']) ? $instance['sort'] : 'votes';
        $direction = !empty($instance['direction']) ? $instance['direction'] : 'desc';
        
        // Display options - use instance values or default to admin settings
        $show_hostname = isset($instance['show_hostname']) ? $instance['show_hostname'] : get_option('list2play_show_hostname', '1');
        $show_status = isset($instance['show_status']) ? $instance['show_status'] : get_option('list2play_show_status', '1');
        $show_address = isset($instance['show_address']) ? $instance['show_address'] : get_option('list2play_show_address', '1');
        $show_game = isset($instance['show_game']) ? $instance['show_game'] : get_option('list2play_show_game', '1');
        $show_region = isset($instance['show_region']) ? $instance['show_region'] : get_option('list2play_show_region', '1');
        $show_players = isset($instance['show_players']) ? $instance['show_players'] : get_option('list2play_show_players', '1');
        $show_map = isset($instance['show_map']) ? $instance['show_map'] : get_option('list2play_show_map', '1');
        $show_votes = isset($instance['show_votes']) ? $instance['show_votes'] : get_option('list2play_show_votes', '1');
        $show_chart = isset($instance['show_chart']) ? $instance['show_chart'] : get_option('list2play_show_chart', '0');
        $show_stats = isset($instance['show_stats']) ? $instance['show_stats'] : get_option('list2play_show_stats', '1');
        $show_vote_button = isset($instance['show_vote_button']) ? $instance['show_vote_button'] : get_option('list2play_show_vote_button', '1');
        $style_preset = !empty($instance['style_preset']) ? sanitize_key($instance['style_preset']) : $global_style_preset;
        ?>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php esc_html_e('Title:', 'list2play-servers'); ?></label>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>" 
                   name="<?php echo esc_attr($this->get_field_name('title')); ?>" 
                   type="text" value="<?php echo esc_attr($title); ?>">
        </p>
        
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('single_server_id')); ?>"><?php esc_html_e('Show Single Server (optional):', 'list2play-servers'); ?></label>
            <input class="tiny-text" id="<?php echo esc_attr($this->get_field_id('single_server_id')); ?>" 
                   name="<?php echo esc_attr($this->get_field_name('single_server_id')); ?>" 
                   type="number" min="0" value="<?php echo esc_attr(!empty($instance['single_server_id']) ? absint($instance['single_server_id']) : ''); ?>" 
                   placeholder="<?php esc_attr_e('Server ID', 'list2play-servers'); ?>">
            <br><small><?php esc_html_e('Enter a server ID to display only that server. Leave empty to show multiple servers.', 'list2play-servers'); ?></small>
        </p>
        
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('per_page')); ?>"><?php esc_html_e('Number of servers:', 'list2play-servers'); ?></label>
            <input class="tiny-text" id="<?php echo esc_attr($this->get_field_id('per_page')); ?>" 
                   name="<?php echo esc_attr($this->get_field_name('per_page')); ?>" 
                   type="number" min="1" max="20" value="<?php echo esc_attr($per_page); ?>">
            <br><small><?php esc_html_e('Widget displays servers selected in plugin settings. Ignored if single server ID is set.', 'list2play-servers'); ?></small>
        </p>
        
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('status')); ?>"><?php esc_html_e('Status:', 'list2play-servers'); ?></label>
            <select class="widefat" id="<?php echo esc_attr($this->get_field_id('status')); ?>" 
                    name="<?php echo esc_attr($this->get_field_name('status')); ?>">
                <option value="" <?php selected($status, ''); ?>><?php esc_html_e('All', 'list2play-servers'); ?></option>
                <option value="online" <?php selected($status, 'online'); ?>><?php esc_html_e('Online Only', 'list2play-servers'); ?></option>
                <option value="offline" <?php selected($status, 'offline'); ?>><?php esc_html_e('Offline Only', 'list2play-servers'); ?></option>
            </select>
        </p>
        
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('sort')); ?>"><?php esc_html_e('Sort by:', 'list2play-servers'); ?></label>
            <select class="widefat" id="<?php echo esc_attr($this->get_field_id('sort')); ?>" 
                    name="<?php echo esc_attr($this->get_field_name('sort')); ?>">
                <option value="votes" <?php selected($sort, 'votes'); ?>><?php esc_html_e('Votes', 'list2play-servers'); ?></option>
                <option value="activity" <?php selected($sort, 'activity'); ?>><?php esc_html_e('Activity', 'list2play-servers'); ?></option>
                <option value="newest" <?php selected($sort, 'newest'); ?>><?php esc_html_e('Newest', 'list2play-servers'); ?></option>
            </select>
        </p>
        
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('direction')); ?>"><?php esc_html_e('Sort direction:', 'list2play-servers'); ?></label>
            <select class="widefat" id="<?php echo esc_attr($this->get_field_id('direction')); ?>" 
                    name="<?php echo esc_attr($this->get_field_name('direction')); ?>">
                <option value="desc" <?php selected($direction, 'desc'); ?>><?php esc_html_e('Descending', 'list2play-servers'); ?></option>
                <option value="asc" <?php selected($direction, 'asc'); ?>><?php esc_html_e('Ascending', 'list2play-servers'); ?></option>
            </select>
        </p>
        
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('style_preset')); ?>"><?php esc_html_e('Style preset:', 'list2play-servers'); ?></label>
            <select class="widefat" id="<?php echo esc_attr($this->get_field_id('style_preset')); ?>"
                    name="<?php echo esc_attr($this->get_field_name('style_preset')); ?>">
                <option value="default" <?php selected($style_preset, 'default'); ?>><?php esc_html_e('Default', 'list2play-servers'); ?></option>
                <option value="neon-cyan" <?php selected($style_preset, 'neon-cyan'); ?>><?php esc_html_e('Cyber Cyan', 'list2play-servers'); ?></option>
                <option value="neon-purple" <?php selected($style_preset, 'neon-purple'); ?>><?php esc_html_e('Violet Pulse', 'list2play-servers'); ?></option>
                <option value="neon-red" <?php selected($style_preset, 'neon-red'); ?>><?php esc_html_e('Inferno Red', 'list2play-servers'); ?></option>
                <option value="neon-toxic" <?php selected($style_preset, 'neon-toxic'); ?>><?php esc_html_e('Toxic Green', 'list2play-servers'); ?></option>
            </select>
        </p>
        
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('game_type')); ?>"><?php esc_html_e('Game Type (optional):', 'list2play-servers'); ?></label>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('game_type')); ?>" 
                   name="<?php echo esc_attr($this->get_field_name('game_type')); ?>" 
                   type="text" value="<?php echo esc_attr($game_type); ?>" 
                   placeholder="<?php esc_attr_e('e.g., cs16, tf2', 'list2play-servers'); ?>">
        </p>
        
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('country')); ?>"><?php esc_html_e('Country Code (optional):', 'list2play-servers'); ?></label>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('country')); ?>" 
                   name="<?php echo esc_attr($this->get_field_name('country')); ?>" 
                   type="text" value="<?php echo esc_attr($country); ?>" 
                   placeholder="<?php esc_attr_e('e.g., US, GB, LT', 'list2play-servers'); ?>" 
                   maxlength="2" style="text-transform: uppercase;">
        </p>
        
        <hr style="margin: 15px 0;">
        <p><strong><?php esc_html_e('Display Options', 'list2play-servers'); ?></strong></p>
        <p><small><?php esc_html_e('Select which information to display in this widget.', 'list2play-servers'); ?></small></p>
        
        <p>
            <label>
                <input type="checkbox" name="<?php echo esc_attr($this->get_field_name('show_hostname')); ?>" value="1" <?php checked($show_hostname, '1'); ?> />
                <?php esc_html_e('Hostname', 'list2play-servers'); ?>
            </label><br>
            <label>
                <input type="checkbox" name="<?php echo esc_attr($this->get_field_name('show_status')); ?>" value="1" <?php checked($show_status, '1'); ?> />
                <?php esc_html_e('Status', 'list2play-servers'); ?>
            </label><br>
            <label>
                <input type="checkbox" name="<?php echo esc_attr($this->get_field_name('show_address')); ?>" value="1" <?php checked($show_address, '1'); ?> />
                <?php esc_html_e('Address', 'list2play-servers'); ?>
            </label><br>
            <label>
                <input type="checkbox" name="<?php echo esc_attr($this->get_field_name('show_game')); ?>" value="1" <?php checked($show_game, '1'); ?> />
                <?php esc_html_e('Game', 'list2play-servers'); ?>
            </label><br>
            <label>
                <input type="checkbox" name="<?php echo esc_attr($this->get_field_name('show_region')); ?>" value="1" <?php checked($show_region, '1'); ?> />
                <?php esc_html_e('Region', 'list2play-servers'); ?>
            </label><br>
            <label>
                <input type="checkbox" name="<?php echo esc_attr($this->get_field_name('show_players')); ?>" value="1" <?php checked($show_players, '1'); ?> />
                <?php esc_html_e('Players', 'list2play-servers'); ?>
            </label><br>
            <label>
                <input type="checkbox" name="<?php echo esc_attr($this->get_field_name('show_map')); ?>" value="1" <?php checked($show_map, '1'); ?> />
                <?php esc_html_e('Map', 'list2play-servers'); ?>
            </label><br>
            <label>
                <input type="checkbox" name="<?php echo esc_attr($this->get_field_name('show_votes')); ?>" value="1" <?php checked($show_votes, '1'); ?> />
                <?php esc_html_e('Votes', 'list2play-servers'); ?>
            </label><br>
            <label>
                <input type="checkbox" name="<?php echo esc_attr($this->get_field_name('show_chart')); ?>" value="1" <?php checked($show_chart, '1'); ?> />
                <?php esc_html_e('Player History Chart', 'list2play-servers'); ?>
            </label><br>
            <label>
                <input type="checkbox" name="<?php echo esc_attr($this->get_field_name('show_stats')); ?>" value="1" <?php checked($show_stats, '1'); ?> />
                <?php esc_html_e('Server Stats', 'list2play-servers'); ?>
            </label><br>
            <label>
                <input type="checkbox" name="<?php echo esc_attr($this->get_field_name('show_vote_button')); ?>" value="1" <?php checked($show_vote_button, '1'); ?> />
                <?php esc_html_e('Vote Button', 'list2play-servers'); ?>
            </label>
        </p>
        <?php
    }
    
    /**
     * Update widget settings
     */
    public function update($new_instance, $old_instance) {
        $instance = [];
        $instance['title'] = !empty($new_instance['title']) ? sanitize_text_field($new_instance['title']) : '';
        $instance['per_page'] = !empty($new_instance['per_page']) ? absint($new_instance['per_page']) : 5;
        $instance['single_server_id'] = !empty($new_instance['single_server_id']) ? absint($new_instance['single_server_id']) : 0;
        $instance['game_type'] = !empty($new_instance['game_type']) ? sanitize_text_field($new_instance['game_type']) : '';
        $instance['country'] = !empty($new_instance['country']) ? strtoupper(sanitize_text_field($new_instance['country'])) : '';
        $instance['status'] = !empty($new_instance['status']) ? sanitize_text_field($new_instance['status']) : '';
        $instance['sort'] = !empty($new_instance['sort']) ? sanitize_text_field($new_instance['sort']) : 'votes';
        $instance['direction'] = !empty($new_instance['direction']) ? sanitize_text_field($new_instance['direction']) : 'desc';
        
        // Display options - use isset() to properly handle unchecked checkboxes
        $instance['show_hostname'] = isset($new_instance['show_hostname']) && $new_instance['show_hostname'] === '1' ? '1' : '0';
        $instance['show_status'] = isset($new_instance['show_status']) && $new_instance['show_status'] === '1' ? '1' : '0';
        $instance['show_address'] = isset($new_instance['show_address']) && $new_instance['show_address'] === '1' ? '1' : '0';
        $instance['show_game'] = isset($new_instance['show_game']) && $new_instance['show_game'] === '1' ? '1' : '0';
        $instance['show_region'] = isset($new_instance['show_region']) && $new_instance['show_region'] === '1' ? '1' : '0';
        $instance['show_players'] = isset($new_instance['show_players']) && $new_instance['show_players'] === '1' ? '1' : '0';
        $instance['show_map'] = isset($new_instance['show_map']) && $new_instance['show_map'] === '1' ? '1' : '0';
        $instance['show_votes'] = isset($new_instance['show_votes']) && $new_instance['show_votes'] === '1' ? '1' : '0';
        $instance['show_chart'] = isset($new_instance['show_chart']) && $new_instance['show_chart'] === '1' ? '1' : '0';
        $instance['show_stats'] = isset($new_instance['show_stats']) && $new_instance['show_stats'] === '1' ? '1' : '0';
        $instance['show_vote_button'] = isset($new_instance['show_vote_button']) && $new_instance['show_vote_button'] === '1' ? '1' : '0';
        $allowed_presets = ['default', 'neon-cyan', 'neon-purple', 'neon-red', 'neon-toxic'];
        $preset = !empty($new_instance['style_preset']) ? sanitize_key($new_instance['style_preset']) : 'default';
        $instance['style_preset'] = in_array($preset, $allowed_presets, true) ? $preset : 'default';
        
        // Limit per_page to 20 for widgets
        if ($instance['per_page'] > 20) {
            $instance['per_page'] = 20;
        }
        if ($instance['per_page'] < 1) {
            $instance['per_page'] = 1;
        }
        
        return $instance;
    }
}

