<?php
/**
 * Admin management dashboard (overview, live metrics, tasks, quick actions).
 *
 * @package Maca_Menu_List
 */

if (!defined('ABSPATH')) {
    exit;
}

require_once MACA_MENULIST_PLUGIN_DIR . 'includes/dashboard-data.php';

/**
 * Management dashboard admin screen.
 */
class Maca_MenuList_Admin_Dashboard {

    /**
     * Constructor.
     *
     * @param bool $register_hooks When false, only rendering helpers are available (public overview).
     */
    public function __construct($register_hooks = true) {
        if (!$register_hooks) {
            return;
        }

        add_action('admin_menu', array($this, 'add_admin_menu'), 15);
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_action('wp_ajax_maca_dashboard_refresh', array($this, 'ajax_refresh'));
        add_action('wp_ajax_maca_dashboard_history', array($this, 'ajax_history'));
    }

    /**
     * Register dashboard submenu (first in menu order via admin.php reorder).
     */
    public function add_admin_menu() {
        add_submenu_page(
            'maca-restu',
            __('Översikt', 'maca-restu-pro'),
            __('Översikt', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-dashboard',
            array($this, 'render_page')
        );
    }

    /**
     * Enqueue dashboard assets.
     *
     * @param string $hook Admin page hook.
     */
    public function enqueue_scripts($hook) {
        if ($hook !== 'maca-restu_page_maca-restu-dashboard') {
            return;
        }

        wp_enqueue_style(
            'maca-menulist-admin-dashboard',
            MACA_MENULIST_PLUGIN_URL . 'assets/css/admin-dashboard.css',
            array(),
            MACA_MENULIST_VERSION
        );

        wp_enqueue_script(
            'chart-js',
            MACA_MENULIST_PLUGIN_URL . 'assets/vendor/chartjs/chart.umd.min.js',
            array(),
            '4.4.1',
            true
        );

        wp_enqueue_script(
            'maca-menulist-admin-dashboard-charts',
            MACA_MENULIST_PLUGIN_URL . 'assets/js/admin-dashboard-charts.js',
            array('chart-js'),
            MACA_MENULIST_VERSION,
            true
        );

        wp_enqueue_script(
            'maca-menulist-admin-dashboard',
            MACA_MENULIST_PLUGIN_URL . 'assets/js/admin-dashboard.js',
            array('maca-menulist-admin-dashboard-charts'),
            MACA_MENULIST_VERSION,
            true
        );

        wp_localize_script(
            'maca-menulist-admin-dashboard',
            'macaMenulistDashboard',
            array(
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('maca_dashboard_refresh'),
                'pollInterval' => 60000,
                'currency' => function_exists('maca_menulist_get_price_currency')
                    ? maca_menulist_get_price_currency()
                    : 'SEK',
                'today' => maca_menulist_dashboard_today_date(),
                'initial' => maca_menulist_get_dashboard_payload(),
                'labels' => array(
                    'live' => __('Live', 'maca-restu-pro'),
                    'updating' => __('Uppdaterar…', 'maca-restu-pro'),
                    'updateError' => __('Kunde inte uppdatera data. Försöker igen…', 'maca-restu-pro'),
                    'lastUpdated' => __('Senast uppdaterad', 'maca-restu-pro'),
                    'noActions' => __('Inget behöver åtgärdas just nu.', 'maca-restu-pro'),
                    'historyTitle' => __('Historik', 'maca-restu-pro'),
                    'presetToday' => __('Idag', 'maca-restu-pro'),
                    'presetYesterday' => __('Igår', 'maca-restu-pro'),
                    'preset7days' => __('Senaste 7 dagarna', 'maca-restu-pro'),
                    'preset30days' => __('Senaste 30 dagarna', 'maca-restu-pro'),
                    'dateFrom' => __('Från', 'maca-restu-pro'),
                    'dateTo' => __('Till', 'maca-restu-pro'),
                    'applyPeriod' => __('Visa period', 'maca-restu-pro'),
                    'topDishes' => __('Topprätter (klick)', 'maca-restu-pro'),
                    'clicks' => __('klick', 'maca-restu-pro'),
                    'noDishStats' => __('Inga rättklick registrerade för perioden ännu.', 'maca-restu-pro'),
                    'viewAllStats' => __('Visa all rättstatistik', 'maca-restu-pro'),
                    'periodOrders' => __('Ordrar i perioden', 'maca-restu-pro'),
                    'periodRevenue' => __('Intäkter i perioden', 'maca-restu-pro'),
                    'periodBookings' => __('Bokningar i perioden', 'maca-restu-pro'),
                    'periodPending' => __('väntande', 'maca-restu-pro'),
                    'totalClicks' => __('Totala klick', 'maca-restu-pro'),
                    'chartsTitle' => __('Diagram', 'maca-restu-pro'),
                    'noCharts' => __('Ingen diagramdata för perioden ännu. Prova ett längre intervall eller invänta gästaktivitet.', 'maca-restu-pro'),
                ),
            )
        );
    }

    /**
     * AJAX: refresh metrics and action items.
     */
    public function ajax_refresh() {
        check_ajax_referer('maca_dashboard_refresh', 'nonce');

        if (!maca_menulist_user_can_manage_plugin()) {
            wp_send_json_error(array('message' => __('Forbidden', 'maca-restu-pro')), 403);
        }

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

        wp_send_json_success(
            array(
                'metrics' => maca_menulist_get_dashboard_metrics(),
                'actions' => maca_menulist_get_dashboard_action_items(),
                'history' => maca_menulist_get_dashboard_history($date_from, $date_to),
            )
        );
    }

    /**
     * AJAX: load history for a custom period.
     */
    public function ajax_history() {
        check_ajax_referer('maca_dashboard_refresh', 'nonce');

        if (!maca_menulist_user_can_manage_plugin()) {
            wp_send_json_error(array('message' => __('Forbidden', 'maca-restu-pro')), 403);
        }

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

        wp_send_json_success(maca_menulist_get_dashboard_history($date_from, $date_to));
    }

    /**
     * Render dashboard page (wp-admin).
     */
    public function render_page() {
        if (!maca_menulist_user_can_manage_plugin()) {
            return;
        }

        $this->render_dashboard(false);
    }

    /**
     * Render dashboard markup (admin or public read-only).
     *
     * @param bool $readonly When true, hide links and write affordances.
     */
    public function render_dashboard($readonly = false) {
        $metrics = maca_menulist_get_dashboard_metrics();
        $actions = maca_menulist_get_dashboard_action_items();
        $quick_actions = $readonly ? array() : maca_menulist_get_dashboard_quick_actions();
        $history = maca_menulist_get_dashboard_history();
        $unlicensed = !$readonly
            && defined('MACA_MENULIST_PRO')
            && function_exists('maca_menulist_pro_is_active')
            && !maca_menulist_pro_is_active();

        if ($readonly) {
            $sanitized = maca_menulist_sanitize_dashboard_payload_readonly(
                array(
                    'metrics' => $metrics,
                    'actions' => $actions,
                    'history' => $history,
                )
            );
            $metrics = $sanitized['metrics'];
            $actions = $sanitized['actions'];
            $history = $sanitized['history'];
        }

        $wrap_class = $readonly ? 'maca-dashboard-wrap maca-dashboard-wrap--readonly' : 'wrap maca-dashboard-wrap';
        ?>
        <div class="<?php echo esc_attr($wrap_class); ?>">
            <h1><?php esc_html_e('Översikt', 'maca-restu-pro'); ?></h1>
            <?php if ($readonly) : ?>
                <p class="maca-dashboard-readonly-notice"><?php esc_html_e('Skrivskyddad vy — inga ändringar kan göras här.', 'maca-restu-pro'); ?></p>
            <?php endif; ?>

            <div class="maca-dashboard-header">
                <span class="maca-dashboard-live" id="maca-dashboard-live" aria-live="polite">
                    <span class="maca-dashboard-live-dot" aria-hidden="true"></span>
                    <?php esc_html_e('Live', 'maca-restu-pro'); ?>
                </span>
                <span class="maca-dashboard-updated" id="maca-dashboard-updated">
                    <?php
                    echo esc_html(
                        sprintf(
                            /* translators: %s: time */
                            __('Senast uppdaterad %s', 'maca-restu-pro'),
                            $metrics['updated_at_label']
                        )
                    );
                    ?>
                </span>
                <span class="maca-dashboard-updated-spacer" aria-hidden="true"></span>
                <div class="maca-dashboard-header-links" aria-label="<?php esc_attr_e('Shortcuts', 'maca-restu-pro'); ?>">
                    <?php if (!empty($metrics['campaign']) && !empty($metrics['campaign']['title'])) : ?>
                        <?php if ($readonly) : ?>
                            <span class="maca-dashboard-header-link maca-dashboard-header-link--readonly" id="maca-dashboard-link-campaign">
                                <span class="maca-dashboard-header-link-label"><?php esc_html_e('Aktiv meny', 'maca-restu-pro'); ?></span>
                                <span class="maca-dashboard-header-link-count" id="maca-dashboard-active-campaign-title"><?php echo esc_html((string) $metrics['campaign']['title']); ?></span>
                            </span>
                        <?php elseif (!empty($metrics['campaign']['url'])) : ?>
                            <a class="maca-dashboard-header-link" id="maca-dashboard-link-campaign" href="<?php echo esc_url($metrics['campaign']['url']); ?>">
                                <span class="maca-dashboard-header-link-label"><?php esc_html_e('Aktiv meny', 'maca-restu-pro'); ?></span>
                                <span class="maca-dashboard-header-link-count" id="maca-dashboard-active-campaign-title"><?php echo esc_html((string) $metrics['campaign']['title']); ?></span>
                            </a>
                        <?php endif; ?>
                    <?php endif; ?>
                    <?php if (!empty($metrics['bookings_enabled']) && !empty($metrics['bookings'])) : ?>
                        <?php $pending_reservations = (int) ($metrics['bookings']['pending_all'] ?? 0); ?>
                        <?php if ($readonly) : ?>
                            <?php $this->render_day_occupancy_header($metrics['bookings']); ?>
                            <span class="maca-dashboard-header-link maca-dashboard-header-link--readonly" id="maca-dashboard-link-pending-reservations">
                                <span class="maca-dashboard-header-link-label"><?php esc_html_e('Väntande bordsreservationer', 'maca-restu-pro'); ?></span>
                                <span class="maca-dashboard-header-link-count" id="maca-dashboard-count-pending-reservations"><?php echo esc_html((string) $pending_reservations); ?></span>
                            </span>
                        <?php else : ?>
                            <a class="maca-dashboard-header-link" id="maca-dashboard-link-pending-reservations" href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-bookings')); ?>">
                                <span class="maca-dashboard-header-link-label"><?php esc_html_e('Väntande bordsreservationer', 'maca-restu-pro'); ?></span>
                                <span class="maca-dashboard-header-link-count" id="maca-dashboard-count-pending-reservations"><?php echo esc_html((string) $pending_reservations); ?></span>
                            </a>
                            <?php $this->render_day_occupancy_header($metrics['bookings']); ?>
                            <a class="maca-dashboard-header-link" id="maca-dashboard-link-floor-overview" href="<?php echo esc_url(add_query_arg('booking_date', wp_date('Y-m-d'), admin_url('admin.php?page=maca-restu-bookings&tab=floor'))); ?>">
                                <span class="maca-dashboard-header-link-label"><?php esc_html_e('Salongsöversikt', 'maca-restu-pro'); ?></span>
                            </a>
                        <?php endif; ?>
                    <?php endif; ?>
                    <?php if (!empty($metrics['orders_enabled']) && !empty($metrics['orders'])) : ?>
                        <?php $unpaid_active = (int) ($metrics['orders']['unpaid_active'] ?? 0); ?>
                        <?php if ($readonly) : ?>
                            <span class="maca-dashboard-header-link maca-dashboard-header-link--readonly" id="maca-dashboard-link-unpaid">
                                <span class="maca-dashboard-header-link-label"><?php esc_html_e('Ej betalda ordrar', 'maca-restu-pro'); ?></span>
                                <span class="maca-dashboard-header-link-count" id="maca-dashboard-count-unpaid"><?php echo esc_html((string) $unpaid_active); ?></span>
                            </span>
                        <?php else : ?>
                            <a class="maca-dashboard-header-link" id="maca-dashboard-link-unpaid" href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-orders&status_filter=active')); ?>">
                                <span class="maca-dashboard-header-link-label"><?php esc_html_e('Ej betalda ordrar', 'maca-restu-pro'); ?></span>
                                <span class="maca-dashboard-header-link-count" id="maca-dashboard-count-unpaid"><?php echo esc_html((string) $unpaid_active); ?></span>
                            </a>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>

            <div id="maca-dashboard-metrics" class="maca-dashboard-metrics">
                <?php $this->render_metrics_cards($metrics); ?>
            </div>

            <?php if (maca_menulist_is_dishes_mode()) : ?>
            <section class="maca-dashboard-panel maca-dashboard-panel--history" aria-labelledby="maca-dashboard-history-heading">
                <h2 id="maca-dashboard-history-heading"><?php esc_html_e('Historik', 'maca-restu-pro'); ?></h2>

                <form id="maca-dashboard-history-form" class="maca-dashboard-history-form" action="#" method="get">
                    <div class="maca-dashboard-history-presets" role="group" aria-label="<?php esc_attr_e('Snabbperiod', 'maca-restu-pro'); ?>">
                        <button type="button" class="button maca-dashboard-preset" data-preset="today"><?php esc_html_e('Idag', 'maca-restu-pro'); ?></button>
                        <button type="button" class="button maca-dashboard-preset" data-preset="yesterday"><?php esc_html_e('Igår', 'maca-restu-pro'); ?></button>
                        <button type="button" class="button maca-dashboard-preset" data-preset="7days"><?php esc_html_e('Senaste 7 dagarna', 'maca-restu-pro'); ?></button>
                        <button type="button" class="button maca-dashboard-preset" data-preset="30days"><?php esc_html_e('Senaste 30 dagarna', 'maca-restu-pro'); ?></button>
                    </div>
                    <div class="maca-dashboard-history-dates">
                        <label>
                            <?php esc_html_e('Från', 'maca-restu-pro'); ?>
                            <input type="date" name="date_from" id="maca-dashboard-date-from" value="<?php echo esc_attr($history['date_from']); ?>">
                        </label>
                        <label>
                            <?php esc_html_e('Till', 'maca-restu-pro'); ?>
                            <input type="date" name="date_to" id="maca-dashboard-date-to" value="<?php echo esc_attr($history['date_to']); ?>">
                        </label>
                        <button type="submit" class="button button-secondary"><?php esc_html_e('Visa period', 'maca-restu-pro'); ?></button>
                    </div>
                </form>

                <p class="maca-dashboard-history-period" id="maca-dashboard-history-period">
                    <?php echo esc_html($history['period_label']); ?>
                </p>

                <div id="maca-dashboard-history-summary" class="maca-dashboard-history-summary">
                    <?php $this->render_history_summary($history); ?>
                </div>

                <h3 class="maca-dashboard-subheading"><?php esc_html_e('Diagram', 'maca-restu-pro'); ?></h3>
                <div id="maca-dashboard-charts" class="maca-dashboard-charts" aria-live="polite"></div>

                <h3 class="maca-dashboard-subheading"><?php esc_html_e('Topprätter (klick)', 'maca-restu-pro'); ?></h3>
                <ol id="maca-dashboard-top-dishes" class="maca-dashboard-top-dishes">
                    <?php $this->render_top_dishes($history, $readonly); ?>
                </ol>

                <?php if (!$readonly && !empty($history['stats_url'])) : ?>
                    <p class="maca-dashboard-history-link-wrap">
                        <a id="maca-dashboard-stats-link" class="button button-link" href="<?php echo esc_url($history['stats_url']); ?>">
                            <?php esc_html_e('Visa all rättstatistik', 'maca-restu-pro'); ?> →
                        </a>
                    </p>
                <?php endif; ?>
            </section>
            <?php endif; ?>

            <div class="maca-dashboard-columns<?php echo $readonly ? ' maca-dashboard-columns--readonly' : ''; ?><?php echo $unlicensed ? ' maca-dashboard-columns--unlicensed' : ''; ?>">
                <section class="maca-dashboard-panel maca-dashboard-panel--actions" aria-labelledby="maca-dashboard-actions-heading">
                    <h2 id="maca-dashboard-actions-heading"><?php esc_html_e('Behöver åtgärd', 'maca-restu-pro'); ?></h2>
                    <ul id="maca-dashboard-actions" class="maca-dashboard-actions">
                        <?php $this->render_action_items($actions, $readonly); ?>
                    </ul>
                    <?php if ($unlicensed && !empty($quick_actions)) : ?>
                        <h3 class="maca-dashboard-subheading maca-dashboard-subheading--quick" id="maca-dashboard-quick-heading"><?php esc_html_e('Snabbåtgärder', 'maca-restu-pro'); ?></h3>
                        <?php $this->render_quick_actions($quick_actions); ?>
                    <?php endif; ?>
                </section>

                <?php if (!$readonly && !$unlicensed) : ?>
                <section class="maca-dashboard-panel maca-dashboard-panel--quick" aria-labelledby="maca-dashboard-quick-heading">
                    <h2 id="maca-dashboard-quick-heading"><?php esc_html_e('Snabbåtgärder', 'maca-restu-pro'); ?></h2>
                    <?php $this->render_quick_actions($quick_actions); ?>
                </section>
                <?php endif; ?>
            </div>
        </div>
        <?php
    }

    /**
     * Output metric stat cards.
     *
     * @param array<string, mixed> $metrics Metrics payload.
     */
    private function render_metrics_cards($metrics) {
        if (!empty($metrics['orders_enabled']) && !empty($metrics['orders'])) {
            $o = $metrics['orders'];
            $this->render_metric_card('orders_today', __('Orders today', 'maca-restu-pro'), (string) (int) $o['count_today']);
            $this->render_metric_card('revenue', __('Revenue today', 'maca-restu-pro'), $o['revenue_label']);
            $this->render_metric_card('active_orders', __('Active orders', 'maca-restu-pro'), (string) (int) $o['active']);
            $this->render_metric_card('avg_time', __('Avg. handling time', 'maca-restu-pro'), $o['avg_minutes_label']);
            $this->render_metric_card('paid_today', __('Paid today', 'maca-restu-pro'), (string) (int) $o['paid_today']);
            $this->render_metric_card('pending_pay', __('Awaiting payment', 'maca-restu-pro'), (string) (int) $o['pending_payment']);
        }

        if (!empty($metrics['bookings_enabled']) && !empty($metrics['bookings'])) {
            $b = $metrics['bookings'];
            $this->render_metric_card('bookings_today', __('Bookings today', 'maca-restu-pro'), (string) (int) $b['today_total']);
            $this->render_metric_card('guests_today', __('Confirmed guests', 'maca-restu-pro'), (string) (int) $b['confirmed_guests']);
            $this->render_metric_card('pending_book_today', __('Pending today', 'maca-restu-pro'), (string) (int) $b['pending_today']);
            $this->render_metric_card('pending_book_all', __('Pending bookings', 'maca-restu-pro'), (string) (int) $b['pending_all']);
        }

        if (empty($metrics['orders_enabled']) && empty($metrics['bookings_enabled'])) {
            echo '<p class="maca-dashboard-empty-metrics">';
            esc_html_e('Aktivera bordsbeställning eller bokning under Inställningar för att se live-statistik här.', 'maca-restu-pro');
            echo '</p>';
        }
    }

    /**
     * Single metric card.
     *
     * @param string $key   Metric key for JS updates.
     * @param string $label Card label.
     * @param string $value Display value (may contain safe HTML from format_price).
     */
    private function render_metric_card($key, $label, $value) {
        echo '<div class="maca-dashboard-metric" data-metric="' . esc_attr($key) . '">';
        echo '<span class="maca-dashboard-metric-value">' . wp_kses_post($value) . '</span>';
        echo '<span class="maca-dashboard-metric-label">' . esc_html($label) . '</span>';
        echo '</div>';
    }

    /**
     * Day occupancy in the dashboard header (above Salongsöversikt).
     *
     * @param array<string, mixed> $bookings Bookings metrics block.
     */
    private function render_day_occupancy_header($bookings) {
        $occ = isset($bookings['day_occupancy']) && is_array($bookings['day_occupancy'])
            ? $bookings['day_occupancy']
            : array();
        $level = isset($occ['level']) ? sanitize_key((string) $occ['level']) : 'low';

        if (!in_array($level, array('low', 'medium', 'high'), true)) {
            $level = 'low';
        }

        $label_text = isset($occ['label']) ? (string) $occ['label'] : '—';

        echo '<span class="maca-dashboard-header-link maca-dashboard-header-link--occupancy" id="maca-dashboard-header-day-occupancy" data-metric="day_occupancy" data-occupancy-level="' . esc_attr($level) . '">';
        echo '<span class="maca-dashboard-header-link-label">' . esc_html__('Day occupancy', 'maca-restu-pro') . '</span>';
        echo '<span class="maca-dashboard-header-link-count maca-booking-occupancy maca-booking-occupancy-' . esc_attr($level) . '">';
        echo esc_html($label_text);
        echo '</span>';
        echo '</span>';
    }

    /**
     * Quick-action button row.
     *
     * @param array<int, array<string, string>> $quick_actions Quick actions.
     */
    private function render_quick_actions($quick_actions) {
        if (empty($quick_actions)) {
            return;
        }

        echo '<div class="maca-dashboard-quick-actions">';
        foreach ($quick_actions as $action) {
            echo '<a';
            echo ' href="' . esc_url($action['url']) . '"';
            echo ' class="' . esc_attr($action['class']) . '"';
            if (!empty($action['target'])) {
                echo ' target="' . esc_attr($action['target']) . '" rel="noopener noreferrer"';
            }
            echo '>';
            echo esc_html($action['label']);
            echo '</a>';
        }
        echo '</div>';
    }

    /**
     * Action item list markup.
     *
     * @param array<int, array<string, mixed>> $actions  Action items.
     * @param bool                             $readonly Read-only (no admin links).
     */
    private function render_action_items($actions, $readonly = false) {
        if (empty($actions)) {
            echo '<li class="maca-dashboard-action maca-dashboard-action--empty">';
            esc_html_e('Inget behöver åtgärdas just nu.', 'maca-restu-pro');
            echo '</li>';
            return;
        }

        foreach ($actions as $item) {
            $severity = isset($item['severity']) ? sanitize_html_class($item['severity']) : 'info';
            echo '<li class="maca-dashboard-action maca-dashboard-action--' . esc_attr($severity) . '">';
            if ($readonly || empty($item['url'])) {
                echo '<div class="maca-dashboard-action-inner">';
            } else {
                echo '<a href="' . esc_url($item['url']) . '">';
            }
            if (!empty($item['count'])) {
                echo '<span class="maca-dashboard-action-count">' . esc_html((string) (int) $item['count']) . '</span>';
            }
            echo '<span class="maca-dashboard-action-label">' . esc_html($item['label']) . '</span>';
            echo ($readonly || empty($item['url'])) ? '</div>' : '</a>';
            echo '</li>';
        }
    }

    /**
     * Period summary chips for history section.
     *
     * @param array<string, mixed> $history History payload.
     */
    private function render_history_summary($history) {
        if (isset($history['total_clicks'])) {
            echo '<span class="maca-dashboard-history-chip">';
            echo esc_html(
                sprintf(
                    /* translators: %d: click count */
                    __('Totala klick: %d', 'maca-restu-pro'),
                    (int) $history['total_clicks']
                )
            );
            echo '</span>';
        }

        if (!empty($history['orders'])) {
            $o = $history['orders'];
            echo '<span class="maca-dashboard-history-chip">';
            echo esc_html(
                sprintf(
                    /* translators: 1: order count, 2: revenue */
                    __('Ordrar: %1$d · Intäkter: %2$s', 'maca-restu-pro'),
                    (int) $o['count'],
                    $o['revenue_label']
                )
            );
            echo '</span>';
        }

        if (!empty($history['bookings'])) {
            $b = $history['bookings'];
            echo '<span class="maca-dashboard-history-chip">';
            echo esc_html(
                sprintf(
                    /* translators: 1: booking count, 2: pending count */
                    __('Bokningar: %1$d (%2$d väntande)', 'maca-restu-pro'),
                    (int) $b['count'],
                    (int) $b['pending']
                )
            );
            echo '</span>';
        }
    }

    /**
     * Top dishes ordered list.
     *
     * @param array<string, mixed> $history   History payload.
     * @param bool                 $readonly Read-only (no edit links).
     */
    private function render_top_dishes($history, $readonly = false) {
        $top = isset($history['top_dishes']) ? $history['top_dishes'] : array();

        if (empty($top)) {
            echo '<li class="maca-dashboard-top-dish maca-dashboard-top-dish--empty">';
            esc_html_e('Inga rättklick registrerade för perioden ännu.', 'maca-restu-pro');
            echo '</li>';
            return;
        }

        $rank = 1;
        foreach ($top as $dish) {
            echo '<li class="maca-dashboard-top-dish">';
            echo '<span class="maca-dashboard-top-dish-rank">' . esc_html((string) $rank) . '</span>';
            if ($readonly || empty($dish['edit_url'])) {
                echo '<span class="maca-dashboard-top-dish-title">';
                echo esc_html($dish['title']);
                echo '</span>';
            } else {
                echo '<a class="maca-dashboard-top-dish-title" href="' . esc_url($dish['edit_url']) . '">';
                echo esc_html($dish['title']);
                echo '</a>';
            }
            echo '<span class="maca-dashboard-top-dish-count">';
            echo esc_html(
                sprintf(
                    /* translators: %d: number of clicks */
                    _n('%d click', '%d clicks', (int) $dish['clicks'], 'maca-restu-pro'),
                    (int) $dish['clicks']
                )
            );
            echo '</span>';
            echo '</li>';
            $rank++;
        }
    }
}
