<?php

declare(strict_types=1);

require_once dirname(__DIR__, 3) . '/system/bootstrap.php';

$currentUser        = myronRequireDesignAccess();
$canManageDesign    = myronUserCanManageDesign($currentUser);
$footerRepository   = myronFooterDesignRepository();
$designEntitlements = myronDesignLibraryEntitlementPolicy();
$fileRepository     = myronFileRepository();
$uploadHandler      = myronAssetUploadRequestHandler();
$siteTypeRepository = myronSiteTypeRegistryRepository();

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (!$canManageDesign) {
            throw new RuntimeException('Your current role cannot update footer design settings.');
        }

        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $action = trim((string) ($_POST['action'] ?? $_POST['asset_picker_action'] ?? ''));
        // APO-193 Card 4 — every footer mutation funnels through
        // MyronFooterDesignActionService; the admin form path here is now a
        // thin caller that maps form fields → service method args. The API
        // path (POST /api/v1/design/footers/...) calls the SAME service. No
        // drift possible because there's only one implementation.
        $footerService = myronFooterDesignActionService();
        $callerCtx = myronActionCallerContextForUser($currentUser);

        if ($action === 'activate-footer-design') {
            try {
                $footerService->activate(trim((string) ($_POST['variant_id'] ?? '')), $callerCtx);
                myronRedirectWithFlash(myronBuildAdminUrl('design.footers'), 'Activated footer variant.', 'success');
            } catch (Throwable $e) {
                myronRedirectWithFlash(myronBuildAdminUrl('design.footers'), $e->getMessage(), 'error');
            }
        }

        if ($action === 'deactivate-footer-design') {
            try {
                $footerService->deactivate(trim((string) ($_POST['variant_id'] ?? '')), $callerCtx);
                myronRedirectWithFlash(myronBuildAdminUrl('design.footers'), 'Deactivated footer variant.', 'success');
            } catch (Throwable $e) {
                myronRedirectWithFlash(myronBuildAdminUrl('design.footers'), $e->getMessage(), 'error');
            }
        }

        if ($action === 'set-default-footer-design') {
            // APO-186 Card 3 — admin form path + PATCH /api/v1/design/footers/{variantId}/default
            // share MyronFooterDesignActionService::setDefault.
            try {
                $footerService->setDefault(trim((string) ($_POST['variant_id'] ?? '')), $callerCtx);
                myronRedirectWithFlash(myronBuildAdminUrl('design.footers'), 'Updated default footer variant.', 'success');
            } catch (Throwable $e) {
                myronRedirectWithFlash(myronBuildAdminUrl('design.footers'), $e->getMessage(), 'error');
            }
        }

        if ($action === 'apply-footer-recommendation') {
            try {
                $footerService->applyRecommendation(
                    trim((string) ($_POST['bundle_id'] ?? '')),
                    trim((string) ($_POST['footer_variant'] ?? 'footer.standard')),
                    $callerCtx
                );
                myronRedirectWithFlash(myronBuildAdminUrl('design.footers'), 'Applied footer recommendation.', 'success');
            } catch (Throwable $e) {
                myronRedirectWithFlash(myronBuildAdminUrl('design.footers'), $e->getMessage(), 'error');
            }
        }

        if ($action === 'dismiss-footer-recommendation') {
            try {
                $footerService->dismissRecommendation(
                    trim((string) ($_POST['bundle_id'] ?? '')),
                    trim((string) ($_POST['footer_variant'] ?? 'footer.standard')),
                    $callerCtx
                );
                myronRedirectWithFlash(myronBuildAdminUrl('design.footers'), 'Dismissed footer recommendation.', 'success');
            } catch (Throwable $e) {
                myronRedirectWithFlash(myronBuildAdminUrl('design.footers'), $e->getMessage(), 'error');
            }
        }

        // APO-180 Card 6 → APO-193 Card 4 — per-zone Apply defaults via the
        // canonical service method. The side-sheet button is named
        // `apply_zone_defaults` with the zone id as its value; the API URI is
        // POST /api/v1/design/footers/{variantId}/zones/{zoneId}/apply-defaults.
        $applyZoneDefaultsZone = trim((string) ($_POST['apply_zone_defaults'] ?? ''));
        if ($applyZoneDefaultsZone !== '') {
            try {
                $outcome = $footerService->applyDefaultsForZone(
                    trim((string) ($_POST['variant_id'] ?? '')),
                    $applyZoneDefaultsZone,
                    $callerCtx
                );
                $zoneLabelLookup = myronFooterVariantCompositionService()->zoneLabels();
                $message = $outcome['applied']
                    ? 'Applied default content for ' . ($zoneLabelLookup[$applyZoneDefaultsZone] ?? $applyZoneDefaultsZone) . '.'
                    : 'No default content available for this zone in your current site type.';
                myronRedirectWithFlash(myronBuildAdminUrl('design.footers'), $message, $outcome['applied'] ? 'success' : 'info');
            } catch (Throwable $e) {
                myronRedirectWithFlash(myronBuildAdminUrl('design.footers'), $e->getMessage(), 'error');
            }
        }

        if ($action === 'update-footer-configuration') {
            try {
                $variantId = trim((string) ($_POST['variant_id'] ?? ''));
                $zones = myronFooterVariantCompositionService()->orderedZonesFor($variantId);
                $rawVisibility = is_array($_POST['footer']['zone_visibility'] ?? null) ? $_POST['footer']['zone_visibility'] : [];
                $visibility = [];
                foreach ($zones as $zoneId) {
                    $visibility[$zoneId] = isset($rawVisibility[$zoneId]);
                }
                $rawContent = is_array($_POST['zone_content'] ?? null) ? $_POST['zone_content'] : [];
                $footerService->updateConfiguration($variantId, $visibility, $rawContent, $callerCtx);
                myronRedirectWithFlash(myronBuildAdminUrl('design.footers'), 'Updated footer configuration.', 'success');
            } catch (Throwable $e) {
                myronRedirectWithFlash(myronBuildAdminUrl('design.footers'), $e->getMessage(), 'error');
            }
        }

        // APO-196: `update-footer-zone-content` admin branch removed.
        // It had been retired (always threw a "use Configure on the activated
        // variant" error) and existed only as a backlog/drift-guard placeholder.
        // The Configure flow uses `update-footer-configuration` which lands in
        // MyronUpdateFooterConfigurationAction (APO-193 Card 4).

        if ($action === 'upload-asset-picker') {
            $assetClass = trim((string) ($_POST['asset_class'] ?? 'image'));
            if ($assetClass !== 'image') {
                throw new RuntimeException('Only image asset uploads are supported in this slice.');
            }
            $result = $uploadHandler->handle(
                $_FILES,
                $_POST,
                $userId,
                ['assetClass' => 'image', 'metadataRequired' => true]
            );
            if (myronRequestExpectsJson()) {
                if (($result['ok'] ?? false) !== true) {
                    myronJsonResponse([
                        'ok' => false,
                        'error' => (string) ($result['error'] ?? 'Upload failed.'),
                    ], (int) ($result['status'] ?? 422));
                }
                myronJsonResponse([
                    'ok' => true,
                    'asset' => $result['asset'] ?? [],
                ]);
            }
            if (($result['ok'] ?? false) !== true) {
                throw new RuntimeException((string) ($result['error'] ?? 'Upload failed.'));
            }
            myronRedirectWithFlash(myronBuildAdminUrl('design.footers'), 'Image asset uploaded.', 'success');
        }

        throw new RuntimeException('Unknown footer design action.');
    } catch (Throwable $exception) {
        if (myronRequestExpectsJson()) {
            myronJsonResponse([
                'ok' => false,
                'error' => $exception->getMessage(),
            ], 422);
        }
        myronRedirectWithFlash(myronBuildAdminUrl('design.footers'), $exception->getMessage(), 'error');
    }
}

$schemaService      = myronFooterZoneContentSchemaService();
$compositionService = myronFooterVariantCompositionService();
$variantRows        = $designEntitlements->filterFooterRows($footerRepository->listVariants());
$variantsById       = [];
foreach ($variantRows as $row) {
    $variantsById[(string) ($row['variant_id'] ?? '')] = $row;
}
$defaultFooter      = $footerRepository->getDefault();
$defaultVariant     = (string) ($defaultFooter['variant_id'] ?? 'footer.standard');
$activatedVariants  = $designEntitlements->filterFooterRows($footerRepository->listActivatedSorted());
$variantLabels      = $compositionService->variantLabels();
$zoneLabels         = $compositionService->zoneLabels();
$state              = myronOnboardingStateRepository()->getState();
$currentBundleId    = trim((string) ($state['primary_bundle_id'] ?? ''));
$currentSiteType    = $currentBundleId !== '' ? $siteTypeRepository->findSiteTypeById($currentBundleId) : null;
$recommendedVariant = $compositionService->recommendedVariantForSiteType($currentSiteType);
$showRecommendation = $currentBundleId !== ''
    && $recommendedVariant !== ''
    && $recommendedVariant !== $defaultVariant
    && $designEntitlements->isFooterVariantAvailable($recommendedVariant)
    && !$footerRepository->isRecommendationDismissed($currentBundleId, $recommendedVariant);
$availableImageFiles = array_values(array_filter(
    $fileRepository->listFiles(),
    static fn (array $file): bool => (bool) ($file['is_image'] ?? false)
));
$csrfToken = myronCsrfToken();

$zoneSummary = static function (array $content, array $schema): string {
    $summary = [];
    foreach (is_array($schema['fields'] ?? null) ? $schema['fields'] : [] as $field) {
        $key = (string) ($field['key'] ?? '');
        if (trim((string) ($content[$key] ?? '')) !== '') {
            $summary[] = (string) ($field['label'] ?? $key);
        }
    }
    foreach (is_array($schema['repeaters'] ?? null) ? $schema['repeaters'] : [] as $repeater) {
        $key = (string) ($repeater['key'] ?? '');
        $items = array_values(array_filter(is_array($content[$key] ?? null) ? $content[$key] : [], 'is_array'));
        if ($items !== []) {
            $summary[] = count($items) . ' ' . strtolower((string) ($repeater['itemLabel'] ?? 'item')) . (count($items) === 1 ? '' : 's');
        }
    }
    return $summary === [] ? 'No custom content yet' : implode(', ', array_slice($summary, 0, 3));
};

$renderAssetField = static function (string $id, string $label, string $name, string $value, bool $disabled): string {
    return MyronAssetPickerView::renderField([
        'id' => $id,
        'label' => $label,
        'name' => $name,
        'value' => $value,
        'pickerId' => 'footer-zone-asset-picker',
        'disabled' => $disabled,
    ]);
};

$renderZoneFields = static function (string $zoneId, array $schema, bool $canEdit) use ($renderAssetField): void {
    foreach (is_array($schema['fields'] ?? null) ? $schema['fields'] : [] as $field) {
        $fieldKey   = (string) ($field['key'] ?? '');
        $fieldLabel = (string) ($field['label'] ?? $fieldKey);
        $fieldType  = (string) ($field['type'] ?? 'text');
        $fieldValue = (string) ($field['value'] ?? '');
        $name       = 'zone_content[' . $zoneId . '][' . $fieldKey . ']';
        $id         = 'footer-' . myronNormalizeSlug($zoneId . '-' . $fieldKey);
        if ($fieldType === 'asset') {
            echo '<div class="mc-footer-config-zone__span-full">' . "\n";
            echo $renderAssetField($id, $fieldLabel, $name, $fieldValue, !$canEdit) . "\n";
            echo '</div>' . "\n";
            continue;
        }
        echo '<label class="sg-field' . ($fieldType === 'textarea' ? ' sg-field--full' : '') . '">';
        echo '<span class="sg-field__label">' . myronEscape($fieldLabel) . '</span>';
        if ($fieldType === 'textarea') {
            echo '<textarea class="sg-field__control sg-field__control--textarea" name="' . myronEscape($name) . '" rows="4" data-mc-richtext="true"' . ($canEdit ? '' : ' disabled') . '>' . myronEscape($fieldValue) . '</textarea>';
        } else {
            echo '<input class="sg-field__control" type="text" name="' . myronEscape($name) . '" value="' . myronEscape($fieldValue) . '"' . ($canEdit ? '' : ' disabled') . '>';
        }
        echo '</label>' . "\n";
    }

    foreach (is_array($schema['repeaters'] ?? null) ? $schema['repeaters'] : [] as $group) {
        $groupKey = (string) ($group['key'] ?? '');
        $items = is_array($group['items'] ?? null) ? $group['items'] : [];
        $fields = is_array($group['fields'] ?? null) ? $group['fields'] : [];
        echo '<fieldset class="sg-fieldset mc-footer-repeater mc-footer-config-zone__span-full" data-mc-footer-repeater="' . myronEscape($groupKey) . '">';
        echo '<legend class="sg-fieldset__legend">' . myronEscape((string) ($group['label'] ?? $groupKey)) . '</legend>';
        echo '<div class="sg-fieldset__body" data-mc-repeatable-group="' . myronEscape($groupKey) . '">';
        foreach ($items as $itemIndex => $item) {
            if (!is_array($item)) {
                continue;
            }
            echo '<div class="sg-fieldset__item mc-footer-repeater__item" data-mc-footer-repeater-row>';
            echo '<div class="mc-footer-repeater__row-header"><span class="sg-fieldset__item-label">' . myronEscape((string) ($group['itemLabel'] ?? 'Item') . ' ' . ($itemIndex + 1)) . '</span>';
            echo '<span class="mc-footer-repeater__controls"><button class="sg-button" type="button" data-mc-footer-repeater-move="up"' . ($canEdit ? '' : ' disabled') . '>Move up</button><button class="sg-button" type="button" data-mc-footer-repeater-move="down"' . ($canEdit ? '' : ' disabled') . '>Move down</button></span></div>';
            echo '<input type="hidden" data-mc-footer-repeater-order name="zone_content[' . myronEscape($zoneId) . '][' . myronEscape($groupKey) . '][' . $itemIndex . '][__order]" value="' . ($itemIndex + 1) . '">';
            echo '<div class="mc-footer-repeater__item-fields">';
            foreach ($fields as $field) {
                $fieldKey = (string) ($field['key'] ?? '');
                $fieldLabel = (string) ($field['label'] ?? $fieldKey);
                $fieldType = (string) ($field['type'] ?? 'text');
                $value = trim((string) ($item[$fieldKey] ?? ''));
                $name = 'zone_content[' . $zoneId . '][' . $groupKey . '][' . $itemIndex . '][' . $fieldKey . ']';
                if ($fieldType === 'asset') {
                    echo '<div class="mc-footer-config-zone__span-full">' . $renderAssetField('footer-' . myronNormalizeSlug($zoneId . '-' . $groupKey . '-' . $itemIndex . '-' . $fieldKey), $fieldLabel, $name, $value, !$canEdit) . '</div>';
                } else {
                    echo '<label class="sg-field"><span class="sg-field__label">' . myronEscape($fieldLabel) . '</span><input class="sg-field__control" type="text" name="' . myronEscape($name) . '" value="' . myronEscape($value) . '"' . ($canEdit ? '' : ' disabled') . '></label>';
                }
            }
            echo '</div>';
            if ($canEdit) {
                echo '<label class="sg-checkbox"><input type="checkbox" name="zone_content[' . myronEscape($zoneId) . '][' . myronEscape($groupKey) . '][' . $itemIndex . '][__remove]" value="1"> Remove</label>';
            }
            echo '</div>';
        }
        echo '</div>';
        if ($canEdit) {
            echo '<button class="sg-button sg-button--secondary" type="button" data-mc-footer-repeater-add>Add Row</button>';
        }
        echo '</fieldset>';
    }
};

$legalVisibility = is_array($defaultFooter['zone_visibility'] ?? null) ? $defaultFooter['zone_visibility'] : [];
$legalStripActive = !isset($legalVisibility['zone.legal-strip']) || $legalVisibility['zone.legal-strip'] !== false;
$validationSignals = [
    ['status' => 'ready', 'label' => 'Activated variants', 'message' => count($activatedVariants) . ' variants activated.'],
    ['status' => 'ready', 'label' => 'Default', 'message' => 'Default: ' . $defaultVariant],
    ['status' => $legalStripActive ? 'ready' : 'warning', 'label' => 'Legal strip', 'message' => $legalStripActive ? 'Legal strip zone is active on the default variant.' : 'Legal strip zone is disabled on the default variant.'],
];

myronRenderAdminShellStart($currentUser, [
    'title' => 'Footer Design',
    'titleContext' => 'Footer Design',
    'activeItem' => 'design-footers',
    'headScripts' => [myronBuildAssetUrl('runtime/js/asset-picker.js'), myronBuildAssetUrl('runtime/js/admin-footer-design.js')],
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Design', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Building', 'href' => myronBuildAdminUrl('content.sections')],
      ['label' => 'Footers'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Footer Design</h1>
  </div>
  <p class="mc-workspace__subtitle">Design Context / Building / Footers manages activated footer variants and the site default footer.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main" id="top">
    <?php if ($showRecommendation): ?>
    <section class="sg-section mc-footer-recommendation" id="footer-recommendation">
      <div>
        <strong>This site type now recommends <?= myronEscape($recommendedVariant) ?>.</strong>
        <span class="myron-text myron-text--muted">Apply recommendation?</span>
      </div>
      <form method="post" action="<?= myronEscape(myronBuildAdminUrl('design.footers')) ?>">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="bundle_id" value="<?= myronEscape($currentBundleId) ?>">
        <input type="hidden" name="footer_variant" value="<?= myronEscape($recommendedVariant) ?>">
        <button class="sg-button sg-button--primary" type="submit" name="action" value="apply-footer-recommendation">Apply</button>
        <button class="sg-button" type="submit" name="action" value="dismiss-footer-recommendation">Dismiss</button>
      </form>
    </section>
    <?php endif; ?>

    <section class="sg-section" id="footer-default">
      <form method="post" action="<?= myronEscape(myronBuildAdminUrl('design.footers')) ?>" class="sg-form-grid mc-footer-default-form">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="action" value="set-default-footer-design">
        <label class="sg-field">
          <span class="sg-field__label">Default footer variant</span>
          <select class="sg-field__control" name="variant_id"<?= count($activatedVariants) <= 1 || !$canManageDesign ? ' disabled' : '' ?>>
            <?php foreach ($activatedVariants as $row): ?>
            <?php $variantId = (string) ($row['variant_id'] ?? ''); ?>
            <option value="<?= myronEscape($variantId) ?>"<?= $defaultVariant === $variantId ? ' selected' : '' ?>><?= myronEscape($variantLabels[$variantId] ?? $variantId) ?></option>
            <?php endforeach; ?>
          </select>
        </label>
        <div class="sg-card__actions">
          <button class="sg-button sg-button--primary" type="submit"<?= count($activatedVariants) <= 1 || !$canManageDesign ? ' disabled' : '' ?>>Update Default</button>
        </div>
      </form>
    </section>

    <section class="sg-section" id="footer-library">
      <div class="mc-footer-variant-gallery" data-footer-variant-gallery>
        <?php foreach ($variantRows as $row): ?>
        <?php
          $variantId = (string) ($row['variant_id'] ?? '');
          $zones = $compositionService->orderedZonesFor($variantId);
          $isActivated = (bool) ($row['is_activated'] ?? false);
          $isDefault = (bool) ($row['is_default'] ?? false);
          $isRecommended = $recommendedVariant === $variantId;
        ?>
        <article class="mc-footer-variant-card<?= $isActivated ? ' mc-footer-variant-card--activated' : ' mc-footer-variant-card--deactivated' ?><?= $isDefault ? ' mc-footer-variant-card--default' : '' ?>" data-footer-variant-card data-footer-variant="<?= myronEscape($variantId) ?>">
          <div class="mc-footer-variant-card__button">
            <span class="mc-footer-variant-card__header">
              <span class="mc-footer-variant-card__name"><?= myronEscape($variantLabels[$variantId] ?? $variantId) ?></span>
              <span class="mc-footer-variant-card__badge"><?= count($zones) ?> zones</span>
            </span>
            <?php if ($isDefault): ?><span class="mc-footer-variant-card__recommended">Default</span><?php endif; ?>
            <?php if ($isRecommended): ?><span class="mc-footer-variant-card__recommended">Recommended for your site type</span><?php endif; ?>
            <span class="mc-footer-variant-card__diagram" aria-hidden="true">
              <?php foreach ($zones as $zoneId): ?><span class="mc-footer-variant-card__diagram-zone"></span><?php endforeach; ?>
            </span>
            <span class="mc-footer-variant-card__zones">
              <?php foreach ($zones as $zoneId): ?><span><?= myronEscape($zoneLabels[$zoneId] ?? $zoneId) ?></span><?php endforeach; ?>
            </span>
          </div>
          <div class="sg-card__actions">
            <form method="post" action="<?= myronEscape(myronBuildAdminUrl('design.footers')) ?>">
              <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
              <input type="hidden" name="variant_id" value="<?= myronEscape($variantId) ?>">
              <?php if ($isActivated): ?>
              <button class="sg-button sg-button--secondary" type="button" data-mc-sidesheet-open="footer-configure-sheet" data-mc-footer-variant="<?= myronEscape($variantId) ?>"<?= $canManageDesign ? '' : ' disabled' ?>>Configure</button>
              <?php if (!$isDefault): ?>
              <button class="sg-button" type="submit" name="action" value="set-default-footer-design"<?= $canManageDesign ? '' : ' disabled' ?>>Set as default</button>
              <button class="sg-button sg-button--danger-ghost" type="submit" name="action" value="deactivate-footer-design"<?= $canManageDesign ? '' : ' disabled' ?>>Deactivate</button>
              <?php else: ?>
              <button class="sg-button" type="submit" name="action" value="deactivate-footer-design" disabled title="Set a new default before deactivating this variant">Deactivate</button>
              <?php endif; ?>
              <?php else: ?>
              <button class="sg-button sg-button--primary" type="submit" name="action" value="activate-footer-design"<?= $canManageDesign ? '' : ' disabled' ?>>Activate</button>
              <?php endif; ?>
            </form>
          </div>
        </article>
        <?php endforeach; ?>
      </div>
    </section>

    <?php ob_start(); ?>
    <div class="mc-editor-section-tree" data-mc-footer-configure-panels>
      <div class="sg-status" role="status" data-mc-visual-section-empty>Select Configure on an activated footer variant.</div>
      <?php foreach ($variantRows as $row): ?>
      <?php
        $variantId = (string) ($row['variant_id'] ?? '');
        $zones = $compositionService->orderedZonesFor($variantId);
        $visibility = is_array($row['zone_visibility'] ?? null) ? $row['zone_visibility'] : [];
        $contentByZone = is_array($row['zone_content'] ?? null) ? $row['zone_content'] : [];
      ?>
      <section class="mc-editor-section-node" data-mc-footer-config-panel data-footer-variant="<?= myronEscape($variantId) ?>" hidden aria-hidden="true">
        <div class="mc-editor-section-node__header">
          <div>
            <h3 class="sg-card__title">Configure <?= myronEscape($variantLabels[$variantId] ?? $variantId) ?></h3>
            <p class="myron-paragraph myron-paragraph--muted">Update Footer saves visibility and zone content for this variant only.</p>
          </div>
        </div>
        <form method="post" action="<?= myronEscape(myronBuildAdminUrl('design.footers')) ?>" class="mc-sidesheet-form">
          <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
          <input type="hidden" name="action" value="update-footer-configuration">
          <input type="hidden" name="variant_id" value="<?= myronEscape($variantId) ?>">
          <?php foreach ($zones as $zoneId): ?>
          <?php
            $zoneContent = is_array($contentByZone[$zoneId] ?? null) ? $contentByZone[$zoneId] : [];
            $schema = $schemaService->schemaForZone($zoneId, $zoneContent);
            $isVisible = !isset($visibility[$zoneId]) || $visibility[$zoneId] !== false;
            $summary = $zoneSummary($zoneContent, $schema);
          ?>
          <fieldset class="sg-fieldset mc-footer-config-zone" data-mc-footer-zone-section>
            <legend class="sg-fieldset__legend"><?= myronEscape($zoneLabels[$zoneId] ?? $zoneId) ?></legend>
            <div class="mc-footer-config-zone__meta">
              <label class="sg-checkbox mc-footer-config-zone__visible">
                <input type="checkbox" name="footer[zone_visibility][<?= myronEscape($zoneId) ?>]" value="1"<?= $isVisible ? ' checked' : '' ?><?= $canManageDesign ? '' : ' disabled' ?> data-mc-footer-zone-toggle>
                <span>Visible</span>
              </label>
              <p class="myron-paragraph myron-paragraph--muted"><?= myronEscape($summary) ?></p>
            </div>
            <div class="mc-sidesheet-form__grid mc-footer-config-zone__content" data-mc-footer-zone-content<?= $isVisible ? '' : ' hidden' ?>>
              <?php $renderZoneFields($zoneId, $schema, $canManageDesign); ?>
            </div>
            <?php if ($canManageDesign): ?>
            <div class="mc-footer-config-zone__defaults">
              <button class="sg-button sg-button--ghost sg-button--sm"
                      type="submit"
                      name="apply_zone_defaults"
                      value="<?= myronEscape($zoneId) ?>"
                      formnovalidate
                      onclick="return confirm('Replace this zone&apos;s content with the default for your site type? Your current edits to this zone will be overwritten.');">
                Apply default content to this zone
              </button>
            </div>
            <?php endif; ?>
          </fieldset>
          <?php endforeach; ?>
          <div class="sg-card__actions">
            <button class="sg-button sg-button--primary" type="submit"<?= $canManageDesign ? '' : ' disabled' ?>>Update Footer</button>
            <button class="sg-button" type="button" data-mc-sidesheet-close>Cancel</button>
          </div>
        </form>
      </section>
      <?php endforeach; ?>
    </div>
    <?php $footerConfigureBody = (string) ob_get_clean(); ?>
    <?php myronRenderAdminSidesheet('footer-configure-sheet', 'Configure Footer', $footerConfigureBody, [
        'description' => 'Variant-scoped zone visibility and content. Preview updates after save.',
        'size' => 'lg',
    ]); ?>
    <?= MyronAssetPickerView::renderModal('footer-zone-asset-picker', $availableImageFiles, $csrfToken, myronBuildAdminUrl('design.footers'), [
        'assetClass' => 'image',
        'canUpload' => $canManageDesign,
        'title' => 'Choose Footer Asset',
    ]) . "\n" ?>

    <section class="sg-section" id="footer-status">
      <div class="mc-navigation-validation-grid">
        <?php foreach ($validationSignals as $signal): ?>
        <article class="sg-card mc-navigation-validation-card mc-navigation-validation-card--<?= myronEscape((string) $signal['status']) ?>">
          <span class="mc-navigation-validation-card__label"><?= myronEscape((string) $signal['label']) ?></span>
          <p class="myron-paragraph"><?= myronEscape((string) $signal['message']) ?></p>
        </article>
        <?php endforeach; ?>
      </div>
    </section>

    <section class="sg-section" id="footer-render">
      <div class="mc-navigation-preview-grid">
        <?php
        $previewVisibility = is_array($defaultFooter['zone_visibility'] ?? null) ? $defaultFooter['zone_visibility'] : [];
        $previewFooter = myronDefinitionTemplateRenderer()->renderFooterPreview(myronPublicBasePath(), $defaultVariant, $previewVisibility, $zoneLabels);
        foreach ([
            'desktop' => ['label' => 'Desktop', 'class' => 'mc-navigation-preview-frame--desktop'],
            'tablet'  => ['label' => 'Tablet', 'class' => 'mc-navigation-preview-frame--tablet'],
            'mobile'  => ['label' => 'Mobile',  'class' => 'mc-navigation-preview-frame--mobile'],
        ] as $preview):
        ?>
        <article class="mc-navigation-preview">
          <div class="mc-navigation-preview__header"><span class="mc-navigation-preview__label"><?= myronEscape($preview['label']) ?></span></div>
          <div class="mc-navigation-preview-frame <?= myronEscape($preview['class']) ?>"><?= $previewFooter . "\n" ?></div>
        </article>
        <?php endforeach; ?>
      </div>
    </section>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
