<?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();
$sectionRepository = myronSectionRegistryRepository();
$sectionBridgeRepository = myronSectionBridgeRepository();
$customSectionService = myronCustomSectionTemplateActionService();
$componentRepository = myronComponentRegistryRepository();
$currentSiteUsage = myronCurrentSiteUsageReadModel();
$sectionDefaults = myronSectionComponentDefaultsRepository();
$sectionContentDefaults = myronSectionContentDefaultsRepository();
$sectionContentSchema = myronSectionContentSchemaService();
$primitiveRenderer = myronPrimitiveRenderer();
$designEntitlements = myronDesignLibraryEntitlementPolicy();
$availableImageFiles = array_values(array_filter(
    myronFileRepository()->listFiles(),
    static fn (array $file): bool => (bool) ($file['is_image'] ?? false)
));
$rawLibraryUsageIndex = myronSectionUsageService()->usageIndex();
$libraryUsageIndex = $designEntitlements->filterSectionUsageIndex($rawLibraryUsageIndex);
$componentIdSet = array_fill_keys($componentRepository->listComponentIds(), true);
$renderableComponents = array_values(array_filter(
    $componentRepository->listComponents('primitive'),
    static fn (array $component): bool => myronPrimitiveRenderer()->canRender((string) ($component['id'] ?? ''))
));

$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';
};

$queryFromFilters = static function (array $groups, array $types, array $statuses, string $usageScope = 'current'): array {
    $query = [];
    if ($usageScope !== 'current') {
        $query['usage'] = $usageScope;
    }
    if ($groups !== []) {
        $query['group'] = implode(',', array_values(array_map('strval', $groups)));
    }
    if ($types !== []) {
        $query['type'] = implode(',', array_values(array_map('strval', $types)));
    }
    if ($statuses !== []) {
        $query['status'] = implode(',', array_values(array_map('strval', $statuses)));
    }

    return $query;
};

$primaryComponentsFromPost = static function (mixed $value): array {
    $source = is_array($value) ? implode(',', array_map('strval', $value)) : (string) $value;
    $parts = preg_split('/[,\r\n]+/', $source);
    $components = [];
    foreach (is_array($parts) ? $parts : [] as $part) {
        $componentId = trim((string) $part);
        if ($componentId !== '') {
            $components[$componentId] = true;
        }
    }

    return array_keys($components);
};

$defaultEditabilityFromPost = static function (mixed $value): ?int {
    $normalized = trim((string) $value);
    if ($normalized === 'editable') {
        return 1;
    }
    if ($normalized === 'inspect-only') {
        return 0;
    }

    return null;
};

$jsonObjectFromPost = static function (mixed $value, string $label): array {
    if (is_array($value)) {
        return $value;
    }
    $text = trim((string) $value);
    if ($text === '') {
        return [];
    }
    $decoded = json_decode($text, true);
    if (!is_array($decoded)) {
        throw new InvalidArgumentException($label . ' must be valid JSON object syntax.');
    }

    return $decoded;
};

/**
 * @return array{fields:list<array<string,mixed>>,repeaters:list<array<string,mixed>>}
 */
if (!function_exists('myronCustomSectionTemplateDefaultEditingContract')) {
    function myronCustomSectionTemplateDefaultEditingContract(): array
    {
        return [
            'fields' => [
                ['key' => 'headline', 'label' => 'Headline', 'type' => 'text', 'richtext' => true],
                ['key' => 'body', 'label' => 'Body', 'type' => 'textarea', 'richtext' => true],
            ],
            'repeaters' => [],
        ];
    }
}

/**
 * @param array<string,mixed> $defaultContent
 * @param array<string,mixed> $editingContract
 * @return list<array{label:string,key:string,type:string,default:string,required:bool,richtext:bool}>
 */
if (!function_exists('myronCustomSectionTemplateFieldBuilderRows')) {
    function myronCustomSectionTemplateFieldBuilderRows(array $defaultContent, array $editingContract): array
    {
        $fields = is_array($editingContract['fields'] ?? null)
            ? array_values(array_filter($editingContract['fields'], 'is_array'))
            : [];
        if ($fields === []) {
            $fields = myronCustomSectionTemplateDefaultEditingContract()['fields'];
        }

        $rows = [];
        $seen = [];
        foreach ($fields as $field) {
            $key = trim((string) ($field['key'] ?? $field['name'] ?? ''));
            if ($key === '' || isset($seen[$key])) {
                continue;
            }
            $seen[$key] = true;
            $type = strtolower(trim((string) ($field['type'] ?? 'text')));
            if (!in_array($type, ['text', 'textarea', 'url', 'image'], true)) {
                $type = 'text';
            }
            $value = $defaultContent[$key] ?? ($field['default'] ?? '');
            $rows[] = [
                'label' => trim((string) ($field['label'] ?? $field['title'] ?? $key)),
                'key' => $key,
                'type' => $type,
                'default' => is_scalar($value) ? (string) $value : '',
                'required' => filter_var($field['required'] ?? false, FILTER_VALIDATE_BOOL),
                'richtext' => filter_var($field['richtext'] ?? false, FILTER_VALIDATE_BOOL),
            ];
        }

        return $rows !== [] ? $rows : myronCustomSectionTemplateFieldBuilderRows([], myronCustomSectionTemplateDefaultEditingContract());
    }
}

/**
 * @param array<string,mixed> $defaultContent
 * @param array<string,mixed> $editingContract
 */
if (!function_exists('myronRenderCustomSectionTemplateFieldBuilder')) {
    function myronRenderCustomSectionTemplateFieldBuilder(array $defaultContent, array $editingContract): void
    {
    $rows = myronCustomSectionTemplateFieldBuilderRows($defaultContent, $editingContract);
    $defaultContentJson = json_encode($defaultContent, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    $editingJson = json_encode($editingContract !== [] ? $editingContract : myronCustomSectionTemplateDefaultEditingContract(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    $quickFields = [
        ['label' => 'Eyebrow', 'key' => 'eyebrow', 'type' => 'text', 'richtext' => true],
        ['label' => 'Intro', 'key' => 'intro', 'type' => 'textarea', 'richtext' => true],
        ['label' => 'CTA Label', 'key' => 'ctaLabel', 'type' => 'text', 'richtext' => true],
        ['label' => 'CTA Link', 'key' => 'ctaHref', 'type' => 'url', 'richtext' => false],
        ['label' => 'Image', 'key' => 'image', 'type' => 'image', 'richtext' => false],
    ];
    ?>
        <section class="mc-admin-form__section mc-field-builder" aria-label="Section defaults" data-mc-section-field-builder>
          <div class="mc-admin-form__section-header">
            <h3 class="mc-admin-form__section-title">Editable Fields</h3>
            <p class="mc-admin-form__section-description">Choose the content fields editors can change when this section is used on a page.</p>
          </div>
          <div class="mc-field-builder__quick-actions" aria-label="Common editable fields">
            <?php foreach ($quickFields as $field): ?>
            <button
              class="sg-button sg-button--secondary"
              type="button"
              data-mc-section-field-add
              data-label="<?= myronEscape((string) $field['label']) ?>"
              data-key="<?= myronEscape((string) $field['key']) ?>"
              data-type="<?= myronEscape((string) $field['type']) ?>"
              data-richtext="<?= !empty($field['richtext']) ? '1' : '0' ?>"
            >Add <?= myronEscape((string) $field['label']) ?></button>
            <?php endforeach; ?>
            <button class="sg-button sg-button--secondary" type="button" data-mc-section-field-add>Add Custom Field</button>
          </div>
          <div class="mc-field-builder__rows" data-mc-section-field-rows>
            <?php foreach ($rows as $row): ?>
            <div class="mc-field-builder__row" data-mc-section-field-row>
              <label class="sg-field">
                <span class="sg-field__label">Field Label</span>
                <input class="sg-field__control" type="text" value="<?= myronEscape($row['label']) ?>" data-mc-section-field-label>
              </label>
              <label class="sg-field">
                <span class="sg-field__label">Field Key</span>
                <input class="sg-field__control" type="text" value="<?= myronEscape($row['key']) ?>" data-mc-section-field-key>
              </label>
              <label class="sg-field">
                <span class="sg-field__label">Type</span>
                <select class="sg-field__control" data-mc-section-field-type>
                  <?php foreach (['text' => 'Text', 'textarea' => 'Long text', 'url' => 'URL', 'image' => 'Image'] as $value => $label): ?>
                  <option value="<?= myronEscape($value) ?>" <?= $row['type'] === $value ? 'selected' : '' ?>><?= myronEscape($label) ?></option>
                  <?php endforeach; ?>
                </select>
              </label>
              <label class="sg-field">
                <span class="sg-field__label">Initial Content</span>
                <input class="sg-field__control" type="text" value="<?= myronEscape($row['default']) ?>" data-mc-section-field-default>
              </label>
              <label class="sg-field sg-field--checkbox">
                <span class="sg-field__label">Required</span>
                <span class="sg-field__checkbox">
                  <input type="checkbox" value="1" data-mc-section-field-required <?= $row['required'] ? 'checked' : '' ?>>
                  <span>Require a value</span>
                </span>
              </label>
              <label class="sg-field sg-field--checkbox">
                <span class="sg-field__label">Rich Text</span>
                <span class="sg-field__checkbox">
                  <input type="checkbox" value="1" data-mc-section-field-richtext <?= $row['richtext'] ? 'checked' : '' ?>>
                  <span>Use rich-text editor</span>
                </span>
              </label>
              <div class="mc-field-builder__row-actions">
                <button class="sg-button sg-button--secondary" type="button" data-mc-section-field-remove>Remove</button>
              </div>
            </div>
            <?php endforeach; ?>
          </div>
          <details class="sg-fieldset sg-fieldset--collapsible mc-field-builder__advanced">
            <summary class="sg-fieldset__summary">Advanced JSON</summary>
            <div class="mc-admin-form__grid">
              <label class="sg-field">
                <span class="sg-field__label">Default Content JSON</span>
                <textarea class="sg-field__control" name="default_content_json" rows="8" data-mc-section-default-content-json="true"><?= myronEscape($defaultContentJson !== false ? $defaultContentJson : '{}') ?></textarea>
              </label>
              <label class="sg-field">
                <span class="sg-field__label">Editing Contract JSON</span>
                <textarea class="sg-field__control" name="editing_contract_json" rows="10" data-mc-section-editing-contract-json="true"><?= myronEscape($editingJson !== false ? $editingJson : '{"fields":[],"repeaters":[]}') ?></textarea>
              </label>
            </div>
          </details>
        </section>
    <?php
    }
}

$statusOptions = [
    'governed' => 'Governed',
    'live' => 'Live',
    'needs mapping' => 'Needs Mapping',
    'operator-owned' => 'Operator Owned',
    'review required' => 'Review Required',
    'runtime override' => 'Runtime Override',
];

$editabilityLabel = static function (mixed $value): string {
    if ((string) $value === '1') {
        return 'Editable';
    }
    if ((string) $value === '0') {
        return 'Inspect only';
    }

    return 'Inherit';
};

$usageScope = $usageScopeFromValue($_REQUEST['return_usage'] ?? $_GET['usage'] ?? 'current');

$assertSectionAvailable = static function (string $sectionKey) use ($sectionRepository, $designEntitlements, $rawLibraryUsageIndex): void {
    $sectionKey = trim($sectionKey);
    if ($sectionKey === '') {
        return;
    }

    $section = $sectionRepository->findSectionByKey($sectionKey);
    if (!is_array($section)) {
        return;
    }

    if ($designEntitlements->filterSectionRows([$section], $rawLibraryUsageIndex) !== []) {
        return;
    }

    throw new InvalidArgumentException('This section is not available for the current license.');
};

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

        if ($action === 'update-section-defaults') {
            $componentId = trim((string) ($_POST['component_id'] ?? ''));
            $variant = trim((string) ($_POST['variant'] ?? ''));
            if ($componentId === '' || !isset($componentIdSet[$componentId])) {
                throw new InvalidArgumentException('Choose a valid live render component.');
            }

            $postedSectionKey = trim((string) ($_POST['section_key'] ?? ''));
            $assertSectionAvailable($postedSectionKey);
            $content = myronNormalizeSectionContentInput($_POST['default_content'] ?? []);
            $editability = $defaultEditabilityFromPost($_POST['default_editability'] ?? 'inherit');

            // APO-193 Card 8 — admin form path + PATCH /api/v1/design/section-defaults
            // share MyronSectionDefaultsActionService::updateDefaults.
            $callerCtx = myronActionCallerContextForUser($currentUser);
            myronSectionDefaultsActionService()->updateDefaults(
                $componentId,
                $variant,
                $postedSectionKey,
                $content,
                $editability,
                $callerCtx
            );

            $query = $queryFromFilters(
                $filterValues($_POST['return_group'] ?? ''),
                $filterValues($_POST['return_type'] ?? ''),
                $filterValues($_POST['return_status'] ?? ''),
                $usageScopeFromValue($_POST['return_usage'] ?? 'current')
            );
            if ($postedSectionKey !== '') {
                $query['section'] = $postedSectionKey;
            } else {
                $query['component'] = $componentId;
                if ($variant !== '') {
                    $query['variant'] = $variant;
                }
            }
            myronRedirectWithFlash(myronBuildAdminUrl('design.sectionsManager', $query), 'Updated section defaults and flags.', 'success');
        }

        if (in_array($action, ['create-custom-section-template', 'update-custom-section-template'], true)) {
            $callerCtx = myronActionCallerContextForUser($currentUser);
            $editing = $jsonObjectFromPost($_POST['editing_contract_json'] ?? '', 'Editing contract');
            $payload = [
                'sectionKey' => trim((string) ($_POST['custom_section_key'] ?? $_POST['section_key'] ?? '')),
                'label' => trim((string) ($_POST['label'] ?? '')),
                'description' => trim((string) ($_POST['description'] ?? '')),
                'jtbdGroup' => trim((string) ($_POST['jtbd_group'] ?? 'custom')),
                'sectionType' => trim((string) ($_POST['section_type'] ?? 'custom')),
                'primaryComponentId' => trim((string) ($_POST['primary_component_id'] ?? '')),
                'variant' => trim((string) ($_POST['variant'] ?? 'default')),
                'defaultContentEditable' => ($_POST['default_editability'] ?? 'editable') === 'editable',
                'defaultContent' => $jsonObjectFromPost($_POST['default_content_json'] ?? '', 'Default content'),
                'editing' => $editing,
            ];
            $saved = $action === 'create-custom-section-template'
                ? $customSectionService->create($payload, $callerCtx)
                : $customSectionService->update((string) ($_POST['section_key'] ?? ''), $payload, $callerCtx);

            myronRedirectWithFlash(
                myronBuildAdminUrl('design.sectionsManager', ['usage' => 'library', 'section' => (string) ($saved['sectionKey'] ?? '')]),
                $action === 'create-custom-section-template' ? 'Created custom section template.' : 'Updated custom section template.',
                'success'
            );
        }

        if ($action === 'delete-custom-section-template') {
            $customSectionService->delete((string) ($_POST['section_key'] ?? ''));
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.sectionsManager', ['usage' => 'library']),
                'Deleted custom section template.',
                'success'
            );
        }

        if ($action !== 'update-section-bridge') {
            throw new InvalidArgumentException('Unknown section manager action.');
        }

        $sectionKey = trim((string) ($_POST['section_key'] ?? ''));
        $sectionRepository->assertGovernedSectionKey($sectionKey, 'design-sections-manager');
        $assertSectionAvailable($sectionKey);
        if (in_array($sectionKey, MyronSectionRegistryRepository::forbiddenBodySectionKeys(), true)) {
            throw new InvalidArgumentException('Chrome and primitive-only keys cannot be managed as body sections.');
        }

        $primaryComponents = MyronSectionBridgeRepository::normalizePrimaryComponents($primaryComponentsFromPost($_POST['primary_components'] ?? ''));
        foreach ($primaryComponents as $componentId) {
            if (!isset($componentIdSet[$componentId])) {
                throw new InvalidArgumentException('Unknown render component `' . $componentId . '`.');
            }
            if (in_array($componentId, ['header', 'footer'], true)) {
                throw new InvalidArgumentException('Header and footer cannot be used as body-section render components.');
            }
        }

        $remediationStatus = trim((string) ($_POST['remediation_status'] ?? 'governed'));
        if (!isset($statusOptions[$remediationStatus]) || $remediationStatus === 'live') {
            throw new InvalidArgumentException('Choose a valid section readiness status.');
        }

        $sectionBridgeRepository->saveOverride(
            $sectionKey,
            trim((string) ($_POST['label_override'] ?? '')) ?: null,
            trim((string) ($_POST['description_override'] ?? '')) ?: null,
            $primaryComponents,
            $remediationStatus,
            $defaultEditabilityFromPost($_POST['default_editability'] ?? 'inherit'),
            (string) ($currentUser['id'] ?? '')
        );

        $query = $queryFromFilters(
            $filterValues($_POST['return_group'] ?? ''),
            $filterValues($_POST['return_type'] ?? ''),
            $filterValues($_POST['return_status'] ?? ''),
            'library'
        );
        $query['section'] = $sectionKey;
        myronRedirectWithFlash(myronBuildAdminUrl('design.sectionsManager', $query), 'Updated section bridge metadata.', 'success');
    } catch (Throwable $exception) {
        $query = $queryFromFilters(
            $filterValues($_POST['return_group'] ?? ''),
            $filterValues($_POST['return_type'] ?? ''),
            $filterValues($_POST['return_status'] ?? ''),
            $usageScope
        );
        $postedComponentId = trim((string) ($_POST['component_id'] ?? ''));
        $postedSectionKey = trim((string) ($_POST['section_key'] ?? ''));
        if ($postedComponentId !== '') {
            $query['component'] = $postedComponentId;
            $postedVariant = trim((string) ($_POST['variant'] ?? ''));
            if ($postedVariant !== '') {
                $query['variant'] = $postedVariant;
            }
        } elseif ($postedSectionKey !== '') {
            $query['section'] = $postedSectionKey;
        }
        myronRedirectWithFlash(myronBuildAdminUrl('design.sectionsManager', $query), $exception->getMessage(), 'error');
    }
}

$selectedGroups = $filterValues($_GET['group'] ?? '');
$selectedTypes = $filterValues($_GET['type'] ?? '');
$selectedStatuses = $filterValues($_GET['status'] ?? '');
$selectedSectionKey = trim((string) ($_GET['section'] ?? ''));
$isCreateCustomMode = $usageScope === 'library' && $selectedSectionKey === '__new_custom_section__';

$currentRows = $designEntitlements->filterSectionRows($currentSiteUsage->governedSectionInventoryRows(), $rawLibraryUsageIndex);
$libraryRows = $designEntitlements->filterSectionRows($sectionRepository->listSections(), $rawLibraryUsageIndex);
$sectionRows = $usageScope === 'library' ? $libraryRows : $currentRows;
$currentRowsByKey = [];
foreach ($currentRows as $row) {
    $key = trim((string) ($row['sectionKey'] ?? ''));
    if ($key !== '') {
        $currentRowsByKey[$key] = $row;
    }
}
$libraryRowsByKey = [];
foreach ($libraryRows as $row) {
    $key = trim((string) ($row['sectionKey'] ?? ''));
    if ($key !== '') {
        $libraryRowsByKey[$key] = $row;
    }
}

$groupOptions = [];
$typeOptions = [];
$availableStatusOptions = [];
foreach ($sectionRows as $section) {
    $group = trim((string) ($section['jtbdGroup'] ?? ''));
    $type = trim((string) ($section['sectionType'] ?? ''));
    $status = trim((string) ($section['remediationStatus'] ?? ''));
    if ($group !== '') {
        $groupOptions[$group] = $group;
    }
    if ($type !== '') {
        $typeOptions[$type] = $type;
    }
    if ($status !== '') {
        $availableStatusOptions[$status] = $statusOptions[$status] ?? ucwords(str_replace('-', ' ', $status));
    }
}
ksort($groupOptions);
ksort($typeOptions);
ksort($availableStatusOptions);

$selectedGroups = array_values(array_filter($selectedGroups, static fn (string $value): bool => isset($groupOptions[$value])));
$selectedTypes = array_values(array_filter($selectedTypes, static fn (string $value): bool => isset($typeOptions[$value])));
$selectedStatuses = array_values(array_filter($selectedStatuses, static fn (string $value): bool => isset($availableStatusOptions[$value])));

$listQuery = $queryFromFilters($selectedGroups, $selectedTypes, $selectedStatuses, $usageScope);
$selectedLiveSection = $usageScope === 'current' && $selectedSectionKey !== ''
    ? ($currentRowsByKey[$selectedSectionKey] ?? null)
    : null;
$selectedLibrarySection = $usageScope === 'library' && $selectedSectionKey !== '' && !$isCreateCustomMode
    ? ($libraryRowsByKey[$selectedSectionKey] ?? null)
    : null;
$isCurrentDetailMode = is_array($selectedLiveSection);
$isLibraryDetailMode = is_array($selectedLibrarySection);
$isDetailMode = $isCurrentDetailMode || $isLibraryDetailMode || $isCreateCustomMode;
$backToSectionsUrl = myronBuildAdminUrl('design.sectionsManager', $listQuery);
$scopeUrl = static fn (string $scope): string => myronBuildAdminUrl('design.sectionsManager', $scope === 'current' ? [] : ['usage' => $scope]);
$currentDetailUrl = static fn (array $row): string => myronBuildAdminUrl('design.sectionsManager', array_merge($listQuery, ['section' => (string) ($row['sectionKey'] ?? '')]));
$libraryDetailUrl = static fn (string $sectionKey): string => myronBuildAdminUrl('design.sectionsManager', array_merge($listQuery, ['section' => $sectionKey]));
$createCustomUrl = myronBuildAdminUrl('design.sectionsManager', ['usage' => 'library', 'section' => '__new_custom_section__']);

$renderReturnFilterInputs = static function () use ($selectedGroups, $selectedTypes, $selectedStatuses, $usageScope): void {
    echo '<input type="hidden" name="return_usage" value="' . myronEscape($usageScope) . '">' . "\n";
    foreach ($selectedGroups as $value) {
        echo '<input type="hidden" name="return_group[]" value="' . myronEscape((string) $value) . '">' . "\n";
    }
    foreach ($selectedTypes as $value) {
        echo '<input type="hidden" name="return_type[]" value="' . myronEscape((string) $value) . '">' . "\n";
    }
    foreach ($selectedStatuses as $value) {
        echo '<input type="hidden" name="return_status[]" value="' . myronEscape((string) $value) . '">' . "\n";
    }
};

$renderDefaultContentFields = static function (array $fields, array $repeaters) use ($availableImageFiles): void {
    if ($fields === [] && $repeaters === []) {
        echo '<p class="mc-page-grid__muted">This section has no schema-backed default content fields yet.</p>' . "\n";
        return;
    }

    if ($fields !== []) {
        echo '<div class="sg-form-grid">' . "\n";
        foreach ($fields as $field) {
            if (!is_array($field)) {
                continue;
            }
            $fieldKey = (string) ($field['key'] ?? '');
            if ($fieldKey === '') {
                continue;
            }
            $inputName = 'default_content[' . $fieldKey . ']';
            echo myronRenderSectionContentFieldControl($field, $inputName, (string) ($field['value'] ?? ''), $availableImageFiles) . "\n";
        }
        echo '</div>' . "\n";
    }

    foreach ($repeaters as $group) {
        if (!is_array($group)) {
            continue;
        }
        $groupKey = (string) ($group['key'] ?? '');
        $groupFields = array_values(array_filter((array) ($group['fields'] ?? []), 'is_array'));
        if ($groupKey === '' || $groupFields === []) {
            continue;
        }
        $items = array_values(array_filter((array) ($group['items'] ?? []), 'is_array'));
        $items[] = [];
        echo '<section class="mc-repeatable-group" data-mc-repeatable-group="' . myronEscape($groupKey) . '">' . "\n";
        echo '<div class="mc-repeatable-group__header"><h3>' . myronEscape((string) ($group['label'] ?? $groupKey)) . '</h3></div>' . "\n";
        foreach ($items as $itemIndex => $item) {
            echo '<section class="mc-repeatable-item" data-mc-repeatable-item>' . "\n";
            echo '<label class="sg-field"><span class="sg-field__label">' . myronEscape((string) ($group['itemLabel'] ?? 'Item')) . ' Order</span><input class="sg-field__control" type="number" name="default_content[' . myronEscape($groupKey) . '][' . myronEscape((string) $itemIndex) . '][__order]" value="' . myronEscape((string) ($itemIndex + 1)) . '"></label>' . "\n";
            echo '<label class="sg-checkbox"><input type="checkbox" name="default_content[' . myronEscape($groupKey) . '][' . myronEscape((string) $itemIndex) . '][__remove]" value="1"> Remove this item</label>' . "\n";
            echo '<div class="sg-form-grid">' . "\n";
            foreach ($groupFields as $groupField) {
                $itemFieldKey = (string) ($groupField['key'] ?? '');
                if ($itemFieldKey === '') {
                    continue;
                }
                $itemInputName = 'default_content[' . $groupKey . '][' . $itemIndex . '][' . $itemFieldKey . ']';
                $itemValue = (string) ($item[$itemFieldKey] ?? '');
                echo myronRenderSectionContentRepeaterFieldControl($groupField, $itemInputName, $itemValue, $availableImageFiles) . "\n";
            }
            echo '</div>' . "\n";
            echo '</section>' . "\n";
        }
        echo '</section>' . "\n";
    }
};

$title = 'Section Manager';
if ($isCreateCustomMode) {
    $title = 'Create Custom Section Template';
} elseif ($isCurrentDetailMode) {
    $title = (string) ($selectedLiveSection['label'] ?? $selectedSectionKey);
} elseif ($isLibraryDetailMode) {
    $title = (string) ($selectedLibrarySection['label'] ?? $selectedSectionKey);
}

myronRenderAdminShellStart($currentUser, [
    'title' => $title,
    'titleContext' => 'Section Templates',
    'activeItem' => 'sections-manager',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs($isDetailMode ? [
      ['label' => 'Design', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Template Studio', 'href' => myronBuildAdminUrl('design.templateStudioSiteTemplates')],
      ['label' => 'Section Templates', 'href' => myronBuildAdminUrl('design.sectionsManager')],
      ['label' => 'Section'],
  ] : [
      ['label' => 'Design', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Template Studio', 'href' => myronBuildAdminUrl('design.templateStudioSiteTemplates')],
      ['label' => 'Section Templates'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title"><?= myronEscape($title) ?></h1>
  </div>
  <p class="mc-workspace__subtitle"><?= $isDetailMode ? 'Inspect the rendered section and manage attributes from the side sheet.' : 'Manage live rendered sections and governed section bridge metadata for template composition.' ?></p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <?php if (!$isDetailMode): ?>
    <section class="sg-section">
      <div class="mc-editor-toolbar">
        <div class="mc-editor-toolbar__summary">
          <span class="sg-pill">custom sections</span>
          <span class="mc-editor-toolbar__meta">Create governed section templates from renderable primitives.</span>
        </div>
        <div class="mc-editor-toolbar__actions">
          <a class="sg-button sg-button--primary" href="<?= myronEscape($createCustomUrl) ?>">Create Custom Section</a>
        </div>
      </div>
    </section>

    <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="JTBD group filters" data-mc-filter-group data-mc-filter-param="group">
        <span class="mc-filter-group__label">JTBD Group</span>
        <div class="mc-filter-pill-row">
          <button class="sg-pill mc-filter-pill<?= $selectedGroups === [] ? ' sg-pill--active' : '' ?>" type="button" data-mc-filter-all aria-pressed="<?= $selectedGroups === [] ? 'true' : 'false' ?>">All</button>
          <?php foreach ($groupOptions as $groupKey => $groupLabel): ?>
          <button class="sg-pill mc-filter-pill<?= in_array((string) $groupKey, $selectedGroups, true) ? ' sg-pill--active' : '' ?>" type="button" data-mc-filter-value="<?= myronEscape((string) $groupKey) ?>" aria-pressed="<?= in_array((string) $groupKey, $selectedGroups, true) ? 'true' : 'false' ?>"><?= myronEscape((string) $groupLabel) ?></button>
          <?php endforeach; ?>
        </div>
      </div>

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

      <div class="mc-filter-group" role="group" aria-label="Readiness filters" data-mc-filter-group data-mc-filter-param="status">
        <span class="mc-filter-group__label">Readiness</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 ($availableStatusOptions as $statusKey => $statusLabel): ?>
          <button class="sg-pill mc-filter-pill<?= in_array((string) $statusKey, $selectedStatuses, true) ? ' sg-pill--active' : '' ?>" type="button" data-mc-filter-value="<?= myronEscape((string) $statusKey) ?>" aria-pressed="<?= in_array((string) $statusKey, $selectedStatuses, true) ? 'true' : 'false' ?>"><?= myronEscape((string) $statusLabel) ?></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($sectionRows)) ?> matching</span>
        <span class="sg-pill"><?= myronEscape((string) count($sectionRows)) ?> <?= $usageScope === 'library' ? 'library sections' : 'current-site sections' ?></span>
      </div>
      <div class="sg-status" role="status" data-mc-filter-empty hidden>No sections match the current filters.</div>

      <div class="mc-page-grid" role="table" aria-label="Design section 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="section"><button class="mc-page-grid__sort" type="button">Section</button></span>
          <span role="columnheader" data-mc-sort-key="group"><button class="mc-page-grid__sort" type="button">JTBD Group</button></span>
          <span role="columnheader" data-mc-sort-key="type"><button class="mc-page-grid__sort" type="button">Section Type</button></span>
          <span role="columnheader" data-mc-sort-key="components"><button class="mc-page-grid__sort" type="button"><?= $usageScope === 'library' ? 'Render Components' : 'Render Component' ?></button></span>
          <span role="columnheader" data-mc-sort-key="editability"><button class="mc-page-grid__sort" type="button">Editability</button></span>
          <span role="columnheader" data-mc-sort-key="usage" data-mc-sort-type="number"><button class="mc-page-grid__sort" type="button">Usage / Status</button></span>
          <span role="columnheader">Actions</span>
        </div>
        <?php foreach ($sectionRows as $section): ?>
        <?php
          $isLibraryRow = $usageScope === 'library';
          $sectionKey = (string) ($section['sectionKey'] ?? '');
          $componentId = $isLibraryRow ? '' : (string) ($section['componentId'] ?? '');
          $variant = $isLibraryRow ? '' : (string) ($section['variant'] ?? '');
          $components = array_values(array_map('strval', is_array($section['primaryComponents'] ?? null) ? $section['primaryComponents'] : []));
          if (!$isLibraryRow && $components === [] && $componentId !== '') {
              $components = [$componentId . ($variant !== '' ? ' / ' . $variant : '')];
          }
          $usageRows = $isLibraryRow
              ? (is_array($libraryUsageIndex[$sectionKey] ?? null) ? $libraryUsageIndex[$sectionKey] : [])
              : (is_array($section['usages'] ?? null) ? $section['usages'] : []);
          $status = (string) ($section['remediationStatus'] ?? '');
          $defaultEditability = $section['defaultContentEditable'] ?? null;
          $editability = $editabilityLabel($defaultEditability);
          $detailUrl = $isLibraryRow ? $libraryDetailUrl($sectionKey) : $currentDetailUrl($section);
        ?>
        <div
          class="mc-page-grid__row"
          role="row"
          data-mc-filter-row
          data-filter-group="<?= myronEscape((string) ($section['jtbdGroup'] ?? '')) ?>"
          data-filter-type="<?= myronEscape((string) ($section['sectionType'] ?? '')) ?>"
          data-filter-status="<?= myronEscape($status) ?>"
          data-sort-section="<?= myronEscape((string) ($section['label'] ?? ($componentId ?: $sectionKey)) . ' ' . $sectionKey) ?>"
          data-sort-group="<?= myronEscape((string) ($section['jtbdGroup'] ?? '')) ?>"
          data-sort-type="<?= myronEscape((string) ($section['sectionType'] ?? '')) ?>"
          data-sort-components="<?= myronEscape(implode(', ', $components)) ?>"
          data-sort-editability="<?= myronEscape($editability) ?>"
          data-sort-usage="<?= myronEscape((string) count($usageRows)) ?>"
        >
          <span class="mc-page-grid__cell mc-page-grid__cell--name" role="cell">
            <span class="mc-page-grid__name"><?= myronEscape((string) ($section['label'] ?? ($componentId ?: $sectionKey))) ?></span>
            <span class="mc-page-grid__subtle"><code><?= myronEscape($sectionKey !== '' ? $sectionKey : (string) ($section['identityKey'] ?? $componentId)) ?></code></span>
          </span>
          <span class="mc-page-grid__cell" role="cell"><?= myronEscape((string) ($section['jtbdGroup'] ?? '')) ?></span>
          <span class="mc-page-grid__cell" role="cell"><?= myronEscape((string) ($section['sectionType'] ?? '')) ?></span>
          <span class="mc-page-grid__cell" role="cell"><?= myronEscape(implode(', ', $components)) ?></span>
          <span class="mc-page-grid__cell" role="cell"><?= myronEscape($editability) ?></span>
          <span class="mc-page-grid__cell" role="cell">
            <span class="sg-pill"><?= myronEscape((string) count($usageRows)) ?> <?= $usageScope === 'library' ? 'templates' : 'occurrences' ?></span>
            <span class="sg-pill"><?= myronEscape($availableStatusOptions[$status] ?? $status) ?></span>
          </span>
          <span class="mc-page-grid__cell mc-page-grid__cell--actions" role="cell">
            <a class="sg-button sg-button--secondary" href="<?= myronEscape($detailUrl) ?>">Open</a>
          </span>
        </div>
        <?php endforeach; ?>
      </div>
    </section>
    <?php elseif ($isCreateCustomMode): ?>
    <section class="sg-section mc-template-manager-viewer">
      <div class="mc-editor-toolbar">
        <div class="mc-editor-toolbar__summary">
          <span class="sg-pill">operator-owned</span>
          <span class="mc-editor-toolbar__meta">Backed by an existing renderable primitive.</span>
        </div>
        <div class="mc-editor-toolbar__actions">
          <a class="sg-button sg-button--secondary" href="<?= myronEscape($backToSectionsUrl) ?>">Back to Sections</a>
        </div>
      </div>
      <form method="post" class="mc-admin-form mc-admin-form--wide">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <section class="mc-admin-form__section" aria-label="Section identity">
          <div class="mc-admin-form__section-header">
            <h3 class="mc-admin-form__section-title">Identity</h3>
            <p class="mc-admin-form__section-description">Name the template and bind it to a renderable primitive.</p>
          </div>
          <div class="mc-admin-form__grid mc-admin-form__grid--three">
            <label class="sg-field">
              <span class="sg-field__label">Label</span>
              <input class="sg-field__control" type="text" name="label" required>
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Section Key</span>
              <input class="sg-field__control" type="text" name="custom_section_key" placeholder="generated from label if left blank">
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Primary Primitive</span>
              <select class="sg-field__control" name="primary_component_id" required>
                <option value="">Choose primitive</option>
                <?php foreach ($renderableComponents as $component): ?>
                <option value="<?= myronEscape((string) ($component['id'] ?? '')) ?>"><?= myronEscape((string) ($component['id'] ?? '')) ?></option>
                <?php endforeach; ?>
              </select>
            </label>
            <label class="sg-field mc-admin-form__span-full">
              <span class="sg-field__label">Description</span>
              <textarea class="sg-field__control" name="description" rows="3"></textarea>
            </label>
          </div>
        </section>
        <section class="mc-admin-form__section" aria-label="Section classification">
          <div class="mc-admin-form__section-header">
            <h3 class="mc-admin-form__section-title">Classification</h3>
            <p class="mc-admin-form__section-description">Set inventory grouping, type, variant, and default editability.</p>
          </div>
          <div class="mc-admin-form__grid mc-admin-form__grid--three">
            <label class="sg-field">
              <span class="sg-field__label">JTBD Group</span>
              <input class="sg-field__control" type="text" name="jtbd_group" value="custom">
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Section Type</span>
              <input class="sg-field__control" type="text" name="section_type" value="custom">
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Variant</span>
              <input class="sg-field__control" type="text" name="variant" value="default">
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Default Editability</span>
              <select class="sg-field__control" name="default_editability">
                <option value="editable">Editable by default</option>
                <option value="inspect-only">Inspect only by default</option>
              </select>
            </label>
          </div>
        </section>
        <?php myronRenderCustomSectionTemplateFieldBuilder([], myronCustomSectionTemplateDefaultEditingContract()); ?>
        <div class="mc-admin-form__actions">
          <button class="sg-button sg-button--primary" type="submit" name="action" value="create-custom-section-template">Create Custom Section Template</button>
        </div>
      </form>
    </section>
    <?php elseif ($isCurrentDetailMode): ?>
    <?php
      $componentId = (string) ($selectedLiveSection['componentId'] ?? '');
      $variant = (string) ($selectedLiveSection['variant'] ?? '');
      $sectionInstanceKey = myronSectionInstanceKey([
          'componentId' => $componentId,
          'variant' => $variant,
          'sectionKey' => (string) ($selectedLiveSection['sectionKey'] ?? ''),
      ], 0);
      $defaultContent = is_array($selectedLiveSection['defaultContent'] ?? null) ? $selectedLiveSection['defaultContent'] : [];
      $defaultHeadline = (string) ($defaultContent['headline'] ?? $selectedLiveSection['label'] ?? '');
      $defaultBody = (string) ($defaultContent['body'] ?? '');
      $defaultSectionSchema = $sectionContentSchema->schemaForSection([
          'componentId' => $componentId,
          'variant' => $variant,
          'sectionKey' => (string) ($selectedLiveSection['sectionKey'] ?? ''),
      ], 0, $defaultContent, 'section-default');
      $sourceTemplates = is_array($selectedLiveSection['sourceTemplateIds'] ?? null) ? $selectedLiveSection['sourceTemplateIds'] : [];
      $sourceTemplateId = (string) ($sourceTemplates[0] ?? '');
      $renderedSection = $primitiveRenderer->renderById($componentId, [
          'variant' => $variant,
          'title' => $defaultHeadline,
          'body' => $defaultBody,
          'content' => $defaultContent,
      ], [
          'templateId' => $sourceTemplateId,
          'basePath' => myronPublicBasePath(),
      ]);
    ?>
    <section class="sg-section mc-template-manager-viewer" data-myron-section-manager-detail data-component-id="<?= myronEscape($componentId) ?>" data-section-identity="<?= myronEscape((string) ($selectedLiveSection['identityKey'] ?? $componentId)) ?>">
      <div class="mc-editor-toolbar">
        <div class="mc-editor-toolbar__summary">
          <span class="sg-pill">rendered section</span>
          <span class="mc-editor-toolbar__meta"><code><?= myronEscape((string) ($selectedLiveSection['identityKey'] ?? $componentId)) ?></code></span>
        </div>
        <div class="mc-editor-toolbar__actions">
          <a class="sg-button sg-button--secondary" href="<?= myronEscape($backToSectionsUrl) ?>">Back to Sections</a>
          <button class="sg-button sg-button--secondary" type="button" data-mc-sidesheet-open="section-attributes-sheet" data-mc-visual-section-editor-trigger>Section Attributes</button>
        </div>
      </div>

      <div class="mc-section-render-preview mc-editor-visual-canvas" data-myron-rendered-section-preview data-mc-visual-editor-canvas>
        <div data-myron-editor-section="true" data-section-instance-key="<?= myronEscape($sectionInstanceKey) ?>" data-section-key="<?= myronEscape((string) ($selectedLiveSection['sectionKey'] ?? '')) ?>" data-myron-component-id="<?= myronEscape($componentId) ?>" data-myron-editability="<?= (string) ($selectedLiveSection['defaultContentEditable'] ?? '') === '0' ? 'inspect-only' : 'editable' ?>">
        <?= $renderedSection ?>
        </div>
      </div>
    </section>

    <?php ob_start(); ?>
    <div class="sg-status" role="status" data-mc-visual-section-empty>Select the rendered section to manage its attributes.</div>
    <div data-mc-visual-section-panel data-section-instance-key="<?= myronEscape($sectionInstanceKey) ?>">
    <dl class="sg-definition-list">
      <div class="sg-definition-list__row">
        <dt>Component ID</dt>
        <dd><code><?= myronEscape($componentId) ?></code></dd>
      </div>
      <div class="sg-definition-list__row">
        <dt>Variant</dt>
        <dd><?= $variant !== '' ? myronEscape($variant) : '<span class="mc-page-grid__muted">Default</span>' ?></dd>
      </div>
      <div class="sg-definition-list__row">
        <dt>Section Key</dt>
        <dd><?= trim((string) ($selectedLiveSection['sectionKey'] ?? '')) !== '' ? '<code>' . myronEscape((string) $selectedLiveSection['sectionKey']) . '</code>' : '<span class="mc-page-grid__muted">Unmapped</span>' ?></dd>
      </div>
      <div class="sg-definition-list__row">
        <dt>Usage</dt>
        <dd><?= myronEscape((string) (int) ($selectedLiveSection['usageCount'] ?? 0)) ?> live occurrences</dd>
      </div>
      <div class="sg-definition-list__row">
        <dt>Default Source</dt>
        <dd><?= myronEscape((string) ($selectedLiveSection['defaultContentSource'] ?? 'registry')) ?></dd>
      </div>
    </dl>
    <form method="post" class="mc-sidesheet-form">
      <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
      <input type="hidden" name="component_id" value="<?= myronEscape($componentId) ?>">
      <input type="hidden" name="variant" value="<?= myronEscape($variant) ?>">
      <input type="hidden" name="section_key" value="<?= myronEscape((string) ($selectedLiveSection['sectionKey'] ?? '')) ?>">
      <?php $renderReturnFilterInputs(); ?>
      <?php $renderDefaultContentFields($defaultSectionSchema['fields'], $defaultSectionSchema['repeaters']); ?>
      <label class="sg-field">
        <span class="sg-field__label">Allow Content Editing</span>
        <select class="sg-field__control" name="default_editability">
          <option value="inherit" <?= ($selectedLiveSection['defaultContentEditable'] ?? null) === null ? 'selected' : '' ?>>Inherit</option>
          <option value="editable" <?= (string) ($selectedLiveSection['defaultContentEditable'] ?? '') === '1' ? 'selected' : '' ?>>Editable by default</option>
          <option value="inspect-only" <?= (string) ($selectedLiveSection['defaultContentEditable'] ?? '') === '0' ? 'selected' : '' ?>>Inspect only by default</option>
        </select>
      </label>
      <div class="sg-card__actions">
        <button class="sg-button sg-button--primary" type="submit" name="action" value="update-section-defaults">Save Section Defaults</button>
      </div>
    </form>
    </div>
    <?php $sheetBody = (string) ob_get_clean(); ?>
    <?php myronRenderAdminSidesheet('section-attributes-sheet', 'Section Attributes', $sheetBody, [
        'description' => 'Design-owned default content and flags for this rendered section.',
        'size' => 'lg',
    ]); ?>
    <?php else: ?>
    <?php
      $sectionKey = (string) ($selectedLibrarySection['sectionKey'] ?? $selectedSectionKey);
      $bridge = is_array($selectedLibrarySection['_bridge'] ?? null) ? $selectedLibrarySection['_bridge'] : [];
      $customMeta = is_array($selectedLibrarySection['_custom'] ?? null) ? $selectedLibrarySection['_custom'] : [];
      $isCustomSection = $customMeta !== [];
      $components = array_values(array_map('strval', is_array($selectedLibrarySection['primaryComponents'] ?? null) ? $selectedLibrarySection['primaryComponents'] : []));
      $usageRows = is_array($libraryUsageIndex[$sectionKey] ?? null) ? $libraryUsageIndex[$sectionKey] : [];
      $defaultEditability = $selectedLibrarySection['defaultContentEditable'] ?? null;
    ?>
    <section class="sg-section mc-template-manager-viewer" data-myron-section-manager-detail data-section-key="<?= myronEscape($sectionKey) ?>">
      <div class="mc-editor-toolbar">
        <div class="mc-editor-toolbar__summary">
          <span class="sg-pill"><?= myronEscape((string) ($customMeta['sourceAuthority'] ?? $bridge['sourceAuthority'] ?? 'canonical-section-registry')) ?></span>
          <span class="mc-editor-toolbar__meta"><code><?= myronEscape($sectionKey) ?></code></span>
        </div>
        <div class="mc-editor-toolbar__actions">
          <a class="sg-button sg-button--secondary" href="<?= myronEscape($backToSectionsUrl) ?>">Back to Sections</a>
          <button class="sg-button sg-button--secondary" type="button" data-mc-sidesheet-open="section-attributes-sheet">Section Attributes</button>
        </div>
      </div>
      <div class="mc-editor-section-tree" data-myron-section-detail-surface>
        <section class="mc-editor-section-node">
          <div class="mc-editor-section-node__header">
            <div>
              <h2 class="mc-editor-section-node__title"><?= myronEscape((string) ($selectedLibrarySection['label'] ?? $sectionKey)) ?></h2>
              <p class="mc-page-grid__subtle"><?= myronEscape((string) ($selectedLibrarySection['jtbdGroup'] ?? '')) ?> · <?= myronEscape((string) ($selectedLibrarySection['sectionType'] ?? '')) ?></p>
            </div>
          </div>
          <dl class="sg-definition-list">
            <div class="sg-definition-list__row">
              <dt>Primary Render Components</dt>
              <dd><?= myronEscape(implode(', ', $components)) ?></dd>
            </div>
            <div class="sg-definition-list__row">
              <dt>Template Usage</dt>
              <dd><?= myronEscape((string) count($usageRows)) ?> packaged templates</dd>
            </div>
          </dl>
        </section>
      </div>
    </section>
    <?php ob_start(); ?>
    <?php if ($isCustomSection): ?>
    <form method="post" class="sg-form-grid">
      <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
      <input type="hidden" name="section_key" value="<?= myronEscape($sectionKey) ?>">
      <?php $renderReturnFilterInputs(); ?>
      <label class="sg-field">
        <span class="sg-field__label">Label</span>
        <input class="sg-field__control" type="text" name="label" value="<?= myronEscape((string) ($selectedLibrarySection['label'] ?? '')) ?>" required>
      </label>
      <label class="sg-field">
        <span class="sg-field__label">Description</span>
        <textarea class="sg-field__control" name="description" rows="3"><?= myronEscape((string) ($selectedLibrarySection['description'] ?? '')) ?></textarea>
      </label>
      <label class="sg-field">
        <span class="sg-field__label">Primary Primitive</span>
        <select class="sg-field__control" name="primary_component_id" required>
          <?php foreach ($renderableComponents as $component): ?>
          <?php $optionId = (string) ($component['id'] ?? ''); ?>
          <option value="<?= myronEscape($optionId) ?>" <?= ($components[0] ?? '') === $optionId ? 'selected' : '' ?>><?= myronEscape($optionId) ?></option>
          <?php endforeach; ?>
        </select>
      </label>
      <label class="sg-field">
        <span class="sg-field__label">JTBD Group</span>
        <input class="sg-field__control" type="text" name="jtbd_group" value="<?= myronEscape((string) ($selectedLibrarySection['jtbdGroup'] ?? 'custom')) ?>">
      </label>
      <label class="sg-field">
        <span class="sg-field__label">Section Type</span>
        <input class="sg-field__control" type="text" name="section_type" value="<?= myronEscape((string) ($selectedLibrarySection['sectionType'] ?? 'custom')) ?>">
      </label>
      <label class="sg-field">
        <span class="sg-field__label">Variant</span>
        <input class="sg-field__control" type="text" name="variant" value="<?= myronEscape((string) ($selectedLibrarySection['variant'] ?? 'default')) ?>">
      </label>
      <label class="sg-field">
        <span class="sg-field__label">Default Content Editability</span>
        <select class="sg-field__control" name="default_editability">
          <option value="editable" <?= (string) $defaultEditability !== '0' ? 'selected' : '' ?>>Editable by default</option>
          <option value="inspect-only" <?= (string) $defaultEditability === '0' ? 'selected' : '' ?>>Inspect only by default</option>
        </select>
      </label>
      <?php myronRenderCustomSectionTemplateFieldBuilder(
          is_array($selectedLibrarySection['defaultContent'] ?? null) ? $selectedLibrarySection['defaultContent'] : [],
          is_array($selectedLibrarySection['editing'] ?? null) ? $selectedLibrarySection['editing'] : ['fields' => [], 'repeaters' => []]
      ); ?>
      <div class="sg-card__actions">
        <button class="sg-button sg-button--primary" type="submit" name="action" value="update-custom-section-template">Save Custom Section</button>
      </div>
    </form>
    <form method="post" class="sg-form-grid" onsubmit="return confirm('Delete this unused custom section template?');">
      <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
      <input type="hidden" name="section_key" value="<?= myronEscape($sectionKey) ?>">
      <button class="sg-button sg-button--secondary" type="submit" name="action" value="delete-custom-section-template">Delete Custom Section</button>
    </form>
    <?php else: ?>
    <form method="post" class="sg-form-grid">
      <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
      <input type="hidden" name="section_key" value="<?= myronEscape($sectionKey) ?>">
      <?php $renderReturnFilterInputs(); ?>
      <label class="sg-field">
        <span class="sg-field__label">Display Label Override</span>
        <input class="sg-field__control" type="text" name="label_override" value="<?= myronEscape((string) ($selectedLibrarySection['label'] ?? '')) ?>">
      </label>
      <label class="sg-field">
        <span class="sg-field__label">Description Override</span>
        <textarea class="sg-field__control" name="description_override" rows="3"><?= myronEscape((string) ($selectedLibrarySection['description'] ?? '')) ?></textarea>
      </label>
      <label class="sg-field">
        <span class="sg-field__label">Primary Render Components</span>
        <textarea class="sg-field__control" name="primary_components" rows="3"><?= myronEscape(implode(', ', $components)) ?></textarea>
      </label>
      <label class="sg-field">
        <span class="sg-field__label">Readiness Status</span>
        <select class="sg-field__control" name="remediation_status">
          <?php foreach ($statusOptions as $statusKey => $statusLabel): ?>
          <?php if ($statusKey !== 'live'): ?>
          <option value="<?= myronEscape($statusKey) ?>" <?= (string) ($selectedLibrarySection['remediationStatus'] ?? '') === $statusKey ? 'selected' : '' ?>><?= myronEscape($statusLabel) ?></option>
          <?php endif; ?>
          <?php endforeach; ?>
        </select>
      </label>
      <label class="sg-field">
        <span class="sg-field__label">Default Content Editability</span>
        <select class="sg-field__control" name="default_editability">
          <option value="inherit" <?= $defaultEditability === null ? 'selected' : '' ?>>Inherit</option>
          <option value="editable" <?= (string) $defaultEditability === '1' ? 'selected' : '' ?>>Editable by default</option>
          <option value="inspect-only" <?= (string) $defaultEditability === '0' ? 'selected' : '' ?>>Inspect only by default</option>
        </select>
      </label>
      <div class="sg-card__actions">
        <button class="sg-button sg-button--primary" type="submit" name="action" value="update-section-bridge">Save Section Bridge</button>
      </div>
    </form>
    <?php endif; ?>
    <?php $sheetBody = (string) ob_get_clean(); ?>
    <?php myronRenderAdminSidesheet('section-attributes-sheet', 'Section Attributes', $sheetBody, [
        'description' => 'Design-owned bridge metadata for governed section composition.',
        'size' => 'lg',
    ]); ?>
    <?php endif; ?>
  </div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
  function normalizeKey(label) {
    var parts = String(label || '').trim().split(/[^A-Za-z0-9]+/).filter(Boolean);
    if (!parts.length) {
      return 'field';
    }
    return parts.map(function (part, index) {
      var value = part.charAt(0).toUpperCase() + part.slice(1);
      return index === 0 ? value.charAt(0).toLowerCase() + value.slice(1) : value;
    }).join('');
  }

  function rowValue(row, selector) {
    var control = row.querySelector(selector);
    return control ? control.value.trim() : '';
  }

  function addRow(builder, source) {
    var rows = builder.querySelector('[data-mc-section-field-rows]');
    if (!rows) {
      return null;
    }
    var label = source.label || 'Custom Field';
    var key = source.key || normalizeKey(label);
    if (key !== '') {
      var exists = Array.prototype.some.call(rows.querySelectorAll('[data-mc-section-field-key]'), function (control) {
        return control.value.trim() === key;
      });
      if (exists) {
        return null;
      }
    }
    var row = document.createElement('div');
    row.className = 'mc-field-builder__row';
    row.setAttribute('data-mc-section-field-row', 'true');
    row.innerHTML = [
      '<label class="sg-field"><span class="sg-field__label">Field Label</span><input class="sg-field__control" type="text" data-mc-section-field-label></label>',
      '<label class="sg-field"><span class="sg-field__label">Field Key</span><input class="sg-field__control" type="text" data-mc-section-field-key></label>',
      '<label class="sg-field"><span class="sg-field__label">Type</span><select class="sg-field__control" data-mc-section-field-type><option value="text">Text</option><option value="textarea">Long text</option><option value="url">URL</option><option value="image">Image</option></select></label>',
      '<label class="sg-field"><span class="sg-field__label">Initial Content</span><input class="sg-field__control" type="text" data-mc-section-field-default></label>',
      '<label class="sg-field sg-field--checkbox"><span class="sg-field__label">Required</span><span class="sg-field__checkbox"><input type="checkbox" value="1" data-mc-section-field-required><span>Require a value</span></span></label>',
      '<label class="sg-field sg-field--checkbox"><span class="sg-field__label">Rich Text</span><span class="sg-field__checkbox"><input type="checkbox" value="1" data-mc-section-field-richtext><span>Use rich-text editor</span></span></label>',
      '<div class="mc-field-builder__row-actions"><button class="sg-button sg-button--secondary" type="button" data-mc-section-field-remove>Remove</button></div>'
    ].join('');
    row.querySelector('[data-mc-section-field-label]').value = label;
    row.querySelector('[data-mc-section-field-key]').value = key;
    row.querySelector('[data-mc-section-field-type]').value = source.type || 'text';
    row.querySelector('[data-mc-section-field-default]').value = source.defaultValue || '';
    row.querySelector('[data-mc-section-field-required]').checked = Boolean(source.required);
    row.querySelector('[data-mc-section-field-richtext]').checked = Boolean(source.richtext);
    rows.appendChild(row);
    syncBuilder(builder);
    return row;
  }

  function syncBuilder(builder) {
    var defaultJson = builder.querySelector('[data-mc-section-default-content-json]');
    var editingJson = builder.querySelector('[data-mc-section-editing-contract-json]');
    if (!defaultJson || !editingJson) {
      return;
    }
    var content = {};
    var fields = [];
    builder.querySelectorAll('[data-mc-section-field-row]').forEach(function (row) {
      var label = rowValue(row, '[data-mc-section-field-label]');
      var key = rowValue(row, '[data-mc-section-field-key]') || normalizeKey(label);
      if (!key) {
        return;
      }
      var type = rowValue(row, '[data-mc-section-field-type]') || 'text';
      var defaultValue = rowValue(row, '[data-mc-section-field-default]');
      var required = row.querySelector('[data-mc-section-field-required]');
      var richtext = row.querySelector('[data-mc-section-field-richtext]');
      var field = {
        key: key,
        label: label || key,
        type: ['text', 'textarea', 'url', 'image'].indexOf(type) === -1 ? 'text' : type
      };
      if (required && required.checked) {
        field.required = true;
      }
      if (richtext && richtext.checked && (field.type === 'text' || field.type === 'textarea')) {
        field.richtext = true;
      }
      content[key] = defaultValue;
      fields.push(field);
    });
    defaultJson.value = JSON.stringify(content, null, 2);
    editingJson.value = JSON.stringify({ fields: fields, repeaters: [] }, null, 2);
  }

  document.querySelectorAll('[data-mc-section-field-builder]').forEach(function (builder) {
    builder.addEventListener('input', function (event) {
      if (event.target && event.target.matches('[data-mc-section-field-label]')) {
        var row = event.target.closest('[data-mc-section-field-row]');
        var key = row && row.querySelector('[data-mc-section-field-key]');
        if (key && key.value.trim() === '') {
          key.value = normalizeKey(event.target.value);
        }
      }
      if (event.target && !event.target.matches('[data-mc-section-default-content-json], [data-mc-section-editing-contract-json]')) {
        syncBuilder(builder);
      }
    });
    builder.addEventListener('change', function (event) {
      if (event.target && !event.target.matches('[data-mc-section-default-content-json], [data-mc-section-editing-contract-json]')) {
        syncBuilder(builder);
      }
    });
    builder.addEventListener('click', function (event) {
      var add = event.target.closest('[data-mc-section-field-add]');
      var remove = event.target.closest('[data-mc-section-field-remove]');
      if (add) {
        event.preventDefault();
        var row = addRow(builder, {
          label: add.getAttribute('data-label') || 'Custom Field',
          key: add.getAttribute('data-key') || '',
          type: add.getAttribute('data-type') || 'text',
          richtext: add.getAttribute('data-richtext') === '1'
        });
        if (row) {
          row.querySelector('[data-mc-section-field-label]').focus();
        }
      }
      if (remove) {
        event.preventDefault();
        var targetRow = remove.closest('[data-mc-section-field-row]');
        if (targetRow) {
          targetRow.remove();
          syncBuilder(builder);
        }
      }
    });
    if (builder.form) {
      builder.form.addEventListener('submit', function () {
        syncBuilder(builder);
      });
    }
    syncBuilder(builder);
  });
});
</script>
<?php myronRenderAdminShellEnd(); ?>
