<?php 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;

// Defaults
$newssync_d = is_array($newssync_display) ? $newssync_display : [];
$newssync_d = wp_parse_args($newssync_d, [
    'compact' => false,
    'date_format' => 'd/m/Y H:i',
]);

$items = is_array($items) ? $items : [];
?>
<ul class="rsp-list rsp-list-minimal <?php echo ! empty( $newssync_d['compact'] ) ? 'rsp-compact' : ''; ?>" style="list-style:none;padding-left:0;margin:0;">
    <?php if ( empty( $items ) ): ?>
        <li class="rsp-item-empty" style="list-style:none;"><?php echo esc_html__( 'No items to display.', 'daazsync' ); ?></li>
    <?php endif; ?>

    <?php foreach ( (array) $items as $item ):
        // Valores brutos
        $newssync_title_raw = $item['title'] ?? '';
        $newssync_category_raw = $item['category'] ?? '';
        $newssync_source_name = $item['source_name'] ?? '';
        $newssync_source_url = $item['source_url'] ?? '';
        $newssync_date_formatted = $item['date'] ?? '';
        $newssync_date_ts = isset($item['date_timestamp']) ? (int)$item['date_timestamp'] : 0;

        // Limpeza do título e categoria: substituir underscores por espaços e sanitizar
        $newssync_title = trim( preg_replace( '/\s+/', ' ', str_replace( '_', ' ', (string) $newssync_title_raw ) ) );
        $newssync_title = sanitize_text_field( $newssync_title );

        $newssync_category = trim( preg_replace( '/\s+/', ' ', str_replace( '_', ' ', (string) $newssync_category_raw ) ) );
        $newssync_category = sanitize_text_field( $newssync_category );

        /* Resolver possível link/permalink/post id do item (fallbacks ampliados) */
        $newssync_link = '';

        // 1) Campos diretos comuns
        $newssync_candidate_fields = array( 'link', 'permalink', 'guid', 'url', 'href', 'origin', 'orig_link', 'source' );
        foreach ( $newssync_candidate_fields as $f ) {
            if ( isset( $item[ $f ] ) && ! empty( $item[ $f ] ) ) {
                $val = $item[ $f ];
                if ( is_array( $val ) && ! empty( $val['url'] ) ) {
                    $newssync_link = $val['url'];
                    break;
                } elseif ( is_string( $val ) ) {
                    $newssync_link = $val;
                    break;
                }
            }
        }

        // 2) enclosure arrays (ex.: enclosure => ['url' => '...'] ou enclosure[0]['url'])
        if ( empty( $newssync_link ) && ! empty( $item['enclosure'] ) ) {
            $newssync_enc = $item['enclosure'];
            if ( is_array( $newssync_enc ) ) {
                if ( ! empty( $newssync_enc['url'] ) ) {
                    $newssync_link = $newssync_enc['url'];
                } elseif ( isset( $newssync_enc[0]['url'] ) && ! empty( $newssync_enc[0]['url'] ) ) {
                    $newssync_link = $newssync_enc[0]['url'];
                }
            }
        }

        // 3) Tentativa a partir de possíveis objetos (caso chegue como object)
        if ( empty( $newssync_link ) && is_object( $item ) ) {
            if ( ! empty( $item->link ) ) {
                $newssync_link = (string) $item->link;
            } elseif ( ! empty( $item->guid ) ) {
                $newssync_link = is_object( $item->guid ) && ! empty( $item->guid->rendered ) ? (string) $item->guid->rendered : (string) $item->guid;
            }
        }

        // 4) Fallback por post_id/ID (já tinha)
        if ( empty( $newssync_link ) && ( ! empty( $item['post_id'] ) || ! empty( $item['ID'] ) ) ) {
            $newssync_pid = ! empty( $item['post_id'] ) ? $item['post_id'] : $item['ID'];
            $newssync_link = get_permalink( (int) $newssync_pid );
        }

        // normalizar
        $newssync_link = is_string( $newssync_link ) ? trim( $newssync_link ) : '';
        if ( $newssync_link ) {
            // assegurar URL válida
            $newssync_link = esc_url_raw( $newssync_link );
        }

        // Preparar um rótulo legível para o link (remove underscores, %5F, decodifica slugs)
        $newssync_link_display = '';
        if ( ! empty( $newssync_link ) ) {
            $parts = wp_parse_url( $newssync_link );

            if ( ! empty( $parts['host'] ) ) {
                $newssync_link_display = $parts['host'];
            }

            if ( ! empty( $parts['path'] ) ) {
                $newssync_basename = trim( basename( $parts['path'] ), '/' );
                if ( $newssync_basename ) {
                    $newssync_basename = urldecode( $newssync_basename );
                    $newssync_basename = str_replace( array( '_', '%5F' ), ' ', $newssync_basename );
                    $newssync_basename = preg_replace( '/\s+/', ' ', $newssync_basename );
                    if ( $newssync_link_display ) {
                        $newssync_link_display .= ' / ' . $newssync_basename;
                    } else {
                        $newssync_link_display = $newssync_basename;
                    }
                }
            }

            // limpeza final e fallback de label
            $newssync_link_display = trim( preg_replace( '/\s+/', ' ', str_replace( array( '_', '%5F' ), ' ', $newssync_link_display ) ) );
            $newssync_link_display = sanitize_text_field( $newssync_link_display );
            if ( empty( $newssync_link_display ) ) {
                $newssync_link_display = __( 'Ler notícia', 'daazsync' );
            }
        }

        // Debug (mostra comentário HTML apenas se WP_DEBUG activo e utilizador admin)
        if ( defined( 'WP_DEBUG' ) && WP_DEBUG && function_exists( 'current_user_can' ) && current_user_can( 'manage_options' ) ) {
            printf( "\n<!-- newssync link: %s -->\n", esc_html( $newssync_link ?: 'EMPTY' ) );
        }
    ?>
        <li class="rsp-item" style="list-style:none;">
            <div class="rsp-title">
                <?php if ( $newssync_link && $newssync_title ): ?>
                    <a class="rsp-no-underline" href="<?php echo esc_url( $newssync_link ); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html( $newssync_title ); ?></a>
                <?php elseif ( $newssync_link && ! $newssync_title ): ?>
                    <!-- Sem título: mostrar rótulo amigável do URL (sem underscores) -->
                    <a class="rsp-no-underline" href="<?php echo esc_url( $newssync_link ); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html( $newssync_link_display ); ?></a>
                <?php else: ?>
                    <?php echo esc_html( $newssync_title ); ?>
                <?php endif; ?>
            </div>
            <div class="rsp-meta">
                <?php
                // Build meta parts respecting display flags from $newssync_d
                $meta_parts = array();

                // Date (only if enabled)
                if ( ! empty( $newssync_d['date'] ) ) {
                    if ( ! empty( $newssync_date_formatted ) ) {
                        $meta_parts[] = esc_html( $newssync_date_formatted );
                    } elseif ( $newssync_date_ts ) {
                        $wp_offset = (int) get_option( 'gmt_offset', 0 );
                        $local_ts = $newssync_date_ts + ( $wp_offset * 3600 );
                        $meta_parts[] = esc_html( date_i18n( $newssync_d['date_format'], $local_ts ) );
                    }
                }

                // Source/category (only if enabled)
                if ( ! empty( $newssync_d['source'] ) ) {
                    if ( ! empty( $newssync_source_name ) ) {
                        if ( ! empty( $newssync_source_url ) ) {
                            /* translators: %s: source website name */
                            $newssync_visit_title = sprintf( __( 'Visit %s', 'daazsync' ), $newssync_source_name );
                            $meta_parts[] = '<a href="' . esc_url( $newssync_source_url ) . '" target="_blank" rel="noopener noreferrer" title="' . esc_attr( $newssync_visit_title ) . '">' . esc_html( $newssync_source_name ) . '</a>';
                        } else {
                            $meta_parts[] = esc_html( $newssync_source_name );
                        }
                    } elseif ( $newssync_category ) {
                        $meta_parts[] = esc_html( $newssync_category );
                    }
                }

                if ( ! empty( $meta_parts ) ) {
                    // Join parts with separator; allow anchors via kses
                    $out = implode( ' - ', $meta_parts );
                    echo wp_kses_post( $out );
                }
                ?>
            </div>
        </li>
    <?php endforeach; ?>
</ul>
<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
