<?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(true);

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

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

function myronDesignSystemsRedirect(string $type, string $message): never
{
    $params = (string) ($_POST['preview_open'] ?? '') === '1' ? ['design_preview' => '1'] : [];
    myronRedirectWithFlash(myronBuildAdminUrl('design.systems', $params), $message, $type);
}

/**
 * @param array<string, mixed> $definition
 * @param array<string, mixed> $tokenMap
 */
function myronDesignSystemsPreviewCss(array $definition, array $tokenMap): string
{
    $compiledLayers = [
        StyleDefinitionRuntime::compileDefinition($definition, $tokenMap),
        StyleDefinitionRuntime::compileFontRolesDefinition($definition),
    ];
    $scopedLayers = [];

    foreach ($compiledLayers as $compiledCss) {
        $scopedLayers[] = myronDesignSystemsScopePreviewCss($compiledCss);
    }

    return trim(implode("\n\n", array_filter($scopedLayers)));
}

function myronDesignSystemsScopePreviewCss(string $css): string
{
    return str_replace(
        [
            ':root[data-appearance="dark"]',
            ':root[data-appearance="light"]',
            ':root:not([data-appearance="light"])',
            ':root',
        ],
        [
            '.mc-design-system-preview-frame[data-appearance="dark"]',
            '.mc-design-system-preview-frame[data-appearance="light"]',
            '.mc-design-system-preview-frame:not([data-appearance="light"])',
            '.mc-design-system-preview-frame',
        ],
        $css
    );
}

function myronDesignSystemsInertPreviewMarkup(string $html): string
{
    $html = (string) preg_replace('/\saction="[^"]*"/i', ' action="#"', $html);
    $html = (string) preg_replace('/\shref="[^"]*"/i', ' href="#"', $html);

    return $html;
}

function myronDesignSystemsTokenPatchStatusMessage(): string
{
    myronTokenPatchRepository()->compileRuntimeOverrides();
    $patches = myronTokenPatchRepository()->listPatchesByToken();
    if ($patches === []) {
        return '';
    }

    $registry = new DesignSystemRegistry();
    $current = $registry->currentDefinition();
    $definition = StyleDefinitionRuntime::loadJson((string) ($current['path'] ?? ''));
    $tokenMap = StyleDefinitionRuntime::loadTokenMap();
    $compiled = StyleDefinitionRuntime::compileDefinition($definition, $tokenMap)
        . "\n" . StyleDefinitionRuntime::compileFontRolesDefinition($definition);
    $validTokens = array_keys(StyleDefinitionRuntime::parseCssVariables($compiled));
    $orphans = myronTokenPatchRepository()->orphanPatches($validTokens);

    return ' Preserved ' . count($patches) . ' token override patch(es).'
        . ($orphans !== [] ? ' ' . count($orphans) . ' patch(es) no longer map to the active token vocabulary.' : '');
}

/**
 * @return array<string, mixed>
 */
function myronDesignSystemsPreviewPage(): array
{
    $sections = [
        ['componentId' => 'hero-with-cta', 'variant' => 'layout-centered', 'sectionKey' => 'design-preview-hero', '_previewMode' => true],
        ['componentId' => 'cta-band', 'variant' => 'layout-centered', 'sectionKey' => 'design-preview-cta', '_previewMode' => true],
        ['componentId' => 'card', 'variant' => 'default', 'sectionKey' => 'design-preview-card', '_previewMode' => true],
    ];

    $sectionContent = [];
    foreach ($sections as $index => $section) {
        $sectionContent[myronSectionInstanceKey($section, $index)] = match ((string) $section['componentId']) {
            'hero-with-cta' => [
                'headline' => 'A focused system for modern publishing',
                'body' => 'A compact preview of type, rhythm, color, and action states.',
                'ctaLabel' => 'Start here',
                'ctaHref' => '#',
            ],
            'cta-band' => [
                'headline' => 'Make the primary action unmistakable',
                'body' => 'Accent color and foreground contrast carry the conversion moment.',
                'ctaLabel' => 'Apply direction',
                'ctaHref' => '#',
            ],
            default => [
                'headline' => 'Surface and structure',
                'body' => 'Cards reveal background contrast, border strength, radius, shadow, and readable supporting text.',
            ],
        };
    }

    return [
        'template_key' => 'design-system-preview',
        'title' => 'Design System Preview',
        'version_title' => 'Design System Preview',
        'source_template_id' => 'template.design-system-preview.v1',
        'source_bundle_id' => 'site-type.preview',
        'preview_mode' => true,
        'content' => [
            'headline' => 'Design System Preview',
            'intro' => 'Preview the active design system.',
            'body' => '',
            'sections' => $sectionContent,
        ],
        'template_schema' => [
            'sourceTemplateId' => 'template.design-system-preview.v1',
            'sourceBundleId' => 'site-type.preview',
            'chrome' => [
                'header' => ['inherit' => 'global', 'variant' => 'preview'],
                'footer' => ['inherit' => 'none', 'variant' => 'hidden'],
            ],
            'headerCapabilities' => [],
            'bridge' => [
                'normalizedBodySections' => true,
                'legacyChromeSectionCount' => 0,
                'bodySectionCount' => count($sections),
            ],
            'sections' => $sections,
        ],
    ];
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $action = (string) ($_POST['action'] ?? '');

    // APO-205-011 Fix B — admin POST handlers route through the canonical
    // apply service so onboarding_state.applied_design_system_id stays in sync
    // (the same write that the MCP action layer triggers). Closes the gap
    // where post-wizard admin applies left applied_design_system_id stale.
    $definitionsService = myronDefinitionsActionService();
    $adminCallerCtx = myronActionCallerContextForUser($currentUser);

    try {
        if ($action === 'apply-stored') {
            $record = $definitionsService->applyStored((string) ($_POST['definition_id'] ?? ''), $adminCallerCtx);
            myronDesignSystemsRedirect('success', 'Applied design system `' . (string) $record['name'] . '`.' . myronDesignSystemsTokenPatchStatusMessage());
        }

        if ($action === 'apply-definition') {
            $record = $definitionsService->applyDefinition((string) ($_POST['definition_id'] ?? ''), $adminCallerCtx);
            myronDesignSystemsRedirect('success', 'Applied design system `' . (string) $record['name'] . '`.' . myronDesignSystemsTokenPatchStatusMessage());
        }

        if ($action === 'reset-baseline') {
            $record = $definitionsService->resetBaseline($adminCallerCtx);
            myronDesignSystemsRedirect('success', 'Reset to baseline `' . (string) $record['name'] . '`.' . myronDesignSystemsTokenPatchStatusMessage());
        }

        if ($action === 'remove-stored') {
            $result = $definitionsService->removeStored((string) ($_POST['definition_id'] ?? ''), $adminCallerCtx);
            $message = 'Removed design system `' . (string) $result['name'] . '`.';
            if (($result['removedActive'] ?? false) === true) {
                $message .= ' The app was safely reset to baseline `' . (string) ($result['fallbackName'] ?? 'MyronCMS Default') . '`.';
            }
            myronDesignSystemsRedirect('success', $message);
        }

        if ($action === 'remove-system-archetype') {
            $result = $definitionsService->removeSystemArchetype((string) ($_POST['definition_id'] ?? ''), $adminCallerCtx);
            $message = 'Removed system archetype `' . (string) $result['name'] . '` from the loaded list.';
            if (($result['removedActive'] ?? false) === true) {
                $message .= ' The app was safely reset to baseline `' . (string) ($result['fallbackName'] ?? 'MyronCMS Default') . '`.';
            }
            myronDesignSystemsRedirect('success', $message);
        }

        if ($action === 'import-definition') {
            $upload = $_FILES['design_system_file'] ?? null;
            if (!is_array($upload) || (int) ($upload['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
                throw new RuntimeException('A valid JSONM file is required for import.');
            }

            $record = $registry->importDefinitionFile(
                (string) $upload['tmp_name'],
                is_string($_POST['import_name'] ?? null) ? (string) $_POST['import_name'] : null,
                isset($_POST['apply_immediately']) && $_POST['apply_immediately'] === '1'
            );

            $verb = (isset($_POST['apply_immediately']) && $_POST['apply_immediately'] === '1') ? 'Imported and applied' : 'Imported';
            myronDesignSystemsRedirect('success', $verb . ' design system `' . (string) $record['name'] . '`.');
        }

        throw new RuntimeException('Unknown action.');
    } catch (Throwable $e) {
        myronDesignSystemsRedirect('error', $e->getMessage());
    }
}

$current = $registry->currentDefinition();
$baseline = $registry->baselineRecord();
$archetypes = $registry->listPackagedArchetypes();
$definitions = $registry->listDefinitions();
$activeId = (string) ($current['id'] ?? '');
$baselineId = (string) ($baseline['id'] ?? '');
$previewRequestedId = trim((string) ($_GET['preview_definition_id'] ?? ''));
$previewRecord = $previewRequestedId !== '' ? $registry->findSelectableDefinition($previewRequestedId) : null;
if ($previewRecord === null) {
    $previewRecord = $current;
}
$tokenMap = StyleDefinitionRuntime::loadTokenMap();
$previewDefinition = StyleDefinitionRuntime::loadJson((string) $previewRecord['path']);
$previewModeCss = myronDesignSystemsPreviewCss($previewDefinition, $tokenMap);
$previewDefaultMode = StyleDefinitionRuntime::resolveDefaultMode($previewDefinition);
$previewHeaderHtml = myronDesignSystemsInertPreviewMarkup(myronPublicNavigationRenderer()->renderHeader(
    'Myron',
    '',
    [
        ['label' => 'Work', 'path' => '/work'],
        ['label' => 'About', 'path' => '/about'],
    ],
    '/',
    ['appearance_mode_policy' => 'light', 'density' => 'compact', 'surface_treatment' => 'bordered']
));
$previewPageHtml = myronDesignSystemsInertPreviewMarkup(myronDefinitionTemplateRenderer()->renderPublishedPage(myronDesignSystemsPreviewPage(), '', []));

$designSystemRows = array_merge($archetypes, $definitions);
usort(
    $designSystemRows,
    static fn (array $left, array $right): int => strcasecmp((string) ($left['name'] ?? ''), (string) ($right['name'] ?? ''))
);
$designSystemRows = array_merge([$baseline], $designSystemRows);

myronRenderAdminShellStart($currentUser, [
    'title' => 'Design System',
    'titleContext' => 'Design System',
    'activeItem' => 'design-system',
    'definitionFontUrls' => [StyleDefinitionRuntime::definitionGoogleFontsCss2Url($previewDefinition)],
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Design', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Design Studio', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Design Systems'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Design System</h1>
  </div>
  <p class="mc-workspace__subtitle">Library management for available design system archetypes and custom JSONM definitions. Apply, import, preview, or remove design systems here. To save the current token state or export a JSONM file, use Token Designer.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main" id="top">
    <section class="sg-section" id="loaded-design-systems">
      <h2 class="sg-section__title">Loaded Archetypes</h2>
      <p class="sg-section__subtitle">Canonical system archetypes and custom JSONM definitions available for the current site.</p>

      <div class="mc-page-grid mc-page-grid--design-systems" role="table" aria-label="Loaded design systems" data-mc-sortable-grid>
        <div class="mc-page-grid__row mc-page-grid__row--head" role="row">
          <span role="columnheader" data-mc-sort-key="name"><button class="mc-page-grid__sort" type="button">Archetype Name</button></span>
          <span role="columnheader" data-mc-sort-key="description"><button class="mc-page-grid__sort" type="button">Description</button></span>
          <span role="columnheader" data-mc-sort-key="system"><button class="mc-page-grid__sort" type="button">System</button></span>
          <span role="columnheader">Actions</span>
        </div>
        <?php foreach ($designSystemRows as $row): ?>
        <?php
          $rowId = (string) ($row['id'] ?? '');
          $rowSource = (string) ($row['source'] ?? '');
          $isCustom = $rowSource === 'stored';
          $isBaseline = $rowId === $baselineId;
          $isRemovableSystem = $rowSource === 'archetype';
          $isActive = $rowId !== '' && $rowId === $activeId;
          $systemLabel = $isCustom ? '[CUSTOM]' : '[SYSTEM]';
          $applyAction = $isCustom ? 'apply-stored' : 'apply-definition';
        ?>
        <div
          class="mc-page-grid__row<?= $isActive ? ' mc-page-grid__row--active' : '' ?>"
          role="row"
          data-sort-name="<?= myronDesignSystemsEscape((string) ($row['name'] ?? '')) ?>"
          data-sort-description="<?= myronDesignSystemsEscape((string) ($row['description'] ?? '')) ?>"
          data-sort-system="<?= myronDesignSystemsEscape($systemLabel) ?>"
        >
          <span class="mc-page-grid__cell mc-page-grid__cell--name" role="cell">
            <span class="mc-page-grid__name"><?= myronDesignSystemsEscape((string) ($row['name'] ?? '')) ?></span>
            <br>
            <a
              class="sg-link"
              href="<?= myronDesignSystemsEscape(myronBuildAdminUrl('design.systems', ['design_preview' => '1', 'preview_definition_id' => $rowId])) ?>"
            >Preview</a>
          </span>
          <span class="mc-page-grid__cell" role="cell"><?= myronDesignSystemsEscape((string) ($row['description'] ?? '')) ?></span>
          <span class="mc-page-grid__cell" role="cell"><span class="sg-pill"><?= myronDesignSystemsEscape($systemLabel) ?></span></span>
          <span class="mc-page-grid__cell mc-page-grid__cell--actions" role="cell">
            <?php if ($isActive): ?>
            <span class="sg-pill sg-pill--active">active</span>
            <?php else: ?>
            <form method="post" class="sg-inline-form" data-design-preview-preserve data-design-system-confirm="Apply this design system?">
              <input type="hidden" name="action" value="<?= myronDesignSystemsEscape($applyAction) ?>">
              <input type="hidden" name="definition_id" value="<?= myronDesignSystemsEscape($rowId) ?>">
              <input type="hidden" name="preview_open" value="0" data-design-preview-open-field>
              <button class="sg-button sg-button--primary" type="submit">Apply</button>
            </form>
            <?php endif; ?>
            <?php if ($isCustom): ?>
            <form method="post" class="sg-inline-form" data-design-system-confirm="Remove this custom design system?">
              <input type="hidden" name="action" value="remove-stored">
              <input type="hidden" name="definition_id" value="<?= myronDesignSystemsEscape($rowId) ?>">
              <button class="sg-button sg-button--danger" type="submit">Remove</button>
            </form>
            <?php elseif ($isRemovableSystem && !$isBaseline): ?>
            <form method="post" class="sg-inline-form" data-design-system-confirm="Remove this system archetype from the loaded list?">
              <input type="hidden" name="action" value="remove-system-archetype">
              <input type="hidden" name="definition_id" value="<?= myronDesignSystemsEscape($rowId) ?>">
              <button class="sg-button sg-button--danger" type="submit">Remove</button>
            </form>
            <?php endif; ?>
          </span>
        </div>
        <?php endforeach; ?>
      </div>
    </section>

    <section class="sg-section" id="import-definition">
      <h2 class="sg-section__title">Import Design System</h2>
      <p class="sg-section__subtitle">Upload a JSONM design system, validate it against the canonical day-1 corpus, and optionally apply it immediately.</p>

      <form method="post" enctype="multipart/form-data" class="sg-form-grid" data-design-system-confirm="Import this design system JSONM file?">
        <input type="hidden" name="action" value="import-definition">

        <label class="sg-field sg-field--full">
          <span class="sg-field__label">JSONM File</span>
          <input class="sg-field__control" type="file" name="design_system_file" accept=".json,.jsonm,application/json" required>
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Override Name</span>
          <input class="sg-field__control" type="text" name="import_name" placeholder="Optional display name">
        </label>

        <label class="sg-field sg-field--checkbox">
          <span class="sg-field__label">Apply Immediately</span>
          <span class="sg-field__checkbox">
            <input type="checkbox" name="apply_immediately" value="1">
            <span>Apply the imported design system after validation.</span>
          </span>
        </label>

        <div class="sg-card__actions">
          <button class="sg-button sg-button--primary" type="submit">Import Design System</button>
        </div>
      </form>
    </section>
  </div>
</div>
<button type="button" hidden data-mc-sidesheet-open="design-system-preview-sheet" data-design-system-preview-open>Open Preview</button>
<div class="myron-dialog-backdrop" hidden aria-hidden="true" data-design-system-confirm-backdrop></div>
<div class="myron-dialog myron-dialog--confirmation" id="design-system-confirm-dialog" role="dialog" aria-modal="true" aria-hidden="true" hidden tabindex="-1" data-design-system-confirm-dialog>
  <div class="myron-dialog__header">
    <div>
      <h3 class="myron-heading" data-level="4" data-design-system-confirm-title>Confirm change?</h3>
      <p class="myron-paragraph myron-paragraph--muted">This action updates the active Design System state.</p>
    </div>
    <button class="myron-dialog__close" type="button" aria-label="Close design system confirmation" data-design-system-confirm-close>&times;</button>
  </div>
  <div class="myron-dialog__body">
    <p class="myron-paragraph" data-design-system-confirm-message>Confirm this design system change.</p>
  </div>
  <div class="myron-dialog__actions">
    <button class="myron-button myron-button--intent-neutral myron-button--appearance-outline myron-button--size-md" type="button" data-design-system-confirm-close>Cancel</button>
    <button class="myron-button myron-button--intent-primary myron-button--appearance-solid myron-button--size-md" type="button" data-design-system-confirm-submit>Confirm</button>
  </div>
</div>
<?php ob_start(); ?>
<div class="mc-design-system-preview" data-design-system-preview>
  <?php if ($previewModeCss !== ''): ?>
  <style data-design-system-preview-tokens>
<?= $previewModeCss . "\n" ?>
  </style>
  <?php endif; ?>
  <div class="mc-design-system-preview__toolbar">
    <span class="sg-pill"><?= myronDesignSystemsEscape((string) ($previewRecord['name'] ?? 'Preview')) ?></span>
    <div class="mc-design-system-preview__modes" role="group" aria-label="Preview appearance mode">
      <button class="sg-button sg-button--secondary" type="button" data-design-preview-mode="light" aria-pressed="<?= $previewDefaultMode === 'light' ? 'true' : 'false' ?>">Light</button>
      <button class="sg-button sg-button--secondary" type="button" data-design-preview-mode="dark" aria-pressed="<?= $previewDefaultMode === 'dark' ? 'true' : 'false' ?>">Dark</button>
    </div>
  </div>
  <div
    class="mc-design-system-preview-frame"
    data-design-system-preview-frame
    data-appearance="<?= myronDesignSystemsEscape($previewDefaultMode) ?>"
    data-appearance-default="<?= myronDesignSystemsEscape($previewDefaultMode) ?>"
  >
    <?= $previewHeaderHtml . "\n" ?>
    <main class="mc-design-system-preview-frame__canvas">
      <?= $previewPageHtml . "\n" ?>
    </main>
  </div>
</div>
<?php $previewSheetBody = (string) ob_get_clean(); ?>
<?php myronRenderAdminSidesheet('design-system-preview-sheet', 'Design System Preview', $previewSheetBody, [
    'description' => 'Mobile-width preview of the active design system.',
    'size' => 'sm',
]); ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
  var root = document.querySelector('[data-design-system-preview]');
  var sheet = document.getElementById('design-system-preview-sheet');
  if (root) {
    var frame = root.querySelector('[data-design-system-preview-frame]');
    var buttons = Array.prototype.slice.call(root.querySelectorAll('[data-design-preview-mode]'));
    var setMode = function (mode) {
      if (!frame || (mode !== 'light' && mode !== 'dark')) return;
      frame.setAttribute('data-appearance', mode);
      buttons.forEach(function (button) {
        var active = button.getAttribute('data-design-preview-mode') === mode;
        button.setAttribute('aria-pressed', active ? 'true' : 'false');
        button.classList.toggle('sg-button--primary', active);
        button.classList.toggle('sg-button--secondary', !active);
      });
    };
    buttons.forEach(function (button) {
      button.addEventListener('click', function () {
        setMode(button.getAttribute('data-design-preview-mode') || '');
      });
    });
    setMode(frame ? frame.getAttribute('data-appearance-default') || 'light' : 'light');
    if (frame) {
      frame.addEventListener('click', function (event) {
        if (event.target && event.target.closest('a[href], button')) {
          event.preventDefault();
        }
      });
      frame.addEventListener('submit', function (event) {
        event.preventDefault();
      });
    }
  }
  document.querySelectorAll('[data-design-preview-preserve]').forEach(function (form) {
    form.addEventListener('submit', function () {
      var field = form.querySelector('[data-design-preview-open-field]');
      if (!field || !sheet) return;
      field.value = sheet.getAttribute('aria-hidden') === 'false' ? '1' : '0';
    });
  });
  var previewParams = new URLSearchParams(window.location.search);
  if (previewParams.get('design_preview') === '1') {
    previewParams.delete('design_preview');
    if (window.history && window.history.replaceState) {
      var nextQuery = previewParams.toString();
      var nextUrl = window.location.pathname + (nextQuery ? '?' + nextQuery : '') + window.location.hash;
      window.history.replaceState(null, document.title, nextUrl);
    }
    var trigger = document.querySelector('[data-design-system-preview-open]');
    if (trigger) {
      window.setTimeout(function () {
        trigger.click();
      }, 0);
    }
  }

  var confirmDialog = document.querySelector('[data-design-system-confirm-dialog]');
  var confirmBackdrop = document.querySelector('[data-design-system-confirm-backdrop]');
  var confirmTitle = document.querySelector('[data-design-system-confirm-title]');
  var confirmMessage = document.querySelector('[data-design-system-confirm-message]');
  var confirmSubmit = document.querySelector('[data-design-system-confirm-submit]');
  var pendingForm = null;
  var closeConfirm = function () {
    pendingForm = null;
    if (confirmDialog) {
      confirmDialog.hidden = true;
      confirmDialog.setAttribute('aria-hidden', 'true');
    }
    if (confirmBackdrop) {
      confirmBackdrop.hidden = true;
      confirmBackdrop.setAttribute('aria-hidden', 'true');
    }
  };
  var openConfirm = function (form, message) {
    pendingForm = form;
    if (!confirmDialog || !confirmBackdrop) {
      form.setAttribute('data-design-system-confirmed', '1');
      form.requestSubmit();
      return;
    }
    if (confirmTitle) confirmTitle.textContent = 'Confirm change?';
    if (confirmMessage) confirmMessage.textContent = message || 'Confirm this design system change.';
    confirmBackdrop.hidden = false;
    confirmBackdrop.setAttribute('aria-hidden', 'false');
    confirmDialog.hidden = false;
    confirmDialog.setAttribute('aria-hidden', 'false');
    confirmDialog.focus();
  };
  document.querySelectorAll('[data-design-system-confirm]').forEach(function (form) {
    form.addEventListener('submit', function (event) {
      if (form.getAttribute('data-design-system-confirmed') === '1') {
        form.removeAttribute('data-design-system-confirmed');
        return;
      }
      event.preventDefault();
      openConfirm(form, form.getAttribute('data-design-system-confirm') || '');
    });
  });
  document.querySelectorAll('[data-design-system-confirm-close]').forEach(function (button) {
    button.addEventListener('click', function (event) {
      event.preventDefault();
      closeConfirm();
    });
  });
  if (confirmBackdrop) {
    confirmBackdrop.addEventListener('click', closeConfirm);
  }
  if (confirmDialog) {
    confirmDialog.addEventListener('keydown', function (event) {
      if (event.key === 'Escape') {
        event.preventDefault();
        closeConfirm();
      }
    });
  }
  if (confirmSubmit) {
    confirmSubmit.addEventListener('click', function (event) {
      event.preventDefault();
      if (!pendingForm) return;
      var form = pendingForm;
      form.setAttribute('data-design-system-confirmed', '1');
      closeConfirm();
      form.requestSubmit();
    });
  }
});
</script>
<?php myronRenderAdminShellEnd(); ?>
