<?php

namespace GriffinForms\Admin\App\Html\Widgets\RightSidebar;

use GriffinForms\Includes\Helpers\Currency;

final class RecentEntries extends \GriffinForms\Admin\App\Html\Widgets\RightSidebar\Format
{
    protected $field_id;
    protected $form_id;
    protected $field_type;
    protected $imageselection_option_map = array();
    protected $recent_entries = array();

    public function getHtml()
    {
        $title = __('Recent Entries', 'griffinforms-form-builder');
        $this->accordionHtml($title);
    }

    protected function accordionBody()
    {
        // Initially empty, will be filled via AJAX
    }

    /**
     * AJAX handler to get recent entries for a selected field.
     */
    public function getRecentEntriesContent()
    {
        $this->checkNonce('recent_entries');

        $this->field_id = isset($_POST['field_id']) ? absint(wp_unslash($_POST['field_id'])) : 0;
        $this->form_id = isset($_POST['form_id']) ? absint(wp_unslash($_POST['form_id'])) : 0;

        // Validate field exists
        if (!$this->sql->itemExists('field', $this->field_id)) {
            $this->errorMessage(__('Field not found.', 'griffinforms-form-builder'));
            wp_die();
        }

        // Validate form exists
        if (!$this->sql->itemExists('form', $this->form_id)) {
            $this->errorMessage(__('Form not found.', 'griffinforms-form-builder'));
            wp_die();
        }

        // Load field to get field type
        $field = $this->sql->itemValues($this->field_id, 'field');
        $this->field_type = strtolower($field->field_type);
        $this->imageselection_option_map = $this->buildImageselectionOptionMap($field);

        // Get recent submissions
        $this->recent_entries = $this->sql->getRecentFieldSubmissions($this->form_id, $this->field_id, 5);

        if (empty($this->recent_entries)) {
            $this->emptyState();
        } else {
            $this->entryList();
        }

        wp_die();
    }

    /**
     * Display list of recent entries.
     */
    protected function entryList()
    {
        echo '<div class="list-group p-3 small">';

        foreach ($this->recent_entries as $index => $entry) {
            $this->entryItem($entry, $index);
        }

        echo '</div>';
    }

    /**
     * Display a single entry item.
     *
     * @param array $entry Entry data
     * @param int $index Entry index
     */
    protected function entryItem($entry, $index)
    {
        $value = $entry['value'];
        $author = $entry['author'];
        $created = $entry['created'];
        $submission_id = $entry['submission_id'];

        // Format the value based on field type
        $formatted_value = $this->formatValue($value, $this->field_type);

        // Get author name
        $author_name = $this->getAuthorName($author);

        // Format date
        $date_formatted = wp_date($this->config->getDateTimeFormat(), strtotime($created));

        // Build submission URL
        $submission_url = admin_url('admin.php?page=griffinforms-submission&id=' . $submission_id);

        echo '<a href="' . esc_url($submission_url) . '" target="_blank" rel="noopener noreferrer" class="list-group-item list-group-item-action px-3 py-2 text-decoration-none" style="color: inherit; cursor: pointer;">';
        echo '<div class="d-flex justify-content-between align-items-start">';

        // Main content
        echo '<div class="flex-grow-1 me-2">';
        echo '<div class="fw-medium mb-1 d-flex align-items-start" style="word-break: break-word;">';

        // Only show field type icon for non-file-upload fields (file uploads already have file icons)
        if ($this->field_type !== 'fileupload') {
            echo $this->getFieldTypeIcon($this->field_type);
        }

        echo '<span class="flex-grow-1">';
        echo wp_kses_post($formatted_value);
        echo '</span>';
        echo '</div>';

        // Metadata
        echo '<div class="text-secondary small">';
        echo '<span class="me-1">';
        echo ' ' . esc_html($author_name);
        echo '</span>';
        echo '•';
        echo '<span class="ms-1">';
        echo esc_html($date_formatted);
        echo '</span>';
        echo '</div>';

        echo '</div>'; // flex-grow-1

        // Badge for file size or value type indicator
        if ($this->field_type === 'fileupload' && is_array($value)) {
            $this->fileSizeBadge($value);
        } elseif ($this->field_type === 'inputaddress' && is_array($value)) {
            // Don't show badge for address fields
        }

        echo '</div>'; // d-flex
        echo '</a>'; // list-group-item link
    }

    /**
     * Format value based on field type.
     *
     * @param mixed $value Field value
     * @param string $field_type Field type
     * @return string Formatted value HTML
     */
    protected function formatValue($value, $field_type)
    {
        // Handle empty/blank values
        if ($value === '' || $value === null || (is_array($value) && empty($value))) {
            return '<span class="text-secondary small">—</span>';
        }

        switch ($field_type) {
            case 'inputlikert':
                $responses = is_string($value) ? json_decode($value, true) : null;
                if (!is_array($responses) || empty($responses)) {
                    return '<span class="text-secondary small">—</span>';
                }
                $parts = [];
                foreach ($responses as $row_id => $col_id) {
                    $parts[] = esc_html($row_id) . ': ' . esc_html((string) $col_id);
                }
                $summary = implode(', ', $parts);
                return '<span class="text-secondary small">' . esc_html(mb_substr($summary, 0, 80)) . (mb_strlen($summary) > 80 ? '…' : '') . '</span>';
            case 'inputrichtext':
                $plain = is_string($value) ? wp_strip_all_tags($value) : '';
                $plain = trim($plain);
                if ($plain === '') {
                    return '<span class="text-secondary small">—</span>';
                }
                return '<span class="text-secondary small">' . esc_html(mb_substr($plain, 0, 80)) . (mb_strlen($plain) > 80 ? '…' : '') . '</span>';
            case 'signature':
                return '<span class="text-secondary small">' . esc_html__('Signature captured', 'griffinforms-form-builder') . '</span>';
            case 'imageselection':
                $selections = $value;
                if (is_string($selections)) {
                    $decoded = json_decode($selections, true);
                    if (json_last_error() === JSON_ERROR_NONE) {
                        $selections = $decoded;
                    } else {
                        $selections = maybe_unserialize($selections);
                    }
                }
                if (!is_array($selections) || empty($selections)) {
                    return '<span class="text-secondary small">—</span>';
                }
                $labels = array();
                foreach ($selections as $selection) {
                    $selection_key = sanitize_key((string) $selection);
                    if ($selection_key === '') {
                        continue;
                    }
                    $labels[] = $this->imageselection_option_map[$selection_key] ?? $selection_key;
                }
                if (empty($labels)) {
                    return '<span class="text-secondary small">—</span>';
                }
                $summary = implode(', ', $labels);
                return '<span class="text-secondary small">' . esc_html(mb_substr($summary, 0, 80)) . (mb_strlen($summary) > 80 ? '…' : '') . '</span>';
            case 'inputrating':
                $rating_value = is_scalar($value) ? trim((string) $value) : '';
                $scale = 5;
                if (is_array($value) && isset($value['scale'])) {
                    $scale = max(1, absint($value['scale']));
                    $rating_value = isset($value['value']) ? trim((string) $value['value']) : '';
                }
                if ($rating_value === '') {
                    return '<span class="text-secondary small">—</span>';
                }
                return '<span>' . esc_html($rating_value) . ' / ' . esc_html((string) $scale) . '</span>';

            case 'fileupload':
                return $this->formatFileValue($value);

            case 'inputaddress':
                return $this->formatAddressValue($value);

            case 'inputemail':
                // Display email as text (not clickable link) since it's inside another link
                return '<span class="text-break">' . esc_html($value) . '</span>';

            case 'inputurl':
                // Display URL as text (not clickable link) since it's inside another link
                return '<span class="text-break">' . esc_html($value) . '</span>';

            case 'inputdate':
                $timestamp = strtotime($value);
                if ($timestamp !== false) {
                    return esc_html(wp_date(get_option('date_format'), $timestamp));
                }
                return esc_html($value);

            case 'inputtime':
                return esc_html($value);

            case 'inputcheckbox':
            case 'inputradio':
                if (is_array($value)) {
                    return esc_html(implode(', ', $value));
                }
                return esc_html($value);

            case 'selectfield':
                return esc_html($value);

            case 'termsconditions':
                if ($value === '1' || $value === 1 || $value === true) {
                    ob_start();
                    echo '<span class="text-success">';
                    $this->mIcon('check_circle', 16);
                    echo ' ' . esc_html__('Accepted', 'griffinforms-form-builder') . '</span>';
                    return ob_get_clean();
                }
                return esc_html($value);

            case 'textarea':
                // Truncate long text
                $text = strip_tags($value);
                if (strlen($text) > 100) {
                    $text = substr($text, 0, 100) . '...';
                }
                return '<span class="text-break">' . esc_html($text) . '</span>';

            case 'payment':
                return $this->formatPaymentValue($value);

            default:
                // InputText, InputNumber, InputPassword, InputPhone
                // Handle string values
                if (is_string($value)) {
                    $text = strip_tags($value);
                    if (strlen($text) > 100) {
                        $text = substr($text, 0, 100) . '...';
                    }
                    return esc_html($text);
                }
                // Handle array values (fallback for unexpected cases)
                if (is_array($value)) {
                    $text = implode(', ', array_filter($value, 'is_string'));
                    if (strlen($text) > 100) {
                        $text = substr($text, 0, 100) . '...';
                    }
                    return esc_html($text);
                }
                return '<span class="text-secondary small">—</span>';
        }
    }

    /**
     * Format address value.
     *
     * @param mixed $value Address data (JSON string or array)
     * @return string Formatted address HTML
     */
    protected function formatAddressValue($value)
    {
        $address_parts = array();

        // Decode if it's a JSON string
        if (is_string($value)) {
            $decoded = json_decode($value, true);
            if (is_array($decoded)) {
                $address_parts = $decoded;
            }
        } elseif (is_array($value)) {
            $address_parts = $value;
        }

        // Filter out empty parts and build address string
        $parts = array();

        if (!empty($address_parts['line1'])) {
            $parts[] = $address_parts['line1'];
        }
        if (!empty($address_parts['line2'])) {
            $parts[] = $address_parts['line2'];
        }
        if (!empty($address_parts['city'])) {
            $parts[] = $address_parts['city'];
        }
        if (!empty($address_parts['state'])) {
            $parts[] = $address_parts['state'];
        }
        if (!empty($address_parts['postal'])) {
            $parts[] = $address_parts['postal'];
        }
        if (!empty($address_parts['country'])) {
            $parts[] = $address_parts['country'];
        }

        if (empty($parts)) {
            return '<span class="text-secondary small">—</span>';
        }

        $address_text = implode(', ', $parts);
        if (strlen($address_text) > 100) {
            $address_text = substr($address_text, 0, 100) . '...';
        }

        return '<span class="text-break">' . esc_html($address_text) . '</span>';
    }

    /**
     * Format file upload value.
     *
     * @param mixed $value File token, comma-separated tokens, or array of tokens
     * @return string Formatted file HTML
     */
    protected function formatFileValue($value)
    {
        $tokens = array();

        // Handle array of tokens
        if (is_array($value)) {
            $tokens = $value;
        }
        // Handle string (could be single token or comma-separated tokens)
        elseif (is_string($value)) {
            // Check if it's comma-separated tokens
            if (strpos($value, ',') !== false) {
                // Multiple tokens separated by commas
                $tokens = array_map('trim', explode(',', $value));
            } else {
                // Single token
                $tokens = array($value);
            }
        }

        // Skip empty values
        if (empty($tokens)) {
            return '<span class="text-muted fst-italic">' . esc_html__('No files', 'griffinforms-form-builder') . '</span>';
        }

        // Process each token
        $file_items = array();
        foreach ($tokens as $token) {
            // Skip empty tokens
            if (empty(trim($token))) {
                continue;
            }

            $file_meta = $this->sql->getFileMetadataByToken($token);
            if (!empty($file_meta['filename'])) {
                $icon = $this->getFileIcon($file_meta['mime'], $file_meta['filename']);
                $file_items[] = $icon . ' ' . esc_html($file_meta['filename']);
            }
        }

        // Return formatted file list
        if (!empty($file_items)) {
            return '<span>' . implode('</span><br><span>', $file_items) . '</span>';
        }

        return '<span class="text-muted fst-italic">' . esc_html__('Files not found', 'griffinforms-form-builder') . '</span>';
    }

    /**
     * Format payment field values (product summary).
     *
     * @param mixed $value Raw payment value from submission.
     * @return string
     */
    protected function formatPaymentValue($value)
    {
        // Decode serialized/JSON values if needed
        $data = $this->maybeDecode($value);
        if (!is_array($data)) {
            return '<span class="text-secondary small">—</span>';
        }

        $items = $data['items'] ?? array();
        if (!is_array($items) || empty($items)) {
            return '<span class="text-secondary small">—</span>';
        }

        $currency_helper = Currency::getInstance();
        $fallback_currency = $this->settings->getOption('payment_currency', 'payments');

        $lines = array();
        foreach ($items as $item) {
            if (!is_array($item)) {
                continue;
            }
            $name = $item['product_name'] ?? ($item['product_id'] ?? __('Item', 'griffinforms-form-builder'));
            $qty = isset($item['quantity']) ? (float) $item['quantity'] : 1;
            $currency = $item['currency'] ?? $fallback_currency;
            $total = isset($item['total']) ? (float) $item['total'] : 0;
            $formatted_total = $currency_helper->formatAmount($total, $currency);
            $lines[] = sprintf(
                '%s × %s — %s',
                esc_html($name),
                esc_html($qty),
                esc_html($formatted_total)
            );
            if (count($lines) >= 3) {
                break;
            }
        }

        if (empty($lines)) {
            return '<span class="text-secondary small">—</span>';
        }

        $html_lines = array_map(
            static function ($line) {
                return '<span class="d-block text-break">' . $line . '</span>';
            },
            $lines
        );

        return implode('', $html_lines);
    }

    /**
     * Build a slug-to-title lookup for Image Selection values.
     *
     * @param object $field Field record from SQL helper.
     * @return array
     */
    protected function buildImageselectionOptionMap($field)
    {
        if (!is_object($field) || empty($field->field_settings)) {
            return array();
        }

        $settings = maybe_unserialize($field->field_settings);
        if (is_string($settings)) {
            $decoded = json_decode($settings, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                $settings = $decoded;
            }
        }

        if (!is_array($settings) || empty($settings['options']) || !is_array($settings['options'])) {
            return array();
        }

        $map = array();
        foreach ($settings['options'] as $option) {
            if (!is_array($option)) {
                continue;
            }

            $value = !empty($option['value']) ? sanitize_key((string) $option['value']) : '';
            if ($value === '') {
                continue;
            }

            $title = !empty($option['title']) ? sanitize_text_field((string) $option['title']) : $value;
            $map[$value] = $title;
        }

        return $map;
    }

    /**
     * Get file icon based on mime type or file extension.
     *
     * @param string $mime MIME type
     * @param string $filename Optional filename to extract extension
     * @return string Icon HTML (img tag)
     */
    protected function getFileIcon($mime, $filename = '')
    {
        $icon_name = 'file'; // Default icon

        // Get file extension from filename if provided
        $extension = '';
        if (!empty($filename)) {
            $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        }

        // Determine icon based on mime type or extension
        if (strpos($mime, 'image/') === 0 || in_array($extension, array('jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'))) {
            if ($extension === 'gif') {
                $icon_name = 'gif';
            } else {
                $icon_name = 'image';
            }
        } elseif (strpos($mime, 'video/') === 0 || in_array($extension, array('mp4', 'avi', 'mov', 'wmv', 'flv', 'webm'))) {
            $icon_name = 'video';
        } elseif (strpos($mime, 'audio/') === 0 || in_array($extension, array('mp3', 'wav', 'ogg', 'flac', 'm4a'))) {
            $icon_name = 'audio';
        } elseif (strpos($mime, 'pdf') !== false || $extension === 'pdf') {
            $icon_name = 'pdf';
        } elseif (strpos($mime, 'zip') !== false || strpos($mime, 'compressed') !== false || in_array($extension, array('zip', 'rar', '7z', 'tar', 'gz'))) {
            $icon_name = 'archive';
        } elseif (in_array($extension, array('doc', 'docx')) || strpos($mime, 'word') !== false) {
            $icon_name = $extension === 'docx' ? 'docx' : 'doc';
        } elseif (in_array($extension, array('xls', 'xlsx')) || strpos($mime, 'excel') !== false || strpos($mime, 'spreadsheet') !== false) {
            $icon_name = $extension === 'xlsx' ? 'xlsx' : 'xls';
        } elseif ($extension === 'ppt' || $extension === 'pptx' || strpos($mime, 'powerpoint') !== false || strpos($mime, 'presentation') !== false) {
            $icon_name = 'ppt';
        } elseif ($extension === 'txt' || strpos($mime, 'text/plain') !== false) {
            $icon_name = 'txt';
        } elseif (in_array($extension, array('json', 'xml', 'html', 'css', 'js', 'php', 'py', 'java', 'cpp', 'c', 'h')) || strpos($mime, 'json') !== false || strpos($mime, 'xml') !== false) {
            if ($extension === 'json') {
                $icon_name = 'json';
            } else {
                $icon_name = 'code';
            }
        }

        // Build icon URL
        $icon_url = $this->config->getRootUrl() . 'frontend/images/fileicons/' . $icon_name . '.svg';

        // Return img tag
        return '<img src="' . esc_url($icon_url) . '" alt="' . esc_attr($icon_name) . '" style="width: 14px; height: 14px; vertical-align: middle;" class="me-1">';
    }

    /**
     * Get field type icon.
     *
     * @param string $field_type Field type (e.g., 'inputtext', 'inputemail')
     * @return string Icon HTML (img tag)
     */
    protected function getFieldTypeIcon($field_type)
    {
        $field_type_lower = strtolower($field_type);

        // Map field types to icon filenames
        $icon_name = 'griffinforms_icon_' . $field_type_lower . '.svg';

        // Check if specific icon exists, otherwise use fallback
        $icon_path = $this->config->getRootPath() . 'admin/images/field-icons/' . $icon_name;

        if (!file_exists($icon_path)) {
            $icon_name = 'griffinforms_icon_fallback.svg';
        }

        // Build icon URL
        $icon_url = $this->config->getRootUrl() . 'admin/images/field-icons/' . $icon_name;

        // Return img tag with proper styling
        return '<img src="' . esc_url($icon_url) . '" alt="' . esc_attr($field_type) . '" style="width: 18px; height: 18px; flex-shrink: 0;" class="me-2">';
    }

    /**
     * Display file size badge.
     *
     * @param mixed $value File token(s) - can be string (single or comma-separated) or array
     */
    protected function fileSizeBadge($value)
    {
        $total_size = 0;
        $file_count = 0;
        $tokens = array();

        // Normalize to array of tokens
        if (is_array($value)) {
            $tokens = $value;
        } elseif (is_string($value)) {
            // Check if it's comma-separated tokens
            if (strpos($value, ',') !== false) {
                $tokens = array_map('trim', explode(',', $value));
            } else {
                $tokens = array($value);
            }
        }

        // Calculate total size
        foreach ($tokens as $token) {
            if (empty(trim($token))) {
                continue;
            }

            $file_meta = $this->sql->getFileMetadataByToken($token);
            if (!empty($file_meta['size_bytes'])) {
                $total_size += $file_meta['size_bytes'];
                $file_count++;
            }
        }

        if ($file_count > 0) {
            $formatted_size = size_format($total_size);
            echo '<span class="badge bg-secondary" style="font-size: 0.7rem;">';
            echo esc_html($formatted_size);
            echo '</span>';
        }
    }

    /**
     * Get author name from user ID.
     *
     * @param string $author User ID
     * @return string Author display name
     */
    protected function getAuthorName($author)
    {
        $user_id = absint($author);

        if ($user_id === 0) {
            return __('Guest', 'griffinforms-form-builder');
        }

        $user = get_user_by('id', $user_id);

        if ($user !== false) {
            return $user->display_name;
        }

        return __('Unknown User', 'griffinforms-form-builder');
    }

    /**
     * Display empty state when no submissions exist.
     */
    protected function emptyState()
    {
        echo '<div class="text-center my-4 py-4 small">';
        echo '<div class="mb-2">';
        $this->mIcon('inbox', 28);
        echo '</div>';
        echo '<div class="fw-medium">' . esc_html__('No entries for this field', 'griffinforms-form-builder') . '</div>';
        echo '<div class="mx-3 text-muted">' . esc_html__('Recent entries will appear here once users submit data for this field', 'griffinforms-form-builder') . '</div>';
        echo '</div>';
    }

    /**
     * Display error message.
     *
     * @param string $message Error message
     */
    protected function errorMessage($message)
    {
        echo '<div class="alert alert-danger m-2" role="alert">';
        echo esc_html($message);
        echo '</div>';
    }

    /**
     * Generate placeholder skeleton for loading state.
     *
     * @return string HTML for placeholder skeletons
     */
    protected function getPlaceholderSkeleton()
    {
        ob_start();
        echo '<div class="list-group p-3">';

        // Generate 5 placeholder items
        for ($i = 0; $i < 5; $i++) {
            echo '<div class="list-group-item px-3 py-2">';
            echo '<div class="d-flex justify-content-between align-items-start">';

            echo '<div class="flex-grow-1 me-2">';

            // Value placeholder
            echo '<div class="mb-2 d-flex align-items-start">';
            echo '<span class="placeholder bg-secondary me-2" style="width: 18px; height: 18px; display: inline-block; border-radius: 3px;"></span>';
            echo '<span class="placeholder col-' . (7 + ($i % 3)) . ' bg-secondary"></span>';
            echo '</div>';

            // Metadata placeholder
            echo '<div class="d-flex align-items-center gap-2">';
            echo '<span class="placeholder col-3 bg-secondary" style="height: 14px;"></span>';
            echo '<span class="bg-secondary" style="width: 4px; height: 4px; border-radius: 50%; display: inline-block;"></span>';
            echo '<span class="placeholder col-4 bg-secondary" style="height: 14px;"></span>';
            echo '</div>';

            echo '</div>';

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

        echo '</div>';
        return ob_get_clean();
    }

    /**
     * Widget JavaScript.
     */
    public function widgetJs()
    {
        $this->showEntriesJs();
        $this->hideEntriesJs();
    }

    /**
     * JavaScript to show entries when field is selected.
     */
    protected function showEntriesJs()
    {
        $nonce = wp_create_nonce('recent_entries');
        $placeholder_html = $this->getPlaceholderSkeleton();

        echo '
        document.addEventListener("item-selected", () => {

            const selectedItem = $("[data-gf-selected=true]");
            const itemType = selectedItem.attr("data-gf-itemtype");
            const itemId = selectedItem.attr("data-gf-itemid");

            // Only show widget for fields
            if (itemType !== "field") {
                $("#' . esc_attr($this->getHtmlId()) . '").hide();
                return;
            }

            // Get form ID from the form element
            const formElement = $("#griffinforms-app-presentationarea").find("[data-gf-itemtype=form]");
            const formId = formElement.attr("data-gf-itemid");

            if (!formId) {
                $("#' . esc_attr($this->getHtmlId()) . '").hide();
                return;
            }

            // Show widget with placeholder skeleton
            $("#' . esc_attr($this->getHtmlId()) . '").show();
            $("#' . esc_attr($this->getHtmlId('spinner')) . '").hide();
            $("#' . esc_attr($this->getHtmlId('content')) . '").find(".accordion-body").html(`' . addslashes($placeholder_html) . '`);

            const data = {
                "action": "getRecentEntriesContent",
                "field_id": itemId,
                "form_id": formId,
                "nonce": "' . esc_js($nonce) . '"
            };

            $.post(ajaxurl, data, function(response) {
                var gfParsed = null;
                try { gfParsed = JSON.parse(response); } catch(e) {}
                if (gfParsed && gfParsed.success === false) {
                    var gfMsg = gfParsed.msg || "An error occurred. Please try again.";
                    $("#' . esc_attr($this->getHtmlId('content')) . '").find(".accordion-body").html(
                        "<div class=\"alert alert-danger m-2\" role=\"alert\">" + $("<div>").text(gfMsg).html() + "</div>"
                    );
                } else {
                    $("#' . esc_attr($this->getHtmlId('content')) . '").find(".accordion-body").html(response);
                }
                $("#' . esc_attr($this->getHtmlId('spinner')) . '").hide();
            }).fail(function() {
                $("#' . esc_attr($this->getHtmlId('content')) . '").find(".accordion-body").html(
                    "<div class=\"alert alert-danger m-2\">' . esc_js(__('Failed to load recent entries. Please try again.', 'griffinforms-form-builder')) . '</div>"
                );
                $("#' . esc_attr($this->getHtmlId('spinner')) . '").hide();
            });
        });
        ' . PHP_EOL;
    }

    /**
     * JavaScript to hide entries when item is deselected.
     */
    protected function hideEntriesJs()
    {
        echo '
        document.addEventListener("item-deselected", () => {
            $("#' . esc_attr($this->getHtmlId()) . '").hide();
            $("#' . esc_attr($this->getHtmlId()) . '").find(".accordion-body").html("");
        });
        ' . PHP_EOL;
    }

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->setAll();
        add_action('wp_ajax_getRecentEntriesContent', array($this, 'getRecentEntriesContent'));
    }
}
