<?php

namespace MovieEngine\Frontend\Users;

if (! defined("ABSPATH")) {
    exit; // Exit if accessed directly
}

class UserLibrary {

    public function __construct() {
        add_action('wp_ajax_movie_engine_toggle_watchlist', [$this, 'ajax_toggle_watchlist']);
        add_action('wp_ajax_movie_engine_get_watchlist_page', [$this, 'ajax_get_watchlist_page']);
        add_action('wp_ajax_movie_engine_get_playlists_page', [$this, 'ajax_get_playlists_page']);
        add_action('wp_ajax_movie_engine_create_playlist', [$this, 'ajax_create_playlist']);
        add_action('wp_ajax_movie_engine_add_to_playlist', [$this, 'ajax_add_to_playlist']);
        add_action('wp_ajax_movie_engine_rename_playlist', [$this, 'ajax_rename_playlist']);
        add_action('wp_ajax_movie_engine_delete_playlist', [$this, 'ajax_delete_playlist']);
        add_action('wp_ajax_movie_engine_get_liked_page', [$this, 'ajax_get_liked_page']);
        add_shortcode('movie_engine_watchlist', [$this, 'render_watchlist']);
        add_shortcode('movie_engine_playlists', [$this, 'render_playlists']);
        add_shortcode('movie_engine_liked', [$this, 'render_liked_content']);
    }


    public function render_liked_content($atts) {
        $design_settings = get_option('movie_engine_design_settings', []);
        $default_limit = isset($design_settings['archive_items_per_page']) ? intval($design_settings['archive_items_per_page']) : 12;

        $atts = shortcode_atts([
            'limit'          => $default_limit,
            'columns'        => $design_settings['archive_columns_desktop'] ?? 4,
            'columns_laptop' => $design_settings['archive_columns_laptop'] ?? 4,
            'columns_tablet' => $design_settings['archive_columns_tablet'] ?? 3,
            'columns_mobile' => $design_settings['archive_columns_mobile'] ?? 2,
            'ajax_paged'     => 0,
            'title'          => '',
            'view_all_link'  => '',
            'pagination'     => 'true'
        ], $atts);

        if (!is_user_logged_in()) {
            return '<p>' . esc_html__('Please login to view your liked content.', 'cine-movie-engine') . '</p>';
        }

        $user_id = get_current_user_id();
        $liked_ids = get_user_meta($user_id, '_movie_engine_liked_posts', true);
        $liked_ids = is_array($liked_ids) ? array_filter(array_map('absint', $liked_ids)) : [];

        if (empty($liked_ids)) {
            return '<div class="movie-engine-empty-state"><p>' . esc_html__('No liked content found.', 'cine-movie-engine') . '</p></div>';
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET pagination, nonce not used for shareable URLs
        $paged = $atts['ajax_paged'] > 0 ? $atts['ajax_paged'] : (isset($_GET['liked_page']) ? absint($_GET['liked_page']) : 1);

        $args = [
            'post_type'           => ['movie_engine_movie', 'movie_engine_series', 'movie_engine_episode'],
            'post__in'            => $liked_ids,
            'posts_per_page'      => $atts['limit'],
            'paged'               => $paged,
            'orderby'             => 'post__in',
            'ignore_sticky_posts' => true,
            'post_status'         => 'publish'
        ];

        $query = new \WP_Query($args);

        ob_start();
        if ($query && $query->have_posts()) {
            if ($atts['ajax_paged'] == 0) {
                echo '<div id="movie-engine-liked-container" class="movie-engine-ajax-container" data-action="movie_engine_get_liked_page" data-limit="' . esc_attr($atts['limit']) . '">';
            }

            if ($atts['title'] || $atts['view_all_link']) {
                echo '<div class="movie-engine-section-header me-section-header">';
                if ($atts['title']) {
                    echo '<h2 class="movie-engine-section-title me-section-title">' . esc_html($atts['title']) . '</h2>';
                }
                if ($atts['view_all_link']) {
                    echo '<a href="' . esc_url($atts['view_all_link']) . '" class="movie-engine-view-all me-view-all">' . esc_html__('View All', 'cine-movie-engine') . ' <span class="fa-solid fa-angle-right"></span></a>';
                }
                echo '</div>';
            }


            $columns        = intval($atts['columns']);
            $columns_laptop = intval($atts['columns_laptop']);
            $columns_tablet = intval($atts['columns_tablet']);
            $columns_mobile = intval($atts['columns_mobile']);
            $grid_vars      = "--me-grid-columns-desktop: " . intval($columns) . "; --me-grid-columns-laptop: " . intval($columns_laptop) . "; --me-grid-columns-tablet: " . intval($columns_tablet) . "; --me-grid-columns-mobile: " . intval($columns_mobile) . "; --grid-columns: " . intval($columns) . "; --grid-columns-laptop: " . intval($columns_laptop) . "; --grid-columns-tablet: " . intval($columns_tablet) . "; --grid-columns-mobile: " . intval($columns_mobile) . ";";

            echo '<div class="movie-engine-liked-grid-wrapper"><section class="movie-engine-section"><div class="movie-engine-items-grid movie-engine-movie-grid me-liked-grid me-history-grid me-history-grid-dashboard" style="' . esc_attr($grid_vars) . '">';
            while ($query->have_posts()) {
                $query->the_post();
                \MovieEngine\Utils\TemplateLoader::get_template_part('myaccount/content-liked');
            }
            echo '</div></section>';

            if (filter_var($atts['pagination'], FILTER_VALIDATE_BOOLEAN)) {
                $total_pages = $query->max_num_pages;
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- kses_post sanitizes HTML
                echo \MovieEngine\Utils\Helpers::kses_post(\MovieEngine\Utils\Helpers::render_pagination($paged, $total_pages, 'liked_page'));
            }
            echo '</div>';

            if ($atts['ajax_paged'] == 0) {
                echo '</div>';
            }
            wp_reset_postdata();
        } else {
            echo '<div class="movie-engine-empty-state"><p>' . esc_html__('No liked content found.', 'cine-movie-engine') . '</p></div>';
        }
        return ob_get_clean();
    }


    public function ajax_add_to_playlist() {
        check_ajax_referer('movie_engine_nonce', 'nonce');

        if (!is_user_logged_in()) {
            wp_send_json_error(['message' => esc_html__('You must be logged in.', 'cine-movie-engine')]);
        }

        $playlist_id = isset($_POST['playlist_id']) ? sanitize_text_field(wp_unslash($_POST['playlist_id'])) : '';
        $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;

        if (!$playlist_id || !$post_id) {
            wp_send_json_error(['message' => esc_html__('Invalid data.', 'cine-movie-engine')]);
        }

        $user_id = get_current_user_id();
        $result = $this->toggle_playlist_item($user_id, $playlist_id, $post_id);

        if ($result) {
            wp_send_json_success([
                'action' => $result,
                'message' => $result === 'added' ? esc_html__('Added to playlist.', 'cine-movie-engine') : esc_html__('Removed from playlist.', 'cine-movie-engine')
            ]);
        } else {
            wp_send_json_error(['message' => esc_html__('Could not update playlist.', 'cine-movie-engine')]);
        }
    }


    public function toggle_playlist_item($user_id, $playlist_id, $post_id) {
        $playlists = self::get_playlists($user_id);

        if (!isset($playlists[$playlist_id])) {
            return false;
        }

        $items = $playlists[$playlist_id]['items'] ?? [];

        if (in_array($post_id, $items)) {
            // Remove
            $items = array_diff($items, [$post_id]);
            $action = 'removed';
        } else {
            // Add
            $items[] = $post_id;
            $action = 'added';
        }

        $playlists[$playlist_id]['items'] = array_values($items);
        update_user_meta($user_id, '_movie_engine_playlists', $playlists);

        return $action;
    }


    public function ajax_create_playlist() {
        check_ajax_referer('movie_engine_nonce', 'nonce');

        if (!is_user_logged_in()) {
            wp_send_json_error(['message' => esc_html__('You must be logged in.', 'cine-movie-engine')]);
        }

        $name = isset($_POST['name']) ? sanitize_text_field(wp_unslash($_POST['name'])) : '';
        if (empty($name)) {
            wp_send_json_error(['message' => esc_html__('Playlist name is required.', 'cine-movie-engine')]);
        }

        $user_id = get_current_user_id();
        $playlist = $this->create_playlist($user_id, $name);

        if ($playlist) {
            wp_send_json_success([
                'playlist' => $playlist,
                'message' => esc_html__('Playlist created successfully.', 'cine-movie-engine')
            ]);
        } else {
            wp_send_json_error(['message' => esc_html__('Could not create playlist.', 'cine-movie-engine')]);
        }
    }


    public function create_playlist($user_id, $name) {
        $playlists = self::get_playlists($user_id);
        $id = uniqid('pl_');

        $playlist = [
            'id' => $id,
            'name' => $name,
            'items' => [],
            'created_at' => current_time('mysql')
        ];

        $playlists[$id] = $playlist;
        update_user_meta($user_id, '_movie_engine_playlists', $playlists);

        return $playlist;
    }


    public function ajax_rename_playlist() {
        check_ajax_referer('movie_engine_nonce', 'nonce');

        if (!is_user_logged_in()) {
            wp_send_json_error(['message' => esc_html__('You must be logged in.', 'cine-movie-engine')]);
        }

        $playlist_id = isset($_POST['playlist_id']) ? sanitize_text_field(wp_unslash($_POST['playlist_id'])) : '';
        $name = isset($_POST['name']) ? sanitize_text_field(wp_unslash($_POST['name'])) : '';

        if (!$playlist_id || empty($name)) {
            wp_send_json_error(['message' => esc_html__('Invalid data.', 'cine-movie-engine')]);
        }

        $user_id = get_current_user_id();
        $result = $this->rename_playlist($user_id, $playlist_id, $name);

        if ($result) {
            wp_send_json_success(['message' => esc_html__('Playlist renamed.', 'cine-movie-engine')]);
        } else {
            wp_send_json_error(['message' => esc_html__('Could not rename playlist.', 'cine-movie-engine')]);
        }
    }


    public function rename_playlist($user_id, $playlist_id, $name) {
        $playlists = self::get_playlists($user_id);

        if (!isset($playlists[$playlist_id])) {
            return false;
        }

        $playlists[$playlist_id]['name'] = $name;
        update_user_meta($user_id, '_movie_engine_playlists', $playlists);

        return true;
    }


    public function ajax_delete_playlist() {
        check_ajax_referer('movie_engine_nonce', 'nonce');

        if (!is_user_logged_in()) {
            wp_send_json_error(['message' => esc_html__('You must be logged in.', 'cine-movie-engine')]);
        }

        $playlist_id = isset($_POST['playlist_id']) ? sanitize_text_field(wp_unslash($_POST['playlist_id'])) : '';

        if (!$playlist_id) {
            wp_send_json_error(['message' => esc_html__('Invalid data.', 'cine-movie-engine')]);
        }

        $user_id = get_current_user_id();
        $result = $this->delete_playlist($user_id, $playlist_id);

        if ($result) {
            wp_send_json_success(['message' => esc_html__('Playlist deleted.', 'cine-movie-engine')]);
        } else {
            wp_send_json_error(['message' => esc_html__('Could not delete playlist.', 'cine-movie-engine')]);
        }
    }


    public function delete_playlist($user_id, $playlist_id) {
        $playlists = self::get_playlists($user_id);

        if (!isset($playlists[$playlist_id])) {
            return false;
        }

        unset($playlists[$playlist_id]);
        update_user_meta($user_id, '_movie_engine_playlists', $playlists);

        return true;
    }


    public static function get_playlists($user_id) {
        $playlists = get_user_meta($user_id, '_movie_engine_playlists', true);
        return is_array($playlists) ? $playlists : [];
    }



    public function ajax_toggle_watchlist() {
        check_ajax_referer('movie_engine_nonce', 'nonce');

        if (!is_user_logged_in()) {
            wp_send_json_error(['message' => esc_html__('You must be logged in.', 'cine-movie-engine')]);
        }

        $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;
        if (!$post_id) {
            wp_send_json_error(['message' => esc_html__('Invalid post.', 'cine-movie-engine')]);
        }

        $user_id = get_current_user_id();
        $action = $this->toggle_item($user_id, $post_id);

        wp_send_json_success([
            'action' => $action,
            'message' => $action === 'added' ? esc_html__('Added to Watchlist', 'cine-movie-engine') : esc_html__('Removed from Watchlist', 'cine-movie-engine')
        ]);
    }


    public function toggle_item($user_id, $post_id) {
        $watchlist = $this->get_watchlist($user_id);

        if (in_array($post_id, $watchlist)) {
            $watchlist = array_diff($watchlist, [$post_id]);
            $action = 'removed';
        } else {
            $watchlist[] = $post_id;
            $action = 'added';
        }

        update_user_meta($user_id, '_movie_engine_watchlist', array_values($watchlist));
        return $action;
    }


    public static function get_watchlist($user_id) {
        $watchlist = get_user_meta($user_id, '_movie_engine_watchlist', true);
        return is_array($watchlist) ? $watchlist : [];
    }

    public static function get_watchlist_count($user_id) {
        $watchlist = self::get_watchlist($user_id);
        return count($watchlist);
    }


    public static function in_watchlist($user_id, $post_id) {
        $watchlist = self::get_watchlist($user_id);
        return in_array($post_id, $watchlist);
    }

    public function ajax_get_liked_page() {
        check_ajax_referer('movie_engine_nonce', 'nonce');
        $paged = isset($_POST['paged']) ? absint($_POST['paged']) : (isset($_GET['paged']) ? absint($_GET['paged']) : 1);
        $limit = isset($_POST['limit']) ? absint($_POST['limit']) : (isset($_GET['limit']) ? absint($_GET['limit']) : 12);

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- kses_post sanitizes HTML
        echo \MovieEngine\Utils\Helpers::kses_post($this->render_liked_content(['limit' => $limit, 'ajax_paged' => $paged]));
        wp_die();
    }

    public function ajax_get_playlists_page() {
        check_ajax_referer('movie_engine_nonce', 'nonce');
        $paged = isset($_POST['paged']) ? absint($_POST['paged']) : (isset($_GET['paged']) ? absint($_GET['paged']) : 1);
        $limit = isset($_POST['limit']) ? absint($_POST['limit']) : (isset($_GET['limit']) ? absint($_GET['limit']) : 10);

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- kses_post sanitizes HTML
        echo \MovieEngine\Utils\Helpers::kses_post($this->render_playlists(['limit' => $limit, 'ajax_paged' => $paged]));
        wp_die();
    }

    public function ajax_get_watchlist_page() {
        check_ajax_referer('movie_engine_nonce', 'nonce');
        $paged = isset($_POST['paged']) ? absint($_POST['paged']) : (isset($_GET['paged']) ? absint($_GET['paged']) : 1);
        $limit = isset($_POST['limit']) ? absint($_POST['limit']) : (isset($_GET['limit']) ? absint($_GET['limit']) : 10);

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- kses_post sanitizes HTML
        echo \MovieEngine\Utils\Helpers::kses_post($this->render_watchlist(['limit' => $limit, 'ajax_paged' => $paged]));
        wp_die();
    }

    public function render_watchlist($atts) {
        $design_settings = get_option('movie_engine_design_settings', []);
        $default_limit = isset($design_settings['archive_items_per_page']) ? intval($design_settings['archive_items_per_page']) : 12;

        $atts = shortcode_atts([
            'limit'          => $default_limit,
            'columns'        => $design_settings['archive_columns_desktop'] ?? 4,
            'columns_laptop' => $design_settings['archive_columns_laptop'] ?? 4,
            'columns_tablet' => $design_settings['archive_columns_tablet'] ?? 3,
            'columns_mobile' => $design_settings['archive_columns_mobile'] ?? 2,
            'ajax_paged'     => 0,
            'title'          => '',
            'view_all_link'  => '',
            'pagination'     => 'true'
        ], $atts);

        if (!is_user_logged_in()) {
            return '<p>' . esc_html__('Please login to view your watchlist.', 'cine-movie-engine') . '</p>';
        }

        $user_id = get_current_user_id();
        $watchlist = $this->get_watchlist($user_id);
        $watchlist = array_filter(array_map('absint', $watchlist));

        if (empty($watchlist)) {
            return '<div class="movie-engine-watchlist-empty"><p>' . esc_html__('Your watchlist is empty.', 'cine-movie-engine') . '</p></div>';
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET pagination, nonce not used for shareable URLs
        $paged = $atts['ajax_paged'] > 0 ? $atts['ajax_paged'] : (isset($_GET['watchlist_page']) ? absint($_GET['watchlist_page']) : 1);

        $args = [
            'post_type'           => ['movie_engine_movie', 'movie_engine_series', 'movie_engine_episode'],
            'post__in'            => $watchlist,
            'posts_per_page'      => $atts['limit'],
            'paged'               => $paged,
            'orderby'             => 'post__in',
            'ignore_sticky_posts' => true,
            'post_status'         => 'publish'
        ];

        $query = new \WP_Query($args);

        ob_start();
        if ($query->have_posts()) {
            if ($atts['ajax_paged'] == 0) {
                echo '<div id="movie-engine-watchlist-container" class="movie-engine-ajax-container" data-action="movie_engine_get_watchlist_page" data-limit="' . esc_attr($atts['limit']) . '">';
            }

            if ($atts['title'] || $atts['view_all_link']) {
                echo '<div class="movie-engine-section-header me-section-header">';
                if ($atts['title']) {
                    echo '<h2 class="movie-engine-section-title me-section-title">' . esc_html($atts['title']) . '</h2>';
                }
                if ($atts['view_all_link']) {
                    echo '<a href="' . esc_url($atts['view_all_link']) . '" class="movie-engine-view-all me-view-all">' . esc_html__('View All', 'cine-movie-engine') . ' <span class="fa-solid fa-angle-right"></span></a>';
                }
                echo '</div>';
            }

            $columns        = intval($atts['columns']);
            $columns_laptop = intval($atts['columns_laptop']);
            $columns_tablet = intval($atts['columns_tablet']);
            $columns_mobile = intval($atts['columns_mobile']);
            $grid_vars      = "--me-grid-columns-desktop: " . intval($columns) . "; --me-grid-columns-laptop: " . intval($columns_laptop) . "; --me-grid-columns-tablet: " . intval($columns_tablet) . "; --me-grid-columns-mobile: " . intval($columns_mobile) . "; --grid-columns: " . intval($columns) . "; --grid-columns-laptop: " . intval($columns_laptop) . "; --grid-columns-tablet: " . intval($columns_tablet) . "; --grid-columns-mobile: " . intval($columns_mobile) . ";";

            echo '<div class="movie-engine-archive-wrapper"><section class="movie-engine-section"><div class="movie-engine-items-grid movie-engine-movie-grid me-watchlist-grid me-history-grid me-history-grid-dashboard" style="' . esc_attr($grid_vars) . '">';
            while ($query->have_posts()) {
                $query->the_post();
                \MovieEngine\Utils\TemplateLoader::get_template_part('myaccount/content-watchlist');
            }
            echo '</div></section>';

            if (filter_var($atts['pagination'], FILTER_VALIDATE_BOOLEAN)) {
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- kses_post sanitizes HTML
                echo \MovieEngine\Utils\Helpers::kses_post(\MovieEngine\Utils\Helpers::render_pagination($paged, $query->max_num_pages, 'watchlist_page'));
            }

            echo '</div>';

            if ($atts['ajax_paged'] == 0) {
                echo '</div>';
            }

            wp_reset_postdata();
        } else {
            echo '<p>' . esc_html__('No items found.', 'cine-movie-engine') . '</p>';
        }
        return ob_get_clean();
    }


    public function render_playlists($atts = []) {
        $design_settings = get_option('movie_engine_design_settings', []);
        $default_limit = isset($design_settings['archive_items_per_page']) ? intval($design_settings['archive_items_per_page']) : 12;

        $atts = shortcode_atts([
            'limit'          => $default_limit,
            'columns'        => $design_settings['archive_columns_desktop'] ?? 4,
            'columns_laptop' => $design_settings['archive_columns_laptop'] ?? 4,
            'columns_tablet' => $design_settings['archive_columns_tablet'] ?? 3,
            'columns_mobile' => $design_settings['archive_columns_mobile'] ?? 2,
            'ajax_paged'     => 0
        ], $atts);

        if (!is_user_logged_in()) {
            return '<p>' . esc_html__('Please login to view your playlists.', 'cine-movie-engine') . '</p>';
        }

        $user_id   = get_current_user_id();
        $playlists = self::get_playlists($user_id);

        $paged = $atts['ajax_paged'] > 0 ? $atts['ajax_paged'] : ((get_query_var('paged')) ? get_query_var('paged') : 1);
        $total_playlists = count($playlists);
        $total_pages = ceil($total_playlists / $atts['limit']);

        $offset = ($paged - 1) * $atts['limit'];
        $playlists_slice = array_slice($playlists, $offset, $atts['limit']);

        ob_start();

        if ($atts['ajax_paged'] == 0) {
            echo '<div id="movie-engine-playlists-container" class="movie-engine-ajax-container" data-action="movie_engine_get_playlists_page" data-limit="' . esc_attr($atts['limit']) . '">';
        }

        echo '<div class="movie-engine-playlists-wrapper">';

        echo '<div class="movie-engine-playlists-header">';
        echo '<h3>' . esc_html__('My Playlists', 'cine-movie-engine') . '</h3>';
        echo '<button class="movie-engine-btn me-btn-primary me-add-playlist-btn">';
        echo '<span class="dashicons dashicons-plus-alt2"></span> ';
        echo esc_html__('Add Playlist', 'cine-movie-engine');
        echo '</button>';
        echo '</div>';

        if (empty($playlists)) {
            echo '<div class="movie-engine-playlists-empty">
                    <p>' . esc_html__('You haven\'t created any playlists yet.', 'cine-movie-engine') . '</p>
                 </div>';
        } else {
            echo '<div class="movie-engine-playlists-grid">';
            foreach ($playlists_slice as $pl_id => $pl) {
                $count = count($pl['items'] ?? []);


                $thumbnail_url = '';
                if (!empty($pl['items'])) {
                    $first_item_id = $pl['items'][0];
                    $thumbnail_url = get_the_post_thumbnail_url($first_item_id, 'medium');
                }

                echo '<div class="movie-engine-playlist-card" data-playlist-id="' . esc_attr($pl_id) . '">';


                echo '<div class="movie-engine-pl-menu">';
                echo '<button class="movie-engine-pl-menu-btn" aria-label="' . esc_html__('Playlist options', 'cine-movie-engine') . '">';
                echo '<span class="fa-solid fa-ellipsis-vertical"></span>';
                echo '</button>';
                echo '<div class="movie-engine-pl-dropdown">';
                echo '<button class="movie-engine-pl-rename" data-playlist-id="' . esc_attr($pl_id) . '" data-name="' . esc_attr($pl['name'] ?? '') . '">';
                echo '<span class="fa-solid fa-pen-to-square"></span> ' . esc_html__('Rename', 'cine-movie-engine');
                echo '</button>';
                echo '<button class="movie-engine-pl-delete" data-playlist-id="' . esc_attr($pl_id) . '">';
                echo '<span class="fa-solid fa-trash"></span> ' . esc_html__('Delete', 'cine-movie-engine');
                echo '</button>';
                echo '</div>';
                echo '</div>';


                $pl_options = get_option('movie_engine_player_settings', []);
                $pl_slug = isset($pl_options['playlist_slug']) && !empty($pl_options['playlist_slug']) ? trim($pl_options['playlist_slug'], '/') : 'movie-engine-playlist';

                $playlist_player_url = add_query_arg([
                    'playlist' => $pl_id,
                    'v' => 0
                ], home_url('/' . $pl_slug . '/'));

                echo '<a href="' . esc_url($playlist_player_url) . '">';
                echo '<div class="movie-engine-pl-thumbnail">';
                if ($thumbnail_url) {
                    echo '<img src="' . esc_url($thumbnail_url) . '" alt="' . esc_attr($pl['name'] ?? '') . '">';
                } else {
                    echo '<div class="movie-engine-pl-icon-fallback">';
                    echo '<span class="dashicons dashicons-playlist-video"></span>';
                    echo '</div>';
                }
                echo '</div>';
                echo '</a>';

                echo '<div class="movie-engine-pl-info">';
                echo '<h4>' . esc_html($pl['name'] ?? '') . '</h4>';
                echo '<span class="movie-engine-pl-count">' . esc_html($count) . ' ' . esc_html(_n('Item', 'Items', $count, 'cine-movie-engine')) . '</span>';
                echo '<a href="' . esc_url($playlist_player_url) . '" class="movie-engine-pl-view-link">' . esc_html__('View playlist', 'cine-movie-engine') . '</a>';
                echo '</div>';

                echo '</div>';
            }
            echo '</div>';

            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- kses_post sanitizes HTML
            echo \MovieEngine\Utils\Helpers::kses_post(\MovieEngine\Utils\Helpers::render_pagination($paged, $total_pages));
        }

        echo '</div>';

        if ($atts['ajax_paged'] == 0) {
            echo '</div>';
        }

        return ob_get_clean();
    }
}
