<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
if (!defined('ABSPATH')) exit;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
// This template uses the legacy rendering contract variables provided by the shortcode
// (`$newssync_display`, `$items`, `$item`). Renaming them would break includes.
global $newssync_display;

// Fallbacks
$items = is_array($items) ? $items : [];
$display = is_array($newssync_display) ? $newssync_display : [];
?>
<?php if ( empty( $items ) ): ?>
    <div class="rsp-container"><p style="text-align:center;color:#666;"><?php echo esc_html__( 'No items to display.', 'daazsync' ); ?></p></div>
    <?php return; ?>
<?php endif; ?>

<?php
// Prefer templates if exist (open)
$newssync_carousel_open = NEWSSYNC_PLUGIN_DIR . 'includes/templates/carousel/carousel-container-open.php';
$newssync_carousel_item_tpl = NEWSSYNC_PLUGIN_DIR . 'includes/templates/carousel/carousel-item.php';
$newssync_carousel_close = NEWSSYNC_PLUGIN_DIR . 'includes/templates/carousel/carousel-container-close.php';

if ( file_exists( $newssync_carousel_open ) ) {
    include $newssync_carousel_open;
} else {
    echo '<div class="rsp-container"><div class="swiper rsp-carousel"><div class="swiper-wrapper">';
}

foreach ( (array) $items as $item ):
    // Each slide wrapper: item template handles its contents
    echo '<div class="swiper-slide">';
    if ( file_exists( $newssync_carousel_item_tpl ) ) {
        include $newssync_carousel_item_tpl;
    } else {
        // Minimal fallback
        $title = $item['title'] ?? '';
        $link = $item['link'] ?? '#';
        echo '<div class="rsp-card"><h3><a class="rsp-no-underline" href="' . esc_url($link) . '" target="_blank" rel="noopener">' . esc_html($title) . '</a></h3></div>';
    }
    echo '</div>';
endforeach;

if ( file_exists( $newssync_carousel_close ) ) {
    include $newssync_carousel_close;
} else {
    echo '</div></div></div>';
}
// Overflow indicator: show +N more when PRO filters recorded a larger original count
$overflow = 0;
if ( isset( $GLOBALS['newssync_original_count_carousel'] ) ) {
    $original = intval( $GLOBALS['newssync_original_count_carousel'] );
    $after = count( (array) $items );
    if ( $original > $after ) {
        $overflow = $original - $after;
    }
}
if ( $overflow > 0 ) {
    echo '<div class="newssync-overflow-indicator" style="text-align:center;margin-top:6px;color:#666;">+' . intval( $overflow ) . ' ' . esc_html__( 'more', 'daazsync' ) . '</div>';
}
// phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
