<?php

declare(strict_types=1);

/**
 * @param list<array<string, mixed>> $crumbs
 */
function myronRenderAdminBreadcrumbs(array $crumbs): void
{
    $normalizedCrumbs = [];
    foreach ($crumbs as $crumb) {
        if (!is_array($crumb)) {
            continue;
        }
        $label = trim((string) ($crumb['label'] ?? ''));
        if ($label === '') {
            continue;
        }
        $href = trim((string) ($crumb['href'] ?? ''));
        $normalizedCrumbs[] = [
            'label' => $label,
            'href' => $href,
        ];
    }

    if ($normalizedCrumbs === []) {
        return;
    }

    $lastIndex = count($normalizedCrumbs) - 1;
    ?>
  <nav class="mc-workspace__eyebrow mc-admin-breadcrumbs" aria-label="Breadcrumb">
    <ol class="mc-admin-breadcrumbs__list">
      <?php foreach ($normalizedCrumbs as $index => $crumb): ?>
      <?php
        $isCurrent = $index === $lastIndex;
        $href = (string) $crumb['href'];
      ?>
      <li class="mc-admin-breadcrumbs__item">
        <?php if (!$isCurrent && $href !== ''): ?>
        <a class="mc-admin-breadcrumbs__link" href="<?= myronEscape($href) ?>"><?= myronEscape((string) $crumb['label']) ?></a>
        <?php else: ?>
        <span class="mc-admin-breadcrumbs__current"<?= $isCurrent ? ' aria-current="page"' : '' ?>><?= myronEscape((string) $crumb['label']) ?></span>
        <?php endif; ?>
        <?php if (!$isCurrent): ?>
        <span class="mc-admin-breadcrumbs__separator" aria-hidden="true">&gt;</span>
        <?php endif; ?>
      </li>
      <?php endforeach; ?>
    </ol>
  </nav>
    <?php
}

/**
 * @param array<string, mixed> $currentUser
 * @param array<string, mixed> $options
 */
function myronRenderAuthenticatedUtilityChrome(array $currentUser, array $options = []): void
{
    $context = trim((string) ($options['context'] ?? 'admin'));
    $context = $context === 'public' ? 'public' : 'admin';
    $brandLabel = trim((string) ($options['brandLabel'] ?? 'MyronCMS'));
    $brandLabel = $brandLabel !== '' ? $brandLabel : 'MyronCMS';
    $centerAction = is_array($options['centerAction'] ?? null) ? $options['centerAction'] : [];
    $utilityPrimary = is_array($options['utilityPrimary'] ?? null) ? $options['utilityPrimary'] : [];
    $showUpdateNotice = (bool) ($options['showUpdateNotice'] ?? true);
    $showAppearanceToggle = (bool) ($options['showAppearanceToggle'] ?? true);
    $logoutReturnTo = trim((string) ($options['logoutReturnTo'] ?? ''));
    $csrfToken = myronCsrfToken();
    $notificationContext = $showUpdateNotice
        ? myronUserNotificationContext($currentUser)
        : ['unread_messages' => 0, 'system_items' => [], 'has_notifications' => false];
    $systemNotificationItems = is_array($notificationContext['system_items'] ?? null) ? $notificationContext['system_items'] : [];
    $unreadMessages = (int) ($notificationContext['unread_messages'] ?? 0);
    $hasNotifications = !empty($notificationContext['has_notifications']);
    $headerClass = 'mc-shell__utility' . ($context === 'public' ? ' mc-public-shell__utility' : '');
    $headerLabel = $context === 'public' ? 'Authenticated site utilities' : 'Global application utilities';
    $centerHref = trim((string) ($centerAction['href'] ?? ''));
    $centerLabel = trim((string) ($centerAction['label'] ?? ''));
    $environmentBadge = myronAdminEnvironmentBadge();
    $centerClass = 'mc-shell__context-action';
    $centerClassExtra = trim((string) ($centerAction['className'] ?? ''));
    if ($centerClassExtra !== '') {
        $centerClass .= ' ' . $centerClassExtra;
    }
    $displayName = trim((string) ($currentUser['display_name'] ?? ''));
    $displayName = $displayName !== '' ? $displayName : 'User';
    $avatarUrl = myronUserAvatarUrl($currentUser);
    $avatarInitials = myronUserInitials($displayName);
    $avatarAriaLabel = $displayName . ' account menu';
    if ($avatarUrl === null && $avatarInitials !== '') {
        $avatarAriaLabel .= ' (' . $avatarInitials . ')';
    }

    ?>
    <header class="<?= myronEscape($headerClass) ?>" role="banner" aria-label="<?= myronEscape($headerLabel) ?>">
      <div class="mc-shell__utility-slot mc-shell__utility-slot--brand">
        <div class="mc-shell__system-brand" data-sg-release-product><?= myronEscape($brandLabel) ?></div>
        <span class="<?= myronEscape($environmentBadge['className']) ?>" title="Current environment"><?= myronEscape($environmentBadge['label']) ?></span>
      </div>
      <div class="mc-shell__utility-slot mc-shell__utility-slot--center">
        <?php if ($centerHref !== '' && $centerLabel !== ''): ?>
        <a class="<?= myronEscape($centerClass) ?>" href="<?= myronEscape($centerHref) ?>"><?= myronEscape($centerLabel) ?></a>
        <?php endif; ?>
      </div>
      <div class="mc-shell__utility-actions" aria-label="Global utilities">
        <?php if ($utilityPrimary !== []): ?>
        <a
          class="mc-shell__utility-action"
          href="<?= myronEscape((string) ($utilityPrimary['href'] ?? myronBuildAdminUrl('content.pageEditor', ['mode' => 'create']))) ?>"
          aria-label="<?= myronEscape((string) ($utilityPrimary['label'] ?? 'Create page')) ?>"
          title="<?= myronEscape((string) ($utilityPrimary['title'] ?? $utilityPrimary['label'] ?? 'Create page')) ?>"
        >
          <img class="mc-icon" src="<?= myronEscape(myronBuildAssetUrl('icons/bootstrap/' . (string) ($utilityPrimary['icon'] ?? 'plus-lg') . '.svg')) ?>" alt="" aria-hidden="true">
        </a>
        <?php endif; ?>
        <div class="mc-shell__notification-menu-wrap" data-mc-notification-menu-root>
          <button
            class="mc-shell__utility-action mc-shell__utility-action--notice<?= $hasNotifications ? ' mc-shell__utility-action--has-dot' : '' ?>"
            type="button"
            aria-label="<?= $hasNotifications ? 'Open notifications' : 'No notifications' ?>"
            aria-haspopup="menu"
            aria-expanded="false"
            title="<?= $hasNotifications ? 'Notifications' : 'No notifications' ?>"
            data-mc-notification-toggle
          >
            <img class="mc-icon" src="<?= myronEscape(myronBuildAssetUrl('icons/bootstrap/bell.svg')) ?>" alt="" aria-hidden="true">
            <?php if ($hasNotifications): ?><span class="mc-shell__utility-dot" aria-hidden="true"></span><?php endif; ?>
          </button>
          <div class="mc-shell__notification-menu" role="menu" hidden data-mc-notification-menu>
            <?php if ($unreadMessages > 0): ?>
            <a class="mc-shell__notification-menu-item" href="<?= myronEscape(myronBuildAdminUrl('dashboard', ['tab' => 'personal'])) ?>" role="menuitem"><?= myronEscape($unreadMessages === 1 ? 'New message' : 'New messages') ?></a>
            <?php endif; ?>
            <?php foreach ($systemNotificationItems as $item): ?>
            <?php
              $href = trim((string) ($item['href'] ?? ''));
              $title = trim((string) ($item['title'] ?? 'System notification'));
              if ($href === '') {
                  continue;
              }
            ?>
            <a class="mc-shell__notification-menu-item" href="<?= myronEscape($href) ?>" role="menuitem"><?= myronEscape($title) ?></a>
            <?php endforeach; ?>
            <?php if (!$hasNotifications): ?>
            <span class="mc-shell__notification-menu-item mc-shell__notification-menu-item--empty" role="menuitem" aria-disabled="true">No notifications</span>
            <?php endif; ?>
          </div>
        </div>
        <?php if ($showAppearanceToggle): ?>
        <button class="mc-shell__utility-action mc-shell__appearance-toggle" type="button" aria-label="Toggle admin shell appearance mode" title="Toggle admin shell appearance mode" aria-pressed="false" data-mc-shell-appearance-toggle data-mc-shell-appearance-state="light">
          <span class="mc-shell__appearance-toggle-icon mc-shell__appearance-toggle-icon--light" aria-hidden="true">
            <img class="mc-icon mc-shell__appearance-toggle-image" src="<?= myronEscape(myronBuildAssetUrl('icons/bootstrap/sun.svg')) ?>" alt="">
          </span>
          <span class="mc-shell__appearance-toggle-icon mc-shell__appearance-toggle-icon--dark" aria-hidden="true">
            <img class="mc-icon mc-shell__appearance-toggle-image" src="<?= myronEscape(myronBuildAssetUrl('icons/bootstrap/moon-fill.svg')) ?>" alt="">
          </span>
        </button>
        <?php endif; ?>
        <div class="mc-shell__avatar-menu-wrap" data-mc-avatar-menu-root>
          <button
            class="mc-shell__avatar"
            type="button"
            aria-label="<?= myronEscape($avatarAriaLabel) ?>"
            aria-haspopup="menu"
            aria-expanded="false"
            data-mc-avatar-toggle
          >
            <?php if ($avatarUrl !== null): ?>
            <img class="mc-shell__avatar-image" src="<?= myronEscape((string) $avatarUrl) ?>" alt="<?= myronEscape($displayName) ?>">
            <?php else: ?>
            <span class="mc-shell__avatar-badge"><?= myronEscape($avatarInitials) ?></span>
            <?php endif; ?>
          </button>
          <div class="mc-shell__avatar-menu" role="menu" hidden data-mc-avatar-menu>
            <a class="mc-shell__avatar-menu-item" href="<?= myronEscape(myronBuildAdminUrl('identity.profile')) ?>" role="menuitem">Profile</a>
            <form method="post" action="<?= myronEscape(myronBuildAdminUrl('auth.logout')) ?>" class="mc-shell__avatar-menu-form">
              <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
              <?php if ($logoutReturnTo !== ''): ?>
              <input type="hidden" name="public_return_to" value="<?= myronEscape($logoutReturnTo) ?>">
              <?php endif; ?>
              <button class="mc-shell__avatar-menu-item mc-shell__avatar-menu-item--danger" type="submit" role="menuitem">Logout</button>
            </form>
          </div>
        </div>
      </div>
    </header>
    <?php
}

/**
 * @return array{label:string,className:string}
 */
function myronAdminEnvironmentBadge(): array
{
    $raw = strtolower(trim((string) (getenv('MYRON_APP_ENV') ?: 'local')));
    $label = match ($raw) {
        'dev', 'development' => 'Dev',
        'stage', 'staging' => 'Stage',
        'live', 'production', 'prod' => 'Live',
        default => 'Local',
    };
    $tone = match ($label) {
        'Dev' => 'dev',
        'Stage' => 'stage',
        'Live' => 'live',
        default => 'local',
    };
    return [
        'label' => $label,
        'className' => 'mc-shell__environment-badge mc-shell__environment-badge--' . $tone,
    ];
}

/**
 * @param array<string, mixed> $currentUser
 * @param array<string, mixed> $options
 */
function myronRenderAdminShellStart(array $currentUser, array $options = []): void
{
    $title = trim((string) ($options['title'] ?? 'Workspace'));
    $titleContext = trim((string) ($options['titleContext'] ?? $title));
    $activeItem = trim((string) ($options['activeItem'] ?? ''));
    $headStyles = is_array($options['headStyles'] ?? null) ? $options['headStyles'] : [];
    if (function_exists('myronModuleRegistry')) {
        foreach (myronModuleRegistry()->adminStylesheets() as $assetPath) {
            $headStyles[] = myronBuildAssetUrl($assetPath);
        }
    }
    $headScripts = is_array($options['headScripts'] ?? null) ? $options['headScripts'] : [];
    $utilityPrimary = is_array($options['utilityPrimary'] ?? null) ? $options['utilityPrimary'] : [
        'href' => myronBuildAdminUrl('content.pageEditor', ['mode' => 'create']),
        'label' => 'Create page',
        'title' => 'Create page',
        'icon' => 'plus-lg',
    ];
    $sections = myronAdminShellSections($currentUser);

    ?>
<!DOCTYPE html>
<html lang="<?= myronEscape(myronSiteLanguage()) ?>" data-sg-title-context="<?= myronEscape($titleContext) ?>">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= myronEscape(myronComposeDocumentTitle($title)) ?></title>
  <?= myronRenderSiteFaviconLink() . "\n" ?>
  <?= myronRenderDefinitionFontHeadTags(
      is_array($options['definitionFontUrls'] ?? null) ? $options['definitionFontUrls'] : []
  ) . "\n" ?>
  <link rel="stylesheet" href="<?= myronEscape(myronBuildAssetUrl('runtime/css/tokens.css')) ?>">
  <link rel="stylesheet" href="<?= myronEscape(myronBuildAssetUrl('runtime/css/runtime-fonts.css')) ?>">
  <link rel="stylesheet" href="<?= myronEscape(myronBuildAssetUrl('runtime/css/runtime-token-overrides.css')) ?>">
  <link rel="stylesheet" href="<?= myronEscape(myronBuildAssetUrl('runtime/css/base.css')) ?>">
  <link rel="stylesheet" href="<?= myronEscape(myronBuildAssetUrl('runtime/css/components.css')) ?>">
  <link rel="stylesheet" href="<?= myronEscape(myronBuildAssetUrl('runtime/css/public-site.css')) ?>">
  <link rel="stylesheet" href="<?= myronEscape(myronBuildAssetUrl('runtime/css/style-guide.css')) ?>">
  <?php foreach ($headStyles as $stylePath): ?>
  <link rel="stylesheet" href="<?= myronEscape((string) $stylePath) ?>">
  <?php endforeach; ?>
  <script src="<?= myronEscape(myronBuildAssetUrl('runtime/js/release-shell.js')) ?>" defer></script>
  <script src="<?= myronEscape(myronBuildAssetUrl('runtime/js/richtext-toolbar.js')) ?>" defer></script>
  <script src="<?= myronEscape(myronBuildAssetUrl('runtime/js/app-shell.js')) ?>" defer></script>
  <script src="<?= myronEscape(myronBuildAssetUrl('runtime/js/interactive-atoms.min.js')) ?>" defer></script>
  <?php foreach ($headScripts as $scriptPath): ?>
  <script src="<?= myronEscape((string) $scriptPath) ?>" defer></script>
  <?php endforeach; ?>
</head>
<body class="mc-shell-page">
  <div class="mc-shell">
    <?php myronRenderAuthenticatedUtilityChrome($currentUser, [
        'context' => 'admin',
        'centerAction' => [
            'href' => myronBuildPublicPageUrl('/'),
            'label' => 'View Site',
        ],
        'utilityPrimary' => $utilityPrimary,
    ]); ?>
    <?php myronRenderFlashToastRegion(null, ['shellOffset' => true]); ?>

    <div class="mc-shell__frame">
      <aside class="mc-rail" aria-label="Primary navigation">
        <div class="mc-rail__top">
          <button class="mc-shell__toggle mc-shell__toggle--rail" type="button" aria-label="Toggle navigation rail" data-mc-shell-toggle>
            <img class="mc-shell__toggle-icon mc-shell__toggle-icon--collapse" src="<?= myronEscape(myronBuildAssetUrl('icons/bootstrap/chevron-left.svg')) ?>" alt="" aria-hidden="true">
            <img class="mc-shell__toggle-icon mc-shell__toggle-icon--expand" src="<?= myronEscape(myronBuildAssetUrl('icons/bootstrap/chevron-right.svg')) ?>" alt="" aria-hidden="true">
          </button>
          <span class="mc-rail__meta"><span data-sg-release-codename><?= myronEscape(MyronReleaseMetadata::CODENAME) ?></span> <span data-sg-release-version><?= myronEscape(MyronReleaseMetadata::VERSION) ?></span></span>
        </div>

        <div class="mc-rail__groups" data-mc-rail-groups>
          <?php foreach ($sections as $section): ?>
          <?php
            $sectionKey = (string) ($section['key'] ?? '');
            $sectionLabel = (string) ($section['label'] ?? 'Section');
            $defaultHref = (string) ($section['defaultHref'] ?? '#');
            $sectionActive = myronAdminShellSectionIsActive($section, $activeItem);
            $groupClassName = 'mc-rail-group' . ($sectionActive ? ' mc-rail-group--active' : '');
            $jumpClassName = 'mc-rail-group__jump' . ($sectionActive ? ' mc-rail-group__jump--active' : '');
          ?>
          <section class="<?= myronEscape($groupClassName) ?>" data-mc-group="<?= myronEscape($sectionKey) ?>" draggable="true">
            <div class="mc-rail-group__header">
              <img class="mc-icon mc-icon--handle" src="<?= myronEscape(myronBuildAssetUrl('icons/bootstrap/grip-vertical.svg')) ?>" alt="" aria-hidden="true">
              <a
                class="<?= myronEscape($jumpClassName) ?>"
                href="<?= myronEscape($defaultHref) ?>"
                aria-label="<?= myronEscape($sectionLabel) ?>"
                title="<?= myronEscape($sectionLabel) ?>"
                <?= $sectionActive ? ' aria-current="page"' : '' ?>
                data-mc-shell-link
              >
                <img class="mc-icon mc-icon--lead" src="<?= myronEscape(myronBuildAssetUrl('icons/bootstrap/' . (string) $section['icon'] . '.svg')) ?>" alt="" aria-hidden="true">
                <span class="mc-rail-group__title"><?= myronEscape($sectionLabel) ?></span>
              </a>
            </div>
            <?php if (($section['mode'] ?? '') === 'nested'): ?>
            <?php
              $branches = is_array($section['branches'] ?? null) ? $section['branches'] : [];
              if ($branches === [] && ($section['branchTitle'] ?? '') !== '' && is_array($section['items'] ?? null)) {
                  $branches[] = [
                      'title' => (string) $section['branchTitle'],
                      'items' => $section['items'],
                  ];
              }
              $supplementalItems = is_array($section['supplementalItems'] ?? null) ? $section['supplementalItems'] : [];
            ?>
            <div class="mc-rail-group__body mc-rail-group__body--nested">
              <?php foreach ($branches as $branch): ?>
              <?php
                if (!is_array($branch)) {
                    continue;
                }
                $branchTitle = (string) ($branch['title'] ?? '');
                $branchKey = myronAdminShellSlug((string) ($branch['key'] ?? $branchTitle));
                $branchDomId = 'mc-rail-branch-' . myronAdminShellSlug($sectionKey . '-' . $branchKey);
                $branchItems = is_array($branch['items'] ?? null) ? $branch['items'] : [];
                if ($branchItems === []) {
                    continue;
                }
                $branchActive = myronAdminShellItemsContainActive($branchItems, $activeItem);
                $branchClassName = 'mc-rail-branch' . ($branchActive ? ' mc-rail-branch--active' : '');
              ?>
              <div class="<?= myronEscape($branchClassName) ?>" data-mc-rail-branch data-mc-rail-branch-key="<?= myronEscape($sectionKey . '.' . $branchKey) ?>" data-mc-rail-branch-active="<?= $branchActive ? 'true' : 'false' ?>">
                <button class="mc-rail-branch__toggle" type="button" aria-expanded="true" aria-controls="<?= myronEscape($branchDomId) ?>" data-mc-rail-branch-toggle>
                  <span class="mc-rail-branch__title"><?= myronEscape($branchTitle) ?></span>
                  <img class="mc-icon mc-rail-branch__toggle-icon" src="<?= myronEscape(myronBuildAssetUrl('icons/bootstrap/chevron-right.svg')) ?>" alt="" aria-hidden="true">
                </button>
                <nav id="<?= myronEscape($branchDomId) ?>" class="mc-rail-subnav" aria-label="<?= myronEscape($branchTitle !== '' ? $branchTitle : $sectionLabel) ?> navigation" data-mc-rail-branch-body>
                  <?php foreach ($branchItems as $item): ?>
                  <?php
                    $itemKey = (string) ($item['key'] ?? '');
                    $isDisabled = !empty($item['disabled']);
                    $className = 'mc-rail-subnav__link'
                        . ($itemKey === $activeItem ? ' mc-rail-subnav__link--active' : '')
                        . ($isDisabled ? ' mc-rail-subnav__link--disabled' : '');
                  ?>
                  <?php if ($isDisabled): ?>
                  <span class="<?= myronEscape($className) ?>" aria-disabled="true"><?= myronEscape((string) $item['label']) ?></span>
                  <?php else: ?>
                  <a class="<?= myronEscape($className) ?>" href="<?= myronEscape((string) $item['href']) ?>"<?= $itemKey === $activeItem ? ' aria-current="page"' : '' ?> data-mc-shell-link><?= myronEscape((string) $item['label']) ?></a>
                  <?php endif; ?>
                  <?php endforeach; ?>
                </nav>
              </div>
              <?php endforeach; ?>
              <?php if ($supplementalItems !== []): ?>
              <nav class="mc-rail-group__body" aria-label="<?= myronEscape($sectionLabel) ?> navigation">
                <?php foreach ($supplementalItems as $item): ?>
                <?php
                  $itemKey = (string) ($item['key'] ?? '');
                  $isDisabled = !empty($item['disabled']);
                  $className = 'mc-rail-link'
                      . ($itemKey === $activeItem ? ' mc-rail-link--active' : '')
                      . ($isDisabled ? ' mc-rail-link--disabled' : '');
                ?>
                <?php if ($isDisabled): ?>
                <span class="<?= myronEscape($className) ?>" aria-disabled="true">
                  <span class="mc-rail-link__label"><?= myronEscape((string) $item['label']) ?></span>
                </span>
                <?php else: ?>
                <a class="<?= myronEscape($className) ?>" href="<?= myronEscape((string) $item['href']) ?>"<?= $itemKey === $activeItem ? ' aria-current="page"' : '' ?> data-mc-shell-link>
                  <span class="mc-rail-link__label"><?= myronEscape((string) $item['label']) ?></span>
                </a>
                <?php endif; ?>
                <?php endforeach; ?>
              </nav>
              <?php endif; ?>
            </div>
            <?php else: ?>
            <nav class="mc-rail-group__body" aria-label="<?= myronEscape($sectionLabel) ?> navigation">
              <?php foreach (($section['items'] ?? []) as $item): ?>
              <?php
                $itemKey = (string) ($item['key'] ?? '');
                $isDisabled = !empty($item['disabled']);
                $className = 'mc-rail-link'
                    . ($itemKey === $activeItem ? ' mc-rail-link--active' : '')
                    . ($isDisabled ? ' mc-rail-link--disabled' : '');
              ?>
              <?php if ($isDisabled): ?>
              <span class="<?= myronEscape($className) ?>" aria-disabled="true">
                <span class="mc-rail-link__label"><?= myronEscape((string) $item['label']) ?></span>
              </span>
              <?php else: ?>
              <a class="<?= myronEscape($className) ?>" href="<?= myronEscape((string) $item['href']) ?>"<?= $itemKey === $activeItem ? ' aria-current="page"' : '' ?> data-mc-shell-link>
                <span class="mc-rail-link__label"><?= myronEscape((string) $item['label']) ?></span>
              </a>
              <?php endif; ?>
              <?php endforeach; ?>
            </nav>
            <?php endif; ?>
          </section>
          <?php endforeach; ?>
        </div>
      </aside>

      <main class="mc-workspace">
    <?php
}

function myronRenderAdminShellEnd(): void
{
    ?>
      </main>
    </div>
  </div>
</body>
</html>
    <?php
}

/**
 * @param array<string, mixed> $options
 */
function myronRenderAdminSidesheet(string $id, string $title, string $bodyHtml, array $options = []): void
{
    $sheetId = myronAdminShellSlug($id);
    $titleId = $sheetId . '-title';
    $description = trim((string) ($options['description'] ?? ''));
    $descriptionId = $description !== '' ? $sheetId . '-description' : '';
    $size = myronAdminShellSlug((string) ($options['size'] ?? 'md'));
    $className = 'mc-sidesheet-overlay mc-sidesheet-overlay--' . $size;
    $hasRichtext = str_contains($bodyHtml, 'data-mc-richtext');

    ?>
<aside
  class="<?= myronEscape($className) ?>"
  id="<?= myronEscape($sheetId) ?>"
  role="dialog"
  aria-modal="true"
  aria-hidden="true"
  aria-labelledby="<?= myronEscape($titleId) ?>"
  <?= $descriptionId !== '' ? 'aria-describedby="' . myronEscape($descriptionId) . '"' : '' ?>
  hidden
  data-mc-sidesheet
>
  <button class="mc-sidesheet-overlay__backdrop" type="button" aria-label="Close panel" data-mc-sidesheet-close></button>
  <section class="mc-sidesheet-overlay__panel" tabindex="-1" data-mc-sidesheet-panel>
    <header class="mc-sidesheet-overlay__header">
      <div class="mc-sidesheet-overlay__heading">
        <h2 class="mc-sidesheet-overlay__title" id="<?= myronEscape($titleId) ?>"><?= myronEscape($title) ?></h2>
        <?php if ($description !== ''): ?>
        <p class="mc-sidesheet-overlay__description" id="<?= myronEscape($descriptionId) ?>"><?= myronEscape($description) ?></p>
        <?php endif; ?>
      </div>
      <button class="mc-sidesheet-overlay__close" type="button" aria-label="Close panel" data-mc-sidesheet-close data-mc-sidesheet-initial-focus>
        <img class="mc-icon" src="<?= myronEscape(myronBuildAssetUrl('icons/bootstrap/x-circle.svg')) ?>" alt="" aria-hidden="true">
      </button>
      <?php if ($hasRichtext): ?>
      <div class="mc-sidesheet-overlay__toolbar" data-mc-richtext-toolbar></div>
      <?php endif; ?>
    </header>
    <div class="mc-sidesheet-overlay__body">
      <?= $bodyHtml . "\n" ?>
    </div>
  </section>
</aside>
    <?php
}

function myronRenderLegacyWorkspaceFragment(string $sourcePath): void
{
    echo myronLoadLegacyWorkspaceFragment($sourcePath);
}

function myronLoadLegacyWorkspaceFragment(string $sourcePath): string
{
    $markup = @file_get_contents($sourcePath);
    if (!is_string($markup) || $markup === '') {
        throw new RuntimeException('Unable to load the requested workspace source.');
    }

    if (!preg_match('/<main class="mc-workspace">(.*)<\/main>/sU', $markup, $matches)) {
        throw new RuntimeException('Unable to extract workspace fragment from the requested source.');
    }

    return $matches[1];
}

function myronUserAvatarUrl(array $user): ?string
{
    $avatarUrl = trim((string) ($user['avatar_url'] ?? ''));
    return $avatarUrl === '' ? null : $avatarUrl;
}

/**
 * @param array<string, mixed> $section
 */
function myronAdminShellSectionIsActive(array $section, string $activeItem): bool
{
    $activeKeys = is_array($section['activeKeys'] ?? null) ? $section['activeKeys'] : [];
    return in_array($activeItem, $activeKeys, true);
}

/**
 * @param list<array<string, mixed>> $items
 */
function myronAdminShellItemsContainActive(array $items, string $activeItem): bool
{
    foreach ($items as $item) {
        if ((string) ($item['key'] ?? '') === $activeItem) {
            return true;
        }
    }

    return false;
}

/**
 * @param array<string, mixed> $item
 */
function myronAdminShellItemAllowedByLicense(array $item): bool
{
    $capabilities = [];
    if (is_string($item['capability'] ?? null) && trim((string) $item['capability']) !== '') {
        $capabilities[] = trim((string) $item['capability']);
    }
    if (is_array($item['capabilities'] ?? null)) {
        foreach ($item['capabilities'] as $capability) {
            $capability = trim((string) $capability);
            if ($capability !== '') {
                $capabilities[] = $capability;
            }
        }
    }

    if ($capabilities === [] || !function_exists('myronEntitlementGate')) {
        return true;
    }

    foreach (array_values(array_unique($capabilities)) as $capability) {
        try {
            $decision = myronEntitlementGate()->evaluate($capability);
        } catch (Throwable) {
            return false;
        }
        if (in_array((string) ($decision['outcome'] ?? ''), ['allowed', 'warn'], true)) {
            return true;
        }
    }

    return false;
}

/**
 * @param list<array<string, mixed>> $items
 * @return list<array<string, mixed>>
 */
function myronAdminShellFilterItemsForLicense(array $items): array
{
    return array_values(array_filter($items, 'myronAdminShellItemAllowedByLicense'));
}

/**
 * @return list<array<string, mixed>>
 */
function myronAdminShellModuleItems(string $branchKey): array
{
    if (!function_exists('myronModuleRegistry')) {
        return [];
    }

    return myronModuleRegistry()->adminMenuItems($branchKey);
}

/**
 * @return list<string>
 */
function myronAdminShellItemKeys(array $items): array
{
    $keys = [];
    foreach ($items as $item) {
        if (is_array($item) && is_string($item['key'] ?? null) && trim((string) $item['key']) !== '') {
            $keys[] = (string) $item['key'];
        }
    }

    return $keys;
}

/**
 * @param list<array<string, mixed>> $branches
 * @return list<array<string, mixed>>
 */
function myronAdminShellFilterBranchesForLicense(array $branches): array
{
    $filtered = [];
    foreach ($branches as $branch) {
        if (!is_array($branch)) {
            continue;
        }
        $items = is_array($branch['items'] ?? null) ? $branch['items'] : [];
        $branch['items'] = myronAdminShellFilterItemsForLicense($items);
        if ($branch['items'] !== []) {
            $filtered[] = $branch;
        }
    }

    return $filtered;
}

function myronAdminShellSlug(string $value): string
{
    $slug = strtolower(trim($value));
    $slug = preg_replace('/[^a-z0-9_-]+/', '-', $slug);
    $slug = trim(is_string($slug) ? $slug : '', '-');

    return $slug === '' ? 'branch' : $slug;
}

/**
 * @param array<string, mixed> $currentUser
 * @return list<array<string, mixed>>
 */
function myronAdminShellSections(array $currentUser): array
{
    $sections = [];

    if (
        myronUserCanAccessDesign($currentUser)
        || myronUserCanAccessContent($currentUser)
        || myronUserCanAccessAdministration($currentUser)
    ) {
        $sections[] = [
            'key' => 'dashboard',
            'label' => 'Dashboard',
            'icon' => 'speedometer2',
            'defaultHref' => myronBuildAdminUrl('dashboard'),
            'activeKeys' => ['dashboard'],
            'items' => [],
        ];
    }

    if (myronUserCanAccessDesign($currentUser)) {
        $designStudioItems = [
            [
                'key' => 'primitives',
                'label' => 'Primitives',
                'href' => myronBuildAdminUrl('design.primitives'),
            ],
            [
                'key' => 'design-system',
                'label' => 'Design Systems',
                'href' => myronBuildAdminUrl('design.systems'),
            ],
            [
                'key' => 'token-designer',
                'label' => 'Token Designer',
                'href' => myronBuildAdminUrl('design.tokenDesigner'),
            ],
            [
                'key' => 'custom-css',
                'label' => 'Custom Interactions',
                'href' => myronBuildAdminUrl('design.customInteractions'),
                'capability' => 'design_systems',
            ],
            [
                'key' => 'design-layout',
                'label' => 'Layout',
                'href' => myronBuildAdminUrl('design.layout'),
            ],
        ];
        $templateStudioItems = [
            [
                'key' => 'template-studio-site-templates',
                'label' => 'Site Templates',
                'href' => myronBuildAdminUrl('design.templateStudioSiteTemplates'),
            ],
            [
                'key' => 'template-studio-page-templates',
                'label' => 'Page Templates',
                'href' => myronBuildAdminUrl('design.templateStudioPageTemplates'),
            ],
            [
                'key' => 'sections-manager',
                'label' => 'Section Templates',
                'href' => myronBuildAdminUrl('design.sectionsManager'),
            ],
            [
                'key' => 'template-studio-document-templates',
                'label' => 'Document Templates',
                'href' => myronBuildAdminUrl('design.templateStudioDocumentTemplates'),
                'capability' => 'templates.document',
            ],
        ];
        $componentStudioItems = [
            [
                'key' => 'creative-library',
                'label' => 'Creative Library',
                'href' => myronBuildAdminUrl('design.creativeLibrary'),
            ],
            [
                'key' => 'section-variants',
                'label' => 'Section Variants',
                'href' => myronBuildAdminUrl('design.sectionVariants'),
                'capability' => 'templates.section_variants',
            ],
            [
                'key' => 'design-navigation',
                'label' => 'Navigation',
                'href' => myronBuildAdminUrl('design.navigation'),
            ],
            [
                'key' => 'design-footers',
                'label' => 'Footers',
                'href' => myronBuildAdminUrl('design.footers'),
            ],
            [
                'key' => 'component-studio-rails',
                'label' => 'Rails',
                'href' => myronBuildAdminUrl('design.rails'),
            ],
            [
                'key' => 'component-studio-forms',
                'label' => 'Forms',
                'href' => myronBuildAdminUrl('design.forms'),
                'capability' => 'forms.general',
            ],
        ];
        $designAssetItems = [
            [
                'key' => 'design-image-manager',
                'label' => 'Image Manager',
                'href' => myronBuildAdminUrl('design.imageManager'),
            ],
            [
                'key' => 'design-video-manager',
                'label' => 'Video Manager',
                'href' => myronBuildAdminUrl('design.videoManager'),
            ],
            [
                'key' => 'design-audio-manager',
                'label' => 'Audio Manager',
                'href' => myronBuildAdminUrl('design.audioManager'),
            ],
        ];

        if (!myronUserCanManageDesign($currentUser)) {
            // Operators without manage-design rights cannot edit the design system
            // surface; remove those items but keep Primitives, Token Designer, and
            // governed read-only building surfaces.
            $designStudioItems = array_values(array_filter(
                $designStudioItems,
                static fn (array $item): bool => !in_array(($item['key'] ?? ''), ['design-system', 'design-layout'], true)
            ));
        }

        $sections[] = [
            'key' => 'design',
            'label' => 'Design',
            'icon' => 'palette',
            'defaultHref' => myronBuildAdminUrl('design.primitives'),
            'activeKeys' => [
                'primitives',
                'design-system',
                'design-layout',
                'design-navigation',
                'design-footers',
                'component-studio-forms',
                'token-designer',
                'token-reference',
                'components',
                'templates',
                'templates-manager',
                'site-type-studio',
                'template-studio-site-templates',
                'template-studio-page-templates',
                'sections-manager',
                'creative-library',
                'section-variants',
                'design-image-manager',
                'design-video-manager',
                'design-audio-manager',
            ],
            'mode' => 'nested',
            'branches' => [
                [
                    'key' => 'design-studio',
                    'title' => 'Design Studio',
                    'items' => myronAdminShellFilterItemsForLicense($designStudioItems),
                ],
                [
                    'key' => 'template-studio',
                    'title' => 'Template Studio',
                    'items' => myronAdminShellFilterItemsForLicense($templateStudioItems),
                ],
                [
                    'key' => 'component-studio',
                    'title' => 'Component Studio',
                    'items' => myronAdminShellFilterItemsForLicense($componentStudioItems),
                ],
                [
                    'key' => 'assets',
                    'title' => 'Assets Manager',
                    'items' => myronAdminShellFilterItemsForLicense($designAssetItems),
                ],
            ],
        ];
    }

    if (myronUserCanAccessContent($currentUser)) {
        $contentStudioItems = array_merge([
            [
                'key' => 'pages',
                'label' => 'Pages',
                'href' => myronBuildAdminUrl('content.pages'),
            ],
            [
                'key' => 'content-categories',
                'label' => 'Categories',
                'href' => myronBuildAdminUrl('content.categories'),
            ],
            [
                'key' => 'content-comments',
                'label' => 'Comments',
                'href' => myronBuildAdminUrl('content.comments'),
            ],
        ], myronAdminShellModuleItems('content-studio'));
        $contentAssetItems = [
            [
                'key' => 'content-image-viewer',
                'label' => 'Image Viewer',
                'href' => myronBuildAdminUrl('content.imageViewer'),
            ],
            [
                'key' => 'content-video-viewer',
                'label' => 'Video Viewer',
                'href' => myronBuildAdminUrl('content.videoViewer'),
            ],
            [
                'key' => 'content-audio-viewer',
                'label' => 'Audio Viewer',
                'href' => myronBuildAdminUrl('content.audioViewer'),
            ],
            [
                'key' => 'content-document-manager',
                'label' => 'Document Manager',
                'href' => myronBuildAdminUrl('content.documentManager'),
            ],
        ];

        $sections[] = [
            'key' => 'content',
            'label' => 'Content',
            'icon' => 'file-earmark-text',
            'defaultHref' => myronBuildAdminUrl('content.pages'),
                'activeKeys' => array_merge([
                    'pages',
                    'content-categories',
                    'content-comments',
                    'content-image-viewer',
                    'content-video-viewer',
                    'content-audio-viewer',
                    'content-document-manager',
                ], myronAdminShellItemKeys(myronAdminShellModuleItems('content-studio'))),
            'mode' => 'nested',
            'branches' => [
                [
                    'key' => 'content-studio',
                    'title' => 'Content Studio',
                    'items' => myronAdminShellFilterItemsForLicense($contentStudioItems),
                ],
                [
                    'key' => 'asset-manager',
                    'title' => 'Assets Viewer',
                    'items' => myronAdminShellFilterItemsForLicense($contentAssetItems),
                ],
                [
                    'key' => 'content-ai-studio',
                    'title' => 'Content AI Studio',
                    'items' => myronAdminShellFilterItemsForLicense([
                        [
                            'key' => 'content-ai-studio-placeholder',
                            'label' => 'Content AI Studio',
                            'disabled' => true,
                            'capability' => 'mcp.byok_ai_actions',
                        ],
                    ]),
                ],
            ],
        ];
    }

    if (myronUserCanAccessAdministration($currentUser)) {
        $administrationBranches = myronAdminShellFilterBranchesForLicense([
            [
                'key' => 'manage',
                'title' => 'Manage',
                'items' => [
                    [
                        'key' => 'roles-users',
                        'label' => 'Roles & Users',
                        'href' => myronBuildAdminUrl('administration.rolesUsers'),
                    ],
                    [
                        'key' => 'menus',
                        'label' => 'Menus',
                        'href' => myronBuildAdminUrl('administration.menus'),
                    ],
                    [
                        'key' => 'mail-setup',
                        'label' => 'Mail Settings',
                        'href' => myronBuildAdminUrl('administration.mail'),
                        'capability' => 'mail.multiple_configs',
                    ],
                    [
                        'key' => 'notification-emails',
                        'label' => 'Verified Destinations',
                        'href' => myronBuildAdminUrl('administration.notificationEmails'),
                        'capability' => 'mail.multiple_configs',
                    ],
                    ...myronAdminShellModuleItems('administration-manage'),
                    [
                        'key' => 'ai-connections',
                        'label' => 'AI Connections',
                        'href' => myronBuildAdminUrl('administration.aiConnections'),
                        'capability' => 'mcp.site_operations',
                    ],
                ],
            ],
            [
                'key' => 'setup',
                'title' => 'System',
                'items' => [
                    [
                        'key' => 'site-setup',
                        'label' => 'Site Setup',
                        'href' => myronBuildAdminUrl('administration.siteSetup'),
                    ],
                    [
                        'key' => 'site-settings',
                        'label' => 'Site Settings',
                        'href' => myronBuildAdminUrl('administration.siteSettings'),
                    ],
                    [
                        'key' => 'form-protection',
                        'label' => 'Form Protection',
                        'href' => myronBuildAdminUrl('administration.formProtection'),
                        'capability' => 'verification.myron_engine',
                    ],
                    [
                        'key' => 'analytics',
                        'label' => 'Analytics',
                        'href' => myronBuildAdminUrl('administration.analytics'),
                        'capability' => 'analytics.native',
                    ],
                    [
                        'key' => 'snapshot',
                        'label' => 'Snapshot',
                        'href' => myronBuildAdminUrl('administration.snapshot'),
                        'capability' => 'snapshots.basic',
                    ],
                    [
                        'key' => 'license',
                        'label' => 'License',
                        'href' => myronBuildAdminUrl('administration.license'),
                    ],
                    [
                        'key' => 'license-manager',
                        'label' => 'Modules',
                        'href' => myronBuildAdminUrl('administration.licenseManager'),
                    ],
                    [
                        'key' => 'change-log',
                        'label' => 'Change Log',
                        'href' => myronBuildAdminUrl('administration.changelog'),
                        'capability' => 'updates.maintenance',
                    ],
                    [
                        'key' => 'audit-log',
                        'label' => 'Audit Log',
                        'href' => myronBuildAdminUrl('administration.auditLog'),
                        'capability' => 'audit.admin_surface',
                    ],
                ],
            ],
        ]);

        $administrationActiveKeys = array_merge(
            ['roles-users', 'menus', 'site-setup', 'site-settings', 'form-protection', 'analytics', 'snapshot', 'license', 'license-manager', 'mail-setup', 'notification-emails', 'change-log', 'ai-connections', 'audit-log'],
            myronAdminShellItemKeys(myronModuleRegistry()->adminMenuItems('administration-manage'))
        );

        $sections[] = [
            'key' => 'administration',
            'label' => 'Administration',
            'icon' => 'gear',
            'defaultHref' => myronBuildAdminUrl('administration.rolesUsers'),
            'activeKeys' => $administrationActiveKeys,
            'mode' => 'nested',
            'branches' => $administrationBranches,
        ];

        if (myronUserHoldsScope($currentUser, MyronApiScopes::ADMINISTRATION_WRITE)) {
            $extensionItems = myronAdminShellFilterItemsForLicense([
                [
                    'key' => 'extensions-register',
                    'label' => 'Register Extension',
                    'href' => myronBuildAdminUrl('extensions.register'),
                    'capability' => 'extensions.local_registration',
                ],
                [
                    'key' => 'extensions-marketplace',
                    'label' => 'Marketplace',
                    'href' => myronBuildAdminUrl('extensions.marketplace'),
                    'capability' => 'extensions.marketplace_install',
                ],
                [
                    'key' => 'extensions-installed',
                    'label' => 'Installed Extensions',
                    'href' => myronBuildAdminUrl('extensions.installed'),
                    'capability' => 'extensions.marketplace_install',
                ],
            ]);
            if ($extensionItems === []) {
                return $sections;
            }

            $sections[] = [
                'key' => 'extensions',
                'label' => 'Extensions',
                'icon' => 'puzzle',
                'defaultHref' => (string) ($extensionItems[0]['href'] ?? myronBuildAdminUrl('extensions.installed')),
                'activeKeys' => ['extensions-register', 'extensions-marketplace', 'extensions-installed', 'sample-hello'],
                'mode' => 'flat',
                'items' => $extensionItems,
            ];
        }
    }

    return $sections;
}
