<?php
// Detail View - For showing detailed reports of specific networks, positions, or content
$detail_type = isset($_GET['detail_type']) ? sanitize_text_field($_GET['detail_type']) : '';
$detail_item = isset($_GET['detail_item']) ? sanitize_text_field($_GET['detail_item']) : '';

if (empty($detail_item)) {
    echo '<div class="essb-chart-container">';
    echo '<div class="essb-chart-title">Error</div>';
    echo '<p>No detail item specified. <a href="' . essb_get_tab_url('dashboard', $period, $date_from, $date_to) . '" class="essb-link-btn">Return to dashboard</a></p>';
    echo '</div>';
    return;
}

// Get detailed data based on type
$detail_data = essb_get_detail_data($detail_type, $detail_item, $date_from, $date_to);

// Get filterable chart data
$filterable_chart_data = essb_get_filterable_chart_data($detail_type, $detail_item, $date_from, $date_to);

// Set title based on type
$title = '';
if ($detail_type == 'network') {
    $title = essb_stats_get_network_name($detail_item);
} elseif ($detail_type == 'position') {
    $title = ESSBSocialShareAnalyticsBackEnd::position_name($detail_item);
} elseif ($detail_type == 'content') {
    $title = get_the_title($detail_item) ?: 'Post #' . $detail_item;
}

// Prepare available options for dropdowns
$available_positions = array();
$available_networks = array();

if ($detail_type == 'network') {
    $available_positions = array_keys($detail_data['positions']);
} elseif ($detail_type == 'position') {
    $available_networks = array_keys($detail_data['networks']);
} elseif ($detail_type == 'content') {
    $available_positions = array_keys($detail_data['positions']);
    $available_networks = array_keys($detail_data['networks']);
}

// Prepare full chart data for JavaScript
$chart_data_json = json_encode($filterable_chart_data);
?>

<!-- Back Button -->
<div class="essb-filter-bar">
    <?php 
    $back_view = $detail_type;
    if ($detail_type == 'content') {
        $back_view = 'content';
    } elseif ($detail_type == 'network') {
        $back_view = 'networks';
    } elseif ($detail_type == 'position') {
        $back_view = 'positions';
    }
    ?>
    <a href="<?php echo essb_get_tab_url($back_view, $period, $date_from, $date_to); ?>" class="essb-link-btn">
        ← Back to <?php echo ucfirst($back_view); ?> report
    </a>
</div>

<!-- Detail Header with Chips -->
<div class="essb-chart-container">
    <div class="essb-detail-header">
        <div class="essb-detail-title">
            <?php echo esc_html($title); ?>
        </div>
        <div class="essb-detail-chips">
            <div class="essb-chip essb-chip-primary">
                Total: <?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($detail_data['total_clicks']); ?> clicks
            </div>
            <div class="essb-chip essb-chip-desktop">
                Desktop: <?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($detail_data['desktop_clicks']); ?>
            </div>
            <div class="essb-chip essb-chip-mobile">
                Mobile: <?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($detail_data['mobile_clicks']); ?>
            </div>
            <?php if ($detail_data['total_clicks'] > 0): ?>
            <div class="essb-chip essb-chip-percent">
                Desktop: <?php echo round($detail_data['desktop_percent'], 1); ?>% | Mobile: <?php echo round($detail_data['mobile_percent'], 1); ?>%
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Activity Trend Chart with Filters -->
<div class="essb-chart-container">
    <div class="essb-chart-title">
        Activity Trend (<?php echo date('M j, Y', strtotime($date_from)); ?> - <?php echo date('M j, Y', strtotime($date_to)); ?>)
        <div class="essb-chart-filters">
            <?php if ($detail_type == 'network'): ?>
            <select id="chart-device-filter" class="essb-filter-select">
                <option value="all">All Devices</option>
                <option value="desktop">Desktop Only</option>
                <option value="mobile">Mobile Only</option>
            </select>
            <select id="chart-position-filter" class="essb-filter-select">
                <option value="all">All Positions</option>
                <?php foreach ($available_positions as $pos): ?>
                <option value="<?php echo esc_attr($pos); ?>"><?php echo esc_html(ESSBSocialShareAnalyticsBackEnd::position_name($pos)); ?></option>
                <?php endforeach; ?>
            </select>
            <?php elseif ($detail_type == 'position'): ?>
            <select id="chart-device-filter" class="essb-filter-select">
                <option value="all">All Devices</option>
                <option value="desktop">Desktop Only</option>
                <option value="mobile">Mobile Only</option>
            </select>
            <select id="chart-network-filter" class="essb-filter-select">
                <option value="all">All Networks</option>
                <?php foreach ($available_networks as $net): ?>
                <option value="<?php echo esc_attr($net); ?>"><?php echo esc_html(essb_stats_get_network_name($net)); ?></option>
                <?php endforeach; ?>
            </select>
            <?php elseif ($detail_type == 'content'): ?>
            <select id="chart-device-filter" class="essb-filter-select">
                <option value="all">All Devices</option>
                <option value="desktop">Desktop Only</option>
                <option value="mobile">Mobile Only</option>
            </select>
            <select id="chart-position-filter" class="essb-filter-select">
                <option value="all">All Positions</option>
                <?php foreach ($available_positions as $pos): ?>
                <option value="<?php echo esc_attr($pos); ?>"><?php echo esc_html(ESSBSocialShareAnalyticsBackEnd::position_name($pos)); ?></option>
                <?php endforeach; ?>
            </select>
            <select id="chart-network-filter" class="essb-filter-select">
                <option value="all">All Networks</option>
                <?php foreach ($available_networks as $net): ?>
                <option value="<?php echo esc_attr($net); ?>"><?php echo esc_html(essb_stats_get_network_name($net)); ?></option>
                <?php endforeach; ?>
            </select>
            <?php endif; ?>
        </div>
    </div>
    
    <canvas id="detail-trend-chart" style="height: 400px; width: 100%;"></canvas>
</div>

<?php if ($detail_type == 'network'): ?>
    <!-- Network Detail - Show Position and Content Tables -->
    
    <!-- Performance by Position -->
    <div class="essb-chart-container">
        <div class="essb-chart-title">
            Performance by Position
            <div class="essb-table-controls">
                <input type="text" id="position-detail-search" class="essb-table-search" placeholder="Search positions...">
                <select id="position-detail-rows" class="essb-table-rows">
                    <option value="10">10 rows</option>
                    <option value="25" selected>25 rows</option>
                    <option value="50">50 rows</option>
                </select>
            </div>
        </div>
        
        <div class="essb-table-wrapper">
            <table class="essb-modern-table" id="position-detail-table">
                <thead>
                    <tr>
                        <th data-sort="name" class="sortable">Position <span class="sort-icon">↕</span></th>
                        <th data-sort="clicks" class="sortable">Clicks <span class="sort-icon">↕</span></th>
                        <th data-sort="desktop" class="sortable">Desktop <span class="sort-icon">↕</span></th>
                        <th data-sort="mobile" class="sortable">Mobile <span class="sort-icon">↕</span></th>
                        <th data-sort="percent" class="sortable">% of Total <span class="sort-icon">↕</span></th>
                    </thead>
                <tbody id="position-detail-body">
                    <?php 
                    $position_data = $detail_data['positions'] ?? array();
                    if (!empty($position_data) && is_array($position_data)):
                        foreach($position_data as $pos_name => $pos_data):
                            $percentage = $detail_data['total_clicks'] > 0 ? ($pos_data['clicks'] / $detail_data['total_clicks']) * 100 : 0;
                    ?>
                    <tr data-name="<?php echo esc_attr(strtolower(ESSBSocialShareAnalyticsBackEnd::position_name($pos_name))); ?>" 
                        data-clicks="<?php echo $pos_data['clicks']; ?>"
                        data-desktop="<?php echo $pos_data['desktop']; ?>"
                        data-mobile="<?php echo $pos_data['mobile']; ?>"
                        data-percent="<?php echo $percentage; ?>">
                        <td class="essb-table-position">
                            <span class="essb-chip essb-chip-small essb-chip-position"><?php echo esc_html(ESSBSocialShareAnalyticsBackEnd::position_name($pos_name)); ?></span>
                        </td>
                        <td class="essb-table-number"><strong><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($pos_data['clicks']); ?></strong></td>
                        <td class="essb-table-number"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($pos_data['desktop']); ?></td>
                        <td class="essb-table-number"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($pos_data['mobile']); ?></td>
                        <td class="essb-table-number">
                            <?php echo round($percentage, 1); ?>%
                            <div class="essb-progress-bar essb-progress-bar-small">
                                <div class="essb-progress-fill" style="width: <?php echo $percentage; ?>%"></div>
                            </div>
                        </td>
                    </tr>
                    <?php 
                        endforeach;
                    else:
                    ?>
                    <tr><td colspan="5" style="text-align: center; padding: 40px;">No position data available</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
            <div class="essb-table-footer">
                <div class="essb-table-info">Showing <span id="position-detail-start">0</span> to <span id="position-detail-end">0</span> of <span id="position-detail-total">0</span> entries</div>
                <div class="essb-table-pagination">
                    <button class="essb-pagination-btn" data-page="prev" data-table="position-detail" disabled>Previous</button>
                    <span class="essb-pagination-pages" data-table="position-detail"></span>
                    <button class="essb-pagination-btn" data-page="next" data-table="position-detail" disabled>Next</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Performance by Content -->
    <div class="essb-chart-container">
        <div class="essb-chart-title">
            Performance by Content
            <div class="essb-table-controls">
                <input type="text" id="content-detail-search" class="essb-table-search" placeholder="Search content...">
                <select id="content-detail-rows" class="essb-table-rows">
                    <option value="10">10 rows</option>
                    <option value="25" selected>25 rows</option>
                    <option value="50">50 rows</option>
                </select>
            </div>
        </div>
        
        <div class="essb-table-wrapper">
            <table class="essb-modern-table" id="content-detail-table">
                <thead>
                    <tr>
                        <th data-sort="title" class="sortable">Post/Page <span class="sort-icon">↕</span></th>
                        <th data-sort="clicks" class="sortable">Clicks <span class="sort-icon">↕</span></th>
                        <th data-sort="desktop" class="sortable">Desktop <span class="sort-icon">↕</span></th>
                        <th data-sort="mobile" class="sortable">Mobile <span class="sort-icon">↕</span></th>
                        <th data-sort="percent" class="sortable">% of Total <span class="sort-icon">↕</span></th>
                    </thead>
                <tbody id="content-detail-body">
                    <?php 
                    $content_data = $detail_data['content'] ?? array();
                    if (!empty($content_data) && is_array($content_data)):
                        foreach($content_data as $content):
                            $percentage = $detail_data['total_clicks'] > 0 ? ($content['clicks'] / $detail_data['total_clicks']) * 100 : 0;
                            $title = get_the_title($content['post_id']) ?: 'Untitled';
                            $permalink = get_permalink($content['post_id']);
                    ?>
                    <tr data-title="<?php echo esc_attr(strtolower($title)); ?>" 
                        data-clicks="<?php echo $content['clicks']; ?>"
                        data-desktop="<?php echo $content['desktop']; ?>"
                        data-mobile="<?php echo $content['mobile']; ?>"
                        data-percent="<?php echo $percentage; ?>">
                        <td class="essb-table-post"><a href="<?php echo $permalink; ?>" target="_blank"><?php echo esc_html(substr($title, 0, 60)); ?></a></td>
                        <td class="essb-table-number"><strong><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($content['clicks']); ?></strong></td>
                        <td class="essb-table-number"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($content['desktop']); ?></td>
                        <td class="essb-table-number"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($content['mobile']); ?></td>
                        <td class="essb-table-number">
                            <?php echo round($percentage, 1); ?>%
                            <div class="essb-progress-bar essb-progress-bar-small">
                                <div class="essb-progress-fill" style="width: <?php echo $percentage; ?>%"></div>
                            </div>
                        </td>
                    </tr>
                    <?php 
                        endforeach;
                    else:
                    ?>
                    <tr><td colspan="5" style="text-align: center; padding: 40px;">No content data available</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
            <div class="essb-table-footer">
                <div class="essb-table-info">Showing <span id="content-detail-start">0</span> to <span id="content-detail-end">0</span> of <span id="content-detail-total">0</span> entries</div>
                <div class="essb-table-pagination">
                    <button class="essb-pagination-btn" data-page="prev" data-table="content-detail" disabled>Previous</button>
                    <span class="essb-pagination-pages" data-table="content-detail"></span>
                    <button class="essb-pagination-btn" data-page="next" data-table="content-detail" disabled>Next</button>
                </div>
            </div>
        </div>
    </div>

<?php elseif ($detail_type == 'position'): ?>
    <!-- Position Detail - Show Network and Content Tables -->
    
    <!-- Performance by Network -->
    <div class="essb-chart-container">
        <div class="essb-chart-title">
            Performance by Network
            <div class="essb-table-controls">
                <input type="text" id="network-detail-search" class="essb-table-search" placeholder="Search networks...">
                <select id="network-detail-rows" class="essb-table-rows">
                    <option value="10">10 rows</option>
                    <option value="25" selected>25 rows</option>
                    <option value="50">50 rows</option>
                </select>
            </div>
        </div>
        
        <div class="essb-table-wrapper">
            <table class="essb-modern-table" id="network-detail-table">
                <thead>
                    <tr>
                        <th data-sort="name" class="sortable">Network <span class="sort-icon">↕</span></th>
                        <th data-sort="clicks" class="sortable">Clicks <span class="sort-icon">↕</span></th>
                        <th data-sort="desktop" class="sortable">Desktop <span class="sort-icon">↕</span></th>
                        <th data-sort="mobile" class="sortable">Mobile <span class="sort-icon">↕</span></th>
                        <th data-sort="percent" class="sortable">% of Total <span class="sort-icon">↕</span></th>
                    </thead>
                <tbody id="network-detail-body">
                    <?php 
                    $network_data = $detail_data['networks'] ?? array();
                    if (!empty($network_data) && is_array($network_data)):
                        foreach($network_data as $net_name => $net_data):
                            $percentage = $detail_data['total_clicks'] > 0 ? ($net_data['clicks'] / $detail_data['total_clicks']) * 100 : 0;
                    ?>
                    <tr data-name="<?php echo esc_attr(strtolower($net_name)); ?>" 
                        data-clicks="<?php echo $net_data['clicks']; ?>"
                        data-desktop="<?php echo $net_data['desktop']; ?>"
                        data-mobile="<?php echo $net_data['mobile']; ?>"
                        data-percent="<?php echo $percentage; ?>">
                        <td class="essb-table-network"><span class="essb-chip essb-chip-small essb-chip-network"><?php echo essb_stats_get_network_name($net_name); ?></span></td>
                        <td class="essb-table-number"><strong><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($net_data['clicks']); ?></strong></td>
                        <td class="essb-table-number"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($net_data['desktop']); ?></td>
                        <td class="essb-table-number"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($net_data['mobile']); ?></td>
                        <td class="essb-table-number">
                            <?php echo round($percentage, 1); ?>%
                            <div class="essb-progress-bar essb-progress-bar-small">
                                <div class="essb-progress-fill" style="width: <?php echo $percentage; ?>%"></div>
                            </div>
                        </td>
                    </tr>
                    <?php 
                        endforeach;
                    else:
                    ?>
                    <tr><td colspan="5" style="text-align: center; padding: 40px;">No network data available</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
            <div class="essb-table-footer">
                <div class="essb-table-info">Showing <span id="network-detail-start">0</span> to <span id="network-detail-end">0</span> of <span id="network-detail-total">0</span> entries</div>
                <div class="essb-table-pagination">
                    <button class="essb-pagination-btn" data-page="prev" data-table="network-detail" disabled>Previous</button>
                    <span class="essb-pagination-pages" data-table="network-detail"></span>
                    <button class="essb-pagination-btn" data-page="next" data-table="network-detail" disabled>Next</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Performance by Content -->
    <div class="essb-chart-container">
        <div class="essb-chart-title">
            Performance by Content
            <div class="essb-table-controls">
                <input type="text" id="content-detail-search" class="essb-table-search" placeholder="Search content...">
                <select id="content-detail-rows" class="essb-table-rows">
                    <option value="10">10 rows</option>
                    <option value="25" selected>25 rows</option>
                    <option value="50">50 rows</option>
                </select>
            </div>
        </div>
        
        <div class="essb-table-wrapper">
            <table class="essb-modern-table" id="content-detail-table">
                <thead>
                    <tr>
                        <th data-sort="title" class="sortable">Post/Page <span class="sort-icon">↕</span></th>
                        <th data-sort="clicks" class="sortable">Clicks <span class="sort-icon">↕</span></th>
                        <th data-sort="desktop" class="sortable">Desktop <span class="sort-icon">↕</span></th>
                        <th data-sort="mobile" class="sortable">Mobile <span class="sort-icon">↕</span></th>
                        <th data-sort="percent" class="sortable">% of Total <span class="sort-icon">↕</span></th>
                    </thead>
                <tbody id="content-detail-body">
                    <?php 
                    $content_data = $detail_data['content'] ?? array();
                    if (!empty($content_data) && is_array($content_data)):
                        foreach($content_data as $content):
                            $percentage = $detail_data['total_clicks'] > 0 ? ($content['clicks'] / $detail_data['total_clicks']) * 100 : 0;
                            $title = get_the_title($content['post_id']) ?: 'Untitled';
                            $permalink = get_permalink($content['post_id']);
                    ?>
                    <tr data-title="<?php echo esc_attr(strtolower($title)); ?>" 
                        data-clicks="<?php echo $content['clicks']; ?>"
                        data-desktop="<?php echo $content['desktop']; ?>"
                        data-mobile="<?php echo $content['mobile']; ?>"
                        data-percent="<?php echo $percentage; ?>">
                        <td class="essb-table-post"><a href="<?php echo $permalink; ?>" target="_blank"><?php echo esc_html(substr($title, 0, 60)); ?></a></td>
                        <td class="essb-table-number"><strong><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($content['clicks']); ?></strong></td>
                        <td class="essb-table-number"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($content['desktop']); ?></td>
                        <td class="essb-table-number"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($content['mobile']); ?></td>
                        <td class="essb-table-number">
                            <?php echo round($percentage, 1); ?>%
                            <div class="essb-progress-bar essb-progress-bar-small">
                                <div class="essb-progress-fill" style="width: <?php echo $percentage; ?>%"></div>
                            </div>
                        </td>
                    </tr>
                    <?php 
                        endforeach;
                    else:
                    ?>
                    <tr><td colspan="5" style="text-align: center; padding: 40px;">No content data available</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
            <div class="essb-table-footer">
                <div class="essb-table-info">Showing <span id="content-detail-start">0</span> to <span id="content-detail-end">0</span> of <span id="content-detail-total">0</span> entries</div>
                <div class="essb-table-pagination">
                    <button class="essb-pagination-btn" data-page="prev" data-table="content-detail" disabled>Previous</button>
                    <span class="essb-pagination-pages" data-table="content-detail"></span>
                    <button class="essb-pagination-btn" data-page="next" data-table="content-detail" disabled>Next</button>
                </div>
            </div>
        </div>
    </div>

<?php elseif ($detail_type == 'content'): ?>
    <!-- Content Detail - Show Network and Position Tables -->
    
    <!-- Performance by Network -->
    <div class="essb-chart-container">
        <div class="essb-chart-title">
            Performance by Network
            <div class="essb-table-controls">
                <input type="text" id="network-detail-search" class="essb-table-search" placeholder="Search networks...">
                <select id="network-detail-rows" class="essb-table-rows">
                    <option value="10">10 rows</option>
                    <option value="25" selected>25 rows</option>
                    <option value="50">50 rows</option>
                </select>
            </div>
        </div>
        
        <div class="essb-table-wrapper">
            <table class="essb-modern-table" id="network-detail-table">
                <thead>
                    <tr>
                        <th data-sort="name" class="sortable">Network <span class="sort-icon">↕</span></th>
                        <th data-sort="clicks" class="sortable">Clicks <span class="sort-icon">↕</span></th>
                        <th data-sort="desktop" class="sortable">Desktop <span class="sort-icon">↕</span></th>
                        <th data-sort="mobile" class="sortable">Mobile <span class="sort-icon">↕</span></th>
                        <th data-sort="percent" class="sortable">% of Total <span class="sort-icon">↕</span></th>
                    </thead>
                <tbody id="network-detail-body">
                    <?php 
                    $network_data = $detail_data['networks'] ?? array();
                    if (!empty($network_data) && is_array($network_data)):
                        foreach($network_data as $net_name => $net_data):
                            $percentage = $detail_data['total_clicks'] > 0 ? ($net_data['clicks'] / $detail_data['total_clicks']) * 100 : 0;
                    ?>
                    <tr data-name="<?php echo esc_attr(strtolower($net_name)); ?>" 
                        data-clicks="<?php echo $net_data['clicks']; ?>"
                        data-desktop="<?php echo $net_data['desktop']; ?>"
                        data-mobile="<?php echo $net_data['mobile']; ?>"
                        data-percent="<?php echo $percentage; ?>">
                        <td class="essb-table-network"><span class="essb-chip essb-chip-small essb-chip-network"><?php echo essb_stats_get_network_name($net_name); ?></span></td>
                        <td class="essb-table-number"><strong><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($net_data['clicks']); ?></strong></td>
                        <td class="essb-table-number"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($net_data['desktop']); ?></td>
                        <td class="essb-table-number"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($net_data['mobile']); ?></td>
                        <td class="essb-table-number">
                            <?php echo round($percentage, 1); ?>%
                            <div class="essb-progress-bar essb-progress-bar-small">
                                <div class="essb-progress-fill" style="width: <?php echo $percentage; ?>%"></div>
                            </div>
                        </td>
                    </tr>
                    <?php 
                        endforeach;
                    else:
                    ?>
                    <tr><td colspan="5" style="text-align: center; padding: 40px;">No network data available</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
            <div class="essb-table-footer">
                <div class="essb-table-info">Showing <span id="network-detail-start">0</span> to <span id="network-detail-end">0</span> of <span id="network-detail-total">0</span> entries</div>
                <div class="essb-table-pagination">
                    <button class="essb-pagination-btn" data-page="prev" data-table="network-detail" disabled>Previous</button>
                    <span class="essb-pagination-pages" data-table="network-detail"></span>
                    <button class="essb-pagination-btn" data-page="next" data-table="network-detail" disabled>Next</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Performance by Position -->
    <div class="essb-chart-container">
        <div class="essb-chart-title">
            Performance by Position
            <div class="essb-table-controls">
                <input type="text" id="position-detail-search" class="essb-table-search" placeholder="Search positions...">
                <select id="position-detail-rows" class="essb-table-rows">
                    <option value="10">10 rows</option>
                    <option value="25" selected>25 rows</option>
                    <option value="50">50 rows</option>
                </select>
            </div>
        </div>
        
        <div class="essb-table-wrapper">
            <table class="essb-modern-table" id="position-detail-table">
                <thead>
                    <tr>
                        <th data-sort="name" class="sortable">Position <span class="sort-icon">↕</span></th>
                        <th data-sort="clicks" class="sortable">Clicks <span class="sort-icon">↕</span></th>
                        <th data-sort="desktop" class="sortable">Desktop <span class="sort-icon">↕</span></th>
                        <th data-sort="mobile" class="sortable">Mobile <span class="sort-icon">↕</span></th>
                        <th data-sort="percent" class="sortable">% of Total <span class="sort-icon">↕</span></th>
                    </thead>
                <tbody id="position-detail-body">
                    <?php 
                    $position_data = $detail_data['positions'] ?? array();
                    if (!empty($position_data) && is_array($position_data)):
                        foreach($position_data as $pos_name => $pos_data):
                            $percentage = $detail_data['total_clicks'] > 0 ? ($pos_data['clicks'] / $detail_data['total_clicks']) * 100 : 0;
                    ?>
                    <tr data-name="<?php echo esc_attr(strtolower(ESSBSocialShareAnalyticsBackEnd::position_name($pos_name))); ?>" 
                        data-clicks="<?php echo $pos_data['clicks']; ?>"
                        data-desktop="<?php echo $pos_data['desktop']; ?>"
                        data-mobile="<?php echo $pos_data['mobile']; ?>"
                        data-percent="<?php echo $percentage; ?>">
                        <td class="essb-table-position">
                            <span class="essb-chip essb-chip-small essb-chip-position"><?php echo esc_html(ESSBSocialShareAnalyticsBackEnd::position_name($pos_name)); ?></span>
                        </td>
                        <td class="essb-table-number"><strong><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($pos_data['clicks']); ?></strong></td>
                        <td class="essb-table-number"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($pos_data['desktop']); ?></td>
                        <td class="essb-table-number"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($pos_data['mobile']); ?></td>
                        <td class="essb-table-number">
                            <?php echo round($percentage, 1); ?>%
                            <div class="essb-progress-bar essb-progress-bar-small">
                                <div class="essb-progress-fill" style="width: <?php echo $percentage; ?>%"></div>
                            </div>
                        </td>
                    </tr>
                    <?php 
                        endforeach;
                    else:
                    ?>
                    <tr><td colspan="5" style="text-align: center; padding: 40px;">No position data available</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
            <div class="essb-table-footer">
                <div class="essb-table-info">Showing <span id="position-detail-start">0</span> to <span id="position-detail-end">0</span> of <span id="position-detail-total">0</span> entries</div>
                <div class="essb-table-pagination">
                    <button class="essb-pagination-btn" data-page="prev" data-table="position-detail" disabled>Previous</button>
                    <span class="essb-pagination-pages" data-table="position-detail"></span>
                    <button class="essb-pagination-btn" data-page="next" data-table="position-detail" disabled>Next</button>
                </div>
            </div>
        </div>
    </div>

<?php endif; ?>

<style>
.essb-chart-filters {
    display: flex;
    gap: 12px;
    align-items: center;
}

.essb-chart-filters .essb-filter-select {
    padding: 6px 12px;
    font-size: 12px;
    min-width: 130px;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    background: white;
    cursor: pointer;
}

.essb-chart-filters .essb-filter-select:focus {
    outline: none;
    border-color: #3b82f6;
}

@media (max-width: 768px) {
    .essb-chart-title {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
    }
    
    .essb-chart-filters {
        width: 100%;
        flex-wrap: wrap;
    }
    
    .essb-chart-filters .essb-filter-select {
        flex: 1;
        min-width: auto;
    }
}
</style>

<script type="text/javascript">
jQuery(document).ready(function($) {
    // Aggressively prevent form submission from filter dropdowns
    $('.essb-filter-select').each(function() {
        $(this).off('change').on('change', function(e) {
            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();
            
            // Update the chart
            createOrUpdateChart();
            
            return false;
        });
    });
    
    // Prevent the parent form from submitting when dropdowns change
    var $parentForm = $('.essb-filter-select').closest('form');
    if ($parentForm.length) {
        $parentForm.off('submit').on('submit', function(e) {
            // Check if the event target is a filter select
            if ($(e.target).hasClass('essb-filter-select') || $(e.target).closest('.essb-filter-select').length) {
                e.preventDefault();
                e.stopPropagation();
                return false;
            }
            return true;
        });
    }
    
    // Also prevent any click events on dropdowns from bubbling
    $('.essb-filter-select').on('mousedown click', function(e) {
        e.stopPropagation();
    });
    
    // Full chart data from PHP
    var fullChartData = <?php echo $chart_data_json; ?>;
    var chartLabels = [];
    
    // Extract labels from the data
    if (fullChartData.length > 0) {
        chartLabels = fullChartData.map(function(item) { return item.period; });
    }
    
    var chartInstance = null;
    var ctx = document.getElementById('detail-trend-chart').getContext('2d');
    
    function formatNumber(num) {
        if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
        if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
        return num.toString();
    }
    
    function getChartLabel() {
        <?php if ($detail_type == 'network'): ?>
        var device = $('#chart-device-filter').val();
        var position = $('#chart-position-filter').val();
        if (device !== 'all' && position !== 'all') {
            return device.charAt(0).toUpperCase() + device.slice(1) + ' Clicks - ' + $('#chart-position-filter option:selected').text();
        } else if (device !== 'all') {
            return device.charAt(0).toUpperCase() + device.slice(1) + ' Clicks';
        } else if (position !== 'all') {
            return 'Clicks - ' + $('#chart-position-filter option:selected').text();
        }
        return 'Clicks';
        <?php elseif ($detail_type == 'position'): ?>
        var device = $('#chart-device-filter').val();
        var network = $('#chart-network-filter').val();
        if (device !== 'all' && network !== 'all') {
            return device.charAt(0).toUpperCase() + device.slice(1) + ' Clicks - ' + $('#chart-network-filter option:selected').text();
        } else if (device !== 'all') {
            return device.charAt(0).toUpperCase() + device.slice(1) + ' Clicks';
        } else if (network !== 'all') {
            return 'Clicks - ' + $('#chart-network-filter option:selected').text();
        }
        return 'Clicks';
        <?php elseif ($detail_type == 'content'): ?>
        var device = $('#chart-device-filter').val();
        var position = $('#chart-position-filter').val();
        var network = $('#chart-network-filter').val();
        var parts = [];
        if (device !== 'all') parts.push(device.charAt(0).toUpperCase() + device.slice(1) + ' Clicks');
        else parts.push('Clicks');
        if (position !== 'all') parts.push($('#chart-position-filter option:selected').text());
        if (network !== 'all') parts.push($('#chart-network-filter option:selected').text());
        return parts.join(' - ');
        <?php else: ?>
        return 'Clicks';
        <?php endif; ?>
    }
    
    function getFilteredData() {
        <?php if ($detail_type == 'network'): ?>
        var device = $('#chart-device-filter').val();
        var position = $('#chart-position-filter').val();
        
        if (device === 'all' && position === 'all') {
            return fullChartData.map(function(item) { return item.clicks; });
        }
        
        return fullChartData.map(function(item) {
            var value = 0;
            if (position === 'all') {
                for (var pos in item.positions) {
                    if (device === 'all') {
                        value += item.positions[pos].clicks;
                    } else if (device === 'desktop') {
                        value += item.positions[pos].desktop;
                    } else if (device === 'mobile') {
                        value += item.positions[pos].mobile;
                    }
                }
            } else {
                if (item.positions && item.positions[position]) {
                    if (device === 'all') {
                        value = item.positions[position].clicks;
                    } else if (device === 'desktop') {
                        value = item.positions[position].desktop;
                    } else if (device === 'mobile') {
                        value = item.positions[position].mobile;
                    }
                }
            }
            return value;
        });
        <?php elseif ($detail_type == 'position'): ?>
        var device = $('#chart-device-filter').val();
        var network = $('#chart-network-filter').val();
        
        if (device === 'all' && network === 'all') {
            return fullChartData.map(function(item) { return item.clicks; });
        }
        
        return fullChartData.map(function(item) {
            var value = 0;
            if (network === 'all') {
                for (var net in item.networks) {
                    if (device === 'all') {
                        value += item.networks[net].clicks;
                    } else if (device === 'desktop') {
                        value += item.networks[net].desktop;
                    } else if (device === 'mobile') {
                        value += item.networks[net].mobile;
                    }
                }
            } else {
                if (item.networks && item.networks[network]) {
                    if (device === 'all') {
                        value = item.networks[network].clicks;
                    } else if (device === 'desktop') {
                        value = item.networks[network].desktop;
                    } else if (device === 'mobile') {
                        value = item.networks[network].mobile;
                    }
                }
            }
            return value;
        });
        <?php elseif ($detail_type == 'content'): ?>
        var device = $('#chart-device-filter').val();
        var position = $('#chart-position-filter').val();
        var network = $('#chart-network-filter').val();
        
        if (device === 'all' && position === 'all' && network === 'all') {
            return fullChartData.map(function(item) { return item.clicks; });
        }
        
        return fullChartData.map(function(item) {
            var value = 0;
            
            if (network !== 'all') {
                if (item.networks && item.networks[network]) {
                    if (device === 'all') {
                        value = item.networks[network].clicks;
                    } else if (device === 'desktop') {
                        value = item.networks[network].desktop;
                    } else if (device === 'mobile') {
                        value = item.networks[network].mobile;
                    }
                }
            } else if (position !== 'all') {
                if (item.positions && item.positions[position]) {
                    if (device === 'all') {
                        value = item.positions[position].clicks;
                    } else if (device === 'desktop') {
                        value = item.positions[position].desktop;
                    } else if (device === 'mobile') {
                        value = item.positions[position].mobile;
                    }
                }
            } else {
                if (device === 'all') {
                    value = item.clicks;
                } else if (device === 'desktop') {
                    value = item.desktop_clicks;
                } else if (device === 'mobile') {
                    value = item.mobile_clicks;
                }
            }
            return value;
        });
        <?php endif; ?>
    }
    
    function createOrUpdateChart() {
        var chartData = getFilteredData();
        
        var gradient = ctx.createLinearGradient(0, 0, 0, 400);
        gradient.addColorStop(0, 'rgba(59, 130, 246, 0.3)');
        gradient.addColorStop(1, 'rgba(59, 130, 246, 0.02)');
        
        if (chartInstance) {
            chartInstance.data.datasets[0].data = chartData;
            chartInstance.data.datasets[0].label = getChartLabel();
            chartInstance.update();
        } else {
            chartInstance = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: chartLabels,
                    datasets: [{
                        label: getChartLabel(),
                        data: chartData,
                        borderColor: '#3b82f6',
                        backgroundColor: gradient,
                        borderWidth: 3,
                        pointRadius: 4,
                        pointHoverRadius: 6,
                        pointBackgroundColor: '#3b82f6',
                        pointBorderColor: '#ffffff',
                        pointBorderWidth: 2,
                        tension: 0.4,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top',
                            labels: {
                                usePointStyle: true,
                                boxWidth: 8,
                                font: { size: 12 }
                            }
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            callbacks: {
                                label: function(context) {
                                    return context.dataset.label + ': ' + formatNumber(context.parsed.y);
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: { color: '#e2e8f0' },
                            ticks: {
                                callback: function(value) {
                                    return formatNumber(value);
                                }
                            }
                        },
                        x: {
                            grid: { display: false },
                            ticks: { maxRotation: 45, minRotation: 45, autoSkip: true, maxTicksLimit: 15 }
                        }
                    }
                }
            });
        }
    }
    
    // Load Chart.js and initialize
    function initChart() {
        if (typeof Chart === 'undefined') {
            var script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js';
            script.onload = function() {
                createOrUpdateChart();
            };
            document.head.appendChild(script);
        } else {
            createOrUpdateChart();
        }
    }
    
    // Initialize chart
    initChart();
    
    // Initialize tables function
    function initDetailTable(tableId) {
        var $table = $('#' + tableId + '-table');
        if (!$table.length) return;
        
        var $tbody = $('#' + tableId + '-body');
        var $rows = $tbody.find('tr');
        if ($rows.length === 0 || ($rows.length === 1 && $rows.find('td[colspan]').length)) return;
        
        var $searchInput = $('#' + tableId + '-search');
        var $rowsSelect = $('#' + tableId + '-rows');
        var $infoStart = $('#' + tableId + '-start');
        var $infoEnd = $('#' + tableId + '-end');
        var $infoTotal = $('#' + tableId + '-total');
        var $prevBtn = $('.essb-pagination-btn[data-table="' + tableId + '"][data-page="prev"]');
        var $nextBtn = $('.essb-pagination-btn[data-table="' + tableId + '"][data-page="next"]');
        var $pagesContainer = $('.essb-pagination-pages[data-table="' + tableId + '"]');
        
        var currentPage = 1;
        var rowsPerPage = 25;
        var filteredRows = $rows.toArray();
        var currentSort = { column: 'clicks', direction: 'desc' };
        
        function sortRows(rows, column, direction) {
            return rows.sort(function(a, b) {
                var aVal, bVal;
                
                if (column === 'name' || column === 'title') {
                    aVal = $(a).data('name') || $(a).data('title') || '';
                    bVal = $(b).data('name') || $(b).data('title') || '';
                    aVal = aVal.toLowerCase();
                    bVal = bVal.toLowerCase();
                } else if (column === 'clicks') {
                    aVal = parseFloat($(a).data('clicks')) || 0;
                    bVal = parseFloat($(b).data('clicks')) || 0;
                } else if (column === 'desktop') {
                    aVal = parseFloat($(a).data('desktop')) || 0;
                    bVal = parseFloat($(b).data('desktop')) || 0;
                } else if (column === 'mobile') {
                    aVal = parseFloat($(a).data('mobile')) || 0;
                    bVal = parseFloat($(b).data('mobile')) || 0;
                } else if (column === 'percent') {
                    aVal = parseFloat($(a).data('percent')) || 0;
                    bVal = parseFloat($(b).data('percent')) || 0;
                } else {
                    return 0;
                }
                
                if (direction === 'asc') {
                    return aVal > bVal ? 1 : -1;
                } else {
                    return aVal < bVal ? 1 : -1;
                }
            });
        }
        
        function filterRows(rows, searchTerm) {
            if (!searchTerm) return rows;
            return rows.filter(function(row) {
                var name = $(row).data('name') || $(row).data('title') || '';
                return name.indexOf(searchTerm.toLowerCase()) > -1;
            });
        }
        
        function renderTable() {
            var filtered = filterRows($rows.toArray(), $searchInput.val());
            var sorted = sortRows(filtered, currentSort.column, currentSort.direction);
            var totalRows = sorted.length;
            var totalPages = Math.ceil(totalRows / rowsPerPage);
            
            if (currentPage > totalPages) currentPage = totalPages || 1;
            var start = (currentPage - 1) * rowsPerPage;
            var end = Math.min(start + rowsPerPage, totalRows);
            var pageData = sorted.slice(start, end);
            
            $tbody.empty();
            for (var i = 0; i < pageData.length; i++) {
                $tbody.append(pageData[i]);
            }
            
            $infoStart.text(totalRows > 0 ? start + 1 : 0);
            $infoEnd.text(end);
            $infoTotal.text(totalRows);
            
            $prevBtn.prop('disabled', currentPage === 1);
            $nextBtn.prop('disabled', currentPage === totalPages || totalPages === 0);
            
            $pagesContainer.empty();
            if (totalPages > 0) {
                var maxPages = Math.min(totalPages, 5);
                var startPage = Math.max(1, currentPage - 2);
                var endPage = Math.min(totalPages, startPage + maxPages - 1);
                
                for (var p = startPage; p <= endPage; p++) {
                    var $pageBtn = $('<button>').addClass('essb-page-btn').text(p);
                    if (p === currentPage) $pageBtn.addClass('active');
                    $pageBtn.on('click', function() {
                        currentPage = parseInt($(this).text());
                        renderTable();
                    });
                    $pagesContainer.append($pageBtn);
                }
            }
        }
        
        $searchInput.on('keyup', function() {
            currentPage = 1;
            renderTable();
        });
        
        $rowsSelect.on('change', function() {
            rowsPerPage = parseInt($(this).val());
            currentPage = 1;
            renderTable();
        });
        
        $table.find('th.sortable').on('click', function() {
            var $th = $(this);
            var column = $th.data('sort');
            var sortIcon = $th.find('.sort-icon');
            
            if (currentSort.column === column) {
                currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
            } else {
                currentSort.column = column;
                currentSort.direction = 'desc';
            }
            
            $table.find('th .sort-icon').text('↕');
            sortIcon.text(currentSort.direction === 'asc' ? '↑' : '↓');
            currentPage = 1;
            renderTable();
        });
        
        $prevBtn.on('click', function() {
            if (currentPage > 1) {
                currentPage--;
                renderTable();
            }
        });
        
        $nextBtn.on('click', function() {
            var totalPages = Math.ceil(filterRows($rows.toArray(), $searchInput.val()).length / rowsPerPage);
            if (currentPage < totalPages) {
                currentPage++;
                renderTable();
            }
        });
        
        renderTable();
    }
    
    // Initialize all tables
    initDetailTable('position-detail');
    initDetailTable('content-detail');
    initDetailTable('network-detail');
});
</script>