/**
 * Admin management dashboard — live metrics and history.
 */
(function () {
    'use strict';

    if (typeof macaMenulistDashboard === 'undefined') {
        return;
    }

    var config = macaMenulistDashboard;
    var readonly = !!config.readonly;
    var labels = config.labels || {};
    var wrap = document.querySelector('.maca-dashboard-wrap');
    var metricsEl = document.getElementById('maca-dashboard-metrics');
    var actionsEl = document.getElementById('maca-dashboard-actions');
    var updatedEl = document.getElementById('maca-dashboard-updated');
    var historyForm = document.getElementById('maca-dashboard-history-form');
    var dateFromInput = document.getElementById('maca-dashboard-date-from');
    var dateToInput = document.getElementById('maca-dashboard-date-to');
    var historyPeriodEl = document.getElementById('maca-dashboard-history-period');
    var historySummaryEl = document.getElementById('maca-dashboard-history-summary');
    var topDishesEl = document.getElementById('maca-dashboard-top-dishes');
    var statsLinkEl = document.getElementById('maca-dashboard-stats-link');
    var pollTimer = null;
    var historyRange = {
        date_from: config.today || '',
        date_to: config.today || '',
    };

    if (config.initial && config.initial.history) {
        historyRange.date_from = config.initial.history.date_from || historyRange.date_from;
        historyRange.date_to = config.initial.history.date_to || historyRange.date_to;
    }

    function escapeHtml(text) {
        var div = document.createElement('div');
        div.textContent = text == null ? '' : String(text);
        return div.innerHTML;
    }

    function formatDateYmd(date) {
        var y = date.getFullYear();
        var m = String(date.getMonth() + 1).padStart(2, '0');
        var d = String(date.getDate()).padStart(2, '0');
        return y + '-' + m + '-' + d;
    }

    function setWrapState(state) {
        if (!wrap) {
            return;
        }
        wrap.classList.remove('is-updating', 'has-error');
        if (state) {
            wrap.classList.add(state);
        }
    }

    function getSelectedRange() {
        return {
            date_from: dateFromInput ? dateFromInput.value : historyRange.date_from,
            date_to: dateToInput ? dateToInput.value : historyRange.date_to,
        };
    }

    function applyPreset(preset) {
        var today = config.today ? new Date(config.today + 'T12:00:00') : new Date();
        var from = new Date(today);
        var to = new Date(today);

        if (preset === 'yesterday') {
            from.setDate(from.getDate() - 1);
            to.setDate(to.getDate() - 1);
        } else if (preset === '7days') {
            from.setDate(from.getDate() - 6);
        } else if (preset === '30days') {
            from.setDate(from.getDate() - 29);
        }

        historyRange.date_from = formatDateYmd(from);
        historyRange.date_to = formatDateYmd(to);

        if (dateFromInput) {
            dateFromInput.value = historyRange.date_from;
        }
        if (dateToInput) {
            dateToInput.value = historyRange.date_to;
        }

        loadHistory();
    }

    function metricValue(metrics, key) {
        if (!metrics.orders_enabled || !metrics.orders) {
            return null;
        }
        var o = metrics.orders;
        switch (key) {
            case 'orders_today':
                return String(o.count_today);
            case 'revenue':
                return o.revenue_label;
            case 'active_orders':
                return String(o.active);
            case 'avg_time':
                return o.avg_minutes_label;
            case 'paid_today':
                return String(o.paid_today);
            case 'pending_pay':
                return String(o.pending_payment);
            default:
                return null;
        }
    }

    function bookingMetricValue(metrics, key) {
        if (!metrics.bookings_enabled || !metrics.bookings) {
            return null;
        }
        var b = metrics.bookings;
        switch (key) {
            case 'bookings_today':
                return String(b.today_total);
            case 'guests_today':
                return String(b.confirmed_guests);
            case 'pending_book_today':
                return String(b.pending_today);
            case 'pending_book_all':
                return String(b.pending_all);
            case 'day_occupancy':
                if (b.day_occupancy && b.day_occupancy.label !== undefined) {
                    return String(b.day_occupancy.label);
                }
                return '—';
            default:
                return null;
        }
    }

    function updateDayOccupancyDisplay(container, metrics) {
        if (!container || !metrics.bookings_enabled || !metrics.bookings || !metrics.bookings.day_occupancy) {
            return;
        }

        var occ = metrics.bookings.day_occupancy;
        var level = occ.level || 'low';
        var valueEl = container.querySelector(
            '.maca-dashboard-header-link-count, .maca-dashboard-metric-value'
        );

        container.setAttribute('data-occupancy-level', level);

        if (valueEl) {
            valueEl.className =
                (valueEl.classList.contains('maca-dashboard-header-link-count')
                    ? 'maca-dashboard-header-link-count '
                    : 'maca-dashboard-metric-value ') +
                'maca-booking-occupancy maca-booking-occupancy-' +
                level;
            valueEl.textContent =
                occ.label !== undefined && occ.label !== null ? String(occ.label) : '—';
        }
    }

    function updateMetrics(metrics) {
        var headerOccupancy = document.getElementById('maca-dashboard-header-day-occupancy');
        if (headerOccupancy) {
            updateDayOccupancyDisplay(headerOccupancy, metrics);
        }

        if (!metricsEl) {
            return;
        }

        metricsEl.querySelectorAll('[data-metric]').forEach(function (card) {
            var key = card.getAttribute('data-metric');

            if (key === 'day_occupancy') {
                updateDayOccupancyDisplay(card, metrics);
                return;
            }

            var val = metricValue(metrics, key);
            if (val === null) {
                val = bookingMetricValue(metrics, key);
            }
            if (val === null) {
                return;
            }
            var valueEl = card.querySelector('.maca-dashboard-metric-value');
            if (valueEl) {
                valueEl.innerHTML = escapeHtml(val);
            }
        });
    }

    function renderActions(actions) {
        if (!actionsEl) {
            return;
        }

        if (!actions || !actions.length) {
            actionsEl.innerHTML =
                '<li class="maca-dashboard-action maca-dashboard-action--empty">' +
                escapeHtml(labels.noActions) +
                '</li>';
            return;
        }

        var html = '';
        actions.forEach(function (item) {
            var severity = item.severity || 'info';
            html += '<li class="maca-dashboard-action maca-dashboard-action--' + escapeHtml(severity) + '">';
            if (readonly || !item.url) {
                html += '<div class="maca-dashboard-action-inner">';
            } else {
                html += '<a href="' + escapeHtml(item.url) + '">';
            }
            if (item.count) {
                html +=
                    '<span class="maca-dashboard-action-count">' +
                    escapeHtml(String(item.count)) +
                    '</span>';
            }
            html +=
                '<span class="maca-dashboard-action-label">' +
                escapeHtml(item.label) +
                '</span>';
            html += readonly || !item.url ? '</div>' : '</a>';
            html += '</li>';
        });
        actionsEl.innerHTML = html;
    }

    function renderHistorySummary(history) {
        if (!historySummaryEl) {
            return;
        }

        var html = '';
        if (history.total_clicks) {
            html +=
                '<span class="maca-dashboard-history-chip">' +
                escapeHtml(labels.totalClicks + ': ' + history.total_clicks) +
                '</span>';
        }
        if (history.orders) {
            html +=
                '<span class="maca-dashboard-history-chip">' +
                escapeHtml(
                    labels.periodOrders +
                        ': ' +
                        history.orders.count +
                        ' · ' +
                        labels.periodRevenue +
                        ': ' +
                        history.orders.revenue_label
                ) +
                '</span>';
        }
        if (history.bookings) {
            html +=
                '<span class="maca-dashboard-history-chip">' +
                escapeHtml(
                    labels.periodBookings +
                        ': ' +
                        history.bookings.count +
                        ' (' +
                        history.bookings.pending +
                        ' ' +
                        (labels.periodPending || 'väntande') +
                        ')'
                ) +
                '</span>';
        }
        historySummaryEl.innerHTML = html;
    }

    function renderTopDishes(history) {
        if (!topDishesEl) {
            return;
        }

        var top = history.top_dishes || [];
        if (!top.length) {
            topDishesEl.innerHTML =
                '<li class="maca-dashboard-top-dish maca-dashboard-top-dish--empty">' +
                escapeHtml(labels.noDishStats) +
                '</li>';
            return;
        }

        var html = '';
        top.forEach(function (dish, index) {
            html += '<li class="maca-dashboard-top-dish">';
            html += '<span class="maca-dashboard-top-dish-rank">' + escapeHtml(String(index + 1)) + '</span>';
            if (readonly || !dish.edit_url) {
                html += '<span class="maca-dashboard-top-dish-title">';
                html += escapeHtml(dish.title);
                html += '</span>';
            } else {
                html += '<a class="maca-dashboard-top-dish-title" href="' + escapeHtml(dish.edit_url) + '">';
                html += escapeHtml(dish.title);
                html += '</a>';
            }
            html += '<span class="maca-dashboard-top-dish-count">';
            html += escapeHtml(dish.clicks + ' ' + labels.clicks);
            html += '</span></li>';
        });
        topDishesEl.innerHTML = html;
    }

    function renderHistory(history) {
        if (!history) {
            return;
        }

        historyRange.date_from = history.date_from;
        historyRange.date_to = history.date_to;

        if (historyPeriodEl && history.period_label) {
            historyPeriodEl.textContent = history.period_label;
        }
        if (!readonly && statsLinkEl && history.stats_url) {
            statsLinkEl.href = history.stats_url;
        }

        renderHistorySummary(history);
        renderTopDishes(history);

        if (window.MacaMenulistDashboardCharts) {
            window.MacaMenulistDashboardCharts.render(history.charts || []);
        }
    }

    function updateTimestamp(metrics) {
        if (!updatedEl || !metrics.updated_at_label) {
            return;
        }
        updatedEl.textContent = labels.lastUpdated + ' ' + metrics.updated_at_label;
    }

    function updateHeaderLinks(metrics) {
        if (!metrics) {
            return;
        }

        var activeCampaignTitleEl = document.getElementById('maca-dashboard-active-campaign-title');
        var activeCampaignLinkEl = document.getElementById('maca-dashboard-link-campaign');
        if (activeCampaignTitleEl && activeCampaignLinkEl) {
            if (metrics.campaign && metrics.campaign.title) {
                activeCampaignTitleEl.textContent = String(metrics.campaign.title);
                if (!readonly && metrics.campaign.url) {
                    activeCampaignLinkEl.href = String(metrics.campaign.url);
                }
                activeCampaignLinkEl.style.display = '';
            } else {
                activeCampaignLinkEl.style.display = 'none';
            }
        }

        var pendingReservationsEl = document.getElementById('maca-dashboard-count-pending-reservations');
        if (
            pendingReservationsEl
            && metrics.bookings
            && metrics.bookings.pending_all !== undefined
        ) {
            pendingReservationsEl.textContent = String(metrics.bookings.pending_all);
        }

        var unpaidEl = document.getElementById('maca-dashboard-count-unpaid');
        if (unpaidEl && metrics.orders && metrics.orders.unpaid_active !== undefined) {
            unpaidEl.textContent = String(metrics.orders.unpaid_active);
        }
    }

    function applyPayload(payload) {
        if (!payload) {
            return;
        }
        if (payload.metrics) {
            updateMetrics(payload.metrics);
            updateTimestamp(payload.metrics);
            updateHeaderLinks(payload.metrics);
        }
        if (payload.actions) {
            renderActions(payload.actions);
        }
        if (payload.history) {
            renderHistory(payload.history);
        }
        setWrapState(null);
    }

    function postDashboard(action, extra) {
        var body = new URLSearchParams();
        body.append('action', action);
        body.append('nonce', config.nonce);
        body.append('date_from', historyRange.date_from);
        body.append('date_to', historyRange.date_to);

        if (readonly && typeof config.getPin === 'function') {
            body.append('pin', config.getPin());
        }

        if (extra) {
            Object.keys(extra).forEach(function (key) {
                body.append(key, extra[key]);
            });
        }

        return fetch(config.ajaxUrl, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            },
            body: body.toString(),
        }).then(function (response) {
            return response.json();
        });
    }

    var refreshAction = config.refreshAction || 'maca_dashboard_refresh';
    var historyAction = config.historyAction || 'maca_dashboard_history';

    function loadHistory() {
        var range = getSelectedRange();
        historyRange = range;

        return postDashboard(historyAction)
            .then(function (data) {
                if (!data || !data.success) {
                    throw new Error('history failed');
                }
                renderHistory(data.data);
            })
            .catch(function () {
                // Keep existing history on error.
            });
    }

    function refresh() {
        historyRange = getSelectedRange();
        setWrapState('is-updating');

        postDashboard(refreshAction)
            .then(function (data) {
                if (!data || !data.success) {
                    throw new Error('refresh failed');
                }
                applyPayload(data.data);
            })
            .catch(function () {
                setWrapState('has-error');
                if (updatedEl) {
                    updatedEl.textContent = labels.updateError;
                }
            });
    }

    function startPolling() {
        if (pollTimer) {
            clearInterval(pollTimer);
        }
        pollTimer = setInterval(refresh, config.pollInterval || 15000);
    }

    if (historyForm) {
        historyForm.addEventListener('submit', function (event) {
            event.preventDefault();
            loadHistory();
        });
    }

    document.querySelectorAll('.maca-dashboard-preset').forEach(function (button) {
        button.addEventListener('click', function () {
            applyPreset(button.getAttribute('data-preset') || 'today');
        });
    });

    if (config.initial && !readonly) {
        applyPayload(config.initial);
        startPolling();
    } else if (readonly) {
        document.addEventListener('maca-management-overview-unlocked', function () {
            applyPayload(window.macaMenulistDashboard && window.macaMenulistDashboard.initial ? window.macaMenulistDashboard.initial : config.initial);
            startPolling();
        });
    } else if (window.MacaMenulistDashboardCharts) {
        window.MacaMenulistDashboardCharts.render([]);
    }
})();
