<?php

declare(strict_types=1);

require_once dirname(__DIR__, 3) . '/system/bootstrap.php';
require_once dirname(__DIR__) . '/shared/section-content-field-controls.php';

$currentUser = myronRequireContentAccess(true);
$repository = myronContentRepository();
$qualityReportService = myronQualityReportService();
$csrfToken = myronCsrfToken();
$pageId = trim((string) ($_GET['page'] ?? ''));
$templateSourceId = trim((string) ($_GET['template_source'] ?? ''));
$returnTo = trim((string) ($_GET['return_to'] ?? ''));
$returnTemplateId = trim((string) ($_GET['return_template'] ?? ''));
$sectionsForContentPayload = static function (string $pageId, string $templateSourceId, string $templateId = '') use ($repository): array {
    if ($pageId !== '') {
        $page = $repository->getEditablePage($pageId);
        $schema = is_array($page['template_schema'] ?? null) ? $page['template_schema'] : [];
        return array_values(array_filter(
            is_array($schema['sections'] ?? null) ? $schema['sections'] : [],
            static fn (mixed $section): bool => is_array($section)
        ));
    }

    if ($templateSourceId !== '') {
        $definition = myronTemplateDefinitionRepository()->findTemplateById($templateSourceId);
        return is_array($definition) ? MyronTemplateDefinitionRepository::bodySectionsForRecord($definition) : [];
    }

    if ($templateId !== '') {
        foreach ($repository->listTemplates() as $template) {
            if ((string) ($template['id'] ?? '') === $templateId) {
                $schema = is_array($template['schema'] ?? null) ? $template['schema'] : [];
                return array_values(array_filter(
                    is_array($schema['sections'] ?? null) ? $schema['sections'] : [],
                    static fn (mixed $section): bool => is_array($section)
                ));
            }
        }
    }

    return [];
};
$siteTypeForTemplateId = static function (string $templateId): string {
    $normalized = trim($templateId);
    if ($normalized === '') {
        return '';
    }

    $parts = explode('.', $normalized);
    if (($parts[0] ?? '') === 'template') {
        array_shift($parts);
    }

    if ($parts !== [] && preg_match('/^v[0-9]+$/', (string) end($parts)) === 1) {
        array_pop($parts);
    }

    return $parts !== [] ? (string) end($parts) : '';
};
$resolvePageEditorTemplate = static function (
    string $submittedTemplateId,
    string $submittedSourceTemplateId,
    bool $instantiateMissingSource
) use ($repository): array {
    $templateId = trim($submittedTemplateId);
    $sourceTemplateId = trim($submittedSourceTemplateId);

    foreach ($repository->listTemplates() as $template) {
        if ((string) ($template['id'] ?? '') === $templateId) {
            return [
                'template' => $template,
                'definition' => null,
                'source_template_id' => trim((string) ($template['source_template_id'] ?? '')),
                'source_bundle_id' => trim((string) ($template['source_bundle_id'] ?? '')),
            ];
        }
    }

    if ($sourceTemplateId === '' && str_starts_with($templateId, 'template.')) {
        $sourceTemplateId = $templateId;
    }

    if ($sourceTemplateId !== '') {
        $runtimeTemplate = $repository->findRuntimeTemplateBySourceTemplateId($sourceTemplateId);
        if (is_array($runtimeTemplate)) {
            return [
                'template' => $runtimeTemplate,
                'definition' => null,
                'source_template_id' => trim((string) ($runtimeTemplate['source_template_id'] ?? $sourceTemplateId)),
                'source_bundle_id' => trim((string) ($runtimeTemplate['source_bundle_id'] ?? '')),
            ];
        }

        if ($instantiateMissingSource) {
            $templateDefinition = myronTemplateDefinitionRepository()->findTemplateById($sourceTemplateId);
            if (!is_array($templateDefinition)) {
                throw new InvalidArgumentException('Selected source template is unavailable.');
            }

            myronTemplateInstantiationService()->instantiateTemplate($templateDefinition);
            $runtimeTemplate = $repository->findRuntimeTemplateBySourceTemplateId($sourceTemplateId);
            if (!is_array($runtimeTemplate)) {
                throw new RuntimeException('Selected template could not be resolved. Choose a template and try again.');
            }
            return [
                'template' => $runtimeTemplate,
                'definition' => $templateDefinition,
                'source_template_id' => trim((string) ($templateDefinition['id'] ?? $sourceTemplateId)),
                'source_bundle_id' => trim((string) ($templateDefinition['bundleId'] ?? ($runtimeTemplate['source_bundle_id'] ?? ''))),
            ];
        }
    }

    throw new InvalidArgumentException('Selected template could not be resolved. Choose a template and try again.');
};
$seoOverridesFromPost = static function (array $post): array {
    return [
        'canonical_override' => trim((string) ($post['canonical_override'] ?? '')),
        'robots_override' => trim((string) ($post['robots_override'] ?? '')),
        'og_title' => trim((string) ($post['og_title'] ?? '')),
        'og_description' => trim((string) ($post['og_description'] ?? '')),
        'og_image' => trim((string) ($post['og_image'] ?? '')),
        'twitter_title' => trim((string) ($post['twitter_title'] ?? '')),
        'twitter_description' => trim((string) ($post['twitter_description'] ?? '')),
        'twitter_image' => trim((string) ($post['twitter_image'] ?? '')),
        'jsonld_mode' => trim((string) ($post['jsonld_mode'] ?? 'auto')),
        'jsonld_type' => trim((string) ($post['jsonld_type'] ?? 'Article')),
        'jsonld_custom' => trim((string) ($post['jsonld_custom'] ?? '')),
        'indexable_override' => trim((string) ($post['indexable_override'] ?? 'default')),
    ];
};

$normalizeBlogCommentsOverride = static function (mixed $value): string {
    $normalized = strtolower(trim((string) $value));
    return in_array($normalized, ['enabled', 'disabled'], true) ? $normalized : 'default';
};

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $postedTemplateSourceId = trim((string) ($_POST['template_source'] ?? ''));
    $postedReturnTo = trim((string) ($_POST['return_to'] ?? ''));
    $postedReturnTemplateId = trim((string) ($_POST['return_template'] ?? ''));
    $postedBlogCategoryIds = is_array($_POST['blog_category_ids'] ?? null)
        ? array_values(array_map('strval', $_POST['blog_category_ids']))
        : [];

    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);

        $action = trim((string) ($_POST['action'] ?? ''));
        $postedPageId = trim((string) ($_POST['page_id'] ?? ''));
        $publishNow = $action === 'publish-page';
        $publishedAt = $publishNow ? myronNormalizePublishedAtInput($_POST['published_at'] ?? null) : null;
        $postedIncludeInNav = isset($_POST['include_in_nav']) && (string) $_POST['include_in_nav'] === '1';

        if ($action === 'save-draft' || $action === 'publish-page') {
            $submittedTemplateId = trim((string) ($_POST['template_id'] ?? ''));
            if ($postedPageId !== '' && $submittedTemplateId === '') {
                $postedPage = $repository->getEditablePage($postedPageId);
                if (is_array($postedPage)) {
                    $submittedTemplateId = trim((string) ($postedPage['template_id'] ?? ''));
                }
            }

            $resolvedTemplate = $resolvePageEditorTemplate(
                $submittedTemplateId,
                $postedTemplateSourceId,
                $postedPageId === ''
            );
            $runtimeTemplate = is_array($resolvedTemplate['template'] ?? null) ? $resolvedTemplate['template'] : [];
            $templateDefinition = is_array($resolvedTemplate['definition'] ?? null) ? $resolvedTemplate['definition'] : null;
            $effectiveTemplateId = trim((string) ($runtimeTemplate['id'] ?? ''));
            if ($effectiveTemplateId === '') {
                throw new InvalidArgumentException('Selected template could not be resolved. Choose a template and try again.');
            }
            $savedTemplateClass = trim((string) ($runtimeTemplate['template_class'] ?? ''));

            if ($postedPageId !== '') {
                $contentSections = $sectionsForContentPayload($postedPageId, '', $effectiveTemplateId);
            } elseif (is_array($templateDefinition)) {
                $contentSections = MyronTemplateDefinitionRepository::bodySectionsForRecord($templateDefinition);
            } else {
                $schema = is_array($runtimeTemplate['schema'] ?? null) ? $runtimeTemplate['schema'] : [];
                $contentSections = array_values(array_filter(
                    is_array($schema['sections'] ?? null) ? $schema['sections'] : [],
                    static fn (mixed $section): bool => is_array($section)
                ));
            }
            $existingPage = $postedPageId !== '' ? $repository->getEditablePage($postedPageId) : null;
            $existingContent = is_array($existingPage['content'] ?? null) ? $existingPage['content'] : null;
            $pageContent = myronContentPayloadFromInput($_POST, $contentSections, $existingContent);
            if ($savedTemplateClass === 'post-single') {
                $pageContent['blog_comments_enabled_override'] = $normalizeBlogCommentsOverride($_POST['blog_comments_enabled_override'] ?? 'default');
            } else {
                unset($pageContent['blog_comments_enabled_override']);
            }

            if ($postedPageId === '') {
                $createdSourceTemplateId = '';
                $createdSourceBundleId = '';
                $resolvedSourceTemplateId = trim((string) ($resolvedTemplate['source_template_id'] ?? ''));
                if (
                    $postedTemplateSourceId !== ''
                    && $resolvedSourceTemplateId !== ''
                    && !str_ends_with($savedTemplateClass, '-single')
                    && $repository->findPageBySourceTemplateId($resolvedSourceTemplateId) === null
                ) {
                    $createdSourceTemplateId = $resolvedSourceTemplateId;
                    $createdSourceBundleId = trim((string) ($resolvedTemplate['source_bundle_id'] ?? ''));
                }

                $postedPageId = $repository->createPage(
                    $effectiveTemplateId,
                    trim((string) ($_POST['page_name'] ?? '')),
                    trim((string) ($_POST['slug'] ?? '')),
                    is_string($_POST['parent_page_id'] ?? null) ? (string) $_POST['parent_page_id'] : null,
                    trim((string) ($_POST['seo_title'] ?? '')),
                    trim((string) ($_POST['meta_description'] ?? '')),
                    $pageContent,
                    $publishNow,
                    $publishedAt,
                    $createdSourceTemplateId,
                    $createdSourceBundleId,
                    $seoOverridesFromPost($_POST),
                    $postedIncludeInNav
                );
            } else {
                $repository->savePage(
                    $postedPageId,
                    $effectiveTemplateId,
                    trim((string) ($_POST['page_name'] ?? '')),
                    trim((string) ($_POST['slug'] ?? '')),
                    is_string($_POST['parent_page_id'] ?? null) ? (string) $_POST['parent_page_id'] : null,
                    trim((string) ($_POST['seo_title'] ?? '')),
                    trim((string) ($_POST['meta_description'] ?? '')),
                    $pageContent,
                    $publishNow,
                    $publishedAt,
                    $seoOverridesFromPost($_POST)
                );
                $repository->setPageIncludeInNav($postedPageId, $postedIncludeInNav);
            }

            $repository->replacePageCategoryAssignments(
                $postedPageId,
                $savedTemplateClass === 'post-single' ? $postedBlogCategoryIds : []
            );

            if (myronUserCanAccessAdministration($currentUser)) {
                $assignments = [];
                $menuEnabled = $_POST['menu_enabled'] ?? [];
                $menuLabels = $_POST['menu_label'] ?? [];
                foreach ($repository->listMenusWithItems() as $menu) {
                    $menuId = (string) $menu['id'];
                    $assignments[$menuId] = [
                        'enabled' => isset($menuEnabled[$menuId]) && (string) $menuEnabled[$menuId] === '1',
                        'label' => is_array($menuLabels) ? (string) ($menuLabels[$menuId] ?? '') : '',
                    ];
                }
                $repository->syncPageMenuAssignments($postedPageId, $assignments);
            }

            $messageText = $publishNow ? 'Page saved and published.' : 'Draft saved successfully.';
            $ogValidation = myronOgImageValidator()->validateDimensions((string) ($_POST['og_image'] ?? ''));
            if (trim((string) ($ogValidation['message'] ?? '')) !== '') {
                $messageText .= ' ' . (string) $ogValidation['message'];
            }
            myronRedirectWithFlash(
                myronBuildAdminUrl('content.pageEditor', ['page' => $postedPageId]),
                $messageText,
                'success'
            );
        }

        if ($action === 'delete-page') {
            $deleted = $repository->deletePage($postedPageId);
            myronRedirectWithFlash(
                myronBuildAdminUrl('content.pages'),
                'Deleted page "' . (string) ($deleted['title'] ?? '') . '".',
                'success'
            );
        }

        throw new RuntimeException('Unknown page editor action.');
    } catch (Throwable $exception) {
        $query = [];
        if ($postedPageId !== '') {
            $query['page'] = $postedPageId;
        } else {
            $query['mode'] = 'create';
            if ($postedTemplateSourceId !== '') {
                $query['template_source'] = $postedTemplateSourceId;
            }
            if ($postedReturnTo !== '') {
                $query['return_to'] = $postedReturnTo;
            }
            if ($postedReturnTemplateId !== '') {
                $query['return_template'] = $postedReturnTemplateId;
            }
        }
        myronRedirectWithFlash(myronBuildAdminUrl('content.pageEditor', $query), $exception->getMessage(), 'error');
    }
}

$templateStartedDefinition = null;
$templateStartedRuntimeTemplate = null;
if ($pageId === '' && $templateSourceId !== '') {
    $templateStartedDefinition = myronTemplateDefinitionRepository()->findTemplateById($templateSourceId);
    if (is_array($templateStartedDefinition)) {
        $templateStartedRuntimeTemplate = $repository->findRuntimeTemplateBySourceTemplateId($templateSourceId);
    }
}

$selectedPage = $pageId !== '' ? $repository->getEditablePage($pageId) : null;
$allRuntimeTemplates = $repository->listTemplates();
$templates = $selectedPage !== null
    ? $allRuntimeTemplates
    : $repository->listAvailablePageTemplates();
$templatesById = [];
foreach ($templates as $template) {
    $templatesById[(string) ($template['id'] ?? '')] = $template;
}
$availableImageFiles = array_values(array_filter(
    myronFileRepository()->listFiles(),
    static fn (array $file): bool => (bool) ($file['is_image'] ?? false)
));
$pageOptions = $repository->listPageOptions($selectedPage !== null ? (string) $selectedPage['id'] : null);
$pageCategories = $repository->listPageCategories(true);
$selectedPageCategoryIds = $selectedPage !== null
    ? array_fill_keys($repository->listCategoryIdsForPage((string) $selectedPage['id']), true)
    : [];
$menus = myronUserCanAccessAdministration($currentUser) ? $repository->listMenusWithItems() : [];
$menuAssignments = $selectedPage['menu_assignments'] ?? array_map(
    static fn (array $menu): array => [
        'menu_id' => (string) $menu['id'],
        'menu_name' => (string) $menu['name'],
        'placement' => (string) ($menu['placement_label'] ?? 'Unassigned'),
        'enabled' => false,
        'label' => '',
    ],
    $menus
);
$selectedPageDeletionPolicy = $selectedPage !== null ? $repository->deletionPolicy((string) $selectedPage['id']) : null;
$selectedQualityReport = $selectedPage !== null ? $qualityReportService->reportForPage((string) $selectedPage['id']) : null;
$selectedPageTemplateLocked = $selectedPage !== null && trim((string) ($selectedPage['source_template_id'] ?? '')) !== '';
$editorSurface = $selectedPage !== null
    ? myronEditorSurfaceReadModel()->pageSurface((string) $selectedPage['id'])
    : ($templateSourceId !== '' ? myronEditorSurfaceReadModel()->templateStartedPageSurface($templateSourceId) : null);
$templateStartedRuntimeTemplateId = is_array($templateStartedRuntimeTemplate) ? trim((string) ($templateStartedRuntimeTemplate['id'] ?? '')) : '';
$templateStartedWorkflow = $selectedPage === null && is_array($templateStartedDefinition);
$abandonUrl = $returnTo === 'content.templates'
    ? myronBuildAdminUrl('content.templates', $returnTemplateId !== '' ? ['template' => $returnTemplateId] : [])
    : myronBuildAdminUrl('content.pages');
$defaultTemplateId = $templateStartedWorkflow
    ? $templateStartedRuntimeTemplateId
    : ($templateStartedRuntimeTemplateId !== ''
    ? $templateStartedRuntimeTemplateId
    : (string) ($selectedPage['template_id'] ?? ($templates[0]['id'] ?? '')));
$defaultTemplateName = is_array($templateStartedRuntimeTemplate)
    ? (string) ($templateStartedRuntimeTemplate['name'] ?? ($templateStartedDefinition['name'] ?? 'Selected template'))
    : ($templateStartedWorkflow
    ? (string) ($templateStartedDefinition['name'] ?? $templateSourceId)
    : (string) ($selectedPage['template_name'] ?? 'Bundled template'));
$defaultTemplateMeta = $templatesById[$defaultTemplateId] ?? (is_array($templateStartedRuntimeTemplate) ? $templateStartedRuntimeTemplate : []);
$defaultTemplateRoleSource = trim((string) ($defaultTemplateMeta['source_template_id'] ?? ''));
if ($defaultTemplateRoleSource === '' && $templateSourceId !== '') {
    $defaultTemplateRoleSource = $templateSourceId;
}
if ($defaultTemplateRoleSource === '') {
    $defaultTemplateRoleSource = trim((string) ($defaultTemplateMeta['template_key'] ?? $defaultTemplateId));
}
$defaultTemplateClass = trim((string) ($defaultTemplateMeta['template_class'] ?? ''));
if ($defaultTemplateClass === '') {
    $defaultTemplateClass = MyronTemplateDefinitionRepository::templateClassForTemplateId($defaultTemplateRoleSource);
}
$defaultIncludeInNav = $selectedPage !== null
    ? ((int) ($selectedPage['include_in_nav'] ?? 1)) === 1
    : $defaultTemplateClass !== 'post-single';
$defaultTemplateSiteType = trim((string) ($defaultTemplateMeta['source_site_type'] ?? ''));
if ($defaultTemplateSiteType === '') {
    $defaultTemplateSiteType = $siteTypeForTemplateId($defaultTemplateRoleSource);
}
$defaultPageName = (string) ($selectedPage['title'] ?? '');
if ($defaultPageName === '' && $templateStartedWorkflow) {
    $defaultPageName = (string) (($templateStartedDefinition['pageTitle'] ?? '') ?: ($templateStartedDefinition['name'] ?? 'New Page'));
}
$selectedContent = is_array($selectedPage['content'] ?? null) ? $selectedPage['content'] : [];
$blogCommentsOverride = $normalizeBlogCommentsOverride($selectedContent['blog_comments_enabled_override'] ?? 'default');
$pageEditorCommandFormId = 'page-editor-command-form';
$seoPanelPage = is_array($selectedPage) ? $selectedPage : [
    'path' => '/',
    'title' => $defaultPageName,
    'version_title' => $defaultPageName,
    'seo_title' => '',
    'meta_description' => '',
    'content' => [],
];
$seoPanelData = myronSeoPanelService()->panelData($seoPanelPage);

$editorCanvasPage = null;
if (is_array($editorSurface)) {
    $editorSchema = is_array($editorSurface['raw']['schema'] ?? null) ? $editorSurface['raw']['schema'] : [];
    $editorSchema['chrome'] = is_array($editorSurface['chrome'] ?? null) ? $editorSurface['chrome'] : ($editorSchema['chrome'] ?? []);
    if ($selectedPage !== null) {
        $editorCanvasPage = $selectedPage;
        $editorCanvasPage['content'] = is_array($selectedPage['content'] ?? null) ? $selectedPage['content'] : [];
    } else {
        // STN-012-017: Pre-fill the canvas with the runtime template's defaultContent so the
        // operator sees the Designer-customized seed copy on first render rather than empty
        // section shells. Saved content from $_POST takes over once the page is created.
        $seedContent = is_array($editorSchema['defaultContent'] ?? null) ? $editorSchema['defaultContent'] : [];
        $editorCanvasPage = [
            'id' => '',
            'title' => $defaultPageName,
            'version_title' => $defaultPageName,
            'template_key' => '',
            'source_template_id' => (string) ($editorSurface['identity']['sourceTemplateId'] ?? ''),
            'source_bundle_id' => (string) ($editorSurface['identity']['sourceBundleId'] ?? ''),
            'content' => $seedContent,
        ];
    }
    $editorCanvasPage['template_schema'] = $editorSchema;
}

if (trim((string) ($_GET['preview'] ?? '')) === 'draft' && $selectedPage !== null) {
    $previewPage = $selectedPage;
    $previewTitle = (string) (($selectedPage['draft_title'] ?? '') ?: ($selectedPage['title'] ?? 'Draft preview'));
    $previewPage['title'] = $previewTitle;
    $previewPage['version_title'] = $previewTitle;
    $previewPage['content'] = is_array($selectedPage['content'] ?? null) ? $selectedPage['content'] : [];
    $previewPage['template_schema'] = is_array($selectedPage['template_schema'] ?? null) ? $selectedPage['template_schema'] : [];
    ?><!doctype html>
<html lang="<?= myronEscape(myronSiteLanguage()) ?>" data-myron-preview-document="page-draft">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= myronEscape(myronComposeDocumentTitle('Draft Preview')) ?></title>
  <?= myronRenderDefinitionFontHeadTags() . "\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')) ?>">
</head>
<body class="myron-site-page mc-preview-document">
  <main class="myron-site__canvas mc-preview-document__canvas" data-myron-page-draft-preview="<?= myronEscape((string) ($selectedPage['id'] ?? '')) ?>">
    <header class="mc-preview-document__header">
      <span class="mc-preview-document__eyebrow">Draft Preview</span>
      <h1 class="mc-preview-document__title"><?= myronEscape($previewTitle) ?></h1>
    </header>
    <?= myronDefinitionTemplateRenderer()->renderPublishedPage($previewPage, myronPublicBasePath(), []) . "\n" ?>
  </main>
</body>
</html><?php
    return;
}

function myronEditorValue(?array $page, string $key): string
{
    if (!is_array($page)) {
        return '';
    }

    $content = $page['content'] ?? [];
    return is_array($content) ? trim((string) ($content[$key] ?? '')) : '';
}

function myronEditorFieldValue(?array $page, string $draftKey, string $publishedKey = ''): string
{
    if (!is_array($page)) {
        return '';
    }

    $publishedField = $publishedKey !== '' ? $publishedKey : $draftKey;
    return trim((string) (($page[$draftKey] ?? '') ?: ($page[$publishedField] ?? '')));
}

myronRenderAdminShellStart($currentUser, [
    'title' => $selectedPage !== null ? 'Edit Page' : 'New Page',
    'titleContext' => 'Page Editor',
    'activeItem' => 'pages',
    'headStyles' => [myronBuildAssetUrl('admin/css/seo-panel.css')],
    'headScripts' => [myronBuildAssetUrl('admin/js/seo-panel.js')],
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Content', 'href' => myronBuildAdminUrl('content.pages')],
      ['label' => 'Pages', 'href' => myronBuildAdminUrl('content.pages')],
      ['label' => $selectedPage !== null ? 'Edit Page' : 'New Page'],
  ]); ?>
  <div class="mc-workspace__title-row mc-workspace__title-row--actions">
    <h1 class="mc-workspace__title"><?= $selectedPage !== null ? 'Edit Page' : 'New Page' ?></h1>
    <div class="mc-workspace__actions">
      <?php if ($templateStartedWorkflow): ?>
      <button class="sg-button sg-button--secondary" type="button" data-page-abandon-open>Abandon</button>
      <?php else: ?>
      <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('content.pages')) ?>">Back to Pages</a>
      <?php endif; ?>
      <?php if ($selectedPage !== null && (string) ($selectedPage['publication_state'] ?? '') === 'published'): ?>
      <a class="sg-button sg-button--primary" href="<?= myronEscape((string) $selectedPage['preview_url']) ?>" target="_blank" rel="noreferrer">View Live</a>
      <?php endif; ?>
    </div>
  </div>
  <p class="mc-workspace__subtitle">Edit page content separately from page attributes and publishing controls.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <form id="<?= myronEscape($pageEditorCommandFormId) ?>" method="post" data-page-editor-form data-page-template-started-workflow="<?= $templateStartedWorkflow ? 'true' : 'false' ?>" data-page-editor-existing-page="<?= $selectedPage !== null ? 'true' : 'false' ?>" data-page-abandon-return="<?= myronEscape($abandonUrl) ?>">
      <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
      <input type="hidden" name="page_id" value="<?= myronEscape((string) ($selectedPage['id'] ?? '')) ?>">
      <input type="hidden" name="template_source" value="<?= myronEscape($templateSourceId) ?>">
      <input type="hidden" name="return_to" value="<?= myronEscape($returnTo) ?>">
      <input type="hidden" name="return_template" value="<?= myronEscape($returnTemplateId) ?>">
      <input type="hidden" name="eyebrow" value="<?= myronEscape(myronEditorValue($selectedPage, 'eyebrow')) ?>">
      <input type="hidden" name="headline" value="<?= myronEscape(myronEditorValue($selectedPage, 'headline')) ?>">
      <input type="hidden" name="intro" value="<?= myronEscape(myronEditorValue($selectedPage, 'intro')) ?>">
      <input type="hidden" name="body" value="<?= myronEscape(myronEditorValue($selectedPage, 'body')) ?>">
      <input type="hidden" name="cta_label" value="<?= myronEscape(myronEditorValue($selectedPage, 'ctaLabel')) ?>">
      <input type="hidden" name="cta_href" value="<?= myronEscape(myronEditorValue($selectedPage, 'ctaHref')) ?>">
    </form>

    <div class="mc-editor-shell">
      <section class="sg-section mc-editor-toolbar">
        <div class="mc-editor-toolbar__summary">
          <span class="sg-pill <?= (string) ($selectedPage['publication_state'] ?? 'draft') === 'published' ? 'sg-pill--active' : '' ?>">
            <?= myronEscape((string) ($selectedPage['publication_state'] ?? 'draft')) ?>
          </span>
          <?php if ($templateStartedWorkflow): ?>
          <span class="mc-editor-toolbar__meta">Template: <?= myronEscape((string) ($templateStartedDefinition['name'] ?? $templateSourceId)) ?></span>
          <?php endif; ?>
          <?php if ($selectedPage !== null): ?>
          <span class="mc-editor-toolbar__meta">Path: <?= myronEscape((string) $selectedPage['path']) ?></span>
          <?php endif; ?>
          <?php if ($selectedPageTemplateLocked): ?>
          <span class="mc-editor-toolbar__meta">Source: <?= myronEscape((string) $selectedPage['source_template_id']) ?></span>
          <?php endif; ?>
          <?php if (is_array($selectedQualityReport)): ?>
          <span class="sg-pill <?= (string) ($selectedQualityReport['status'] ?? '') === 'block' ? '' : 'sg-pill--active' ?>"><?= myronEscape((string) ($selectedQualityReport['status'] ?? 'ready')) ?></span>
          <?php endif; ?>
        </div>
	        <div class="mc-editor-toolbar__actions">
	          <button class="sg-button sg-button--secondary" type="button" data-mc-sidesheet-open="page-info-sheet">Page Info</button>
	          <button class="sg-button sg-button--secondary" type="button" data-mc-sidesheet-open="page-publish-sheet">Publish Settings</button>
	          <button class="sg-button sg-button--secondary" type="button" data-mc-sidesheet-open="page-section-content-sheet" data-mc-visual-section-editor-trigger>Section Content</button>
            <?php if ($selectedPage !== null): ?>
            <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('content.pageEditor', ['page' => (string) $selectedPage['id'], 'preview' => 'draft'])) ?>" target="_blank" rel="noreferrer">Preview Draft</a>
            <?php elseif ($templateStartedWorkflow): ?>
            <button class="sg-button sg-button--secondary" type="button" disabled title="Save draft to preview" data-page-preview-requires-draft>Preview Draft</button>
            <?php endif; ?>
            <?php if ($templateStartedWorkflow): ?>
            <button class="sg-button sg-button--secondary" type="button" data-page-abandon-open>Abandon</button>
            <?php endif; ?>
	          <button class="sg-button sg-button--secondary" type="submit" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="action" value="save-draft">Save Draft</button>
	          <button class="sg-button sg-button--primary" type="submit" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="action" value="publish-page">Publish</button>
	        </div>
	      </section>

	      <section class="sg-section mc-editor-section-surface mc-editor-section-surface--visual" aria-label="Page content sections" data-mc-editor-section-main-surface data-mc-visual-editor-canvas data-source-template-id="<?= myronEscape((string) ($editorSurface['identity']['sourceTemplateId'] ?? '')) ?>">
	        <?php if (!is_array($editorSurface)): ?>
	        <div class="sg-status" role="status"><?= $templateStartedWorkflow ? 'Selected template sections are unavailable.' : 'Choose page information to create a new page draft.' ?></div>
	        <?php else: ?>
	        <div class="mc-editor-visual-canvas__note">
	          <span class="sg-pill">Rendered Canvas</span>
	          <span class="mc-page-grid__subtle">Click an editable section to manage its content in the side sheet.</span>
	        </div>
	        <div class="mc-editor-visual-canvas" data-mc-visual-editor-preview>
	          <?= is_array($editorCanvasPage) ? myronDefinitionTemplateRenderer()->renderPublishedPage($editorCanvasPage, myronPublicBasePath(), []) : '' ?>
	        </div>
	        <?php endif; ?>
	      </section>

      <?php ob_start(); ?>
      <div class="mc-editor-section-tree" data-mc-editor-section-tree data-mc-visual-section-panels>
        <?php if (!is_array($editorSurface)): ?>
        <div class="sg-status" role="status">No editable page sections are available yet.</div>
        <?php else: ?>
        <div class="sg-status" role="status" data-mc-visual-section-empty>Select a section in the rendered canvas to edit its content.</div>
	      <?php foreach ((array) ($editorSurface['sections'] ?? []) as $sectionNode): ?>
	      <?php if (is_array($sectionNode)): ?>
	      <section class="mc-editor-section-node" data-editor-section-node data-mc-visual-section-panel data-section-key="<?= myronEscape((string) ($sectionNode['sectionKey'] ?? '')) ?>" data-section-instance-key="<?= myronEscape((string) ($sectionNode['instanceKey'] ?? '')) ?>" data-component-id="<?= myronEscape((string) ($sectionNode['componentId'] ?? '')) ?>" data-editability="<?= myronEscape((string) ($sectionNode['editability'] ?? 'inspect-only')) ?>">
	            <div class="mc-editor-section-node__header">
	              <div>
	                <h3 class="mc-editor-section-node__title"><?= myronEscape((string) ($sectionNode['label'] ?? 'Section')) ?></h3>
	                <p class="mc-page-grid__subtle">
	                  <code><?= myronEscape((string) (($sectionNode['sectionKey'] ?? '') ?: ($sectionNode['componentId'] ?? 'section'))) ?></code>
	                  · <?= myronEscape((string) ($sectionNode['ownershipState'] ?? 'inspect-only')) ?>
	                </p>
	              </div>
	              <span class="sg-pill <?= (string) ($sectionNode['editability'] ?? '') === 'editable' ? 'sg-pill--active' : 'sg-pill--secondary' ?>"><?= (string) ($sectionNode['editability'] ?? '') === 'editable' ? 'Content editable' : 'Inspect only' ?></span>
	            </div>
	            <?php $editableFields = is_array($sectionNode['editableFields'] ?? null) ? $sectionNode['editableFields'] : []; ?>
	            <?php $repeatableGroups = is_array($sectionNode['repeatableGroups'] ?? null) ? $sectionNode['repeatableGroups'] : []; ?>
	            <?php if ($editableFields === [] && $repeatableGroups === []): ?>
	            <p class="sg-section__subtitle">This section is visible in the page structure and is managed by the template unless Design exposes content fields.</p>
	            <?php else: ?>
	            <?php if ($editableFields !== []): ?>
	            <div class="mc-sidesheet-form">
	              <?php foreach ($editableFields as $field): ?>
	              <?php if (is_array($field)): ?>
	              <?php
	                $fieldKey = (string) ($field['key'] ?? '');
	                $instanceKey = (string) ($sectionNode['instanceKey'] ?? '');
	                $inputName = $instanceKey !== ''
	                      ? 'section_content[' . $instanceKey . '][' . $fieldKey . ']'
	                      : ($fieldKey === 'ctaLabel' ? 'cta_label' : ($fieldKey === 'ctaHref' ? 'cta_href' : $fieldKey));
		              ?>
	              <?= myronRenderSectionContentFieldControl($field, $inputName, (string) ($field['value'] ?? ''), $availableImageFiles, ['formId' => $pageEditorCommandFormId]) ?>
	              <?php endif; ?>
	              <?php endforeach; ?>
	            </div>
	            <?php endif; ?>
	            <?php foreach ($repeatableGroups as $group): ?>
	            <?php if (is_array($group)): ?>
	            <?= myronRenderSectionContentRepeaterGroup($group, $instanceKey, $availableImageFiles, [
	                'formId' => $pageEditorCommandFormId,
	                'gridClass' => 'mc-sidesheet-form__grid',
	            ]) ?>
	            <?php endif; ?>
	            <?php endforeach; ?>
	            <?php endif; ?>
	      </section>
	      <?php endif; ?>
	      <?php endforeach; ?>
        <?php endif; ?>
      </div>
      <?php $pageSectionContentBody = (string) ob_get_clean(); ?>
      <?php myronRenderAdminSidesheet('page-section-content-sheet', 'Section Content', $pageSectionContentBody, [
          'description' => 'Click a rendered section, then edit the content fields exposed by Design.',
          'size' => 'xl',
      ]); ?>

      <?php ob_start(); ?>
      <div class="sg-form-grid">
        <label class="sg-field">
          <span class="sg-field__label">Page Name</span>
          <input class="sg-field__control" type="text" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="page_name" required value="<?= myronEscape($defaultPageName) ?>">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Slug</span>
          <input class="sg-field__control" type="text" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="slug" value="<?= myronEscape((string) ($selectedPage['slug'] ?? '')) ?>">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Template</span>
          <?php if ($selectedPageTemplateLocked || $templateStartedWorkflow): ?>
          <input type="hidden" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="template_id" value="<?= myronEscape($defaultTemplateId) ?>" data-page-template-role="<?= myronEscape($defaultTemplateClass) ?>" data-page-template-source="<?= myronEscape($defaultTemplateRoleSource) ?>" data-page-template-site-type="<?= myronEscape($defaultTemplateSiteType) ?>">
          <input class="sg-field__control" type="text" value="<?= myronEscape($defaultTemplateName) ?>" readonly>
          <?php if ($selectedPageTemplateLocked): ?>
          <span class="sg-field__hint">Template selection is protected for bundled pages from <code><?= myronEscape((string) $selectedPage['source_bundle_id']) ?></code>.</span>
          <?php else: ?>
          <span class="sg-field__hint">This page draft is being started from <code><?= myronEscape($templateSourceId) ?></code>.</span>
          <?php endif; ?>
          <?php else: ?>
          <select class="sg-field__control" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="template_id" data-page-template-select>
            <?php foreach ($templates as $template): ?>
            <option
              value="<?= myronEscape((string) $template['id']) ?>"
              data-page-template-role="<?= myronEscape((string) ($template['template_class'] ?? '')) ?>"
              data-page-template-source="<?= myronEscape((string) ($template['source_template_id'] ?? '')) ?>"
              data-page-template-site-type="<?= myronEscape((string) ($template['source_site_type'] ?? '')) ?>"
              <?= $defaultTemplateId === (string) $template['id'] ? ' selected' : '' ?>
            >
              <?= myronEscape((string) $template['name']) ?>
            </option>
            <?php endforeach; ?>
          </select>
          <?php endif; ?>
        </label>

        <div class="sg-field sg-field--full" data-page-blog-categories<?= $defaultTemplateClass === 'post-single' ? '' : ' hidden' ?>>
          <span class="sg-field__label">Blog Categories</span>
          <?php if ($pageCategories === []): ?>
          <?php if (myronUserCanManageContent($currentUser)): ?>
          <p class="sg-field__hint">No blog categories have been created yet. <a href="<?= myronEscape(myronBuildAdminUrl('content.categories')) ?>">Manage categories</a>.</p>
          <?php else: ?>
          <p class="sg-field__hint">No blog categories have been created yet.</p>
          <?php endif; ?>
          <?php else: ?>
          <div class="mc-context-form__checkboxes">
            <?php foreach ($pageCategories as $category): ?>
            <label class="mc-checkbox mc-checkbox--compact">
              <input
                type="checkbox"
                form="<?= myronEscape($pageEditorCommandFormId) ?>"
                name="blog_category_ids[]"
                value="<?= myronEscape((string) $category['id']) ?>"
                <?= isset($selectedPageCategoryIds[(string) $category['id']]) ? ' checked' : '' ?>
              >
              <span><?= myronEscape((string) $category['title']) ?></span>
            </label>
            <?php endforeach; ?>
          </div>
          <?php endif; ?>
        </div>

        <fieldset class="sg-fieldset sg-field--full" data-page-blog-comments<?= $defaultTemplateClass === 'post-single' ? '' : ' hidden' ?>>
          <legend>Comments</legend>
          <div class="sg-form-grid">
            <label class="sg-field sg-field--checkbox">
              <span class="sg-field__checkbox">
                <input type="radio" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="blog_comments_enabled_override" value="default"<?= $blogCommentsOverride === 'default' ? ' checked' : '' ?>>
                <span>Use the global blog comment default</span>
              </span>
            </label>
            <label class="sg-field sg-field--checkbox">
              <span class="sg-field__checkbox">
                <input type="radio" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="blog_comments_enabled_override" value="enabled"<?= $blogCommentsOverride === 'enabled' ? ' checked' : '' ?>>
                <span>Enable comments for this post</span>
              </span>
            </label>
            <label class="sg-field sg-field--checkbox">
              <span class="sg-field__checkbox">
                <input type="radio" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="blog_comments_enabled_override" value="disabled"<?= $blogCommentsOverride === 'disabled' ? ' checked' : '' ?>>
                <span>Disable comments for this post</span>
              </span>
            </label>
          </div>
          <p class="sg-field__hint">This control appears only for blog post pages and resolves after the global comment setting.</p>
        </fieldset>

        <label class="sg-field">
          <span class="sg-field__label">Parent Page</span>
          <select class="sg-field__control" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="parent_page_id" data-page-parent-select>
            <option value="">Top level</option>
            <?php foreach ($pageOptions as $option): ?>
            <option
              value="<?= myronEscape((string) $option['id']) ?>"
              data-page-template-role="<?= myronEscape((string) ($option['template_class'] ?? '')) ?>"
              data-page-template-source="<?= myronEscape((string) (($option['source_template_id'] ?? '') ?: ($option['template_source_template_id'] ?? ''))) ?>"
              data-page-template-site-type="<?= myronEscape((string) ($option['source_site_type'] ?? '')) ?>"
              data-page-path="<?= myronEscape((string) $option['path']) ?>"
              <?= (string) ($selectedPage['parent_page_id'] ?? '') === (string) $option['id'] ? ' selected' : '' ?>
            >
              <?= myronEscape((string) $option['title']) ?> · <?= myronEscape((string) $option['path']) ?>
            </option>
            <?php endforeach; ?>
          </select>
        </label>

        <label class="sg-field sg-field--checkbox">
          <span class="sg-field__label">Navigation</span>
          <input type="hidden" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="include_in_nav" value="0">
          <span class="sg-field__checkbox">
            <input
              type="checkbox"
              form="<?= myronEscape($pageEditorCommandFormId) ?>"
              name="include_in_nav"
              value="1"
              data-page-nav-visibility
              <?= $defaultIncludeInNav ? ' checked' : '' ?>
            >
            <span>Show in navigation</span>
          </span>
          <span class="sg-field__hint">Controls automatic child-page navigation. Explicit menu membership below remains separate.</span>
        </label>

        <label class="sg-field">
          <span class="sg-field__label">SEO Title</span>
          <input class="sg-field__control" type="text" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="seo_title" value="<?= myronEscape(myronEditorFieldValue($selectedPage, 'draft_seo_title', 'published_seo_title')) ?>">
        </label>

        <label class="sg-field sg-field--full">
          <span class="sg-field__label">Meta Description</span>
          <textarea class="sg-field__control sg-field__control--textarea" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="meta_description" rows="4"><?= myronEscape(myronEditorFieldValue($selectedPage, 'draft_meta_description', 'published_meta_description')) ?></textarea>
        </label>
      </div>

      <?php require __DIR__ . '/../../templates/content/seo-panel.php'; ?>

      <?php
        $selectedBundleId = $selectedPage !== null
            ? trim((string) (($selectedPage['source_bundle_id'] ?? '') ?: ($selectedPage['template_source_bundle_id'] ?? '')))
            : '';
        $selectedBundleLabel = $selectedBundleId !== ''
            ? MyronSiteTypeRegistryRepository::friendlyLabelForCode($selectedBundleId)
            : 'This page type';
        $selectedBundleIndexable = myronSiteTypeRegistryRepository()->getIndexableByBundleId($selectedBundleId);
        $defaultVisibilityLabel = $selectedBundleLabel . ' pages are ' . ($selectedBundleIndexable ? 'indexed' : 'not indexed') . ' by default';
        $currentIndexableOverride = $selectedPage !== null && ($selectedPage['indexable_override'] ?? null) !== null
            ? (string) (int) $selectedPage['indexable_override']
            : '';
        $downloadMarkupEnabled = $selectedPage !== null
            && trim((string) ($selectedPage['current_published_version_id'] ?? '')) !== ''
            && $repository->isPageMarkupDownloadable([
                'indexable_override' => $selectedPage['indexable_override'] ?? null,
                'source_bundle_id' => $selectedPage['source_bundle_id'] ?? '',
                'template_source_bundle_id' => $selectedPage['template_source_bundle_id'] ?? '',
                'robots_override' => $selectedPage['published_robots_override'] ?? $selectedPage['robots_override'] ?? '',
            ]);
        $markupDownloadUrl = $selectedPage !== null
            ? rtrim(myronAdminBasePath(), '/') . '/api/v1/content/pages/' . rawurlencode((string) $selectedPage['id']) . '/markup'
            : '';
        $markdownDownloadUrl = $selectedPage !== null
            ? rtrim(myronAdminBasePath(), '/') . '/api/v1/content/pages/' . rawurlencode((string) $selectedPage['id']) . '/markdown'
            : '';
      ?>
      <fieldset class="sg-fieldset sg-field--full">
        <legend>Sitemap and markup download visibility</legend>
        <div class="sg-form-grid">
          <label class="sg-field sg-field--checkbox">
            <span class="sg-field__checkbox">
              <input type="radio" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="indexable_override" value="default"<?= $currentIndexableOverride === '' ? ' checked' : '' ?>>
              <span>Use the default for this page type — <?= myronEscape($defaultVisibilityLabel) ?></span>
            </span>
          </label>
          <label class="sg-field sg-field--checkbox">
            <span class="sg-field__checkbox">
              <input type="radio" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="indexable_override" value="include"<?= $currentIndexableOverride === '1' ? ' checked' : '' ?>>
              <span>Always include this page</span>
            </span>
          </label>
          <label class="sg-field sg-field--checkbox">
            <span class="sg-field__checkbox">
              <input type="radio" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="indexable_override" value="exclude"<?= $currentIndexableOverride === '0' ? ' checked' : '' ?>>
              <span>Always exclude this page</span>
            </span>
          </label>
        </div>
      </fieldset>

      <?php if ($selectedPage !== null): ?>
      <fieldset class="sg-fieldset sg-field--full">
        <legend>Download Markup</legend>
        <div class="mc-side-sheet__actions">
          <?php if ($downloadMarkupEnabled): ?>
          <a class="sg-button sg-button--secondary" href="<?= myronEscape($markupDownloadUrl) ?>">Download HTML markup</a>
          <?php else: ?>
          <button class="sg-button sg-button--secondary" type="button" disabled>Download HTML markup</button>
          <?php endif; ?>
        </div>
        <p class="sg-section__subtitle">Downloads this page's rendered HTML for SEO analysis or AI agent consumption.</p>
      </fieldset>
      <?php endif; ?>

      <?php if ($selectedPage !== null): ?>
      <fieldset class="sg-fieldset sg-field--full">
        <legend>Download Markdown</legend>
        <div class="mc-side-sheet__actions">
          <?php if ($downloadMarkupEnabled): ?>
          <a class="sg-button sg-button--secondary" href="<?= myronEscape($markdownDownloadUrl) ?>">Download Markdown</a>
          <?php else: ?>
          <button class="sg-button sg-button--secondary" type="button" disabled>Download Markdown</button>
          <?php endif; ?>
        </div>
        <p class="sg-section__subtitle">Downloads this page's content as native Markdown for AI agent consumption with YAML front matter carrying SEO metadata.</p>
      </fieldset>
      <?php endif; ?>

      <div class="mc-side-sheet__actions">
        <button class="sg-button sg-button--secondary" type="submit" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="action" value="save-draft">Save Draft</button>
      </div>

      <?php if ($selectedPage !== null): ?>
      <div class="mc-editor-danger-zone">
        <?php if (($selectedPageDeletionPolicy['allowed'] ?? false) === true): ?>
        <button class="sg-button sg-button--danger" type="button" data-page-delete-open>Delete Page</button>
        <?php else: ?>
        <p class="sg-section__subtitle"><?= myronEscape((string) ($selectedPageDeletionPolicy['reason'] ?? 'This page cannot be deleted.')) ?></p>
        <?php endif; ?>
      </div>
      <?php endif; ?>
      <?php $pageInfoBody = (string) ob_get_clean(); ?>
      <?php myronRenderAdminSidesheet('page-info-sheet', 'Page Information', $pageInfoBody, [
          'description' => 'Page identity, hierarchy, template, and SEO fields.',
          'size' => 'lg',
      ]); ?>

	      <?php ob_start(); ?>
      <div class="sg-form-grid">
        <label class="sg-field">
          <span class="sg-field__label">Published Date</span>
          <input class="sg-field__control" type="datetime-local" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="published_at" value="<?= myronEscape(myronFormatDatetimeForInput((string) ($selectedPage['published_at'] ?? ''))) ?>">
          <span class="sg-field__hint">Optional. Used when publishing this version.</span>
        </label>
      </div>

      <?php if (myronUserCanAccessAdministration($currentUser)): ?>
      <div class="mc-editor-assignment-group">
        <h3 class="sg-section__title sg-section__title--sm">Menu Membership</h3>
        <div class="mc-editor-menu-grid">
          <?php foreach ($menuAssignments as $assignment): ?>
          <article class="mc-editor-menu-card">
            <label class="sg-field sg-field--checkbox">
              <span class="sg-field__label"><?= myronEscape((string) $assignment['menu_name']) ?> · <?= myronEscape((string) $assignment['placement']) ?></span>
              <span class="sg-field__checkbox">
                <input type="checkbox" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="menu_enabled[<?= myronEscape((string) $assignment['menu_id']) ?>]" value="1"<?= ($assignment['enabled'] ?? false) ? ' checked' : '' ?>>
                <span>Include this page in the menu.</span>
              </span>
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Label</span>
              <input class="sg-field__control" type="text" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="menu_label[<?= myronEscape((string) $assignment['menu_id']) ?>]" value="<?= myronEscape((string) ($assignment['label'] ?? '')) ?>">
            </label>
          </article>
          <?php endforeach; ?>
        </div>
      </div>
      <?php endif; ?>

      <?php $publishBody = (string) ob_get_clean(); ?>
      <?php myronRenderAdminSidesheet('page-publish-sheet', 'Publishing and Menus', $publishBody, [
          'description' => 'Publication timing and menu membership.',
          'size' => 'lg',
      ]); ?>

      <?php if ($selectedPage !== null && (($selectedPageDeletionPolicy['allowed'] ?? false) === true)): ?>
      <div class="myron-dialog-backdrop myron-dialog-backdrop--page-editor-delete" hidden aria-hidden="true" data-page-delete-backdrop></div>
      <div class="myron-dialog myron-dialog--confirmation myron-dialog--page-editor-delete" id="page-editor-delete-dialog" role="dialog" aria-modal="true" aria-hidden="true" hidden tabindex="-1" data-page-delete-dialog>
        <div class="myron-dialog__header">
          <div>
            <h3 class="myron-heading" data-level="4">Delete page?</h3>
            <p class="myron-paragraph myron-paragraph--muted">This deletes the page and all of its versions.</p>
          </div>
          <button class="myron-dialog__close" type="button" aria-label="Close delete confirmation" data-page-delete-close>&times;</button>
        </div>
        <div class="myron-dialog__body">
          <p class="myron-paragraph">Delete "<?= myronEscape($defaultPageName) ?>"? This action cannot be undone.</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-page-delete-close>Cancel</button>
          <button class="myron-button myron-button--intent-danger myron-button--appearance-solid myron-button--size-md" type="submit" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="action" value="delete-page" data-page-delete-confirm>Delete Page</button>
        </div>
      </div>
      <?php endif; ?>

      <?php if ($templateStartedWorkflow): ?>
      <div class="myron-dialog-backdrop" hidden aria-hidden="true" data-page-abandon-backdrop></div>
      <div class="myron-dialog myron-dialog--confirmation" id="page-editor-abandon-dialog" role="dialog" aria-modal="true" aria-hidden="true" hidden tabindex="-1" data-page-abandon-dialog>
        <div class="myron-dialog__header">
          <div>
            <h3 class="myron-heading" data-level="4">Abandon page draft?</h3>
            <p class="myron-paragraph myron-paragraph--muted">Save a draft to keep this page, or abandon to return without creating one.</p>
          </div>
          <button class="myron-dialog__close" type="button" aria-label="Close abandon confirmation" data-page-abandon-close>&times;</button>
        </div>
        <div class="myron-dialog__body">
          <p class="myron-paragraph">Unsaved changes on this new page will be discarded.</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-page-abandon-close>Cancel</button>
          <a class="myron-button myron-button--intent-neutral myron-button--appearance-outline myron-button--size-md" href="<?= myronEscape($abandonUrl) ?>" data-page-abandon-discard>Abandon</a>
          <button class="myron-button myron-button--intent-primary myron-button--appearance-solid myron-button--size-md" type="submit" form="<?= myronEscape($pageEditorCommandFormId) ?>" name="action" value="save-draft">Save Draft</button>
        </div>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>
<script>
(() => {
  const templateSelect = document.querySelector('[data-page-template-select]');
  const navVisibility = document.querySelector('[data-page-nav-visibility]');
  if (!templateSelect || !navVisibility) {
    return;
  }

  let operatorTouched = false;
  navVisibility.addEventListener('change', () => {
    operatorTouched = true;
  });

  templateSelect.addEventListener('change', () => {
    if (operatorTouched) {
      return;
    }

    const selected = templateSelect.selectedOptions && templateSelect.selectedOptions[0];
    const role = selected ? String(selected.dataset.pageTemplateRole || '') : '';
    navVisibility.checked = role !== 'post-single';
  });
})();
</script>
<?php myronRenderAdminShellEnd(); ?>
