<?php
declare(strict_types=1);

namespace PSLauncher\Admin;

final class Layout
{
    public static function header(string $title, string $active = ''): void
    {
        Auth::start();
        $isLoggedIn = Auth::isLoggedIn();
        $titleEsc = htmlspecialchars($title);
        $nav = $isLoggedIn ? self::navHtml($active) : '';
        echo <<<HTML
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex,nofollow">
<title>{$titleEsc} — PS_Launcher Admin</title>
<link rel="stylesheet" href="assets/style.css">
</head>
<body>
{$nav}
<main>
HTML;
    }

    public static function footer(): void
    {
        echo "</main></body></html>";
    }

    private static function navHtml(string $active): string
    {
        $items = [
            'dashboard' => ['index.php',    'Dashboard'],
            'licenses'  => ['licenses.php', 'Licenses'],
            'versions'  => ['versions.php', 'Versions'],
            'launcher'  => ['launcher.php', 'Launcher'],
            'audit'     => ['audit.php',    'Audit'],
        ];
        $links = '';
        foreach ($items as $k => [$href, $label]) {
            $cls  = ($k === $active) ? 'active' : '';
            $links .= sprintf(
                '<a href="%s" class="%s">%s</a>',
                htmlspecialchars($href),
                $cls,
                htmlspecialchars($label)
            );
        }
        return <<<HTML
<nav>
  <strong class="brand">PS_Launcher Admin</strong>
  {$links}
  <span class="spacer"></span>
  <a href="logout.php" class="logout">Déconnexion</a>
</nav>
HTML;
    }

    public static function flash(?string $msg, string $type = 'success'): void
    {
        if ($msg === null || $msg === '') return;
        $cls = $type === 'error' ? 'error' : 'success';
        echo "<div class='flash {$cls}'>" . nl2br(htmlspecialchars($msg)) . "</div>";
    }

    public static function csrfField(): string
    {
        return '<input type="hidden" name="csrf" value="' . htmlspecialchars(Auth::csrfToken()) . '">';
    }

    public static function formatBytes(int $bytes): string
    {
        if ($bytes <= 0) return '—';
        $units = ['o', 'Ko', 'Mo', 'Go', 'To'];
        $u = 0;
        $v = (float)$bytes;
        while ($v >= 1024 && $u < count($units) - 1) { $v /= 1024; $u++; }
        return number_format($v, 1) . ' ' . $units[$u];
    }
}
