<?php
/**
 * ESSB Analytics - Redesigned Trends View
 * Replaces the original trends view with a priority-first, action-oriented layout.
 *
 * Expected variables in scope:
 *   $date_from  (string) e.g. '2026-03-01'
 *   $date_to    (string) e.g. '2026-03-31'
 *   $period     (string) e.g. '30days'
 */

$trends_analysis  = essb_analyze_trends( $date_from, $date_to, $period );
$recommendations  = essb_generate_recommendations( $trends_analysis );

// ── Helpers ──────────────────────────────────────────────────────────────────

/**
 * Return the signed-percentage string with a + or − prefix.
 */
function essb_fmt_delta( $change ) {
    if ( $change > 0 ) {
        return '+' . $change . '%';
    } elseif ( $change < 0 ) {
        return '−' . abs( $change ) . '%';
    }
    return '0%';
}

/**
 * Classify a numeric change into 'up' | 'down' | 'flat'.
 */
function essb_delta_dir( $change ) {
    if ( $change > 3 )  return 'up';
    if ( $change < -3 ) return 'down';
    return 'flat';
}

/**
 * Return the CSS modifier class for action banners based on priority.
 */
function essb_banner_class( $priority ) {
    $map = [
        'high'   => '',               // default red
        'medium' => 'tr-action-medium',
        'low'    => 'tr-action-ok',
    ];
    return isset( $map[ $priority ] ) ? $map[ $priority ] : '';
}

/**
 * Return the banner label text.
 */
function essb_banner_label( $priority ) {
    $map = [
        'high'   => 'Action required &middot; High priority',
        'medium' => 'Watch &middot; Medium priority',
        'low'    => 'All good &middot; No action needed',
    ];
    return isset( $map[ $priority ] ) ? $map[ $priority ] : 'Info';
}

/**
 * Convert a recommendation type string to a verdict CSS modifier.
 */
function essb_verdict_class( $type ) {
    $type = strtolower( $type );
    if ( in_array( $type, [ 'alert', 'warning' ] ) )           return 'tr-verdict-type-alert';
    if ( in_array( $type, [ 'opportunity', 'hot spot' ] ) )     return 'tr-verdict-type-opp';
    return 'tr-verdict-type-info';
}

// ── Derived data ──────────────────────────────────────────────────────────────

// Scorecard: top & bottom network
$top_network       = ! empty( $trends_analysis['network_trends'] ) ? $trends_analysis['network_trends'][0] : null;
$watch_network     = null;
if ( ! empty( $trends_analysis['network_trends'] ) ) {
    foreach ( $trends_analysis['network_trends'] as $nt ) {
        if ( $nt['change'] < -5 ) { $watch_network = $nt; break; }
    }
    if ( ! $watch_network ) {
        $last = end( $trends_analysis['network_trends'] );
        if ( $last['change'] <= 0 ) $watch_network = $last;
    }
}

// Hot position
$hot_position = ! empty( $trends_analysis['position_trends'] ) ? $trends_analysis['position_trends'][0] : null;

// Total clicks (sum current period across all networks)
$total_clicks = 0;
if ( ! empty( $trends_analysis['network_trends'] ) ) {
    foreach ( $trends_analysis['network_trends'] as $nt ) {
        $total_clicks += $nt['current'];
    }
}
$prev_total = 0;
if ( ! empty( $trends_analysis['network_trends'] ) ) {
    foreach ( $trends_analysis['network_trends'] as $nt ) {
        $prev_total += $nt['previous'];
    }
}
$total_delta = $prev_total > 0 ? round( ( ( $total_clicks - $prev_total ) / $prev_total ) * 100, 1 ) : 0;

// Mobile split (pulled from desktop/mobile order proxy — approximate)
// Use network performance by device if available
$mobile_pct   = 0;
$mobile_delta = 0;
$device_data  = essb_get_network_performance_by_device( $date_from, $date_to );
if ( ! empty( $device_data ) ) {
    $d_total = 0; $m_total = 0;
    foreach ( $device_data as $d ) {
        $d_total += intval( $d->desktop_clicks );
        $m_total += intval( $d->mobile_clicks );
    }
    $all = $d_total + $m_total;
    $mobile_pct = $all > 0 ? round( ( $m_total / $all ) * 100 ) : 0;
}

// Max current clicks for relative bar widths
$max_clicks = 0;
if ( ! empty( $trends_analysis['network_trends'] ) ) {
    foreach ( $trends_analysis['network_trends'] as $nt ) {
        $max_clicks = max( $max_clicks, $nt['current'], $nt['previous'] );
    }
}
$max_clicks = max( $max_clicks, 1 );

// Desktop & mobile network order
$desktop_order = isset( $trends_analysis['desktop_network_order'] ) ? array_slice( $trends_analysis['desktop_network_order'], 0, 5 ) : [];
$mobile_order  = isset( $trends_analysis['mobile_network_order']  ) ? array_slice( $trends_analysis['mobile_network_order'],  0, 5 ) : [];

// Pre-build action banners from recommendations.
// 'subject' is now provided directly by essb_generate_recommendations() so the label
// line reads e.g. "Action required · Facebook" or "Watch · Inline Top".
$action_banners = [];
if ( ! empty( $recommendations ) ) {
    foreach ( $recommendations as $rec ) {
        $type_lc  = strtolower( $rec['type'] );
        $priority = 'low';
        if ( in_array( $type_lc, [ 'alert' ] ) ) {
            $priority = 'high';
        } elseif ( in_array( $type_lc, [ 'warning', 'opportunity', 'hot spot', 'mobile optimization', 'desktop optimization', 'mobile order', 'order optimization', 'cleanup' ] ) ) {
            $priority = 'medium';
        }

        $action_banners[] = [
            'priority' => $priority,
            'subject'  => isset( $rec['subject'] ) ? $rec['subject'] : '',
            'text'     => ( isset( $rec['action'] ) && $rec['action'] ) ? $rec['action'] : ( isset( $rec['message'] ) ? $rec['message'] : '' ),
        ];
    }
}

// Fallback if nothing generated
if ( empty( $action_banners ) ) {
    $action_banners[] = [
        'priority' => 'low',
        'text'     => 'Your share buttons are performing well. Keep collecting data for better recommendations.',
    ];
}

// Limit banners to top 3 so the page stays scannable
$action_banners = array_slice( $action_banners, 0, 3 );

?>
<!-- ═══════════════════════════════════════════════════════════════════════════
     ESSB Trends View — redesigned
     ═══════════════════════════════════════════════════════════════════════════ -->

<style>
/* ── Fonts ─────────────────────────────────────────────────────────────────── */
@import url('https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=Sora:wght@400;500;600&display=swap');

/* ── Root tokens ────────────────────────────────────────────────────────────── */
.essb-tr-wrap {
    --tr-text:        #1e293b;
    --tr-text-light:  #64748b;
    --tr-border:      #e2e8f0;
    --tr-border-med:  #cbd5e1;
    --tr-bg:          #ffffff;
    --tr-card:        #ffffff;
    --tr-blue:        #185FA5;
    --tr-blue-light:  #E6F1FB;
    --tr-green:       #3B6D11;
    --tr-green-light: #EAF3DE;
    --tr-red:         #A32D2D;
    --tr-red-light:   #FCEBEB;
    --tr-amber:       #854F0B;
    --tr-amber-light: #FAEEDA;
    --tr-gray:        #5F5E5A;
    --tr-gray-light:  #F1EFE8;
    --tr-radius-sm:   6px;
    --tr-radius-md:   8px;
    --tr-radius-lg:   12px;

    font-family:  var(--tr-font);
    color:        var(--tr-text);
    background:   var(--tr-bg);
    padding:      0 0 2rem 0;
    font-size:    14px;
    line-height:  1.5;
    box-sizing:   border-box;
}
.essb-tr-wrap *, .essb-tr-wrap *::before, .essb-tr-wrap *::after { box-sizing: inherit; }

/* ── Hero header ─────────────────────────────────────────────────────────────── */
.tr-hero {
    background:    var(--tr-card);
    border:        1px solid var(--tr-border);
    border-radius: var(--tr-radius-lg);
    padding:       1.25rem 1.5rem;
    margin-bottom: 1rem;
    display:       flex;
    justify-content: space-between;
    align-items:   flex-start;
    gap:           1rem;
    flex-wrap:     wrap;
}
.tr-hero-eyebrow {
    font-size:      11px;
    font-weight:    500;
    color:          var(--tr-text-light);
    letter-spacing: 0.08em;
    text-transform: uppercase;
    margin-bottom:  5px;
}
.tr-hero-title {
    font-size:   20px;
    font-weight: 600;
    color:       var(--tr-text);
    margin:      0 0 3px;
    line-height: 1.2;
}
.tr-hero-sub {
    font-size: 13px;
    color:     var(--tr-text-light);
    margin:    0;
}
.tr-hero-date {
    font-size:     12px;
    color:         var(--tr-text-light);
    font-family:   var(--tr-mono);
    background:    var(--tr-bg);
    border:        1px solid var(--tr-border);
    border-radius: var(--tr-radius-sm);
    padding:       5px 12px;
    white-space:   nowrap;
    align-self:    flex-start;
}

/* ── Action banners ──────────────────────────────────────────────────────────── */
.tr-action-banner {
    background:     var(--tr-card);
    border:         1px solid var(--tr-border);
    border-left:    3px solid var(--tr-red);
    border-radius:  var(--tr-radius-lg);
    padding:        0.875rem 1.25rem;
    margin-bottom:  0.625rem;
    display:        flex;
    align-items:    center;
    gap:            12px;
}
.tr-action-banner-label {
    font-size:      10px;
    font-weight:    600;
    text-transform: uppercase;
    letter-spacing: 0.07em;
    color:          var(--tr-red);
    margin-bottom:  2px;
}
.tr-action-banner-text {
    font-size:   13px;
    color:       var(--tr-text);
    font-weight: 500;
    line-height: 1.4;
}

/* Medium priority */
.tr-action-medium                     { border-left-color: #BA7517; }
.tr-action-medium .tr-action-banner-label { color: var(--tr-amber); }

/* All-good / low priority */
.tr-action-ok                         { border-left-color: #3B6D11; }
.tr-action-ok .tr-action-banner-label { color: var(--tr-green); }

/* ── Score row ───────────────────────────────────────────────────────────────── */
.tr-score-row {
    display:               grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap:                   10px;
    margin-bottom:         1.25rem;
    margin-top:            1rem;
}
.tr-score-card {
    background:     var(--tr-card);
    border:         1px solid var(--tr-border);
    border-radius:  var(--tr-radius-lg);
    padding:        13px 15px 0;
    position:       relative;
    overflow:       hidden;
    padding-bottom: 12px;
}
.tr-score-label {
    font-size:      11px;
    color:          var(--tr-text-light);
    text-transform: uppercase;
    letter-spacing: 0.06em;
    margin-bottom:  6px;
}
.tr-score-value {
    font-size:    21px;
    font-weight:  600;
    color:        var(--tr-text);
    font-family:  var(--tr-mono);
    line-height:  1;
    margin-bottom: 4px;
}
.tr-score-value-lg { font-size: 16px; padding-top: 3px; font-family: var(--tr-font); }
.tr-score-delta    { font-size: 12px; font-weight: 500; }
.tr-delta-up       { color: var(--tr-green); }
.tr-delta-down     { color: var(--tr-red); }
.tr-delta-flat     { color: var(--tr-text-light); }

.tr-score-bar      { position: absolute; bottom: 0; left: 0; height: 3px; background: var(--tr-border); width: 100%; }
.tr-score-bar-fill { height: 100%; transition: width 0.6s ease; border-radius: 0; }
.tr-bar-up         { background: #639922; }
.tr-bar-down       { background: var(--tr-red); }
.tr-bar-flat       { background: #888780; }

/* ── Section heading ─────────────────────────────────────────────────────────── */
.tr-section        { margin-bottom: 1.25rem; }
.tr-section-label  {
    font-size:      11px;
    font-weight:    600;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    color:          var(--tr-text-light);
    margin-bottom:  10px;
    display:        flex;
    align-items:    center;
    gap:            8px;
}
.tr-section-label::after {
    content:    '';
    flex:       1;
    height:     1px;
    background: var(--tr-border);
}

/* ── Network trend rows ──────────────────────────────────────────────────────── */
.tr-network-list { display: flex; flex-direction: column; gap: 7px; }
.tr-network-row {
    background:     var(--tr-card);
    border:         1px solid var(--tr-border);
    border-radius:  var(--tr-radius-md);
    padding:        11px 14px;
    display:        grid;
    grid-template-columns: 120px 1fr 90px 68px;
    align-items:    center;
    gap:            12px;
}
.tr-net-name  { font-size: 13px; font-weight: 500; color: var(--tr-text); }
.tr-net-track {
    background:    var(--tr-bg);
    border-radius: 3px;
    height:        8px;
    overflow:      hidden;
    position:      relative;
}
.tr-net-fill-cur {
    height:        100%;
    position:      absolute;
    top:           0; left: 0;
    border-radius: 3px;
    transition:    width 0.7s ease;
}
.tr-net-fill-prev {
    height:        3px;
    position:      absolute;
    bottom:        0; left: 0;
    border-radius: 3px;
    opacity:       0.4;
    transition:    width 0.7s ease;
}
.tr-net-counts {
    text-align:  right;
    font-family: var(--tr-mono);
    font-size:   11px;
    color:       var(--tr-text-light);
    white-space: nowrap;
}
.tr-net-delta {
    text-align:  right;
    font-size:   12px;
    font-weight: 600;
    font-family: var(--tr-mono);
    white-space: nowrap;
}

/* ── Verdict / recommendation cards ─────────────────────────────────────────── */
.tr-verdict-grid {
    display:               grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap:                   10px;
}
.tr-verdict-card {
    background:    var(--tr-card);
    border:        1px solid var(--tr-border);
    border-radius: var(--tr-radius-lg);
    padding:       14px 16px;
}
.tr-verdict-type {
    font-size:      10px;
    font-weight:    600;
    letter-spacing: 0.07em;
    text-transform: uppercase;
    margin-bottom:  5px;
}
.tr-verdict-type-alert { color: var(--tr-red);   }
.tr-verdict-type-opp   { color: var(--tr-green); }
.tr-verdict-type-info  { color: var(--tr-blue);  }
.tr-verdict-title { font-size: 14px; font-weight: 600; color: var(--tr-text); margin-bottom: 5px; }
.tr-verdict-desc  { font-size: 12px; color: var(--tr-text-light); line-height: 1.5; margin-bottom: 10px; }
.tr-verdict-action {
    background:    var(--tr-bg);
    border-radius: var(--tr-radius-sm);
    padding:       8px 10px;
    font-size:     11px;
    color:         var(--tr-text);
    font-weight:   500;
    border-left:   2px solid var(--tr-border-med);
    line-height:   1.4;
}

/* ── Recommended order ───────────────────────────────────────────────────────── */
.tr-order-grid {
    display:               grid;
    grid-template-columns: 1fr 1fr;
    gap:                   10px;
}
.tr-order-pane {
    background:    var(--tr-card);
    border:        1px solid var(--tr-border);
    border-radius: var(--tr-radius-lg);
    padding:       14px 16px;
}
.tr-order-title {
    font-size:      11px;
    font-weight:    600;
    color:          var(--tr-text-light);
    text-transform: uppercase;
    letter-spacing: 0.06em;
    margin-bottom:  12px;
}
.tr-order-item {
    display:      flex;
    align-items:  center;
    gap:          10px;
    padding:      7px 0;
    border-bottom: 1px solid var(--tr-border);
}
.tr-order-item:last-child { border-bottom: none; padding-bottom: 0; }
.tr-order-rank {
    font-family: var(--tr-mono);
    font-size:   11px;
    font-weight: 500;
    color:       var(--tr-text-light);
    width:       20px;
    flex-shrink: 0;
}
.tr-order-name { font-size: 13px; font-weight: 500; color: var(--tr-text); flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.tr-order-name-dim { color: var(--tr-text-light); }
.tr-order-bar-wrap { width: 60px; background: var(--tr-bg); border-radius: 2px; height: 4px; overflow: hidden; flex-shrink: 0; }
.tr-order-bar-fill { height: 100%; border-radius: 2px; transition: width 0.6s ease; }

/* ── Empty state ─────────────────────────────────────────────────────────────── */
.tr-empty {
    text-align:    center;
    padding:       40px 20px;
    color:         var(--tr-text-light);
    font-size:     13px;
    background:    var(--tr-card);
    border:        1px solid var(--tr-border);
    border-radius: var(--tr-radius-lg);
}

/* ── Responsive ──────────────────────────────────────────────────────────────── */
@media (max-width: 640px) {
    .tr-network-row { grid-template-columns: 100px 1fr 58px; }
    .tr-net-counts  { display: none; }
    .tr-order-grid  { grid-template-columns: 1fr; }
    .tr-score-row   { grid-template-columns: 1fr 1fr; }
}
@media (max-width: 420px) {
    .tr-score-row { grid-template-columns: 1fr; }
}
</style>

<div class="essb-tr-wrap">

    <!-- ── Hero ─────────────────────────────────────────────────────────────── -->
    <div class="tr-hero">
        <div>
            <div class="tr-hero-eyebrow">Share button intelligence</div>
            <h2 class="tr-hero-title">Trends report</h2>
            <p class="tr-hero-sub">
                <?php echo esc_html( date( 'M j, Y', strtotime( $date_from ) ) ); ?>
                &rarr;
                <?php echo esc_html( date( 'M j, Y', strtotime( $date_to ) ) ); ?>
                &nbsp;&middot;&nbsp; vs. previous period
            </p>
        </div>
        <div class="tr-hero-date"><?php echo esc_html( date( 'M j, Y' ) ); ?></div>
    </div>

    <!-- ── Action banners ────────────────────────────────────────────────────── -->
    <?php if ( ! empty( $action_banners ) ) : ?>
        <?php foreach ( $action_banners as $banner ) : ?>
            <div class="tr-action-banner <?php echo esc_attr( essb_banner_class( $banner['priority'] ) ); ?>">
                <div>
                    <div class="tr-action-banner-label">
                        <?php echo essb_banner_label( $banner['priority'] ); ?>
                        <?php if ( ! empty( $banner['subject'] ) ) : ?>
                            &nbsp;&middot;&nbsp; <?php echo esc_html( $banner['subject'] ); ?>
                        <?php endif; ?>
                    </div>
                    <div class="tr-action-banner-text">
                        <?php echo esc_html( $banner['text'] ); ?>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>

    <!-- ── Scorecard row ─────────────────────────────────────────────────────── -->
    <div class="tr-score-row">

        <!-- Total clicks -->
        <div class="tr-score-card">
            <div class="tr-score-label">Total clicks</div>
            <div class="tr-score-value">
                <?php echo esc_html( ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber( $total_clicks ) ); ?>
            </div>
            <?php $d = essb_delta_dir( $total_delta ); ?>
            <div class="tr-score-delta tr-delta-<?php echo $d; ?>">
                <?php echo ( $d === 'up' ? '&uarr;' : ( $d === 'down' ? '&darr;' : '' ) ); ?>
                <?php echo esc_html( essb_fmt_delta( $total_delta ) ); ?> vs prev
            </div>
            <div class="tr-score-bar">
                <div class="tr-score-bar-fill tr-bar-<?php echo $d; ?>"
                     style="width:<?php echo min( 100, max( 20, abs( $total_delta ) * 2 ) ); ?>%"></div>
            </div>
        </div>

        <!-- Top network -->
        <div class="tr-score-card">
            <div class="tr-score-label">Top network</div>
            <?php if ( $top_network ) : ?>
                <div class="tr-score-value tr-score-value-lg">
                    <?php echo esc_html( essb_stats_get_network_name( $top_network['name'] ) ); ?>
                </div>
                <?php $d = essb_delta_dir( $top_network['change'] ); ?>
                <div class="tr-score-delta tr-delta-<?php echo $d; ?>">
                    <?php echo ( $d === 'up' ? '&uarr;' : ( $d === 'down' ? '&darr;' : '' ) ); ?>
                    <?php echo esc_html( essb_fmt_delta( $top_network['change'] ) ); ?> growth
                </div>
                <div class="tr-score-bar">
                    <div class="tr-score-bar-fill tr-bar-<?php echo $d; ?>"
                         style="width:<?php echo min( 100, max( 30, abs( $top_network['change'] ) * 1.5 ) ); ?>%"></div>
                </div>
            <?php else : ?>
                <div class="tr-score-value tr-score-value-lg" style="font-size:14px;">N/A</div>
                <div class="tr-score-delta tr-delta-flat">No data</div>
                <div class="tr-score-bar"><div class="tr-score-bar-fill tr-bar-flat" style="width:0%"></div></div>
            <?php endif; ?>
        </div>

        <!-- Watch network -->
        <div class="tr-score-card">
            <div class="tr-score-label">Watch list</div>
            <?php if ( $watch_network ) : ?>
                <div class="tr-score-value tr-score-value-lg">
                    <?php echo esc_html( essb_stats_get_network_name( $watch_network['name'] ) ); ?>
                </div>
                <?php $d = essb_delta_dir( $watch_network['change'] ); ?>
                <div class="tr-score-delta tr-delta-<?php echo $d; ?>">
                    <?php echo ( $d === 'down' ? '&darr;' : '' ); ?>
                    <?php echo esc_html( essb_fmt_delta( $watch_network['change'] ) ); ?> decline
                </div>
                <div class="tr-score-bar">
                    <div class="tr-score-bar-fill tr-bar-<?php echo $d; ?>"
                         style="width:<?php echo min( 100, max( 20, abs( $watch_network['change'] ) * 2 ) ); ?>%"></div>
                </div>
            <?php else : ?>
                <div class="tr-score-value tr-score-value-lg" style="font-size:14px;">None</div>
                <div class="tr-score-delta tr-delta-flat">All healthy</div>
                <div class="tr-score-bar"><div class="tr-score-bar-fill tr-bar-flat" style="width:15%"></div></div>
            <?php endif; ?>
        </div>

        <!-- Hot position -->
        <div class="tr-score-card">
            <div class="tr-score-label">Hot position</div>
            <?php if ( $hot_position ) : ?>
                <div class="tr-score-value tr-score-value-lg">
                    <?php echo esc_html( ESSBSocialShareAnalyticsBackEnd::position_name( $hot_position['name'] ) ); ?>
                </div>
                <?php $d = essb_delta_dir( $hot_position['change'] ); ?>
                <div class="tr-score-delta tr-delta-<?php echo $d; ?>">
                    <?php echo ( $d === 'up' ? '&uarr;' : '' ); ?>
                    <?php echo esc_html( essb_fmt_delta( $hot_position['change'] ) ); ?> growth
                </div>
                <div class="tr-score-bar">
                    <div class="tr-score-bar-fill tr-bar-<?php echo $d; ?>"
                         style="width:<?php echo min( 100, max( 30, abs( $hot_position['change'] ) * 1.5 ) ); ?>%"></div>
                </div>
            <?php else : ?>
                <div class="tr-score-value tr-score-value-lg" style="font-size:14px;">N/A</div>
                <div class="tr-score-delta tr-delta-flat">No data</div>
                <div class="tr-score-bar"><div class="tr-score-bar-fill tr-bar-flat" style="width:0%"></div></div>
            <?php endif; ?>
        </div>

        <!-- Mobile share -->
        <div class="tr-score-card">
            <div class="tr-score-label">Mobile share</div>
            <div class="tr-score-value"><?php echo esc_html( $mobile_pct ); ?>%</div>
            <div class="tr-score-delta tr-delta-flat">of all clicks</div>
            <div class="tr-score-bar">
                <div class="tr-score-bar-fill tr-bar-<?php echo $mobile_pct > 50 ? 'up' : 'flat'; ?>"
                     style="width:<?php echo esc_attr( $mobile_pct ); ?>%"></div>
            </div>
        </div>

    </div><!-- /.tr-score-row -->

    <!-- ── Network trends ────────────────────────────────────────────────────── -->
    <div class="tr-section">
        <div class="tr-section-label">Network trends</div>

        <?php if ( empty( $trends_analysis['network_trends'] ) ) : ?>
            <div class="tr-empty">No network data available for this period.</div>
        <?php else : ?>
            <div class="tr-network-list">
                <?php foreach ( array_slice( $trends_analysis['network_trends'], 0, 8 ) as $network ) :
                    $cur_w  = round( ( $network['current']  / $max_clicks ) * 100 );
                    $prev_w = round( ( $network['previous'] / $max_clicks ) * 100 );
                    $d      = essb_delta_dir( $network['change'] );
                    $bar_color = $d === 'up' ? '#185FA5' : ( $d === 'down' ? '#A32D2D' : '#5F5E5A' );
                ?>
                <div class="tr-network-row">
                    <div class="tr-net-name"><?php echo esc_html( essb_stats_get_network_name( $network['name'] ) ); ?></div>
                    <div>
                        <div class="tr-net-track">
                            <div class="tr-net-fill-cur"
                                 style="width:<?php echo esc_attr( $cur_w ); ?>%;background:<?php echo esc_attr( $bar_color ); ?>;"></div>
                            <div class="tr-net-fill-prev"
                                 style="width:<?php echo esc_attr( $prev_w ); ?>%;background:<?php echo esc_attr( $bar_color ); ?>;"></div>
                        </div>
                    </div>
                    <div class="tr-net-counts">
                        <?php echo esc_html( ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber( $network['current'] ) ); ?>
                        /
                        <?php echo esc_html( ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber( $network['previous'] ) ); ?>
                    </div>
                    <div class="tr-net-delta tr-delta-<?php echo $d; ?>">
                        <?php echo esc_html( essb_fmt_delta( $network['change'] ) ); ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- ── What to do about it ───────────────────────────────────────────────── -->
    <div class="tr-section">
        <div class="tr-section-label">What to do about it</div>

        <?php if ( empty( $recommendations ) ) : ?>
            <div class="tr-empty">
                Not enough data yet. Keep collecting clicks for personalised recommendations.
            </div>
        <?php else : ?>
            <div class="tr-verdict-grid">
                <?php foreach ( $recommendations as $rec ) : ?>
                <div class="tr-verdict-card">
                    <div class="tr-verdict-type <?php echo esc_attr( essb_verdict_class( $rec['type'] ) ); ?>">
                        <?php echo esc_html( $rec['type'] ); ?>
                    </div>
                    <div class="tr-verdict-title"><?php echo esc_html( $rec['title'] ); ?></div>
                    <div class="tr-verdict-desc"><?php echo esc_html( $rec['message'] ); ?></div>
                    <?php if ( ! empty( $rec['action'] ) ) : ?>
                    <div class="tr-verdict-action"><?php echo esc_html( $rec['action'] ); ?></div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- ── Recommended network order ─────────────────────────────────────────── -->
    <?php if ( ! empty( $desktop_order ) || ! empty( $mobile_order ) ) : ?>
    <div class="tr-section">
        <div class="tr-section-label">Recommended network order</div>
        <div class="tr-order-grid">

            <!-- Desktop -->
            <div class="tr-order-pane">
                <div class="tr-order-title">Desktop</div>
                <?php if ( empty( $desktop_order ) ) : ?>
                    <p style="font-size:12px;color:var(--tr-text-light);">Not enough data yet.</p>
                <?php else :
                    $desk_max = 1;
                    foreach ( $trends_analysis['network_trends'] as $nt ) {
                        if ( in_array( $nt['name'], $desktop_order ) ) $desk_max = max( $desk_max, $nt['desktop_clicks'] ?? $nt['current'] );
                    }
                    foreach ( $desktop_order as $idx => $net_name ) :
                        // Find click count for bar width
                        $net_clicks = 0;
                        foreach ( $trends_analysis['network_trends'] as $nt ) {
                            if ( $nt['name'] === $net_name ) { $net_clicks = $nt['current']; break; }
                        }
                        $bar_w    = $desk_max > 0 ? round( ( $net_clicks / $desk_max ) * 100 ) : 0;
                        $is_last  = $bar_w < 20;
                ?>
                    <div class="tr-order-item">
                        <div class="tr-order-rank"><?php printf( '%02d', $idx + 1 ); ?></div>
                        <div class="tr-order-name <?php echo $is_last ? 'tr-order-name-dim' : ''; ?>">
                            <?php echo esc_html( essb_stats_get_network_name( $net_name ) ); ?>
                        </div>
                        <div class="tr-order-bar-wrap">
                            <div class="tr-order-bar-fill"
                                 style="width:<?php echo esc_attr( $bar_w ); ?>%;background:#185FA5;"></div>
                        </div>
                    </div>
                <?php
                    endforeach;
                endif; ?>
            </div>

            <!-- Mobile -->
            <div class="tr-order-pane">
                <div class="tr-order-title">Mobile</div>
                <?php if ( empty( $mobile_order ) ) : ?>
                    <p style="font-size:12px;color:var(--tr-text-light);">Not enough data yet.</p>
                <?php else :
                    $mob_max = 1;
                    foreach ( $trends_analysis['network_trends'] as $nt ) {
                        if ( in_array( $nt['name'], $mobile_order ) ) $mob_max = max( $mob_max, $nt['mobile_clicks'] ?? $nt['current'] );
                    }
                    foreach ( $mobile_order as $idx => $net_name ) :
                        $net_clicks = 0;
                        foreach ( $trends_analysis['network_trends'] as $nt ) {
                            if ( $nt['name'] === $net_name ) { $net_clicks = $nt['current']; break; }
                        }
                        $bar_w   = $mob_max > 0 ? round( ( $net_clicks / $mob_max ) * 100 ) : 0;
                        $is_last = $bar_w < 20;
                ?>
                    <div class="tr-order-item">
                        <div class="tr-order-rank"><?php printf( '%02d', $idx + 1 ); ?></div>
                        <div class="tr-order-name <?php echo $is_last ? 'tr-order-name-dim' : ''; ?>">
                            <?php echo esc_html( essb_stats_get_network_name( $net_name ) ); ?>
                        </div>
                        <div class="tr-order-bar-wrap">
                            <div class="tr-order-bar-fill"
                                 style="width:<?php echo esc_attr( $bar_w ); ?>%;background:#3B6D11;"></div>
                        </div>
                    </div>
                <?php
                    endforeach;
                endif; ?>
            </div>

        </div><!-- /.tr-order-grid -->
    </div>
    <?php endif; ?>

</div><!-- /.essb-tr-wrap -->