<?php

declare(strict_types=1);

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

$currentUser = myronRequireDesignAccess();
$canManageDesign = myronUserCanManageDesign($currentUser);
$navigationRepository = myronNavigationDesignRepository();
$assignmentRepository = myronTemplateChromeAssignmentRepository();
$contentRepository = myronContentRepository();

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

        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $action = trim((string) ($_POST['action'] ?? ''));
        $userId = (string) ($currentUser['id'] ?? '');
        $versionId = trim((string) ($_POST['version_id'] ?? ''));

        // APO-194 Card 1 — navigation version mutations funnel through
        // MyronNavigationVersionActionService. Admin form path + /api/v1/design/navigation/versions/...
        // share identical service-layer logic; dual-mode parity by construction.
        $navService = myronNavigationVersionActionService();
        $callerCtx = myronActionCallerContextForUser($currentUser);

        if ($action === 'create-navigation-version') {
            $navService->create(trim((string) ($_POST['name'] ?? 'New Navigation')), $callerCtx);
            myronRedirectWithFlash(myronBuildAdminUrl('design.navigation'), 'Created navigation version.', 'success');
        }
        if ($action === 'update-navigation-version') {
            $settings = is_array($_POST['navigation'] ?? null) ? $_POST['navigation'] : [];
            $navService->update($versionId, $settings, $callerCtx);
            myronRedirectWithFlash(myronBuildAdminUrl('design.navigation'), 'Updated navigation version.', 'success');
        }
        if ($action === 'activate-navigation-version') {
            $navService->activate($versionId, $callerCtx);
            myronRedirectWithFlash(myronBuildAdminUrl('design.navigation'), 'Activated navigation version.', 'success');
        }
        if ($action === 'deactivate-navigation-version') {
            $navService->deactivate($versionId, $callerCtx);
            myronRedirectWithFlash(myronBuildAdminUrl('design.navigation'), 'Deactivated navigation version.', 'success');
        }
        if ($action === 'set-default-navigation-version') {
            $navService->setDefault($versionId, $callerCtx);
            myronRedirectWithFlash(myronBuildAdminUrl('design.navigation'), 'Updated default navigation version.', 'success');
        }
        if ($action === 'duplicate-navigation-version') {
            $navService->duplicate($versionId, $callerCtx);
            myronRedirectWithFlash(myronBuildAdminUrl('design.navigation'), 'Duplicated navigation version.', 'success');
        }
        if ($action === 'delete-navigation-version') {
            $navService->delete($versionId, $callerCtx);
            myronRedirectWithFlash(myronBuildAdminUrl('design.navigation'), 'Deleted navigation version.', 'success');
        }
        throw new RuntimeException('Unknown navigation design action.');
    } catch (Throwable $exception) {
        myronRedirectWithFlash(myronBuildAdminUrl('design.navigation'), $exception->getMessage(), 'error');
    }
}

$versions = $navigationRepository->listVersions();
$activatedVersions = $navigationRepository->listActivatedSorted();
$defaultVersion = $navigationRepository->getDefault();
$optionSets = $navigationRepository->optionSets();
$placements = $contentRepository->listMenuPlacements();
$primaryPlacement = null;
foreach ($placements as $placement) {
    if ((string) ($placement['placement_key'] ?? '') === 'primary') {
        $primaryPlacement = $placement;
        break;
    }
}
$primaryNavigation = $contentRepository->listPublishedMenuItemTreeByPlacement('primary', true);
$primaryNavigationLinkCount = count($contentRepository->listPublishedMenuItemsByPlacement('primary'));
$previewPage = $contentRepository->getPublishedPageByPath('/');
$previewContext = myronPublicHeaderContextResolver()->resolve($previewPage, '/', $primaryNavigation);
$previewHeader = myronPublicNavigationRenderer()->renderContext($previewContext, myronPublicBasePath(), '/');
$csrfToken = myronCsrfToken();

$labels = [
    'desktop_alignment' => ['split' => 'Split', 'centered' => 'Centered', 'end' => 'End aligned'],
    'menu_alignment' => ['left' => 'Left', 'center' => 'Center', 'right' => 'Right'],
    'brand_display' => ['title' => 'Title', 'title-subtitle' => 'Title + subtitle', 'logo' => 'Logo', 'lockup' => 'Logo + title'],
    'utility_actions_display' => ['auto' => 'Auto from site type', 'show' => 'Always show', 'hide' => 'Hide globally'],
    'appearance_mode_policy' => ['auto' => 'Auto + user toggle', 'light' => 'Force light', 'dark' => 'Force dark'],
    'density' => ['compact' => 'Compact', 'comfortable' => 'Comfortable', 'spacious' => 'Spacious'],
    'mobile_mode' => ['takeover' => 'Full-screen takeover'],
    'surface_treatment' => ['plain' => 'Plain', 'bordered' => 'Bordered', 'elevated' => 'Elevated'],
    'position_behavior' => ['static' => 'Static', 'sticky' => 'Sticky'],
];

$validationSignals = [];
$primaryMenuName = trim((string) ($primaryPlacement['menu_name'] ?? ''));
$validationSignals[] = [
    'status' => ($primaryPlacement !== null && trim((string) ($primaryPlacement['menu_id'] ?? '')) !== '') ? 'ready' : 'warning',
    'label' => 'Primary menu assignment',
    'message' => ($primaryPlacement !== null && trim((string) ($primaryPlacement['menu_id'] ?? '')) !== '') ? 'Primary menu is assigned to ' . $primaryMenuName . '.' : 'No primary menu is assigned. Manage menu placement in Administration.',
];
$validationSignals[] = ['status' => $primaryNavigation === [] ? 'warning' : 'ready', 'label' => 'Published links', 'message' => $primaryNavigation === [] ? 'Primary navigation has no published links.' : $primaryNavigationLinkCount . ' published primary link(s) are available across the menu tree.'];
$validationSignals[] = ['status' => 'ready', 'label' => 'Activated versions', 'message' => count($activatedVersions) . ' versions activated.'];
$validationSignals[] = ['status' => 'ready', 'label' => 'Default', 'message' => 'Default: ' . (string) ($defaultVersion['name'] ?? 'Primary')];

myronRenderAdminShellStart($currentUser, [
    'title' => 'Navigation Design',
    'titleContext' => 'Navigation Design',
    'activeItem' => 'design-navigation',
    'headScripts' => [
        myronBuildAssetUrl('runtime/js/public-navigation.js'),
        myronBuildAssetUrl('runtime/js/admin-navigation-design.js'),
    ],
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Design', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Component Studio', 'href' => myronBuildAdminUrl('content.sections')],
      ['label' => 'Navigation'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Navigation Design</h1>
  </div>
  <p class="mc-workspace__subtitle">Manage saved navigation versions, activation, and the site default header presentation.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main" id="top">
    <section class="sg-section" id="navigation-default">
      <form method="post" action="<?= myronEscape(myronBuildAdminUrl('design.navigation')) ?>" class="sg-form-grid mc-navigation-default-form">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="action" value="set-default-navigation-version">
        <label class="sg-field">
          <span class="sg-field__label">Default navigation version</span>
          <select class="sg-field__control" name="version_id"<?= count($activatedVersions) <= 1 || !$canManageDesign ? ' disabled' : '' ?>>
            <?php foreach ($activatedVersions as $version): ?>
            <option value="<?= myronEscape((string) ($version['id'] ?? '')) ?>"<?= (string) ($defaultVersion['id'] ?? '') === (string) ($version['id'] ?? '') ? ' selected' : '' ?>><?= myronEscape((string) ($version['name'] ?? 'Navigation')) ?></option>
            <?php endforeach; ?>
          </select>
        </label>
        <div class="sg-card__actions"><button class="sg-button sg-button--primary" type="submit"<?= count($activatedVersions) <= 1 || !$canManageDesign ? ' disabled' : '' ?>>Update Default</button></div>
      </form>
    </section>

    <section class="sg-section" id="navigation-versions">
      <form method="post" action="<?= myronEscape(myronBuildAdminUrl('design.navigation')) ?>" class="sg-form-grid mc-navigation-new-version">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="action" value="create-navigation-version">
        <label class="sg-field"><span class="sg-field__label">New version name</span><input class="sg-field__control" type="text" name="name" value="New Navigation"<?= $canManageDesign ? '' : ' disabled' ?>></label>
        <div class="sg-card__actions"><button class="sg-button sg-button--primary" type="submit"<?= $canManageDesign ? '' : ' disabled' ?>>New Version</button></div>
      </form>
      <div class="mc-navigation-version-library" data-navigation-version-library>
        <?php foreach ($versions as $version): ?>
        <?php
          $versionId = (string) ($version['id'] ?? '');
          $isActivated = (bool) ($version['is_activated'] ?? false);
          $isDefault = (bool) ($version['is_default'] ?? false);
          $isReferenced = $navigationRepository->isReferencedByTemplate($versionId);
        ?>
        <article class="sg-card mc-navigation-version-card<?= $isActivated ? ' mc-navigation-version-card--activated' : ' mc-navigation-version-card--deactivated' ?><?= $isDefault ? ' mc-navigation-version-card--default' : '' ?>" data-navigation-version-card data-navigation-version-id="<?= myronEscape($versionId) ?>">
          <div>
            <h2 class="sg-card__title"><?= myronEscape((string) ($version['name'] ?? 'Navigation')) ?></h2>
            <p class="myron-paragraph myron-paragraph--muted"><?= $isDefault ? 'Default' : ($isActivated ? 'Activated' : 'Deactivated') ?></p>
          </div>
          <div class="mc-navigation-preview-frame mc-navigation-preview-frame--desktop"><?= $previewHeader . "\n" ?></div>
          <form method="post" action="<?= myronEscape(myronBuildAdminUrl('design.navigation')) ?>" class="sg-card__actions">
            <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
            <input type="hidden" name="version_id" value="<?= myronEscape($versionId) ?>">
            <?php if ($isActivated): ?>
            <button class="sg-button sg-button--secondary" type="button" data-mc-sidesheet-open="navigation-configure-sheet" data-mc-navigation-version="<?= myronEscape($versionId) ?>"<?= $canManageDesign ? '' : ' disabled' ?>>Configure</button>
            <?php if (!$isDefault): ?>
            <button class="sg-button" type="submit" name="action" value="set-default-navigation-version"<?= $canManageDesign ? '' : ' disabled' ?>>Set as default</button>
            <button class="sg-button sg-button--danger-ghost" type="submit" name="action" value="deactivate-navigation-version"<?= $canManageDesign ? '' : ' disabled' ?>>Deactivate</button>
            <?php else: ?>
            <button class="sg-button" type="submit" name="action" value="deactivate-navigation-version" disabled title="Set a new default before deactivating this version">Deactivate</button>
            <?php endif; ?>
            <?php else: ?>
            <button class="sg-button sg-button--primary" type="submit" name="action" value="activate-navigation-version"<?= $canManageDesign ? '' : ' disabled' ?>>Activate</button>
            <?php endif; ?>
            <button class="sg-button" type="submit" name="action" value="duplicate-navigation-version"<?= $canManageDesign ? '' : ' disabled' ?>>Duplicate</button>
            <button class="sg-button sg-button--danger-ghost" type="submit" name="action" value="delete-navigation-version"<?= (!$canManageDesign || $isDefault || $isReferenced) ? ' disabled' : '' ?>>Delete</button>
            <?php if ($isReferenced): ?><span class="myron-text myron-text--muted">Templates use this version. Reassign before deleting.</span><?php endif; ?>
          </form>
        </article>
        <?php endforeach; ?>
      </div>
    </section>

    <?php ob_start(); ?>
    <div class="mc-editor-section-tree" data-mc-navigation-configure-panels>
      <div class="sg-status" role="status" data-mc-visual-section-empty>Select Configure on a navigation version.</div>
      <?php foreach ($versions as $version): ?>
      <?php $versionId = (string) ($version['id'] ?? ''); ?>
      <section class="mc-editor-section-node" data-mc-navigation-config-panel data-navigation-version-id="<?= myronEscape($versionId) ?>" hidden aria-hidden="true">
        <div class="mc-editor-section-node__header">
          <div><h3 class="sg-card__title">Configure <?= myronEscape((string) ($version['name'] ?? 'Navigation')) ?></h3></div>
        </div>
        <form method="post" action="<?= myronEscape(myronBuildAdminUrl('design.navigation')) ?>" class="sg-form-grid">
          <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
          <input type="hidden" name="action" value="update-navigation-version">
          <input type="hidden" name="version_id" value="<?= myronEscape($versionId) ?>">
          <label class="sg-field"><span class="sg-field__label">Name</span><input class="sg-field__control" type="text" name="navigation[name]" value="<?= myronEscape((string) ($version['name'] ?? 'Navigation')) ?>"<?= $canManageDesign ? '' : ' disabled' ?>></label>
          <?php foreach ([
              'desktop_alignment' => 'Desktop Alignment',
              'menu_alignment' => 'Menu Alignment',
              'utility_actions_display' => 'Utility Actions',
              'appearance_mode_policy' => 'Appearance Mode',
              'density' => 'Density',
              'mobile_mode' => 'Mobile Mode',
              'surface_treatment' => 'Surface',
              'position_behavior' => 'Position',
              'brand_display' => 'Brand Display',
          ] as $field => $label): ?>
          <label class="sg-field">
            <span class="sg-field__label"><?= myronEscape($label) ?></span>
            <select class="sg-field__control" name="navigation[<?= myronEscape($field) ?>]"<?= $canManageDesign ? '' : ' disabled' ?>>
              <?php foreach (($optionSets[$field] ?? []) as $option): ?>
              <option value="<?= myronEscape($option) ?>"<?= (string) ($version[$field] ?? '') === $option ? ' selected' : '' ?>><?= myronEscape($labels[$field][$option] ?? $option) ?></option>
              <?php endforeach; ?>
            </select>
          </label>
          <?php endforeach; ?>
          <label class="sg-field"><span class="sg-field__label">Brand Subtitle</span><input class="sg-field__control" type="text" name="navigation[brand_subtitle]" value="<?= myronEscape((string) ($version['brand_subtitle'] ?? '')) ?>" maxlength="120"<?= $canManageDesign ? '' : ' disabled' ?>></label>
          <div class="sg-card__actions">
            <button class="sg-button sg-button--primary" type="submit"<?= $canManageDesign ? '' : ' disabled' ?>>Update Navigation</button>
            <button class="sg-button" type="button" data-mc-sidesheet-close>Cancel</button>
          </div>
        </form>
      </section>
      <?php endforeach; ?>
    </div>
    <?php $navigationConfigureBody = (string) ob_get_clean(); ?>
    <?php myronRenderAdminSidesheet('navigation-configure-sheet', 'Configure Navigation', $navigationConfigureBody, [
        'description' => 'Saved version presentation settings.',
        'size' => 'lg',
    ]); ?>

    <section class="sg-section" id="navigation-validation">
      <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="navigation-previews">
      <div class="mc-navigation-preview-grid">
        <?php foreach ([
            'desktop' => ['label' => 'Desktop', 'class' => 'mc-navigation-preview-frame--desktop'],
            'tablet' => ['label' => 'Tablet', 'class' => 'mc-navigation-preview-frame--tablet'],
            'mobile-closed' => ['label' => 'Mobile Closed', 'class' => 'mc-navigation-preview-frame--mobile'],
            'mobile-open' => ['label' => 'Mobile Open', 'class' => 'mc-navigation-preview-frame--mobile mc-navigation-preview-frame--mobile-open'],
        ] 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']) ?>">
            <?= $previewHeader . "\n" ?>
            <div class="mc-navigation-preview-frame__body" aria-hidden="true"></div>
          </div>
        </article>
        <?php endforeach; ?>
      </div>
    </section>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
