<?php
    if (isset($block['data']['isExample']) && $block['data']['isExample']) {
        echo '<img src="' . esc_url( $block['data']['preview_image'] ) . '" style="max-width:100%; min-width:100%" alt="Preview" />';
        return;
    }

    global $rdgb;
    $rdgb = (!empty($rdgb)) ? $rdgb : Rdg_Blocks::instance();

    $block_styles = [];
    $block_name = BLOCK_RDG_AV_PICKS_STICKY;
    $block_classes = [$block_name];
    $block_av_picks_sticky = $rdgb->settings->getBlock($block_name);
    $block_id = (isset($block['data']['custom_id']) && !empty($block['data']['custom_id'])) ? $block['data']['custom_id'] : $block['id'];

    if (!empty($block['backgroundColor'])) {
        $block_classes[] = 'has-background';
        $block_classes[] = 'has-'.$block['backgroundColor'].'-background-color';
    }

    if (!empty($block['style']['color']['background'])) {
        $block_styles[] = 'background-color: '.$block['style']['color']['background'].';';
    }

    // Get ACF fields
    $bar_background_color = get_field('bar_background_color');
    $disable_sticky = get_field('disable_sticky');
    $button_theme = get_field('button_theme');
    $hide_zero_picks = get_field('hide_zero_picks');
    $links_behavior = get_field('links_behavior');
    $link_url_behavior = get_field('link_url_behavior');
    $internal_url = get_field('internal_url');
    $expand_button_background_color = get_field('expand_button_background_color');
    $expand_button_text_color = get_field('expand_button_text_color');
    
    // Get options page fields
    $picks_admin_url = get_field('av_picks_sticky_picks_admin_url', 'option');
    
    // Get custom links mapping if custom links behavior is selected
    $custom_links_map = array();
    if ($link_url_behavior === 'custom') {
        $custom_links = get_field('custom_links');
        if (is_array($custom_links) && !empty($custom_links)) {
            foreach ($custom_links as $custom_link) {
                if (!empty($custom_link['sport_name']) && !empty($custom_link['custom_url'])) {
                    // Use sport name as key (case-sensitive match)
                    $custom_links_map[$custom_link['sport_name']] = $custom_link['custom_url'];
                }
            }
        }
    }
    
    // Apply bar background color if set
    if (!empty($bar_background_color)) {
        $block_styles[] = 'background-color: '.$bar_background_color.';';
    }
    
    // Add sticky class if not disabled
    if (!$disable_sticky) {
        $block_classes[] = 'sticky_top';
    }
    
    // Add button theme class
    if (!empty($button_theme)) {
        $block_classes[] = 'button-theme-' . $button_theme;
    }
    
    // Get API data
    $api_data = null;
    $api_attributes = $block_av_picks_sticky->getApiAttributes();
    
    if (!empty($api_attributes['request'])) {
        $response = $rdgb->helpers->getApiRequest(
            $api_attributes['request'],
            $api_attributes['method'],
            $api_attributes['headers']
        );
        
        if ($response['http_code'] == 200) {
            $api_data = $rdgb->helpers->isJson($response['data']);
        } else {
            error_log(sprintf('%s / %s: API request failed with HTTP code %s', RDGBLOCKS_NAME, $block_name, $response['http_code']));
        }
    }
    
    $position_block = $rdgb->helpers->getBlocksSpaces(get_fields());
?>

<div id="rdg-sticky-picks-bar" class="<?php echo esc_attr(join(' ', $block_classes)); ?>" style="<?php echo $position_block . esc_attr(join(' ', $block_styles)); ?>">
    <div class="rdg-sticky-picks-close-btn"></div>
    <div class="container content grid-container">
        <div class="custom-header-sports-nav">
            <?php if ($api_data && is_array($api_data)): ?>
                <?php $count = 0; ?>
                <?php foreach ($api_data as $sport_key => $sport_data): ?>
                    <?php 
                        // Skip if sport_data is not an array or doesn't have required fields
                        if (!is_array($sport_data) || !isset($sport_data['pick_count'])) {
                            continue;
                        }
                        
                        $pick_count = intval($sport_data['pick_count']);
                        
                        // Hide zero picks if the field is enabled
                        if ($hide_zero_picks && $pick_count === 0) {
                            continue;
                        }
                        
                        $count++;
                        $league_ids = isset($sport_data['league_ids']) && is_array($sport_data['league_ids']) ? $sport_data['league_ids'] : [];
                        $league_id = !empty($league_ids) ? $league_ids[0] : '';
                        
                        // Use sport key as display name (exactly as it comes from API)
                        $sport_name = $sport_key;
                        $url_path = '/games/today/';
                        $backend_url = !empty($picks_admin_url) ? rtrim($picks_admin_url, '/') : '';

                        if (!empty($league_id)) {
                            $url_path .= $league_id;
                        }
                        
                        // Build URL based on link_url_behavior setting
                        if ($link_url_behavior === 'custom') {
                            // Check if custom URL exists for this sport
                            if (isset($custom_links_map[$sport_name]) && !empty($custom_links_map[$sport_name])) {
                                // Use custom URL
                                $url = $custom_links_map[$sport_name];
                            } else {
                                // Leave URL blank if no custom URL found - user must add one
                                $url = '';
                            }
                        } elseif ($link_url_behavior === 'frontend' && !empty($internal_url)) {
                            // Use the custom internal URL from the field
                            $url = $internal_url. '?external=' . $backend_url . $url_path;
                        } else {
                            // Backend behavior: use the original API-based URL logic                            
                            $url = $backend_url . $url_path;
                        }
                        
                        // Set target attribute based on links behavior
                        $target = ($links_behavior === 'blank') ? '_blank' : '_self';
                    ?>
                    <?php if ($count === 1) : ?>
                        <?php
                            $expand_button_styles = [];
                            if (!empty($expand_button_background_color)) {
                                $expand_button_styles[] = 'background-color: ' . esc_attr($expand_button_background_color) . ';';
                            }
                            if (!empty($expand_button_text_color)) {
                                $expand_button_styles[] = 'color: ' . esc_attr($expand_button_text_color) . ';';
                            }
                            $expand_button_style = !empty($expand_button_styles) ? ' style="' . implode(' ', $expand_button_styles) . '"' : '';
                        ?>
                        <div id="rdg-sticky-picks-expand-btn"<?php echo $expand_button_style; ?>>View More Picks</div>
                    <?php endif; ?>  
                    <a href="<?php echo esc_url($url); ?>" target="<?php echo esc_attr($target); ?>" class="custom-header-sport-btn <?php echo ($count === 1) ? 'first-btn' : ''; ?>" title="<?php echo esc_attr($sport_name); ?>">                            
                        <div class="custom-header-sport-info">
                            <span class="custom-header-sport-name"><?php echo esc_html($sport_name); ?></span>
                            <span class="custom-header-sport-picks"><?php echo esc_html($pick_count); ?> Picks</span>
                        </div>
                    </a>                      
                <?php endforeach; ?>
            <?php else: ?>
                <!-- No data available or API error -->
                <p>No picks data available at this time.</p>
            <?php endif; ?>
        </div>
    </div>
</div>
