<?php

declare(strict_types=1);

require_once dirname(__DIR__, 3) . '/system/bootstrap.php';
// DesignSystemRegistry is loaded by bootstrap's app-local JSONM runtime.

$currentUser = myronRequireDesignAccess();
$csrfToken = myronCsrfToken();
$tokenPatchRepository = myronTokenPatchRepository();

$registry = new DesignSystemRegistry();
$registry->ensureStorage();

/**
 * @return list<string>
 */
function myronTokenDesignerValidTokenNames(): array
{
    $tokenReference = myronTokenReferenceService()->snapshot();
    $groups = is_array($tokenReference['groups'] ?? null) ? $tokenReference['groups'] : [];
    $validTokenNames = [];
    foreach ($groups as $group) {
        foreach (is_array($group['entries'] ?? null) ? $group['entries'] : [] as $entry) {
            if (is_array($entry) && (string) ($entry['cssVar'] ?? '') !== '') {
                $validTokenNames[] = (string) $entry['cssVar'];
            }
        }
    }

    return array_values(array_unique($validTokenNames));
}

if (($_GET['action'] ?? '') === 'export-current') {
    try {
        $current = $registry->currentDefinition();
        $json = $registry->exportCurrentJson((string) $current['id'], (string) $current['name']);
        $downloadName = preg_replace('/[^a-z0-9._-]+/i', '-', (string) $current['id']);
        if (!is_string($downloadName) || trim($downloadName) === '') {
            $downloadName = 'myron-design-system';
        }

        header('Content-Type: application/json; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $downloadName . '.jsonm"');
        echo $json;
        exit;
    } catch (Throwable $e) {
        myronRedirectWithFlash(myronBuildAdminUrl('design.tokenDesigner'), $e->getMessage(), 'error');
    }
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $action = trim((string) ($_POST['action'] ?? ''));

        $tokenPatchService = myronTokenPatchActionService();
        $callerCtx = myronActionCallerContextForUser($currentUser);

        if ($action === 'save-token-patch') {
            $tokenPatchService->savePatch(
                (string) ($_POST['token_name'] ?? ''),
                (string) ($_POST['patch_value'] ?? ''),
                (string) ($_POST['patch_note'] ?? ''),
                $callerCtx
            );
            myronRedirectWithFlash(myronBuildAdminUrl('design.tokenDesigner'), 'Saved token override and recompiled runtime patches.', 'success');
        }
        if ($action === 'clear-token-patch') {
            $tokenPatchService->clearPatch((string) ($_POST['token_name'] ?? ''), $callerCtx);
            myronRedirectWithFlash(myronBuildAdminUrl('design.tokenDesigner'), 'Cleared token override and recompiled runtime patches.', 'success');
        }
        if ($action === 'clear-token-patches') {
            $tokenPatchService->clearAllPatches($callerCtx);
            myronRedirectWithFlash(myronBuildAdminUrl('design.tokenDesigner'), 'Cleared all token overrides.', 'success');
        }
        if ($action === 'clear-orphan-token-patches') {
            $outcome = $tokenPatchService->clearOrphanPatches($callerCtx);
            $cleared = (int) $outcome['cleared'];
            $preserved = (int) $outcome['preserved'];
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.tokenDesigner'),
                $cleared . ' orphan patch' . ($cleared === 1 ? '' : 'es') . ' cleared. ' . $preserved . ' non-orphan patch' . ($preserved === 1 ? '' : 'es') . ' preserved.',
                'success'
            );
        }

        if ($action === 'save-current') {
            $definitionsService = myronDefinitionsActionService();
            $designCallerCtx = myronActionCallerContextForUser($currentUser);
            $record = $definitionsService->saveCurrent(
                (string) ($_POST['name'] ?? ''),
                is_string($_POST['requested_id'] ?? null) ? (string) $_POST['requested_id'] : null,
                is_string($_POST['description'] ?? null) ? (string) $_POST['description'] : null,
                $designCallerCtx
            );
            myronRedirectWithFlash(myronBuildAdminUrl('design.tokenDesigner'), 'Saved design system `' . (string) $record['name'] . '`.', 'success');
        }

        throw new InvalidArgumentException('Unknown action.');
    } catch (Throwable $exception) {
        myronRedirectWithFlash(myronBuildAdminUrl('design.tokenDesigner'), $exception->getMessage(), 'error');
    }
}

$tokenReference = null;
$tokenReferenceError = null;
$tokenPatches = $tokenPatchRepository->listPatchesByToken();

try {
    $tokenReference = myronTokenReferenceService()->snapshot();
} catch (Throwable $e) {
    $tokenReferenceError = $e->getMessage();
}

function myronTokenDesignerEscape(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

/**
 * @param list<array<string, mixed>> $preview
 */
function myronTokenDesignerRenderEffectPreview(array $summary, array $preview): void
{
    $total = (int) ($summary['total'] ?? 0);
    ?>
    <div class="sg-token-effects">
      <?php if ($total < 1): ?>
      <p class="sg-token-effects__empty">No registry surfaces currently declare this token.</p>
      <?php else: ?>
      <div class="sg-token-effects__counts">
        <span class="sg-pill"><?= myronTokenDesignerEscape((string) $total) ?> surfaces</span>
        <?php foreach (['atoms' => 'atoms', 'primitives' => 'primitives', 'components' => 'components'] as $key => $label): ?>
        <?php $count = (int) ($summary[$key] ?? 0); ?>
        <?php if ($count > 0): ?>
        <span class="sg-pill"><?= myronTokenDesignerEscape((string) $count) ?> <?= myronTokenDesignerEscape($label) ?></span>
        <?php endif; ?>
        <?php endforeach; ?>
      </div>
      <?php if ($preview !== []): ?>
      <div class="sg-token-effects__preview">
        <?php foreach ($preview as $surface): ?>
        <span class="sg-token-effects__surface">
          <?= myronTokenDesignerEscape((string) ($surface['classification'] ?? 'surface')) ?>:
          <?= myronTokenDesignerEscape((string) ($surface['id'] ?? 'unknown')) ?>
        </span>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>
      <?php endif; ?>
    </div>
    <?php
}

/**
 * @param list<string> $values
 */
function myronTokenDesignerRenderList(array $values): void
{
    if ($values === []) {
        echo '<span class="sg-token-table__empty">—</span>';
        return;
    }

    echo '<div class="sg-token-list">';
    foreach ($values as $value) {
        echo '<span class="sg-token-list__item">' . myronTokenDesignerEscape($value) . '</span>';
    }
    echo '</div>';
}

myronRenderAdminShellStart($currentUser, [
    'title' => 'Token Designer',
    'titleContext' => 'Token Designer',
    'activeItem' => 'token-designer',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Design', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Design Studio', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Token Designer'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Token Designer</h1>
  </div>
  <p class="mc-workspace__subtitle">Live design token editor for the active JSONM system. Override token values to tune the active design system, observe token effects across the component registry, and save or export your work as a named design system.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <?php if ($tokenReferenceError !== null): ?>
  <div class="sg-main">
    <section class="sg-section">
      <h1 class="sg-section__title">Token Designer</h1>
      <p class="sg-section__subtitle">The live token editor could not be generated from the active token and component sources.</p>
      <div class="sg-status sg-status--error" role="status">
        <?= myronTokenDesignerEscape($tokenReferenceError) ?>
      </div>
    </section>
  </div>
  <?php else: ?>
  <?php
    /** @var array<string, mixed> $tokenReference */
    $overview = is_array($tokenReference['overview'] ?? null) ? $tokenReference['overview'] : [];
    $currentSystem = is_array($tokenReference['currentSystem'] ?? null) ? $tokenReference['currentSystem'] : [];
    $groups = is_array($tokenReference['groups'] ?? null) ? $tokenReference['groups'] : [];
    $registry2 = is_array($tokenReference['registry'] ?? null) ? $tokenReference['registry'] : ['summary' => [], 'sections' => []];
    $registrySummary = is_array($registry2['summary'] ?? null) ? $registry2['summary'] : [];
    $registrySections = is_array($registry2['sections'] ?? null) ? $registry2['sections'] : [];
    $sources = is_array($tokenReference['sourceOfTruth'] ?? null) ? $tokenReference['sourceOfTruth'] : [];
    $validTokenNames = [];
    foreach ($groups as $group) {
        foreach (is_array($group['entries'] ?? null) ? $group['entries'] : [] as $entry) {
            if (is_array($entry) && (string) ($entry['cssVar'] ?? '') !== '') {
                $validTokenNames[] = (string) $entry['cssVar'];
            }
        }
    }
    $orphanTokenPatches = $tokenPatchRepository->orphanPatches(array_values(array_unique($validTokenNames)));
  ?>
  <div class="sg-reference-layout">
    <nav class="sg-reference-nav" aria-label="Token reference sections">
      <ul class="sg-nav">
        <li class="sg-nav__item"><a class="sg-nav__link" href="#token-designer-save">Save / Export</a></li>
        <li class="sg-nav__item"><a class="sg-nav__link" href="#token-designer-overview">Overview</a></li>
        <li><span class="sg-nav__section-label">Token Vocabulary</span></li>
        <?php foreach ($groups as $group): ?>
        <?php if (!is_array($group) || (count($group['entries'] ?? []) < 1)) { continue; } ?>
        <li class="sg-nav__item"><a class="sg-nav__link" href="#<?= myronTokenDesignerEscape((string) ($group['id'] ?? 'token-group')) ?>"><?= myronTokenDesignerEscape((string) ($group['title'] ?? 'Token group')) ?></a></li>
        <?php endforeach; ?>
        <li><span class="sg-nav__section-label">Registry Traceability</span></li>
        <li class="sg-nav__item"><a class="sg-nav__link" href="#registry-observability">Registry Coverage</a></li>
        <li class="sg-nav__item"><a class="sg-nav__link" href="#registry-atoms">Atoms</a></li>
        <li class="sg-nav__item"><a class="sg-nav__link" href="#registry-primitives">Primitives</a></li>
        <li class="sg-nav__item"><a class="sg-nav__link" href="#registry-components">Components</a></li>
      </ul>
    </nav>

    <main class="sg-main sg-main--reference">

      <section class="sg-section" id="token-designer-save">
        <h2 class="sg-section__title">Save / Export Design System</h2>
        <p class="sg-section__subtitle">Capture the current applied CSS surfaces as a named JSONM design system in the local registry, or export the raw JSONM file for portability.</p>

        <form method="post" class="sg-form-grid" data-design-system-confirm="Save the current design system as a custom definition?">
          <input type="hidden" name="csrf_token" value="<?= myronTokenDesignerEscape($csrfToken) ?>">
          <input type="hidden" name="action" value="save-current">

          <label class="sg-field">
            <span class="sg-field__label">Name</span>
            <input class="sg-field__control" type="text" name="name" required placeholder="Spring Commerce Theme">
          </label>

          <label class="sg-field">
            <span class="sg-field__label">Requested ID</span>
            <input class="sg-field__control" type="text" name="requested_id" placeholder="spring-commerce-theme">
            <span class="sg-field__hint">Optional. If the ID already exists, a unique suffix will be added.</span>
          </label>

          <label class="sg-field sg-field--full">
            <span class="sg-field__label">Description</span>
            <textarea class="sg-field__control sg-field__control--textarea" name="description" rows="3" placeholder="Saved from the current applied design system."></textarea>
          </label>

          <div class="sg-card__actions">
            <button class="sg-button sg-button--primary" type="submit">Save Current Design System</button>
            <a class="sg-button sg-button--secondary" href="<?= myronTokenDesignerEscape(myronBuildAdminUrl('design.tokenDesigner', ['action' => 'export-current'])) ?>">Export Current JSONM</a>
          </div>
        </form>
      </section>

      <section class="sg-section" id="token-designer-overview">
        <div class="sg-card-grid">
          <article class="sg-card">
            <div class="sg-card__header">
              <h2 class="sg-card__title">Current Applied Design System</h2>
              <span class="sg-pill sg-pill--active"><?= myronTokenDesignerEscape((string) ($currentSystem['kind'] ?? 'active')) ?></span>
            </div>
            <p class="sg-card__text"><?= myronTokenDesignerEscape((string) ($currentSystem['name'] ?? 'Unknown system')) ?></p>
          </article>

          <article class="sg-card">
            <div class="sg-card__header">
              <h2 class="sg-card__title">Observability Scope</h2>
              <span class="sg-pill"><?= myronTokenDesignerEscape((string) ($overview['mappedTokenCount'] ?? 0)) ?> mapped vars</span>
            </div>
            <p class="sg-card__text">The page now renders live token groups from the active JSONM system instead of curated baseline literals.</p>
          </article>

          <article class="sg-card">
            <div class="sg-card__header">
              <h2 class="sg-card__title">Registry Coverage</h2>
              <span class="sg-pill"><?= myronTokenDesignerEscape((string) ($registrySummary['totalImplementedComponents'] ?? 0)) ?> surfaces</span>
            </div>
            <p class="sg-card__text">Traceability comes from the app-owned component inventory snapshot and exposes token effects across the current registry classifications.</p>
            <dl class="sg-definition-list">
              <div class="sg-definition-list__row">
                <dt>Atoms</dt>
                <dd><?= myronTokenDesignerEscape((string) ($registrySummary['atomCount'] ?? (($registrySections['atoms']['count'] ?? 0)))) ?></dd>
              </div>
              <div class="sg-definition-list__row">
                <dt>Primitives</dt>
                <dd><?= myronTokenDesignerEscape((string) ($registrySummary['primitiveCount'] ?? (($registrySections['primitives']['count'] ?? 0)))) ?></dd>
              </div>
              <div class="sg-definition-list__row">
                <dt>Components</dt>
                <dd><?= myronTokenDesignerEscape((string) (($registrySections['components']['count'] ?? 0))) ?></dd>
              </div>
            </dl>
          </article>
        </div>
        <?php if ($tokenPatches !== []): ?>
        <form method="post" class="sg-card__actions">
          <input type="hidden" name="csrf_token" value="<?= myronTokenDesignerEscape($csrfToken) ?>">
          <button class="sg-button sg-button--secondary" type="submit" name="action" value="clear-token-patches">Clear All Token Overrides</button>
        </form>
        <?php endif; ?>
        <?php if ($orphanTokenPatches !== []): ?>
        <?php $orphanCount = count($orphanTokenPatches); ?>
        <div class="sg-status sg-status--warning" role="status" data-myron-orphan-token-status>
          <p class="myron-paragraph">
            <strong><?= myronTokenDesignerEscape((string) $orphanCount) ?> token override patch<?= $orphanCount === 1 ? '' : 'es' ?></strong> no longer map to the active design-system token vocabulary. These patches are preserved in storage but have no effect at runtime until the operator switches back to a design system that defines the affected tokens.
          </p>
          <table class="sg-prop-table sg-token-table sg-token-table--orphans" data-myron-orphan-token-table>
            <thead>
              <tr>
                <th>Token</th>
                <th>Patched Value</th>
                <th>State</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($orphanTokenPatches as $orphanToken => $orphanPatch): ?>
              <?php
                $orphanValue = is_array($orphanPatch) ? (string) ($orphanPatch['patchValue'] ?? '') : '';
              ?>
              <tr data-myron-orphan-token-row>
                <td>
                  <code data-myron-orphan-token-patch><?= myronTokenDesignerEscape((string) $orphanToken) ?></code>
                </td>
                <td>
                  <code><?= myronTokenDesignerEscape($orphanValue) ?></code>
                </td>
                <td>
                  <span class="sg-pill sg-pill--warning" data-myron-orphan-badge title="This token is not in the active design system catalog. The patch is preserved but has no effect.">Orphan</span>
                </td>
                <td>
                  <form method="post" class="sg-inline-form">
                    <input type="hidden" name="csrf_token" value="<?= myronTokenDesignerEscape($csrfToken) ?>">
                    <input type="hidden" name="token_name" value="<?= myronTokenDesignerEscape((string) $orphanToken) ?>">
                    <button class="sg-button sg-button--secondary" type="submit" name="action" value="clear-token-patch">Clear</button>
                  </form>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
          <form method="post" class="sg-inline-form">
            <input type="hidden" name="csrf_token" value="<?= myronTokenDesignerEscape($csrfToken) ?>">
            <button class="sg-button sg-button--secondary" type="submit" name="action" value="clear-orphan-token-patches" onclick="return confirm('Clear <?= myronTokenDesignerEscape((string) $orphanCount) ?> orphan patch<?= $orphanCount === 1 ? '' : 'es' ?>? Non-orphan patches will be preserved. This cannot be undone.');">Clear Orphan Patches</button>
          </form>
        </div>
        <?php endif; ?>
      </section>

      <?php // Applied System Sources section (developer/AI-fit; per APO-178 audience-first taxonomy hidden from operator render). Underlying sources still drive observability via TokenReferenceService snapshot. ?>

      <?php foreach ($groups as $group): ?>
      <?php
        if (!is_array($group)) {
            continue;
        }
        $entries = is_array($group['entries'] ?? null) ? $group['entries'] : [];
        if ($entries === []) {
            continue;
        }
      ?>
      <section class="sg-section" id="<?= myronTokenDesignerEscape((string) ($group['id'] ?? 'token-group')) ?>">
        <h2 class="sg-section__title"><?= myronTokenDesignerEscape((string) ($group['title'] ?? 'Token group')) ?></h2>
        <p class="sg-section__subtitle">
          <?= myronTokenDesignerEscape((string) ($group['description'] ?? '')) ?>
          <?= myronTokenDesignerEscape((string) count($entries)) ?> mapped entries ·
          <?= myronTokenDesignerEscape((string) ($group['surfaceCount'] ?? 0)) ?> declared token effects.
        </p>

        <?php if ((string) ($group['renderMode'] ?? 'table') === 'swatch'): ?>
        <div class="sg-color-grid">
          <?php foreach ($entries as $entry): ?>
          <?php if (!is_array($entry)) { continue; } ?>
          <div class="sg-swatch">
            <div class="sg-swatch__color" style="--myron-token-reference-swatch: <?= myronTokenDesignerEscape((string) ($entry['runtimeValue'] ?? 'transparent')) ?>;"></div>
            <div class="sg-swatch__label">
              <span class="sg-swatch__name"><?= myronTokenDesignerEscape((string) ($entry['name'] ?? 'token')) ?></span>
              <span class="sg-swatch__hex"><code><?= myronTokenDesignerEscape((string) ($entry['runtimeValue'] ?? '')) ?></code></span>
              <span class="sg-swatch__meta"><code><?= myronTokenDesignerEscape((string) ($entry['cssVar'] ?? '')) ?></code></span>
              <?php if ((string) ($entry['sourceValue'] ?? '') !== '' && (string) ($entry['sourceValue'] ?? '') !== (string) ($entry['runtimeValue'] ?? '')): ?>
              <span class="sg-swatch__meta">source: <code><?= myronTokenDesignerEscape((string) $entry['sourceValue']) ?></code></span>
              <?php endif; ?>
              <?php myronTokenDesignerRenderEffectPreview((array) ($entry['dependentSummary'] ?? []), (array) ($entry['dependentPreview'] ?? [])); ?>
              <?php $cssVar = (string) ($entry['cssVar'] ?? ''); ?>
              <?php if ($cssVar !== ''): ?>
              <?php $patch = is_array($tokenPatches[$cssVar] ?? null) ? $tokenPatches[$cssVar] : []; ?>
              <?php if ($patch !== []): ?><span class="sg-pill sg-pill--active">Override active</span><?php endif; ?>
              <form method="post" class="sg-inline-form">
                <input type="hidden" name="csrf_token" value="<?= myronTokenDesignerEscape($csrfToken) ?>">
                <input type="hidden" name="token_name" value="<?= myronTokenDesignerEscape($cssVar) ?>">
                <?= myronTokenControlRenderer()->render('patch_value', (string) ($patch['patchValue'] ?? ''), myronTokenControlRenderer()->controlTypeForToken($cssVar), $cssVar) . "\n" ?>
                <button class="sg-button sg-button--secondary" type="submit" name="action" value="save-token-patch">Save</button>
                <?php if ($patch !== []): ?>
                <button class="sg-button sg-button--secondary" type="submit" name="action" value="clear-token-patch">Clear</button>
                <?php endif; ?>
              </form>
              <?php endif; ?>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
        <?php else: ?>
        <div class="sg-table-specimen">
          <table class="sg-prop-table sg-token-table">
            <thead>
              <tr>
                <th>Token</th>
                <th>Active Runtime</th>
                <th>JSONM Path</th>
                <th>Effects</th>
                <th>Override</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($entries as $entry): ?>
              <?php if (!is_array($entry)) { continue; } ?>
              <tr>
                <td>
                  <strong><?= myronTokenDesignerEscape((string) ($entry['name'] ?? 'token')) ?></strong>
                  <?php if ((string) ($entry['cssVar'] ?? '') !== ''): ?>
                  <div class="sg-token-table__meta"><code><?= myronTokenDesignerEscape((string) $entry['cssVar']) ?></code></div>
                  <?php endif; ?>
                </td>
                <td>
                  <code><?= myronTokenDesignerEscape((string) ($entry['runtimeValue'] ?? '')) ?></code>
                  <?php if ((string) ($entry['sourceValue'] ?? '') !== '' && (string) ($entry['sourceValue'] ?? '') !== (string) ($entry['runtimeValue'] ?? '')): ?>
                  <div class="sg-token-table__meta">source: <code><?= myronTokenDesignerEscape((string) $entry['sourceValue']) ?></code></div>
                  <?php endif; ?>
                </td>
                <td>
                  <code><?= myronTokenDesignerEscape((string) ($entry['jsonPath'] ?? '')) ?></code>
                  <div class="sg-token-table__meta"><?= myronTokenDesignerEscape((string) ($entry['kind'] ?? 'value')) ?></div>
                </td>
                <td><?php myronTokenDesignerRenderEffectPreview((array) ($entry['dependentSummary'] ?? []), (array) ($entry['dependentPreview'] ?? [])); ?></td>
                <td>
                  <?php $cssVar = (string) ($entry['cssVar'] ?? ''); ?>
                  <?php if ($cssVar !== ''): ?>
                  <?php $patch = is_array($tokenPatches[$cssVar] ?? null) ? $tokenPatches[$cssVar] : []; ?>
                  <?php if ($patch !== []): ?><span class="sg-pill sg-pill--active">Override active</span><?php endif; ?>
                  <form method="post" class="sg-inline-form">
                    <input type="hidden" name="csrf_token" value="<?= myronTokenDesignerEscape($csrfToken) ?>">
                    <input type="hidden" name="token_name" value="<?= myronTokenDesignerEscape($cssVar) ?>">
                    <?= myronTokenControlRenderer()->render('patch_value', (string) ($patch['patchValue'] ?? ''), myronTokenControlRenderer()->controlTypeForToken($cssVar), $cssVar) . "\n" ?>
                    <button class="sg-button sg-button--secondary" type="submit" name="action" value="save-token-patch">Save</button>
                    <?php if ($patch !== []): ?>
                    <button class="sg-button sg-button--secondary" type="submit" name="action" value="clear-token-patch">Clear</button>
                    <?php endif; ?>
                  </form>
                  <?php endif; ?>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <?php endif; ?>
      </section>
      <?php endforeach; ?>

      <section class="sg-section" id="registry-observability">
        <h2 class="sg-section__title">Registry Coverage</h2>
        <p class="sg-section__subtitle">The component inventory snapshot is the traceability layer between token vocabulary and the registry surfaces it affects. Composition links come from the inventory <code>compositionTree</code>.</p>
        <?php if ((int) (($registrySections['components']['count'] ?? 0)) < 1): ?>
        <div class="sg-status" role="status">
          No higher-order <code>component</code> classifications are registered yet. The live observability surface still reports atoms and primitives now, and will surface components as the registry expands.
        </div>
        <?php endif; ?>
      </section>

      <?php foreach (['atoms', 'primitives', 'components'] as $bucket): ?>
      <?php
        $section = is_array($registrySections[$bucket] ?? null) ? $registrySections[$bucket] : ['label' => ucfirst($bucket), 'count' => 0, 'items' => []];
        $items = is_array($section['items'] ?? null) ? $section['items'] : [];
      ?>
      <section class="sg-section" id="registry-<?= myronTokenDesignerEscape($bucket) ?>">
        <h2 class="sg-section__title"><?= myronTokenDesignerEscape((string) ($section['label'] ?? ucfirst($bucket))) ?></h2>
        <p class="sg-section__subtitle"><?= myronTokenDesignerEscape((string) ($section['count'] ?? 0)) ?> registered <?= myronTokenDesignerEscape($bucket) ?> currently participate in token observability.</p>
        <?php if ($items === []): ?>
        <div class="sg-empty-state">
          <p class="sg-empty-state__title">No <?= myronTokenDesignerEscape($bucket) ?> are registered yet.</p>
          <p class="sg-empty-state__text">This classification will appear here automatically once the canonical component inventory includes it.</p>
        </div>
        <?php else: ?>
        <div class="sg-table-specimen">
          <table class="sg-prop-table sg-token-table">
            <thead>
              <tr>
                <th>Surface</th>
                <th>Registry Address</th>
                <th>Token Families</th>
                <th>Tokens</th>
                <th>Composition</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($items as $item): ?>
              <?php if (!is_array($item)) { continue; } ?>
              <tr>
                <td>
                  <strong><?= myronTokenDesignerEscape((string) ($item['id'] ?? 'surface')) ?></strong>
                  <?php if ((string) ($item['purpose'] ?? '') !== ''): ?>
                  <div class="sg-token-table__meta"><?= myronTokenDesignerEscape((string) $item['purpose']) ?></div>
                  <?php endif; ?>
                </td>
                <td><code><?= myronTokenDesignerEscape((string) ($item['registryAddress'] ?? '')) ?></code></td>
                <td><?php myronTokenDesignerRenderList((array) ($item['tokenFamilies'] ?? [])); ?></td>
                <td>
                  <div class="sg-token-table__meta">
                    <?= myronTokenDesignerEscape((string) count((array) ($item['tokenDependencies'] ?? []))) ?> dependencies
                  </div>
                  <?php myronTokenDesignerRenderList(array_slice((array) ($item['tokenDependencies'] ?? []), 0, 6)); ?>
                </td>
                <td>
                  <div class="sg-token-table__stack">
                    <div>
                      <span class="sg-token-table__meta">Composed of</span>
                      <?php myronTokenDesignerRenderList((array) ($item['composedOf'] ?? [])); ?>
                    </div>
                    <div>
                      <span class="sg-token-table__meta">Used by</span>
                      <?php myronTokenDesignerRenderList((array) ($item['usedBy'] ?? [])); ?>
                    </div>
                  </div>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <?php endif; ?>
      </section>
      <?php endforeach; ?>
    </main>
  </div>
  <?php endif; ?>
</div>
<?php myronRenderAdminShellEnd(); ?>
