<?php
use Components\Base;
use Components\Button;
use Components\Data\Health;
use Components\Data\Notifications;
use Components\Router;
use Components\Ui\TopBarCount;

$changelogUrl = mh_saas() ? '' : mh_language_documentation_url('https://www.mailbeez.com/documentation/changelog');
$changelogBtn = '';
if ($changelogUrl) {
    $changelogBtn = Button::render(mh_lng('MH_CHANGELOG_TEXT', 'What\'s new?'), [
        'variant' => 'ghost',
        'size' => 'xs',
//        'icon' => Base::SVG_OUTLINE_DOCUMENT_TEXT,
        'iconPosition' => 'front',
        'attrs' => [
            'command' => 'show-modal',
            'commandfor' => 'config-modal',
            'data-width' => '3xl',
            'data-height' => '95vh',
            'data-url' => $changelogUrl,
            'hx-target' => '#config-modal-body',
            'hx-swap' => 'innerHTML',
            'title' => mh_lng('MH_CHANGELOG_TEXT', 'What\'s new?'),
        ],
    ]);
}

$onboardingProgress = 43.0;
$onboardingProgressCss = Base::progressPercent($onboardingProgress);
$onboardingRocketIcon = Base::renderRocketProgressIcon($onboardingProgress, [
    'wrapperClass' => 'relative inline-flex size-7 items-center justify-center text-secondary',
    'iconClass' => 'relative z-[1]',
]);
?>
<div class="w-full h-full ">
    <!-- common notification -->
    <div class="flex  items-center gap-2">
        <div class="flex-1 text-nowrap">
            <?php 
                $margin = false;
                include BEEZUI_ROOT . '/pages/components/notification_common.php'; 
            ?>
        </div>
        <div class=" grow items-center pl-8">
            <?php echo $changelogBtn; ?>
            <?php if (!mh_saas()) : ?>
            <?php include BEEZUI_ROOT . 'pages/components/updates.php'; ?>
            <?php endif; ?>
        </div>

        <div class="pr-0.5 flex items-center gap-6">
            <div class="flex items-center gap-3"
                 x-data="{ 
                    notificationCount: <?= ($pollSummary = Notifications::getPollSummary())['count'] ?>,
                    alertCount: <?= $pollSummary['alert_count'] ?>,
                    lowSeverityCount: <?= $pollSummary['low_severity_count'] ?>,
                    healthCount: <?= ($healthSummary = Health::getPollSummary())['count'] ?>,
                    healthCriticalCount: <?= $healthSummary['critical_count'] ?>,
                    healthWarningCount: <?= $healthSummary['warning_count'] ?>,
                    ignoreUpdatesUntil: 0,
                    updateStatus(data) {
                        if (typeof data === 'string') {
                            try { data = JSON.parse(data); } catch(e) { return; }
                        }
                        const count = parseInt(data.count) || 0;
                        const alerts = parseInt(data.alert_count) || 0;
                        const lowSeverity = parseInt(data.low_severity_count) || 0;
                        
                        if (Date.now() < this.ignoreUpdatesUntil && count > this.notificationCount) {
                            return;
                        }
                        
                        if (alerts > this.alertCount) {
                            this.openNotifications();
                        }
                        
                        if (this.notificationCount !== count) {
                            this.notificationCount = count;
                            $dispatch('notifications-changed', { count: count });
                        }
                        this.alertCount = alerts;
                        this.lowSeverityCount = lowSeverity;
                    },
                    updateHealth(data) {
                        if (typeof data === 'string') {
                            try { data = JSON.parse(data); } catch(e) { return; }
                        }

                        const count = parseInt(data.count) || 0;
                        const critical = parseInt(data.critical_count) || 0;
                        const warning = parseInt(data.warning_count) || 0;

                        if (this.healthCount !== count || this.healthCriticalCount !== critical || this.healthWarningCount !== warning) {
                            this.healthCount = count;
                            this.healthCriticalCount = critical;
                            this.healthWarningCount = warning;
                            $dispatch('health-changed', {
                                count: count,
                                critical_count: critical,
                                warning_count: warning
                            });
                        }
                    },
                    openNotifications() {
                        if (window.MBSitePanel) {
                            MBSitePanel.open({tab: 'notifications'});
                        } else {
                            const btn = this.$el.querySelector('[data-tab=notifications][command=toggle-sitepanel], [data-tab=notifications][command=show-sitepanel], [command=toggle-sitepanel], [command=show-sitepanel]');
                            if (btn) btn.click();
                        }
                    }
                 }" 
                 @notification-dismissed-optimistic.window="notificationCount = Math.max(0, notificationCount - 1); if ($event.detail && $event.detail.severity !== undefined) { if ($event.detail.severity <= 2) { alertCount = Math.max(0, alertCount - 1); } else { lowSeverityCount = Math.max(0, lowSeverityCount - 1); } } ignoreUpdatesUntil = Date.now() + 2000;"
                 @notification-dismissed-optimistic-all.window="notificationCount = 0; alertCount = 0; lowSeverityCount = 0; ignoreUpdatesUntil = Date.now() + 2000;"
            >
                <div hx-get="<?= Router::url('notifications_count', ['partial' => 1]) ?>" 
                     hx-trigger="every 60s, notifications-refresh from:body"
                     hx-swap="none" 
                     data-no-local-loader="true"
                     data-no-global-loader="true"
                     @htmx:after-request="updateStatus($event.detail.xhr.responseText); $dispatch('notifications-polled', { checked_at: new Date().toISOString() })">
                </div>

                <div hx-get="<?= Router::url('health_count', ['partial' => 1]) ?>"
                     hx-trigger="every 60s, health-refresh from:body"
                     hx-swap="none"
                     data-no-local-loader="true"
                     data-no-global-loader="true"
                     @htmx:after-request="updateHealth($event.detail.xhr.responseText); $dispatch('health-polled', { checked_at: new Date().toISOString() })">
                </div>
<!--
                <div class="relative inline-flex">
                    <?= Button::render('', [
                        'variant' => 'outline',
                        'size' => 'md',
                        'rounded' => 'full',
                        'class' => '[&>svg]:size-4.5! p-0.75!',
                        'icon' => $onboardingRocketIcon,
                        'attrs' => [
                            'command' => 'toggle-sitepanel',
                            'commandfor' => 'app-site-panel-body',
                            'data-tab' => 'onboarding',
                            'data-title' => '',
                            'data-no-local-loader' => 'true',
                            'data-no-global-loader' => 'true',
                            'title' => Base::lng('UI_HUB_TAB_ONBOARDING', 'Onboarding') . ' (' . $onboardingProgressCss . '%)',
                        ]
                    ]) ?>
                </div>
-->

                <div class="relative inline-flex">
                    <?= Button::render('', [
                        'variant' => 'ghost',
                        'size' => 'md',
                        'rounded' => 'full',
                        'class' => '[&>svg]:size-4.5! transition-colors cursor-pointer',
                        'icon' => Base::SVG_PULSE,
                        'attrs' => [
                            'command' => 'toggle-sitepanel',
                            'commandfor' => 'app-site-panel-body',
                            'data-tab' => 'health',
                            'data-title' => '',
                            'data-no-local-loader' => 'true',
                            'data-no-global-loader' => 'true',
                            'title' => Base::lng('UI_APPLICATION_HEALTH', 'Application Health'),
                            'x-bind:class' => "healthCriticalCount > 0 ? 'text-danger-200! border-danger-500! bg-danger-500!' : ''",
                        ]
                    ]) ?>

                    <template x-if="healthCount === 0">
                        <span class="absolute right-1.5 top-1.5 flex size-2 pointer-events-none" x-cloak>
                            <span class="absolute inline-flex h-full w-full animate-ping rounded-full bg-success-500 opacity-30"></span>
                            <span class="relative inline-flex size-2 rounded-full bg-success-500 animate-[pulse-soft_3s_ease-in-out_infinite]"></span>
                        </span>
                    </template>

                    <template x-if="healthCriticalCount > 0">
                        <span class="absolute inset-0 pointer-events-none" x-cloak>
                            <span class="absolute inset-1 rounded-full border-2 border-danger-500 animate-ping opacity-50"></span>
                            <span class="absolute inset-0 rounded-full border-0 border-danger-500 opacity-75"></span>
                        </span>
                    </template>

                    <?= TopBarCount::render([
                        'show_when' => 'healthCount > 0',
                        'count_expression' => 'healthCount',
                        'wrapper_class' => 'absolute top-px right-0.5 pointer-events-none',
                        'badge_bind_class' => "healthCriticalCount > 0 ? 'bg-danger-500' : 'bg-warning-500'",
                    ]); ?>
                </div>

                <div class="relative inline-flex">
                    <?= Button::render('', [
                        'variant' => 'ghost',
                        'size' => 'md',
                        'rounded' => 'full',
                        'class' => '[&>svg]:size-4.5! transition-colors cursor-pointer',
                        'icon' => '<span x-show="alertCount > 0" x-cloak>' . Base::SVG_BELL_ALERT . '</span><span x-show="alertCount === 0">' . Base::SVG_BELL . '</span>',
                        'attrs' => [
                            'command' => 'toggle-sitepanel',
                            'commandfor' => 'app-site-panel-body',
                            'data-tab' => 'notifications',
                            'data-title' => '',
                            'data-no-local-loader' => 'true',
                            'data-no-global-loader' => 'true',
                            'title' => Base::lng('UI_NOTIFICATION_HUB', 'Notification Hub'),
                            'x-bind:class' => "alertCount > 0 ? 'text-danger-500! border-danger-500!' : ''",
                        ]
                    ]) ?>

                    <template x-if="alertCount > 0">
                        <span class="absolute inset-0 pointer-events-none" x-cloak>
                            <span class="absolute inset-1 rounded-full border-2  border-danger-500 animate-ping opacity-50"></span>
                            <span class="absolute inset-0 rounded-full border-0 border-danger-500 opacity-75"></span>
                        </span>
                    </template>

                    <?= TopBarCount::render([
                        'show_when' => 'notificationCount > 0',
                        'count_expression' => 'notificationCount',
                        'badge_bind_class' => "alertCount > 0 ? 'bg-danger-500' : (lowSeverityCount > 0 ? 'bg-blue-500' : 'bg-danger-500')",
                    ]); ?>
                </div>
            </div>

            <?php include BEEZUI_ROOT . 'pages/components/mode.php'; ?>
        </div>

    <!-- common notification -->
    </div>
</div>
