<?php

declare(strict_types=1);

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

$currentUser = myronRequireDesignAccess();
$csrfToken = myronCsrfToken();
$templateRepository = myronTemplateDefinitionRepository();
$bundleRepository = myronBundleActivationRepository();
$contentRepository = myronContentRepository();
$sectionRepository = myronSectionRegistryRepository();
$componentRepository = myronComponentRegistryRepository();
$editorSurfaceReadModel = myronEditorSurfaceReadModel();
$currentSiteUsage = myronCurrentSiteUsageReadModel();
$footerDesignRepository = myronFooterDesignRepository();
$navigationDesignRepository = myronNavigationDesignRepository();
$chromeAssignmentRepository = myronTemplateChromeAssignmentRepository();
$sectionVariantRepository = myronSectionVariantRepository();
$allTemplates = $templateRepository->listTemplates();
$availableImageFiles = array_values(array_filter(
    myronFileRepository()->listFiles(),
    static fn (array $file): bool => (bool) ($file['is_image'] ?? false)
));
$availability = $bundleRepository->templateAvailabilityIndex($allTemplates);
$runtimeTemplatesBySource = $contentRepository->listTemplatesBySourceTemplateId();
$currentTemplateSourceIdSet = array_fill_keys($currentSiteUsage->currentTemplateSourceIds(), true);
$siteTypeLabelsByBundleId = [];
foreach (myronSiteTypeRegistryRepository()->listSiteTypes() as $siteType) {
    $bundleId = trim((string) ($siteType['id'] ?? ''));
    if ($bundleId !== '') {
        $siteTypeLabelsByBundleId[$bundleId] = MyronSiteTypeRegistryRepository::displayLabelForSiteType($siteType);
    }
}

$siteTypeLabelForBundle = static function (string $bundleId) use ($siteTypeLabelsByBundleId): string {
    if ($bundleId === 'starter.default') {
        return 'Starter Default';
    }

    return $siteTypeLabelsByBundleId[$bundleId] ?? ucwords(str_replace(['site-type.', '.', '-'], ['', ' ', ' '], $bundleId));
};

$filterValues = static function (mixed $value): array {
    $rawValues = is_array($value) ? $value : explode(',', (string) $value);
    $values = [];
    foreach ($rawValues as $rawValue) {
        $normalized = trim((string) $rawValue);
        if ($normalized !== '') {
            $values[$normalized] = true;
        }
    }

    return array_keys($values);
};

$usageScopeFromValue = static function (mixed $value): string {
    return in_array((string) $value, ['current', 'library'], true) ? (string) $value : 'current';
};

$normalizeHeroMediaLayout = static function (mixed $value): string {
    $layout = strtolower(trim((string) $value));
    $layout = preg_replace('/[^a-z0-9]+/', '-', $layout) ?? '';
    $layout = trim($layout, '-');

    return match ($layout) {
        'full-bleed', 'full-width', 'split' => $layout,
        '', 'auto' => 'auto',
        default => throw new InvalidArgumentException('Hero media layout must be auto, split, full-bleed, or full-width.'),
    };
};

$queryFromFilters = static function (array $purposes, array $bundles, array $statuses, string $usageScope = 'current'): array {
    $query = [];
    if ($usageScope !== 'current') {
        $query['usage'] = $usageScope;
    }
    if ($purposes !== []) {
        $query['purpose'] = implode(',', array_values(array_map('strval', $purposes)));
    }
    if ($bundles !== []) {
        $query['bundle'] = implode(',', array_values(array_map('strval', $bundles)));
    }
    if ($statuses !== []) {
        $query['status'] = implode(',', array_values(array_map('strval', $statuses)));
    }

    return $query;
};

$statusLabelForKey = static fn (string $status): string => $status === 'available'
    ? 'Available'
    : ($status === 'inactive' ? 'Inactive' : MyronTemplateDefinitionRepository::remediationStatusLabel($status));

$redirectToTemplate = static function (string $templateId, array $returnQuery = []): void {
    myronRedirect(myronBuildAdminUrl('design.templatesManager', array_merge($returnQuery, ['template' => $templateId])));
};

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $action = trim((string) ($_POST['action'] ?? ''));
        $sourceTemplateId = trim((string) ($_POST['source_template_id'] ?? ''));
        $returnQuery = $queryFromFilters(
            $filterValues($_POST['return_purpose'] ?? ''),
            $filterValues($_POST['return_bundle'] ?? ''),
            $filterValues($_POST['return_status'] ?? ''),
            $usageScopeFromValue($_POST['return_usage'] ?? 'current')
        );
        $definition = $sourceTemplateId !== '' ? $templateRepository->findTemplateById($sourceTemplateId) : null;
        $runtimeTemplateForRef = $sourceTemplateId !== '' ? $contentRepository->findRuntimeTemplateByIdOrSourceTemplateId($sourceTemplateId) : null;
        $runtimeBackedActions = [
            'update-template-chrome-assignment',
            'insert-section',
            'move-section',
            'duplicate-section',
            'remove-section',
            'reorder-sections',
            'update-section-editability',
            'update-template-section-content',
            'update-section-design',
            'save-section-variant',
            'apply-section-variant',
            'make-custom-template-available',
            'delete-custom-site-template',
        ];
        if (!is_array($definition) && !in_array($action, $runtimeBackedActions, true)) {
            throw new InvalidArgumentException('Choose a valid packaged template definition.');
        }

        if ($action === 'create-runtime-draft') {
            myronTemplateInstantiationService()->instantiateTemplate($definition);
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.templatesManager', array_merge($returnQuery, ['template' => $sourceTemplateId])),
                'Created editable runtime template draft.',
                'success'
            );
        }

        if ($action === 'update-template-chrome-assignment') {
            $navigationDesignId = trim((string) ($_POST['navigation_design_id'] ?? ''));
            $footerVariantId = trim((string) ($_POST['footer_variant_id'] ?? ''));
            $chromeAssignmentRepository->setForTemplate($sourceTemplateId, [
                'navigation_design_id' => $navigationDesignId,
                'footer_variant_id' => in_array($footerVariantId, ['inherit_site', 'inherit_seed', 'inherit'], true) ? null : $footerVariantId,
            ], (string) ($currentUser['id'] ?? ''));
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.templatesManager', array_merge($returnQuery, ['template' => $sourceTemplateId])),
                'Updated Chrome Assignment.',
                'success'
            );
        }

        $runtimeTemplate = $runtimeTemplateForRef;
        if (!is_array($runtimeTemplate)) {
            throw new InvalidArgumentException('Create an editable runtime template draft before changing sections.');
        }

        if ($action === 'make-custom-template-available') {
            $callerCtx = myronActionCallerContextForUser($currentUser);
            $updated = myronTemplateDuplicationActionService()->makeAvailableAsPageTemplate($sourceTemplateId, $callerCtx);
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.templatesManager', array_merge($returnQuery, ['template' => (string) $updated['source_template_id']])),
                'Custom Site Template is now available as a Page Template.',
                'success'
            );
        }

        if ($action === 'delete-custom-site-template') {
            $callerCtx = myronActionCallerContextForUser($currentUser);
            myronTemplateDuplicationActionService()->deleteCustomSiteTemplate($sourceTemplateId, $callerCtx);
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.templatesManager', $returnQuery !== [] ? $returnQuery : ['usage' => 'library']),
                'Custom Site Template deleted.',
                'success'
            );
        }

        $schema = is_array($runtimeTemplate['schema'] ?? null) ? $runtimeTemplate['schema'] : [];
        $sections = array_values(array_filter(
            is_array($schema['sections'] ?? null) ? $schema['sections'] : [],
            static fn (mixed $section): bool => is_array($section)
        ));

        if ($action === 'insert-section') {
            $sectionKey = trim((string) ($_POST['section_key'] ?? ''));
            $insertAt = max(0, min(count($sections), (int) ($_POST['insert_at'] ?? count($sections))));
            myronSectionEditActionService()->insertSection($sourceTemplateId, $sectionKey, $insertAt, myronActionCallerContextForUser($currentUser));
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.templatesManager', array_merge($returnQuery, ['template' => $sourceTemplateId])),
                'Inserted section into runtime template draft.',
                'success'
            );
        }

        if ($action === 'duplicate-section') {
            $position = (int) ($_POST['position'] ?? -1);
            myronSectionEditActionService()->duplicateSection($sourceTemplateId, $position, null, myronActionCallerContextForUser($currentUser));
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.templatesManager', array_merge($returnQuery, ['template' => $sourceTemplateId])),
                'Duplicated runtime template section.',
                'success'
            );
        }

        if ($action === 'remove-section') {
            $position = (int) ($_POST['position'] ?? -1);
            myronSectionEditActionService()->removeSection(
                $sourceTemplateId,
                $position,
                null,
                myronActionCallerContextForUser($currentUser)
            );
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.templatesManager', array_merge($returnQuery, ['template' => $sourceTemplateId])),
                'Removed runtime template section. Existing page-version content remains available for rollback.',
                'success'
            );
        }

        if ($action === 'reorder-sections') {
            $rawOrder = is_array($_POST['section_order'] ?? null) ? $_POST['section_order'] : [];
            myronSectionEditActionService()->reorderSections(
                $sourceTemplateId,
                array_values(array_map('intval', $rawOrder)),
                myronActionCallerContextForUser($currentUser)
            );
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.templatesManager', array_merge($returnQuery, ['template' => $sourceTemplateId])),
                'Reordered runtime template sections.',
                'success'
            );
        }

        if ($action === 'move-section') {
            $position = (int) ($_POST['position'] ?? -1);
            $direction = trim((string) ($_POST['direction'] ?? ''));
            if (!isset($sections[$position]) || !in_array($direction, ['up', 'down'], true)) {
                throw new InvalidArgumentException('Choose a valid section movement.');
            }
            $target = $direction === 'up' ? $position - 1 : $position + 1;
            if (!isset($sections[$target])) {
                $redirectToTemplate($sourceTemplateId, $returnQuery);
            }
            $moving = $sections[$position];
            $sections[$position] = $sections[$target];
            $sections[$target] = $moving;
            $contentRepository->updateRuntimeTemplateSections((string) $runtimeTemplate['id'], $sections);
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.templatesManager', array_merge($returnQuery, ['template' => $sourceTemplateId])),
                'Reordered runtime template section.',
                'success'
            );
        }

        if ($action === 'update-section-editability') {
            $position = (int) ($_POST['position'] ?? -1);
            if (!isset($sections[$position])) {
                throw new InvalidArgumentException('Choose a valid template section.');
            }
            $contentRepository->updateRuntimeTemplateSectionEditability(
                (string) $runtimeTemplate['id'],
                $position,
                (string) ($_POST['content_editable'] ?? '0') === '1'
            );
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.templatesManager', array_merge($returnQuery, ['template' => $sourceTemplateId])),
                'Updated section content editability.',
                'success'
            );
        }

        if ($action === 'update-template-section-content') {
            $contentRepository->updateRuntimeTemplateDefaultContent(
                (string) $runtimeTemplate['id'],
                myronContentPayloadFromInput(
                    $_POST,
                    $sections,
                    is_array($schema['defaultContent'] ?? null) ? $schema['defaultContent'] : []
                )
            );
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.templatesManager', array_merge($returnQuery, ['template' => $sourceTemplateId])),
                'Updated template default section content.',
                'success'
            );
        }

        if ($action === 'update-section-design') {
            $position = (int) ($_POST['position'] ?? -1);
            if (!isset($sections[$position])) {
                throw new InvalidArgumentException('Choose a valid template section.');
            }
            $componentId = (string) ($sections[$position]['componentId'] ?? '');
            $component = $componentRepository->findComponentById($componentId);
            $editableTokens = is_array($component) && is_array($component['editableTokens'] ?? null) ? $component['editableTokens'] : [];
            $designPatch = [
                'customCss' => (string) ($_POST['custom_css'] ?? ''),
                'tokenOverrides' => myronNormalizeEditableTokenOverrideInput(is_array($_POST['token_overrides'] ?? null) ? $_POST['token_overrides'] : [], $editableTokens),
            ];
            if (in_array($componentId, ['hero-simple', 'hero-with-cta'], true)) {
                $mediaLayout = $normalizeHeroMediaLayout($_POST['media_layout'] ?? 'auto');
                $designPatch['mediaLayout'] = $mediaLayout === 'auto' ? null : $mediaLayout;
            }
            $contentRepository->updateRuntimeTemplateSectionDesign((string) $runtimeTemplate['id'], $position, $designPatch);
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.templatesManager', array_merge($returnQuery, ['template' => $sourceTemplateId])),
                'Updated section design overrides.',
                'success'
            );
        }

        if ($action === 'save-section-variant') {
            $position = (int) ($_POST['position'] ?? -1);
            if (!isset($sections[$position])) {
                throw new InvalidArgumentException('Choose a valid template section.');
            }
            $content = myronSectionContentForInstance(
                is_array($schema['defaultContent'] ?? null) ? $schema['defaultContent'] : [],
                $sections[$position],
                $position
            );
            $sectionVariantRepository->saveFromSection(
                (string) ($_POST['variant_name'] ?? ''),
                $sections[$position],
                $content,
                (string) ($currentUser['id'] ?? '')
            );
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.templatesManager', array_merge($returnQuery, ['template' => $sourceTemplateId])),
                'Saved current section as a reusable variant.',
                'success'
            );
        }

        if ($action === 'apply-section-variant') {
            $position = (int) ($_POST['position'] ?? -1);
            if (!isset($sections[$position])) {
                throw new InvalidArgumentException('Choose a valid template section.');
            }
            $savedVariant = $sectionVariantRepository->find((string) ($_POST['section_variant_id'] ?? ''));
            if (!is_array($savedVariant)) {
                throw new InvalidArgumentException('Choose a valid saved section variant.');
            }
            $updatedSection = $sectionVariantRepository->applyToSection($sections[$position], $savedVariant);
            $contentRepository->updateRuntimeTemplateSectionDesign((string) $runtimeTemplate['id'], $position, $updatedSection);
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.templatesManager', array_merge($returnQuery, ['template' => $sourceTemplateId])),
                'Applied saved section variant.',
                'success'
            );
        }

        throw new RuntimeException('Unknown template manager action.');
    } catch (Throwable $exception) {
        $query = [];
        $postedTemplateId = trim((string) ($_POST['source_template_id'] ?? ''));
        if ($postedTemplateId !== '') {
            $query['template'] = $postedTemplateId;
        }
        $query = array_merge(
            $queryFromFilters(
                $filterValues($_POST['return_purpose'] ?? ''),
                $filterValues($_POST['return_bundle'] ?? ''),
                $filterValues($_POST['return_status'] ?? ''),
                $usageScopeFromValue($_POST['return_usage'] ?? 'current')
            ),
            $query
        );
        myronRedirectWithFlash(myronBuildAdminUrl('design.templatesManager', $query), $exception->getMessage(), 'error');
    }
}

$selectedPurposes = $filterValues($_GET['purpose'] ?? ($_GET['class'] ?? ''));
$selectedBundles = $filterValues($_GET['bundle'] ?? '');
$selectedStatuses = $filterValues($_GET['status'] ?? '');
$usageScope = $usageScopeFromValue($_GET['usage'] ?? 'current');
$selectedTemplateId = trim((string) ($_GET['template'] ?? ''));
$templateRows = $usageScope === 'library'
    ? $allTemplates
    : array_values(array_filter(
        $allTemplates,
        static function (array $template) use ($currentTemplateSourceIdSet): bool {
            return isset($currentTemplateSourceIdSet[(string) ($template['id'] ?? '')]);
        }
    ));

$purposeOptions = [];
$bundleOptions = [];
$statusOptions = [];
foreach ($templateRows as $template) {
    $templateId = (string) ($template['id'] ?? '');
    $purpose = MyronTemplateDefinitionRepository::templatePurposeForTemplateId($templateId);
    if ((string) $purpose['key'] !== '') {
        $purposeOptions[(string) $purpose['key']] = (string) $purpose['label'];
    }
    $registry = is_array($template['_registry'] ?? null) ? $template['_registry'] : [];
    $bundleId = (string) ($registry['bundleId'] ?? $template['bundleId'] ?? '');
    if ($bundleId !== '') {
        $bundleOptions[$bundleId] = $siteTypeLabelForBundle($bundleId);
    }
    $templateAvailability = $availability[$templateId] ?? ['available' => false, 'status' => 'Inactive bundle'];
    $availabilityKey = (bool) ($templateAvailability['available'] ?? false) ? 'available' : 'inactive';
    $statusOptions[$availabilityKey] = true;
    $statusOptions[MyronTemplateDefinitionRepository::remediationStatusForTemplate($template)] = true;
}
asort($purposeOptions, SORT_STRING);
asort($bundleOptions, SORT_STRING);
ksort($statusOptions);

$selectedPurposes = array_values(array_filter($selectedPurposes, static fn (string $value): bool => isset($purposeOptions[$value])));
$selectedBundles = array_values(array_filter($selectedBundles, static fn (string $value): bool => isset($bundleOptions[$value])));
$selectedStatuses = array_values(array_filter($selectedStatuses, static fn (string $value): bool => isset($statusOptions[$value])));

$listQuery = $queryFromFilters($selectedPurposes, $selectedBundles, $selectedStatuses, $usageScope);
$isDetailMode = $selectedTemplateId !== '';
$selectedTemplate = $selectedTemplateId !== '' ? $templateRepository->findTemplateById($selectedTemplateId) : null;
$selectedSurface = $selectedTemplateId !== '' ? $editorSurfaceReadModel->templateSurface($selectedTemplateId) : null;
if (!is_array($selectedTemplate) && is_array($selectedSurface) && is_array($selectedSurface['raw']['definition'] ?? null)) {
    $selectedTemplate = $selectedSurface['raw']['definition'];
}
$selectedRuntimeTemplate = is_array($selectedSurface) && is_array($selectedSurface['raw']['runtimeTemplate'] ?? null)
    ? $selectedSurface['raw']['runtimeTemplate']
    : null;
$selectedTemplateLifecycle = is_array($selectedRuntimeTemplate) && is_array($selectedRuntimeTemplate['template_lifecycle'] ?? null)
    ? $selectedRuntimeTemplate['template_lifecycle']
    : [];
$selectedIsCustomSiteTemplate = ($selectedTemplateLifecycle['kind'] ?? '') === 'custom_site_template';
$selectedIsAvailablePageTemplate = (bool) ($selectedTemplateLifecycle['availableAsPageTemplate'] ?? false);
$selectedSections = is_array($selectedSurface['sections'] ?? null) ? $selectedSurface['sections'] : [];
$previewUrl = $selectedTemplateId !== '' ? myronBuildAdminUrl('design.templatePreview', ['id' => $selectedTemplateId]) : '';
$selectedPreviewPage = is_array($selectedTemplate)
    ? myronTemplatePreviewFactory()->buildPreviewPage($selectedTemplate)
    : null;
$activatedFooterVariants = $footerDesignRepository->listActivatedSorted();
$defaultFooterDesign = $footerDesignRepository->getDefault();
$activatedNavigationVersions = $navigationDesignRepository->listActivatedSorted();
$defaultNavigationDesign = $navigationDesignRepository->getDefault();
$savedSectionVariants = $sectionVariantRepository->listVariants();
$footerVariantLabels = myronFooterVariantCompositionService()->variantLabels();
$selectedChromeAssignment = $selectedTemplateId !== '' ? $chromeAssignmentRepository->getForTemplate($selectedTemplateId) : null;
$selectedTemplateChrome = is_array($selectedTemplate['chrome'] ?? null) ? $selectedTemplate['chrome'] : [];
$selectedTemplateFooterChrome = is_array($selectedTemplateChrome['footer'] ?? null) ? $selectedTemplateChrome['footer'] : [];
$selectedFooterChromeSeed = trim((string) ($selectedTemplateFooterChrome['variant'] ?? ''));
if (is_array($selectedPreviewPage) && is_array($selectedSurface) && is_array($selectedRuntimeTemplate)) {
    $runtimeSchema = is_array($selectedSurface['raw']['schema'] ?? null) ? $selectedSurface['raw']['schema'] : [];
    $selectedPreviewPage['template_schema'] = $runtimeSchema;
    if (is_array($runtimeSchema['defaultContent'] ?? null)) {
        $selectedPreviewPage['content'] = array_merge(
            is_array($selectedPreviewPage['content'] ?? null) ? $selectedPreviewPage['content'] : [],
            $runtimeSchema['defaultContent']
        );
    }
}
$governedSections = $sectionRepository->listSections();
$bodyGovernedSections = array_values(array_filter(
    $governedSections,
    static function (array $section): bool {
        $sectionKey = trim((string) ($section['sectionKey'] ?? ''));
        return $sectionKey !== '' && !in_array($sectionKey, MyronSectionRegistryRepository::forbiddenBodySectionKeys(), true);
    }
));
$bodyGovernedSectionsByGroup = [];
foreach ($bodyGovernedSections as $section) {
    $group = trim((string) ($section['jtbdGroup'] ?? 'custom'));
    $bodyGovernedSectionsByGroup[$group !== '' ? $group : 'custom'][] = $section;
}
ksort($bodyGovernedSectionsByGroup, SORT_STRING);
$backToTemplatesUrl = myronBuildAdminUrl('design.templatesManager', $listQuery);
$templateDetailUrl = static fn (string $templateId): string => myronBuildAdminUrl('design.templatesManager', array_merge($listQuery, ['template' => $templateId]));
$scopeUrl = static fn (string $scope): string => myronBuildAdminUrl('design.templatesManager', $scope === 'current' ? [] : ['usage' => $scope]);
$renderReturnFilterInputs = static function () use ($selectedPurposes, $selectedBundles, $selectedStatuses, $usageScope): void {
    echo '<input type="hidden" name="return_usage" value="' . myronEscape($usageScope) . '">' . "\n";
    foreach ($selectedPurposes as $value) {
        echo '<input type="hidden" name="return_purpose[]" value="' . myronEscape((string) $value) . '">' . "\n";
    }
    foreach ($selectedBundles as $value) {
        echo '<input type="hidden" name="return_bundle[]" value="' . myronEscape((string) $value) . '">' . "\n";
    }
    foreach ($selectedStatuses as $value) {
        echo '<input type="hidden" name="return_status[]" value="' . myronEscape((string) $value) . '">' . "\n";
    }
};

myronRenderAdminShellStart($currentUser, [
    'title' => 'Template Manager',
    'titleContext' => 'Templates',
    'activeItem' => 'templates-manager',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs($isDetailMode ? [
      ['label' => 'Design', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Template Studio', 'href' => myronBuildAdminUrl('design.templateStudioSiteTemplates')],
      ['label' => 'Templates', 'href' => myronBuildAdminUrl('design.templatesManager')],
      ['label' => 'Template'],
  ] : [
      ['label' => 'Design', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Template Studio', 'href' => myronBuildAdminUrl('design.templateStudioSiteTemplates')],
      ['label' => 'Templates'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title"><?= myronEscape($isDetailMode && is_array($selectedTemplate) ? (string) ($selectedTemplate['name'] ?? $selectedTemplateId) : 'Template Manager') ?></h1>
  </div>
  <p class="mc-workspace__subtitle"><?= $isDetailMode ? 'Inspect the rendered template and manage template metadata, runtime drafts, and section composition from side sheets.' : 'Manage page templates through table discovery, viewer-first inspection, and runtime-only section composition controls.' ?></p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <?php if (!$isDetailMode): ?>
    <section class="sg-section mc-component-filter mc-inspection-filters" data-mc-live-filter>
      <div class="mc-filter-group" role="group" aria-label="Usage scope">
        <span class="mc-filter-group__label">Usage Scope</span>
        <div class="mc-filter-pill-row">
          <a class="sg-pill mc-filter-pill<?= $usageScope === 'current' ? ' sg-pill--active' : '' ?>" href="<?= myronEscape($scopeUrl('current')) ?>" aria-pressed="<?= $usageScope === 'current' ? 'true' : 'false' ?>">Current Site</a>
          <a class="sg-pill mc-filter-pill<?= $usageScope === 'library' ? ' sg-pill--active' : '' ?>" href="<?= myronEscape($scopeUrl('library')) ?>" aria-pressed="<?= $usageScope === 'library' ? 'true' : 'false' ?>">Library</a>
        </div>
      </div>

      <div class="mc-filter-group" role="group" aria-label="Purpose filters" data-mc-filter-group data-mc-filter-param="purpose">
        <span class="mc-filter-group__label">Purpose</span>
        <div class="mc-filter-pill-row">
          <button class="sg-pill mc-filter-pill<?= $selectedPurposes === [] ? ' sg-pill--active' : '' ?>" type="button" data-mc-filter-all aria-pressed="<?= $selectedPurposes === [] ? 'true' : 'false' ?>">All</button>
          <?php foreach ($purposeOptions as $purposeKey => $purposeLabel): ?>
          <button class="sg-pill mc-filter-pill<?= in_array((string) $purposeKey, $selectedPurposes, true) ? ' sg-pill--active' : '' ?>" type="button" data-mc-filter-value="<?= myronEscape((string) $purposeKey) ?>" aria-pressed="<?= in_array((string) $purposeKey, $selectedPurposes, true) ? 'true' : 'false' ?>"><?= myronEscape((string) $purposeLabel) ?></button>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="mc-filter-group" role="group" aria-label="Bundle filters" data-mc-filter-group data-mc-filter-param="bundle">
        <span class="mc-filter-group__label">Site Type</span>
        <div class="mc-filter-pill-row">
          <button class="sg-pill mc-filter-pill<?= $selectedBundles === [] ? ' sg-pill--active' : '' ?>" type="button" data-mc-filter-all aria-pressed="<?= $selectedBundles === [] ? 'true' : 'false' ?>">All</button>
          <?php foreach ($bundleOptions as $bundleOption => $bundleLabel): ?>
          <button class="sg-pill mc-filter-pill<?= in_array((string) $bundleOption, $selectedBundles, true) ? ' sg-pill--active' : '' ?>" type="button" data-mc-filter-value="<?= myronEscape((string) $bundleOption) ?>" aria-pressed="<?= in_array((string) $bundleOption, $selectedBundles, true) ? 'true' : 'false' ?>"><?= myronEscape((string) $bundleLabel) ?></button>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="mc-filter-group" role="group" aria-label="Availability and Status filters" data-mc-filter-group data-mc-filter-param="status">
        <span class="mc-filter-group__label">Availability / Status</span>
        <div class="mc-filter-pill-row">
          <button class="sg-pill mc-filter-pill<?= $selectedStatuses === [] ? ' sg-pill--active' : '' ?>" type="button" data-mc-filter-all aria-pressed="<?= $selectedStatuses === [] ? 'true' : 'false' ?>">All</button>
          <?php foreach (array_map('strval', array_keys($statusOptions)) as $statusOption): ?>
          <button class="sg-pill mc-filter-pill<?= in_array($statusOption, $selectedStatuses, true) ? ' sg-pill--active' : '' ?>" type="button" data-mc-filter-value="<?= myronEscape($statusOption) ?>" aria-pressed="<?= in_array($statusOption, $selectedStatuses, true) ? 'true' : 'false' ?>"><?= myronEscape($statusLabelForKey($statusOption)) ?></button>
          <?php endforeach; ?>
        </div>
      </div>
    </section>

    <section class="sg-section">
      <div class="mc-template-browser__meta" role="status">
        <span class="sg-pill" data-mc-filter-count data-mc-filter-count-label="matching"><?= myronEscape((string) count($templateRows)) ?> matching</span>
        <span class="sg-pill"><?= myronEscape((string) count($templateRows)) ?> <?= $usageScope === 'library' ? 'library templates' : 'current-site templates' ?></span>
      </div>
      <div class="sg-status" role="status" data-mc-filter-empty hidden>No templates match the current filters.</div>

	      <div class="mc-page-grid" role="table" aria-label="Design template manager" data-mc-sortable-grid>
	        <div class="mc-page-grid__row mc-page-grid__row--head" role="row">
	          <span role="columnheader" data-mc-sort-key="template"><button class="mc-page-grid__sort" type="button">Template</button></span>
	          <span role="columnheader" data-mc-sort-key="purpose"><button class="mc-page-grid__sort" type="button">Purpose</button></span>
	          <span role="columnheader" data-mc-sort-key="site"><button class="mc-page-grid__sort" type="button">Site Type</button></span>
	          <span role="columnheader" data-mc-sort-key="sections" data-mc-sort-type="number"><button class="mc-page-grid__sort" type="button">Body Sections</button></span>
	          <span role="columnheader" data-mc-sort-key="status"><button class="mc-page-grid__sort" type="button">Status</button></span>
	          <span role="columnheader">Actions</span>
	        </div>
        <?php foreach ($templateRows as $template): ?>
        <?php
          $templateId = (string) ($template['id'] ?? '');
	          $purpose = MyronTemplateDefinitionRepository::templatePurposeForTemplateId($templateId);
	          $registry = is_array($template['_registry'] ?? null) ? $template['_registry'] : [];
	          $bundleId = (string) ($registry['bundleId'] ?? $template['bundleId'] ?? '');
	          $siteTypeLabel = $siteTypeLabelForBundle($bundleId);
	          $status = MyronTemplateDefinitionRepository::remediationStatusForTemplate($template);
	          $templateAvailability = $availability[$templateId] ?? ['available' => false, 'status' => 'Inactive bundle'];
	          $availabilityKey = (bool) ($templateAvailability['available'] ?? false) ? 'available' : 'inactive';
	          $runtimeDraft = isset($runtimeTemplatesBySource[$templateId]) && $runtimeTemplatesBySource[$templateId] !== [];
	          $bodySectionCount = (int) ($registry['sectionCount'] ?? count(MyronTemplateDefinitionRepository::bodySectionsForRecord($template)));
	        ?>
	        <div
            class="mc-page-grid__row"
            role="row"
            data-mc-filter-row
            data-filter-purpose="<?= myronEscape((string) $purpose['key']) ?>"
            data-filter-bundle="<?= myronEscape($bundleId) ?>"
            data-filter-status="<?= myronEscape($availabilityKey . '||' . $status) ?>"
            data-sort-template="<?= myronEscape((string) ($template['name'] ?? $templateId) . ' ' . $templateId) ?>"
            data-sort-purpose="<?= myronEscape((string) $purpose['label']) ?>"
            data-sort-site="<?= myronEscape($siteTypeLabel . ' ' . $bundleId . ' ' . (string) ($registry['siteType'] ?? $template['siteType'] ?? '')) ?>"
            data-sort-sections="<?= myronEscape((string) $bodySectionCount) ?>"
            data-sort-status="<?= myronEscape($statusLabelForKey($availabilityKey) . ' ' . $statusLabelForKey($status) . ($runtimeDraft ? ' runtime draft' : '')) ?>"
          >
	          <span class="mc-page-grid__cell mc-page-grid__cell--name" role="cell">
	            <span class="mc-page-grid__name"><?= myronEscape((string) ($template['name'] ?? $templateId)) ?></span>
	            <span class="mc-page-grid__subtle"><code><?= myronEscape($templateId) ?></code></span>
	          </span>
	          <span class="mc-page-grid__cell" role="cell"><?= myronEscape((string) $purpose['label']) ?></span>
	          <span class="mc-page-grid__cell" role="cell">
	            <?= myronEscape($siteTypeLabel) ?>
	            <span class="mc-page-grid__subtle"><?= myronEscape((string) ($registry['siteType'] ?? $template['siteType'] ?? '')) ?></span>
	          </span>
	          <span class="mc-page-grid__cell" role="cell"><?= myronEscape((string) $bodySectionCount) ?></span>
	          <span class="mc-page-grid__cell" role="cell">
	            <span class="sg-pill <?= $availabilityKey === 'available' ? 'sg-pill--active' : 'sg-pill--secondary' ?>"><?= myronEscape($statusLabelForKey($availabilityKey)) ?></span>
	            <span class="sg-pill <?= $status === 'governed' ? 'sg-pill--active' : 'sg-pill--secondary' ?>"><?= myronEscape($statusLabelForKey($status)) ?></span>
	            <?php if ($runtimeDraft): ?><span class="sg-pill sg-pill--active">runtime draft</span><?php endif; ?>
	          </span>
          <span class="mc-page-grid__cell mc-page-grid__cell--actions" role="cell">
            <a class="sg-button sg-button--secondary" href="<?= myronEscape($templateDetailUrl($templateId)) ?>">Open</a>
          </span>
        </div>
        <?php endforeach; ?>
      </div>
    </section>
    <?php else: ?>

    <section class="sg-section mc-template-manager-viewer" data-myron-template-manager-viewer data-myron-template-main-viewer>
      <?php if (!is_array($selectedTemplate) || !is_array($selectedPreviewPage)): ?>
      <div class="mc-editor-toolbar">
        <div class="mc-editor-toolbar__summary">
          <span class="sg-pill sg-pill--secondary">Template unavailable</span>
          <span class="mc-editor-toolbar__meta"><code><?= myronEscape($selectedTemplateId) ?></code></span>
        </div>
        <div class="mc-editor-toolbar__actions">
          <a class="sg-button sg-button--secondary" href="<?= myronEscape($backToTemplatesUrl) ?>">Back to Templates</a>
        </div>
      </div>
      <div class="sg-status" role="status">The selected template could not be loaded.</div>
      <?php else: ?>
      <div class="mc-editor-toolbar">
        <div class="mc-editor-toolbar__summary">
          <span class="sg-pill"><?= myronEscape((string) ($selectedSurface['ownershipState'] ?? 'packaged-definition')) ?></span>
          <span class="mc-editor-toolbar__meta"><code><?= myronEscape($selectedTemplateId) ?></code></span>
        </div>
        <div class="mc-editor-toolbar__actions">
          <a class="sg-button sg-button--secondary" href="<?= myronEscape($backToTemplatesUrl) ?>">Back to Templates</a>
          <button class="sg-button sg-button--secondary" type="button" data-mc-sidesheet-open="template-info-sheet">Template Info</button>
	          <button class="sg-button sg-button--secondary" type="button" data-mc-sidesheet-open="template-composition-sheet">Sections</button>
          <button class="sg-button sg-button--secondary" type="button" data-mc-sidesheet-open="template-section-content-sheet" data-mc-visual-section-editor-trigger>Section Content</button>
          <button class="sg-button sg-button--secondary" type="button" data-mc-sidesheet-open="template-section-design-sheet" data-mc-visual-section-editor-trigger>Section Design</button>
          <?php if ($selectedIsCustomSiteTemplate && !$selectedIsAvailablePageTemplate): ?>
          <form method="post" class="sg-inline-form">
            <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
            <input type="hidden" name="source_template_id" value="<?= myronEscape($selectedTemplateId) ?>">
            <?php $renderReturnFilterInputs(); ?>
            <button class="sg-button sg-button--primary" type="submit" name="action" value="make-custom-template-available">Make Available as Page Template</button>
          </form>
          <?php endif; ?>
          <a class="sg-button sg-button--secondary" href="<?= myronEscape($previewUrl) ?>" target="_blank" rel="noreferrer">Open Preview</a>
        </div>
      </div>
	      <div class="mc-editor-viewer__canvas mc-template-manager-viewer__canvas mc-editor-visual-canvas" data-myron-template-rendered-viewer data-mc-visual-editor-canvas data-source-template-id="<?= myronEscape($selectedTemplateId) ?>">
	        <div data-mc-visual-editor-preview>
	        <?= myronDefinitionTemplateRenderer()->renderPublishedPage($selectedPreviewPage, myronPublicBasePath(), [], MyronCustomCssRepository::CONTEXT_ADMIN_PREVIEW) . "\n" ?>
	        </div>
	      </div>
	      <?php endif; ?>
	    </section>

    <?php if (is_array($selectedTemplate)): ?>
    <?php ob_start(); ?>
    <?php
      $assignedNavigationId = is_array($selectedChromeAssignment) ? trim((string) ($selectedChromeAssignment['navigation_design_id'] ?? '')) : '';
      $assignedFooterVariant = is_array($selectedChromeAssignment) ? trim((string) ($selectedChromeAssignment['footer_variant_id'] ?? '')) : '';
      $footerSelectedValue = $assignedFooterVariant !== ''
          ? $assignedFooterVariant
          : ($selectedFooterChromeSeed !== '' ? 'inherit_seed' : 'inherit_site');
    ?>
    <form method="post" class="sg-form-grid mc-template-chrome-assignment-form">
      <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
      <input type="hidden" name="source_template_id" value="<?= myronEscape($selectedTemplateId) ?>">
      <?php $renderReturnFilterInputs(); ?>
      <section class="sg-card mc-template-chrome-assignment-slot">
        <h3 class="sg-card__title">Navigation</h3>
        <label class="sg-field">
          <span class="sg-field__label">Navigation version</span>
          <select class="sg-field__control" name="navigation_design_id">
            <option value=""<?= $assignedNavigationId === '' ? ' selected' : '' ?>>Use site default (<?= myronEscape((string) ($defaultNavigationDesign['name'] ?? 'Primary')) ?>)</option>
            <?php foreach ($activatedNavigationVersions as $version): ?>
            <?php $versionId = (string) ($version['id'] ?? ''); ?>
            <option value="<?= myronEscape($versionId) ?>"<?= $assignedNavigationId === $versionId ? ' selected' : '' ?>><?= myronEscape((string) ($version['name'] ?? 'Navigation')) ?></option>
            <?php endforeach; ?>
          </select>
          <span class="mc-footer-chrome-seed-hint">When set to a specific version, this template overrides the site default.</span>
        </label>
      </section>

    <dl class="sg-definition-list">
      <div class="sg-definition-list__row">
        <dt>Template Key</dt>
        <dd><code><?= myronEscape($selectedTemplateId) ?></code></dd>
      </div>
      <div class="sg-definition-list__row">
        <dt>Source Authority</dt>
        <dd><?= myronEscape((string) ($selectedSurface['sourceAuthority'] ?? 'packaged-template-definition')) ?></dd>
      </div>
      <div class="sg-definition-list__row">
        <dt>Chrome Declaration</dt>
        <dd><?= myronEscape((string) ($selectedSurface['chromeSummary'] ?? '')) ?></dd>
      </div>
      <div class="sg-definition-list__row">
        <dt>Runtime Usage</dt>
        <dd><?= is_array($selectedRuntimeTemplate) ? 'Editable runtime template draft exists.' : 'No runtime draft exists. Packaged definition is read-only.' ?></dd>
      </div>
      <div class="sg-definition-list__row">
        <dt>Source Path</dt>
        <dd><code><?= myronEscape((string) ($selectedTemplate['_registry']['sourcePath'] ?? 'unknown')) ?></code></dd>
      </div>
    </dl>
      <section class="sg-card mc-template-chrome-assignment-slot">
        <h3 class="sg-card__title">Footer</h3>
        <label class="sg-field">
          <span class="sg-field__label">Footer variant</span>
          <select class="sg-field__control" name="footer_variant_id">
            <option value="inherit_site"<?= $footerSelectedValue === 'inherit_site' ? ' selected' : '' ?>>Use site default (<?= myronEscape((string) ($defaultFooterDesign['variant_id'] ?? 'footer.standard')) ?>)</option>
            <?php if ($selectedFooterChromeSeed !== ''): ?>
            <option value="inherit_seed"<?= $footerSelectedValue === 'inherit_seed' ? ' selected' : '' ?>>Use template chrome (<?= myronEscape($selectedFooterChromeSeed) ?>)</option>
            <?php endif; ?>
            <?php foreach ($activatedFooterVariants as $footer): ?>
            <?php $variantId = (string) ($footer['variant_id'] ?? ''); ?>
            <option value="<?= myronEscape($variantId) ?>"<?= $footerSelectedValue === $variantId ? ' selected' : '' ?>><?= myronEscape($footerVariantLabels[$variantId] ?? $variantId) ?></option>
            <?php endforeach; ?>
          </select>
          <?php if ($selectedFooterChromeSeed !== ''): ?>
          <span class="mc-footer-chrome-seed-hint">Use template chrome preserves the packaged chrome.footer.variant seed until a specific override is selected.</span>
          <?php endif; ?>
          <span class="mc-footer-chrome-seed-hint">When set to a specific variant, this template overrides the site default.</span>
        </label>
      </section>
      <div class="sg-card__actions">
        <button class="sg-button sg-button--primary" type="submit" name="action" value="update-template-chrome-assignment">Update Chrome Assignment</button>
      </div>
    </form>
    <?php if (!is_array($selectedRuntimeTemplate)): ?>
    <form method="post" class="sg-card__actions">
      <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
      <input type="hidden" name="source_template_id" value="<?= myronEscape($selectedTemplateId) ?>">
      <?php $renderReturnFilterInputs(); ?>
      <button class="sg-button sg-button--primary" type="submit" name="action" value="create-runtime-draft">Create Editable Runtime Draft</button>
    </form>
    <?php endif; ?>
    <?php if ($selectedIsCustomSiteTemplate && myronUserCanManageDesign($currentUser)): ?>
    <section class="sg-card mc-template-danger-zone">
      <h3 class="sg-card__title">Delete Custom Site Template</h3>
      <p class="sg-card__text">Delete this operator-owned architectural template if it is not being used by any pages. Packaged Site Templates cannot be deleted.</p>
      <form method="post" class="sg-card__actions">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="source_template_id" value="<?= myronEscape($selectedTemplateId) ?>">
        <?php $renderReturnFilterInputs(); ?>
        <button class="sg-button sg-button--secondary" type="submit" name="action" value="delete-custom-site-template">Delete Custom Site Template</button>
      </form>
    </section>
    <?php endif; ?>
    <?php $templateInfoBody = (string) ob_get_clean(); ?>
    <?php myronRenderAdminSidesheet('template-info-sheet', 'Template Information', $templateInfoBody, [
        'description' => 'Template metadata, source authority, chrome, and runtime usage.',
        'size' => 'lg',
    ]); ?>

    <?php ob_start(); ?>
    <?php $sectionContentReadOnly = !is_array($selectedRuntimeTemplate); ?>
    <?php if ($sectionContentReadOnly): ?>
    <div class="sg-status" role="status" data-myron-section-content-readonly="true">
      Packaged template section content is read-only until an editable runtime draft exists.
      <form method="post" class="sg-inline-form">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="source_template_id" value="<?= myronEscape($selectedTemplateId) ?>">
        <?php $renderReturnFilterInputs(); ?>
        <button class="sg-button sg-button--primary" type="submit" name="action" value="create-runtime-draft">Create Editable Runtime Draft</button>
      </form>
    </div>
    <?php endif; ?>
    <form method="post" class="mc-editor-section-tree" data-mc-visual-section-panels data-myron-template-section-content>
      <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
      <input type="hidden" name="source_template_id" value="<?= myronEscape($selectedTemplateId) ?>">
      <?php $renderReturnFilterInputs(); ?>
      <div class="sg-status" role="status" data-mc-visual-section-empty>Select a section in the rendered template to manage its defaults.</div>
      <fieldset class="mc-editor-section-tree__fieldset"<?= $sectionContentReadOnly ? ' disabled' : '' ?>>
      <?php foreach ($selectedSections as $sectionNode): ?>
      <?php if (is_array($sectionNode)): ?>
      <?php
        $editableFields = is_array($sectionNode['editableFields'] ?? null) ? $sectionNode['editableFields'] : [];
        $repeatableGroups = is_array($sectionNode['repeatableGroups'] ?? null) ? $sectionNode['repeatableGroups'] : [];
        $instanceKey = (string) ($sectionNode['instanceKey'] ?? '');
      ?>
      <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($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' ? 'Template default editable' : 'Inspect only' ?></span>
        </div>
        <?php if ($editableFields === [] && $repeatableGroups === []): ?>
        <p class="sg-section__subtitle">This section is visible in the template and is inspect-only until Design allows content editing.</p>
        <?php else: ?>
        <?php if ($editableFields !== []): ?>
        <div class="sg-form-grid">
          <?php foreach ($editableFields as $field): ?>
          <?php if (is_array($field)): ?>
	          <?php
	            $fieldKey = (string) ($field['key'] ?? '');
	            $inputName = 'section_content[' . $instanceKey . '][' . $fieldKey . ']';
	          ?>
          <?= myronRenderSectionContentFieldControl($field, $inputName, (string) ($field['value'] ?? ''), $availableImageFiles) ?>
          <?php endif; ?>
          <?php endforeach; ?>
        </div>
        <?php endif; ?>
        <?php foreach ($repeatableGroups as $group): ?>
        <?php if (is_array($group)): ?>
        <?= myronRenderSectionContentRepeaterGroup($group, $instanceKey, $availableImageFiles) ?>
        <?php endif; ?>
        <?php endforeach; ?>
        <?php endif; ?>
      </section>
      <?php endif; ?>
      <?php endforeach; ?>
      <div class="sg-card__actions">
        <button class="sg-button sg-button--primary" type="submit" name="action" value="update-template-section-content"<?= $sectionContentReadOnly ? ' disabled' : '' ?>>Save Template Defaults</button>
      </div>
      </fieldset>
    </form>
    <?php $templateSectionContentBody = (string) ob_get_clean(); ?>
	    <?php myronRenderAdminSidesheet('template-section-content-sheet', 'Section Content', $templateSectionContentBody, [
	        'description' => 'Design-owned default content for this runtime template draft.',
	        'size' => 'xl',
	    ]); ?>

	    <?php ob_start(); ?>
	    <div class="sg-status" role="status" data-mc-visual-section-empty>Select a section in the rendered template to manage design overrides.</div>
	    <?php $sectionDesignReadOnly = !is_array($selectedRuntimeTemplate); ?>
	    <?php if ($sectionDesignReadOnly): ?>
	    <div class="sg-status" role="status" data-myron-section-design-readonly="true">
	      Packaged template section design is read-only until an editable runtime draft exists.
	      <form method="post" class="sg-inline-form">
	        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
	        <input type="hidden" name="source_template_id" value="<?= myronEscape($selectedTemplateId) ?>">
	        <?php $renderReturnFilterInputs(); ?>
	        <button class="sg-button sg-button--primary" type="submit" name="action" value="create-runtime-draft">Create Editable Runtime Draft</button>
	      </form>
	    </div>
	    <?php endif; ?>
	    <div class="mc-editor-section-tree" data-mc-visual-section-panels data-myron-template-section-design>
	      <?php foreach ($selectedSections as $sectionNode): ?>
      <?php if (is_array($sectionNode)): ?>
      <?php
        $instanceKey = (string) ($sectionNode['instanceKey'] ?? '');
        $position = (int) ($sectionNode['position'] ?? 0);
        $editableTokens = array_values(array_filter(is_array($sectionNode['editableTokens'] ?? null) ? $sectionNode['editableTokens'] : [], 'is_array'));
        $tokenOverrides = is_array($sectionNode['tokenOverrides'] ?? null) ? $sectionNode['tokenOverrides'] : [];
        $componentId = (string) ($sectionNode['componentId'] ?? '');
        $isHeroMediaSection = in_array($componentId, ['hero-simple', 'hero-with-cta'], true);
        $mediaLayout = $normalizeHeroMediaLayout($sectionNode['mediaLayout'] ?? 'auto');
        $sectionKey = (string) ($sectionNode['sectionKey'] ?? '');
        $matchingVariants = array_values(array_filter($savedSectionVariants, static function (array $variant) use ($componentId, $sectionKey): bool {
            $variantComponent = (string) ($variant['componentId'] ?? '');
            $variantSection = (string) ($variant['sectionKey'] ?? '');
            return $variantComponent === $componentId && ($variantSection === '' || $sectionKey === '' || $variantSection === $sectionKey);
        }));
      ?>
	      <section class="mc-editor-section-node" data-editor-section-node data-mc-visual-section-panel data-myron-section-design-readonly="<?= $sectionDesignReadOnly ? 'true' : 'false' ?>" data-section-instance-key="<?= myronEscape($instanceKey) ?>" data-section-key="<?= myronEscape($sectionKey) ?>" data-component-id="<?= myronEscape($componentId) ?>">
        <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['sectionUuid'] ?? '')) ?></code> · <?= myronEscape($componentId) ?></p>
          </div>
          <span class="sg-pill"><?= myronEscape((string) count($editableTokens)) ?> editable tokens</span>
        </div>
        <form method="post" class="sg-form-grid">
          <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
          <input type="hidden" name="source_template_id" value="<?= myronEscape($selectedTemplateId) ?>">
          <input type="hidden" name="position" value="<?= myronEscape((string) $position) ?>">
          <?php $renderReturnFilterInputs(); ?>
          <?php if ($editableTokens !== []): ?>
	          <fieldset class="sg-fieldset"<?= $sectionDesignReadOnly ? ' disabled' : '' ?>>
            <legend>Token Overrides</legend>
            <div class="sg-form-grid">
              <?php foreach ($editableTokens as $token): ?>
              <?php
                $cssVar = (string) ($token['cssVar'] ?? $token['token'] ?? '');
                if ($cssVar === '') {
                    continue;
                }
                $controlType = (string) ($token['controlType'] ?? 'text');
                $options = array_values(array_map('strval', is_array($token['options'] ?? null) ? $token['options'] : []));
                $value = (string) ($tokenOverrides[$cssVar] ?? '');
              ?>
              <label class="sg-field">
                <span class="sg-field__label"><?= myronEscape((string) ($token['label'] ?? $cssVar)) ?></span>
                <?= myronTokenControlRenderer()->render('token_overrides[' . $cssVar . ']', $value, $controlType, $cssVar, $options) . "\n" ?>
                <span class="mc-page-grid__subtle"><code><?= myronEscape($cssVar) ?></code> · <?= myronEscape($controlType) ?></span>
              </label>
              <?php endforeach; ?>
            </div>
          </fieldset>
          <?php endif; ?>
          <?php if ($isHeroMediaSection): ?>
          <label class="sg-field">
            <span class="sg-field__label">Hero Media Layout</span>
            <select class="sg-field__control" name="media_layout"<?= $sectionDesignReadOnly ? ' disabled' : '' ?>>
              <?php foreach ([
                  'auto' => 'Auto from variant',
                  'split' => 'Split image',
                  'full-bleed' => 'Full bleed image',
                  'full-width' => 'Full width image',
              ] as $layoutValue => $layoutLabel): ?>
              <option value="<?= myronEscape($layoutValue) ?>"<?= $mediaLayout === $layoutValue ? ' selected' : '' ?>><?= myronEscape($layoutLabel) ?></option>
              <?php endforeach; ?>
            </select>
            <span class="mc-page-grid__subtle">Controls public image <code>sizes</code> and large hero rendition candidates.</span>
          </label>
          <?php endif; ?>
          <label class="sg-field">
            <span class="sg-field__label">Section Custom CSS</span>
	            <textarea class="sg-field__control sg-field__control--code" name="custom_css" rows="8" spellcheck="false"<?= $sectionDesignReadOnly ? ' readonly' : '' ?>><?= myronEscape((string) ($sectionNode['customCss'] ?? '')) ?></textarea>
	          </label>
	          <div class="sg-card__actions">
	            <button class="sg-button sg-button--primary" type="submit" name="action" value="update-section-design"<?= $sectionDesignReadOnly ? ' disabled' : '' ?>>Save Section Design</button>
	          </div>
	        </form>
	        <div class="sg-card__actions">
          <form method="post" class="sg-inline-form">
            <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
            <input type="hidden" name="source_template_id" value="<?= myronEscape($selectedTemplateId) ?>">
            <input type="hidden" name="position" value="<?= myronEscape((string) $position) ?>">
            <?php $renderReturnFilterInputs(); ?>
	            <input class="sg-field__control" type="text" name="variant_name" placeholder="Variant name"<?= $sectionDesignReadOnly ? ' disabled' : '' ?>>
	            <button class="sg-button sg-button--secondary" type="submit" name="action" value="save-section-variant"<?= $sectionDesignReadOnly ? ' disabled' : '' ?>>Save Current as Variant</button>
          </form>
          <?php if ($matchingVariants !== []): ?>
          <form method="post" class="sg-inline-form">
            <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
            <input type="hidden" name="source_template_id" value="<?= myronEscape($selectedTemplateId) ?>">
            <input type="hidden" name="position" value="<?= myronEscape((string) $position) ?>">
            <?php $renderReturnFilterInputs(); ?>
            <select class="sg-field__control" name="section_variant_id"<?= $sectionDesignReadOnly ? ' disabled' : '' ?>>
              <?php foreach ($matchingVariants as $variant): ?>
              <option value="<?= myronEscape((string) ($variant['id'] ?? '')) ?>"><?= myronEscape((string) ($variant['name'] ?? 'Variant')) ?></option>
              <?php endforeach; ?>
            </select>
            <button class="sg-button sg-button--secondary" type="submit" name="action" value="apply-section-variant"<?= $sectionDesignReadOnly ? ' disabled' : '' ?>>Apply Variant</button>
          </form>
          <?php endif; ?>
        </div>
      </section>
      <?php endif; ?>
      <?php endforeach; ?>
    </div>
    <?php $templateSectionDesignBody = (string) ob_get_clean(); ?>
	    <?php myronRenderAdminSidesheet('template-section-design-sheet', 'Section Design', $templateSectionDesignBody, [
	        'description' => 'Per-section custom CSS, token overrides, and saved section variant actions.',
	        'size' => 'xl',
	    ]); ?>

	    <?php ob_start(); ?>
    <?php if (is_array($selectedRuntimeTemplate)): ?>
    <form method="post" id="mc-template-section-reorder-form" data-template-section-reorder-form>
      <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
      <input type="hidden" name="source_template_id" value="<?= myronEscape($selectedTemplateId) ?>">
      <?php $renderReturnFilterInputs(); ?>
      <input type="hidden" name="action" value="reorder-sections">
    </form>
    <?php endif; ?>
    <div class="mc-editor-section-tree mc-template-section-composition" data-myron-template-composition data-template-section-dnd-list>
      <?php foreach ($selectedSections as $sectionNode): ?>
      <?php if (is_array($sectionNode)): ?>
      <?php $sectionPosition = (int) ($sectionNode['position'] ?? 0); ?>
	      <section
            class="mc-editor-section-node mc-template-section-composition__item"
            data-template-section-node
            data-template-section-drag-item
            data-template-section-drag-position="<?= myronEscape((string) $sectionPosition) ?>"
            data-position="<?= myronEscape((string) $sectionPosition) ?>"
            <?= is_array($selectedRuntimeTemplate) ? 'draggable="true"' : '' ?>
          >
	        <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['componentId'] ?? '')) ?></p>
	          </div>
	          <div class="mc-editor-section-node__badges">
	            <?php if (is_array($selectedRuntimeTemplate)): ?><span class="sg-pill mc-template-section-composition__handle" aria-hidden="true">Drag</span><?php endif; ?>
	            <span class="sg-pill"><?= myronEscape((string) ($sectionNode['sourceAuthority'] ?? 'template-composition')) ?></span>
	            <span class="sg-pill <?= (string) ($sectionNode['editability'] ?? '') === 'editable' ? 'sg-pill--active' : 'sg-pill--secondary' ?>"><?= (string) ($sectionNode['editability'] ?? '') === 'editable' ? 'Content editable' : 'Inspect only' ?></span>
	          </div>
	        </div>
	        <?php if (is_array($selectedRuntimeTemplate)): ?>
	        <div class="sg-card__actions">
	          <form method="post">
	            <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
	            <input type="hidden" name="source_template_id" value="<?= myronEscape($selectedTemplateId) ?>">
	            <?php $renderReturnFilterInputs(); ?>
	            <input type="hidden" name="position" value="<?= myronEscape((string) ($sectionNode['position'] ?? 0)) ?>">
	            <input type="hidden" name="content_editable" value="<?= (string) ($sectionNode['editability'] ?? '') === 'editable' ? '0' : '1' ?>">
	            <button class="sg-button sg-button--secondary" type="submit" name="action" value="update-section-editability"><?= (string) ($sectionNode['editability'] ?? '') === 'editable' ? 'Make Inspect Only' : 'Allow Content Editing' ?></button>
	          </form>
	          <form method="post">
	            <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
	            <input type="hidden" name="source_template_id" value="<?= myronEscape($selectedTemplateId) ?>">
            <?php $renderReturnFilterInputs(); ?>
            <input type="hidden" name="position" value="<?= myronEscape((string) ($sectionNode['position'] ?? 0)) ?>">
            <input type="hidden" name="direction" value="up">
            <button class="sg-button sg-button--secondary" type="submit" name="action" value="move-section">Move Up</button>
          </form>
          <form method="post">
            <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
            <input type="hidden" name="source_template_id" value="<?= myronEscape($selectedTemplateId) ?>">
            <?php $renderReturnFilterInputs(); ?>
            <input type="hidden" name="position" value="<?= myronEscape((string) ($sectionNode['position'] ?? 0)) ?>">
            <input type="hidden" name="direction" value="down">
            <button class="sg-button sg-button--secondary" type="submit" name="action" value="move-section">Move Down</button>
          </form>
          <form method="post">
            <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
            <input type="hidden" name="source_template_id" value="<?= myronEscape($selectedTemplateId) ?>">
            <?php $renderReturnFilterInputs(); ?>
            <input type="hidden" name="position" value="<?= myronEscape((string) ($sectionNode['position'] ?? 0)) ?>">
            <button class="sg-button sg-button--secondary" type="submit" name="action" value="duplicate-section">Duplicate</button>
          </form>
          <form method="post" onsubmit="return window.confirm('Remove this section from the runtime template? Existing page-version content will be retained for rollback.');">
            <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
            <input type="hidden" name="source_template_id" value="<?= myronEscape($selectedTemplateId) ?>">
            <?php $renderReturnFilterInputs(); ?>
            <input type="hidden" name="position" value="<?= myronEscape((string) ($sectionNode['position'] ?? 0)) ?>">
            <button class="sg-button sg-button--danger" type="submit" name="action" value="remove-section">Remove</button>
          </form>
        </div>
        <?php endif; ?>
      </section>
      <?php endif; ?>
      <?php endforeach; ?>
    </div>
    <?php if (is_array($selectedRuntimeTemplate)): ?>
    <form method="post" class="mc-template-insert-form mc-template-section-picker" data-template-section-picker>
      <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
      <input type="hidden" name="source_template_id" value="<?= myronEscape($selectedTemplateId) ?>">
      <?php $renderReturnFilterInputs(); ?>
      <label class="sg-field">
        <span class="sg-field__label">Find a section by name</span>
        <input class="sg-field__control" type="search" placeholder="Search section names, keys, or groups" data-template-section-picker-search>
      </label>
      <div class="mc-template-section-picker__groups" data-template-section-picker-list>
        <?php foreach ($bodyGovernedSectionsByGroup as $group => $sectionsForGroup): ?>
        <fieldset class="sg-fieldset mc-template-section-picker__group" data-template-section-picker-group>
          <legend><?= myronEscape(ucwords(str_replace(['-', '_'], ' ', $group))) ?></legend>
          <div class="mc-template-section-picker__rows">
            <?php foreach ($sectionsForGroup as $section): ?>
            <?php
              $sectionKey = (string) ($section['sectionKey'] ?? '');
              $primaryComponents = array_values(array_map('strval', is_array($section['primaryComponents'] ?? null) ? $section['primaryComponents'] : []));
              $primaryComponentId = trim((string) ($primaryComponents[0] ?? ''));
              $hasRenderBridge = $primaryComponentId !== '' && is_array($componentRepository->findComponentById($primaryComponentId));
              $searchText = strtolower(trim((string) ($section['label'] ?? $sectionKey) . ' ' . $sectionKey . ' ' . $group . ' ' . implode(' ', $primaryComponents)));
            ?>
            <label class="mc-template-section-picker__row<?= $hasRenderBridge ? '' : ' is-disabled' ?>" data-template-section-picker-row data-search-text="<?= myronEscape($searchText) ?>">
              <input type="radio" name="section_key" value="<?= myronEscape($sectionKey) ?>" required<?= $hasRenderBridge ? '' : ' disabled' ?>>
              <span>
                <strong><?= myronEscape((string) ($section['label'] ?? $sectionKey)) ?></strong>
                <span><code><?= myronEscape($sectionKey) ?></code> · <?= myronEscape(implode(', ', $primaryComponents)) ?></span>
              </span>
              <span class="sg-pill<?= $hasRenderBridge ? '' : ' sg-pill--secondary' ?>"><?= myronEscape($hasRenderBridge ? (string) ($section['remediationStatus'] ?? 'governed') : 'Needs bridge') ?></span>
            </label>
            <?php endforeach; ?>
          </div>
        </fieldset>
        <?php endforeach; ?>
      </div>
      <label class="sg-field">
        <span class="sg-field__label">Position</span>
        <input class="sg-field__control" type="number" name="insert_at" min="0" max="<?= myronEscape((string) count($selectedSections)) ?>" value="<?= myronEscape((string) count($selectedSections)) ?>">
      </label>
      <button class="sg-button sg-button--primary" type="submit" name="action" value="insert-section">Insert Section</button>
    </form>
    <?php else: ?>
    <div class="sg-status" role="status">Create an editable runtime draft before inserting or reordering sections.</div>
    <?php endif; ?>
    <?php $templateCompositionBody = (string) ob_get_clean(); ?>
    <?php myronRenderAdminSidesheet('template-composition-sheet', 'Template Sections', $templateCompositionBody, [
        'description' => 'Section sequence, insertion, and deterministic reordering for runtime template drafts.',
        'size' => 'lg',
    ]); ?>
    <?php endif; ?>
    <?php endif; ?>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
