<?php
// pages/components/health_hub.php
use Components\Base;
use Components\Data\Health;
use Components\Ui\EmptyState;

$issues = Health::getIssues();
$issueCount = count($issues);
$issueCriticalCount = 0;
$issueWarningCount = 0;

foreach ($issues as $issue) {
    if (($issue['severity'] ?? 'warning') === 'critical') {
        $issueCriticalCount++;
        continue;
    }

    $issueWarningCount++;
}

$checks = array_values(array_filter(Health::getChecks(), static function (array $check): bool {
    return ($check['key'] ?? '') !== 'overall';
}));
$notOkCriticalChecks = [];
$notOkWarningChecks = [];
$okChecks = [];

foreach ($checks as $check) {
    if (($check['state'] ?? 'not_ok') === 'ok') {
        $okChecks[] = $check;
        continue;
    }

    if (($check['severity'] ?? 'warning') === 'critical') {
        $notOkCriticalChecks[] = $check;
        continue;
    }

    $notOkWarningChecks[] = $check;
}

$notOkChecks = array_merge($notOkCriticalChecks, $notOkWarningChecks);
$checks = array_merge($notOkChecks, $okChecks);
$checkCount = count($checks);
$checkNotOkCount = count($notOkChecks);

$invalidCheckGroups = [
        [
                'label' => Base::lng('UI_NOTIFICATION_GROUP_ALERTS', 'Alerts'),
                'badgeClass' => 'notification-group__count notification-group__count--danger',
                'checks' => $notOkCriticalChecks,
        ],
        [
                'label' => Base::lng('UI_NOTIFICATION_GROUP_WARNINGS', 'Warnings'),
                'badgeClass' => 'notification-group__count notification-group__count--warning',
                'checks' => $notOkWarningChecks,
        ],
];

$validCheckGroup = [
        'label' => Base::lng('UI_APPLICATION_HEALTH_OK', 'OK'),
        'badgeClass' => 'notification-group__count notification-group__count--info',
        'checks' => $okChecks,
];

$hasContent = ($issueCount > 0 || $checkCount > 0);
$criticalHealthCount = $issueCriticalCount + count($notOkCriticalChecks);
$warningHealthCount = $issueWarningCount + count($notOkWarningChecks);
$healthIssueCount = $criticalHealthCount + $warningHealthCount;
$isAllClear = ($healthIssueCount === 0);
$healthSummaryState = $isAllClear ? 'healthy' : ($criticalHealthCount > 0 ? 'critical' : 'warning');
$issueSummaryTitle = ($healthIssueCount === 1)
        ? Base::lng('UI_APPLICATION_HEALTH_ISSUE_SUMMARY_SINGLE', 'There is an issue')
        : Base::lng('UI_APPLICATION_HEALTH_ISSUE_SUMMARY_MULTIPLE', 'There are multiple issues');
$healthSummaryTitle = $isAllClear
        ? Base::lng('UI_APPLICATION_HEALTH_ALL_CAUGHT_UP_TITLE', 'All caught up!')
        : $issueSummaryTitle;
$healthSummaryText = $isAllClear
        ? Base::lng('UI_APPLICATION_HEALTH_ALL_CAUGHT_UP_TEXT', 'No health issues at the moment.')
        : Base::lng('UI_APPLICATION_HEALTH_CHECK_SUMMARY_NOT_OK', 'Please follow the highlighted guidance.');
$healthSummaryIcon = $isAllClear ? Base::SVG_CHECK_CIRCLE : Base::SVG_PULSE;
$healthLastCheckedIso = date('c');
$healthLastCheckedRaw = date('Y-m-d H:i:s');
$healthSummaryToneClasses = [
        'healthy' => [
                'section' => 'border-success-300/25 bg-success-500/4',
                'aura' => 'bg-success-500/70 blur-3xl',
                'ring' => 'border-success-200/80 bg-success-50/90',
                'icon' => 'bg-success-500 [box-shadow:0_6px_16px_color-mix(in_srgb,var(--color-success-500)_14%,transparent)]',
                'title' => 'text-success-700',
                'text' => 'text-success-700/90',
        ],
        'warning' => [
                'section' => 'border-warning-300/30 bg-warning-500/5',
                'aura' => 'bg-warning-500/10 [filter:blur(16px)] scale-[0.92] opacity-60',
                'ring' => 'border-warning-200/70 bg-warning-50/85',
                'icon' => 'bg-warning-500 [box-shadow:0_6px_14px_color-mix(in_srgb,var(--color-warning-500)_16%,transparent)]',
                'title' => 'text-warning-700',
                'text' => 'text-warning-700/90',
        ],
        'critical' => [
                'section' => 'border-danger-300/35 bg-danger-500/7',
                'aura' => 'bg-danger-500/50 blur-3xl opacity-84 [animation-duration:4s]',
                'ring' => 'border-danger-200/80 bg-danger-50/90',
                'icon' => 'bg-danger-500 [box-shadow:0_10px_22px_color-mix(in_srgb,var(--color-danger-500)_24%,transparent),0_3px_8px_rgb(15_23_42_/_0.08)]',
                'title' => 'text-danger-700',
                'text' => 'text-danger-700/90',
        ],
];
$healthSummaryTone = $healthSummaryToneClasses[$healthSummaryState] ?? $healthSummaryToneClasses['warning'];

$renderCheckCard = static function (array $check): string {
    $isOk = ($check['state'] ?? 'not_ok') === 'ok';
    $isCritical = ($check['severity'] ?? 'warning') === 'critical';
    $cardClass = $isOk
            ? 'border-success-500/30 bg-success-500/7'
            : ($isCritical ? 'border-danger-500/30 bg-danger-500/7' : 'border-warning-500/30 bg-warning-500/7');
    $iconClass = $isOk
            ? 'text-success-500'
            : ($isCritical ? 'text-danger-500' : 'text-warning-500');
    $titleClass = $isOk
            ? 'text-success-700 dark:text-success-300'
            : ($isCritical ? 'text-danger-700 dark:text-danger-300' : 'text-warning-700 dark:text-warning-300');
    $detailClass = $isOk
            ? 'text-success-700/80 dark:text-success-300/80'
            : ($isCritical ? 'text-danger-700/80 dark:text-danger-300/80' : 'text-warning-700/80 dark:text-warning-300/80');
    $badgeClass = $isOk
            ? 'bg-success-500/12 text-success-600 dark:text-success-400'
            : ($isCritical ? 'bg-danger-500/12 text-danger-600 dark:text-danger-400' : 'bg-warning-500/12 text-warning-600 dark:text-warning-400');
    $detailRows = (isset($check['detail_rows']) && is_array($check['detail_rows'])) ? $check['detail_rows'] : [];
    $hasDetails = !empty($check['summary']) || !empty($check['details']);
    if (!empty($detailRows)) {
        $hasDetails = true;
    }
    $isCollapsible = $isOk && $hasDetails;

    ob_start();
    ?>
    <?php if ($isCollapsible): ?>
        <article class="rounded-xl border px-3 py-2 <?= $cardClass ?>"
                 x-data="{ open: false, overswing: false, overswingExpanding: false }"
                 :class="{ 'animate-overswing-itemlist': overswing, 'animate-overswing-expanding-itemlist': overswingExpanding }">
            <button type="button"
                    class="flex w-full items-center gap-2 text-left cursor-pointer"
                    :aria-expanded="open ? 'true' : 'false'"
                    @click="open = !open; if (open) { <?= Base::overswingAlpineTrigger('overswingExpanding', 100, 180) ?> } else { <?= Base::overswingAlpineTrigger('overswing', 100, 150) ?> }">
                <span class="inline-flex size-5 shrink-0 items-center justify-center <?= $iconClass ?>">
                    <?= Base::SVG_CHECK_CIRCLE ?>
                </span>
                <span class="min-w-0 flex-1 text-sm font-semibold <?= $titleClass ?>">
                    <?= Base::h($check['title'] ?? '') ?>
                </span>
                <span class="inline-flex size-4 shrink-0 items-center justify-center <?= $iconClass ?> transition-transform duration-200"
                      :class="{ 'rotate-180': open }">
                    <?= Base::SVG_CHEVRON_DOWN ?>
                </span>
            </button>

            <div class="pl-7 pt-1"
                 x-cloak
                 x-show="open"
                 x-collapse.duration.180ms>
                <?php if (!empty($check['summary'])): ?>
                    <p class="text-xs <?= $detailClass ?>">
                        <?= Base::h($check['summary']) ?>
                    </p>
                <?php endif; ?>
                <?php if (!empty($check['details']) || !empty($detailRows)): ?>
                    <p class="mt-1 text-xs <?= $detailClass ?>">
                        <?php if (!empty($detailRows)): ?>
                            <?php foreach ($detailRows as $rowIndex => $row): ?>
                                <?php if ($rowIndex > 0): ?><br><?php endif; ?>
                                <?php if (($row['type'] ?? 'text') === 'timestamp' && !empty($row['raw']) && !empty($row['iso'])): ?>
                                    <?php
                                    $template = (string)($row['template'] ?? '%s');
                                    $placeholder = '__MB_HEALTH_TIME__';
                                    $templateWithPlaceholder = sprintf($template, $placeholder);
                                    $templateParts = explode($placeholder, $templateWithPlaceholder, 2);
                                    $templatePrefix = $templateParts[0] ?? '';
                                    $templateSuffix = $templateParts[1] ?? '';
                                    ?>
                                    <?= Base::h($templatePrefix, false) ?>
                                    <time datetime="<?= Base::h((string)$row['iso'], false) ?>"
                                          title="<?= Base::h((string)$row['raw'], false) ?>"
                                          x-data="{ date: new Date('<?= Base::h((string)$row['iso'], false) ?>') }"
                                          x-timeago="date">...</time>
                                    <?= Base::h($templateSuffix, false) ?>
                                <?php else: ?>
                                    <?= Base::h((string)($row['text'] ?? '')) ?>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <?= Base::h($check['details']) ?>
                        <?php endif; ?>
                    </p>
                <?php endif; ?>
            </div>
        </article>
    <?php else: ?>
        <article class="rounded-xl border px-3 py-2 <?= $cardClass ?>">
            <div class="flex items-center gap-2">
                <span class="inline-flex size-5 shrink-0 items-center justify-center <?= $iconClass ?>">
                    <?= $isOk ? Base::SVG_CHECK_CIRCLE : Base::SVG_PULSE ?>
                </span>
                <p class="min-w-0 flex-1 text-sm font-semibold <?= $titleClass ?>">
                    <?= Base::h($check['title'] ?? '') ?>
                </p>
                <?php if (!$isOk): ?>
                    <span class="inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide <?= $badgeClass ?>">
                        <?= Base::h(Base::lng('UI_APPLICATION_HEALTH_NOT_OK', 'NOT OK')) ?>
                    </span>
                <?php endif; ?>
            </div>

            <?php if ($hasDetails): ?>
                <div class="pl-7 pt-1">
                    <?php if (!empty($check['summary'])): ?>
                        <p class="text-xs <?= $detailClass ?>">
                            <?= Base::h($check['summary']) ?>
                        </p>
                    <?php endif; ?>
                    <?php if (!empty($check['details']) || !empty($detailRows)): ?>
                        <p class="mt-1 text-xs <?= $detailClass ?>">
                            <?php if (!empty($detailRows)): ?>
                                <?php foreach ($detailRows as $rowIndex => $row): ?>
                                    <?php if ($rowIndex > 0): ?><br><?php endif; ?>
                                    <?php if (($row['type'] ?? 'text') === 'timestamp' && !empty($row['raw']) && !empty($row['iso'])): ?>
                                        <?php
                                        $template = (string)($row['template'] ?? '%s');
                                        $placeholder = '__MB_HEALTH_TIME__';
                                        $templateWithPlaceholder = sprintf($template, $placeholder);
                                        $templateParts = explode($placeholder, $templateWithPlaceholder, 2);
                                        $templatePrefix = $templateParts[0] ?? '';
                                        $templateSuffix = $templateParts[1] ?? '';
                                        ?>
                                        <?= Base::h($templatePrefix, false) ?>
                                        <time datetime="<?= Base::h((string)$row['iso'], false) ?>"
                                              title="<?= Base::h((string)$row['raw'], false) ?>"
                                              x-data="{ date: new Date('<?= Base::h((string)$row['iso'], false) ?>') }"
                                              x-timeago="date">...</time>
                                        <?= Base::h($templateSuffix, false) ?>
                                    <?php else: ?>
                                        <?= Base::h((string)($row['text'] ?? '')) ?>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <?= Base::h($check['details']) ?>
                            <?php endif; ?>
                        </p>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </article>
    <?php endif; ?>
    <?php

    return (string)ob_get_clean();
};
?>

<div class="flex flex-col h-full -mt-3 -mx-4"
     data-no-local-loader="true"
     data-no-global-loader="true"
     hx-get="<?= \Components\Router::url('health_hub', ['hub_tab' => 'health', 'partial' => 1]) ?>"
     hx-trigger="health-refresh from:body, health-changed from:body"
     hx-target="this"
     hx-swap="outerHTML"
>
    <div class="flex-1 min-h-0 overflow-auto pb-2">
        <?php if ($hasContent): ?>
            <div class="mb-3 px-3 py-6">
                <section class="relative px-4 pt-6 pb-4 text-center">
                    <div class="relative mx-auto mb-1 flex size-32 items-center justify-center">
                        <div class="health-summary-breathe absolute inset-3 rounded-full <?= Base::h($healthSummaryTone['aura']) ?>" aria-hidden="true"></div>
                        <div class="absolute size-24 rounded-full border <?= Base::h($healthSummaryTone['ring']) ?>" aria-hidden="true"></div>
                        <div class="relative z-10 flex size-16 items-center justify-center rounded-full text-white shadow-sm [&>svg]:size-7 <?= Base::h($healthSummaryTone['icon']) ?>">
                            <?= $healthSummaryIcon ?>
                        </div>
                    </div>
                    <p class="text-sm font-normal tracking-tight <?= Base::h($healthSummaryTone['title']) ?>"><?= Base::h($healthSummaryTitle) ?></p>
                    <p class="mt-1 text-xs <?= Base::h($healthSummaryTone['text']) ?>"><?= Base::h($healthSummaryText) ?></p>
                </section>
            </div>

        <div class="px-4">

            <?php if ($issueCount > 0): ?>
                <div class="mb-3 rounded-xl border border-danger-500/25 bg-danger-500/8 px-3 py-2">
                    <p class="text-sm font-medium text-danger-600 dark:text-danger-400">
                        <?= Base::h(Base::lng('UI_APPLICATION_HEALTH_ISSUES', 'Application Health Issues')) ?>
                        <span class="ml-1 inline-flex min-w-[18px] items-center justify-center rounded-full bg-danger-500 px-1.5 py-0.5 text-[10px] font-bold leading-none text-white">
                        <?= (int)$issueCount ?>
                    </span>
                    </p>
                </div>
                <div class="space-y-2">
                    <?php foreach ($issues as $issue): ?>
                        <?php $isCritical = ($issue['severity'] ?? 'warning') === 'critical'; ?>
                        <?php
                        $issueTitleClass = $isCritical
                                ? 'text-danger-700 dark:text-danger-300'
                                : 'text-warning-700 dark:text-warning-300';
                        $issueDetailClass = $isCritical
                                ? 'text-danger-700/80 dark:text-danger-300/80'
                                : 'text-warning-700/80 dark:text-warning-300/80';
                        ?>
                        <article
                                class="rounded-xl border px-3 py-3 <?= $isCritical ? 'border-danger-500/30 bg-danger-500/7' : 'border-warning-500/30 bg-warning-500/7' ?>">
                            <div class="flex items-start gap-2">
                            <span class="mt-0.5 inline-flex size-5 shrink-0 items-center justify-center <?= $isCritical ? 'text-danger-500' : 'text-warning-500' ?>">
                                <?= Base::SVG_PULSE ?>
                            </span>
                                <div class="min-w-0 flex-1">
                                    <p class="text-sm font-semibold <?= $issueTitleClass ?>">
                                        <?= Base::h($issue['title'] ?? '') ?>
                                    </p>
                                    <?php if (!empty($issue['summary'])): ?>
                                        <p class="mt-0.5 text-xs <?= $issueDetailClass ?>">
                                            <?= Base::h($issue['summary']) ?>
                                        </p>
                                    <?php endif; ?>
                                    <?php if (!empty($issue['details'])): ?>
                                        <p class="mt-1 text-xs <?= $issueDetailClass ?>">
                                            <?= Base::h($issue['details']) ?>
                                        </p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <?php if ($checkCount > 0): ?>
                <?php if (!empty($checks)): ?>
                    <div class="space-y-4 mb-3">
                        <?php if ($checkNotOkCount > 0): ?>
                            <div class="space-y-5" >
                                <?php foreach ($invalidCheckGroups as $groupMeta): ?>
                                    <?php $groupChecks = $groupMeta['checks'] ?? []; ?>
                                    <?php if (empty($groupChecks)) continue; ?>
                                    <div class="notification-group__header mt-2 mb-2 first:mt-0">
                                        <span><?= Base::h($groupMeta['label'] ?? '') ?></span>
                                        <span class="<?= Base::h($groupMeta['badgeClass'] ?? '') ?>">
                                            <?= count($groupChecks) ?>
                                        </span>
                                    </div>
                                    <div class="space-y-3">
                                        <?php foreach ($groupChecks as $check): ?>
                                            <?= $renderCheckCard($check) ?>
                                        <?php endforeach; ?>
                                        <div></div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>

                        <?php if (!empty($validCheckGroup['checks'])): ?>
                            <div>
                        <?php if ($checkNotOkCount > 0): ?>
                                <div class="notification-group__header mt-2 mb-2 first:mt-0">
                                    <span><?= Base::h($validCheckGroup['label'] ?? '') ?></span>
                                    <!--                            <span class="-->
                                    <?php //= Base::h($validCheckGroup['badgeClass'] ?? '') ?><!--">-->
                                    <!--                                --><?php //= count($validCheckGroup['checks']) ?>
                                    <!--                            </span>-->
                                </div>
                        <?php endif; ?>
                                <div class="space-y-3">
                                    <?php foreach ($validCheckGroup['checks'] as $check): ?>
                                        <?= $renderCheckCard($check) ?>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        <?php else: ?>
            <?= \Components\Ui\EmptyState::simple([
                    'icon' => Base::SVG_PULSE,
                    'title' => Base::lng('UI_APPLICATION_HEALTH', 'System Status'),
                    'text' => Base::lng('UI_APPLICATION_HEALTH_NO_ISSUES', 'No issues detected.')
            ]) ?>
        <?php endif; ?>
        </div>

        <div class="mt-6 flex items-center justify-center gap-1.5 text-xs text-secondary/55">
            <span>
                <?= Base::h(Base::lng('UI_LAST_CHECKED_PREFIX', 'Last checked')) ?>
                <time datetime="<?= Base::h($healthLastCheckedIso) ?>"
                      title="<?= Base::h($healthLastCheckedRaw, false) ?>"
                      x-data="{ date: new Date('<?= Base::h($healthLastCheckedIso) ?>') }"
                      @health-polled.window="date = new Date(($event.detail && $event.detail.checked_at) ? $event.detail.checked_at : new Date().toISOString())"
                      x-timeago="date">...</time>
            </span>
            <button type="button"
                    @click="refreshCurrentTab()"
                    class="group relative flex size-5 items-center justify-center hover:text-primary transition-all active:scale-95"
                    title="<?= Base::h(Base::lng('UI_REFRESH', 'Refresh')) ?>">
                <div class="[&_svg]:size-3.5" :class="isRefreshing ? 'animate-spin' : ''">
                    <?= Base::SVG_REFRESH ?>
                </div>
            </button>
        </div>
    </div>
</div>
