<?php

declare(strict_types=1);

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

$currentUser = myronRequireContentAccess();
$templateRepository = myronTemplateDefinitionRepository();
$bundleRepository = myronBundleActivationRepository();
$contentRepository = myronContentRepository();
$currentSiteUsage = myronCurrentSiteUsageReadModel();
$allTemplates = $templateRepository->listTemplates();
$availability = $bundleRepository->templateAvailabilityIndex($allTemplates);
$runtimeTemplatesBySource = $contentRepository->listTemplatesBySourceTemplateId();
$currentTemplateUsageIndex = $currentSiteUsage->templateUsageIndex();
$currentTemplateSourceIdSet = array_fill_keys($currentSiteUsage->currentTemplateSourceIds(), true);

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

$queryFromFilters = static function (array $classes, array $statuses): array {
    $query = [];
    if ($classes !== []) {
        $query['class'] = implode(',', array_values(array_map('strval', $classes)));
    }
    if ($statuses !== []) {
        $query['status'] = implode(',', array_values(array_map('strval', $statuses)));
    }

    return $query;
};

$selectedTemplateClasses = $filterValues($_GET['class'] ?? '');
$selectedStatuses = $filterValues($_GET['status'] ?? '');
$selectedTemplateId = trim((string) ($_GET['template'] ?? ''));

$currentTemplates = array_values(array_filter(
    $allTemplates,
    static function (array $template) use ($currentTemplateSourceIdSet): bool {
        $templateId = (string) ($template['id'] ?? '');
        return isset($currentTemplateSourceIdSet[$templateId]);
    }
));

$classOptions = [];
$statusOptions = [];
foreach ($currentTemplates as $template) {
    $templateId = (string) ($template['id'] ?? '');
    $templateClass = MyronTemplateDefinitionRepository::templateClassForTemplateId($templateId);
    if ($templateClass !== '') {
        $classOptions[$templateClass] = $templateClass;
    }
    $status = MyronTemplateDefinitionRepository::remediationStatusForTemplate($template);
    if ($status !== '') {
        $statusOptions[$status] = $status;
    }
}
ksort($classOptions);
ksort($statusOptions);

$selectedTemplateClasses = array_values(array_filter($selectedTemplateClasses, static fn (string $value): bool => isset($classOptions[$value])));
$selectedStatuses = array_values(array_filter($selectedStatuses, static fn (string $value): bool => isset($statusOptions[$value])));

$listQuery = $queryFromFilters($selectedTemplateClasses, $selectedStatuses);
$selectedTemplate = $selectedTemplateId !== '' ? $templateRepository->findTemplateById($selectedTemplateId) : null;
$isDetailMode = $selectedTemplateId !== '';
$selectedPreviewPage = is_array($selectedTemplate)
    ? myronTemplatePreviewFactory()->buildPreviewPage($selectedTemplate)
    : null;
$backToTemplatesUrl = myronBuildAdminUrl('content.templates', $listQuery);
$templateDetailUrl = static fn (string $templateId): string => myronBuildAdminUrl('content.templates', array_merge($listQuery, ['template' => $templateId]));
$useTemplateUrl = static fn (string $templateId): string => myronBuildAdminUrl('content.pageEditor', [
    'mode' => 'create',
    'template_source' => $templateId,
    'return_to' => 'content.templates',
    'return_template' => $templateId,
]);

myronRenderAdminShellStart($currentUser, [
    'title' => 'Page Templates',
    'titleContext' => 'Content',
    'activeItem' => 'content-templates',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs($isDetailMode ? [
      ['label' => 'Content', 'href' => myronBuildAdminUrl('content.pages')],
      ['label' => 'Page Templates', 'href' => myronBuildAdminUrl('content.templates')],
      ['label' => 'Template'],
  ] : [
      ['label' => 'Content', 'href' => myronBuildAdminUrl('content.pages')],
      ['label' => 'Page Templates'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title"><?= myronEscape($isDetailMode && is_array($selectedTemplate) ? (string) ($selectedTemplate['name'] ?? $selectedTemplateId) : 'Page Templates') ?></h1>
  </div>
  <p class="mc-workspace__subtitle"><?= $isDetailMode ? 'Preview the page template and start a new page from its structure.' : 'Browse the page templates available in this site and start a new page from one.' ?></p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <?php if (!$isDetailMode): ?>
    <section class="sg-section mc-component-filter mc-inspection-filters" data-mc-live-filter>
      <div class="mc-filter-group" role="group" aria-label="Page Type filters" data-mc-filter-group data-mc-filter-param="class">
        <span class="mc-filter-group__label">Page Type</span>
        <div class="mc-filter-pill-row">
          <button class="sg-pill mc-filter-pill<?= $selectedTemplateClasses === [] ? ' sg-pill--active' : '' ?>" type="button" data-mc-filter-all aria-pressed="<?= $selectedTemplateClasses === [] ? 'true' : 'false' ?>">All</button>
          <?php foreach ($classOptions as $templateClass): ?>
          <button class="sg-pill mc-filter-pill<?= in_array($templateClass, $selectedTemplateClasses, true) ? ' sg-pill--active' : '' ?>" type="button" data-mc-filter-value="<?= myronEscape($templateClass) ?>" aria-pressed="<?= in_array($templateClass, $selectedTemplateClasses, true) ? 'true' : 'false' ?>"><?= myronEscape(ucwords(str_replace('-', ' ', $templateClass))) ?></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($currentTemplates)) ?> matching</span>
        <span class="sg-pill"><?= myronEscape((string) count($currentTemplates)) ?> page templates available</span>
      </div>
      <div class="sg-status" role="status" data-mc-filter-empty hidden>No page templates match the current filters.</div>

      <div class="mc-page-grid" role="table" aria-label="Page templates" data-mc-sortable-grid>
        <div class="mc-page-grid__row mc-page-grid__row--head" role="row">
          <span role="columnheader" data-mc-sort-key="template"><button class="mc-page-grid__sort" type="button">Template</button></span>
          <span role="columnheader" data-mc-sort-key="class"><button class="mc-page-grid__sort" type="button">Page Type</button></span>
          <span role="columnheader" data-mc-sort-key="site"><button class="mc-page-grid__sort" type="button">Site Type</button></span>
          <span role="columnheader" data-mc-sort-key="sections" data-mc-sort-type="number"><button class="mc-page-grid__sort" type="button">Sections</button></span>
          <span role="columnheader" data-mc-sort-key="usage" data-mc-sort-type="number"><button class="mc-page-grid__sort" type="button">In Use</button></span>
          <span role="columnheader">Actions</span>
        </div>

        <?php foreach ($currentTemplates as $template): ?>
        <?php
          $templateId = (string) ($template['id'] ?? '');
          $registry = is_array($template['_registry'] ?? null) ? $template['_registry'] : [];
          $templateClass = MyronTemplateDefinitionRepository::templateClassForTemplateId($templateId);
          $bodySections = is_array($template['bodySections'] ?? null) ? $template['bodySections'] : [];
          $remediationStatus = MyronTemplateDefinitionRepository::remediationStatusForTemplate($template);
          $runtimeTemplates = $runtimeTemplatesBySource[$templateId] ?? [];
          $currentUsage = $currentTemplateUsageIndex[$templateId] ?? ['pageCount' => 0, 'pages' => []];
          $pageCount = (int) ($currentUsage['pageCount'] ?? 0);
          $siteTypeValue = (string) ($registry['siteType'] ?? $template['siteType'] ?? '');
          $siteTypeFriendly = MyronSiteTypeRegistryRepository::friendlyLabelForCode($siteTypeValue);
          $bundleValue = (string) ($registry['bundleId'] ?? $template['bundleId'] ?? '');
        ?>
        <div
          class="mc-page-grid__row"
          role="row"
          data-mc-filter-row
          data-filter-class="<?= myronEscape($templateClass) ?>"
          data-filter-status="<?= myronEscape($remediationStatus) ?>"
          data-sort-template="<?= myronEscape((string) ($template['name'] ?? $templateId)) ?>"
          data-sort-class="<?= myronEscape($templateClass) ?>"
          data-sort-site="<?= myronEscape($siteTypeFriendly) ?>"
          data-sort-sections="<?= myronEscape((string) count($bodySections)) ?>"
          data-sort-usage="<?= myronEscape((string) $pageCount) ?>"
          data-sort-status="<?= myronEscape($remediationStatus) ?>"
        >
          <span class="mc-page-grid__cell mc-page-grid__cell--name" role="cell">
            <span class="mc-page-grid__name"><?= myronEscape((string) ($template['name'] ?? $templateId)) ?></span>
          </span>
          <span class="mc-page-grid__cell" role="cell"><?= myronEscape(ucwords(str_replace('-', ' ', $templateClass))) ?></span>
          <span class="mc-page-grid__cell" role="cell"><?= myronEscape($siteTypeFriendly) ?></span>
          <span class="mc-page-grid__cell" role="cell"><?= myronEscape((string) count($bodySections)) ?></span>
          <span class="mc-page-grid__cell" role="cell"><?= $pageCount === 0 ? 'Not yet used' : myronEscape((string) $pageCount) . ' page' . ($pageCount === 1 ? '' : 's') ?></span>
          <span class="mc-page-grid__cell mc-page-grid__cell--actions" role="cell">
            <a class="sg-button sg-button--secondary" href="<?= myronEscape($templateDetailUrl($templateId)) ?>">Preview</a>
          </span>
        </div>
        <?php endforeach; ?>
      </div>
    </section>
    <?php else: ?>
    <section class="sg-section mc-template-manager-viewer" data-myron-content-template-detail data-source-template-id="<?= myronEscape($selectedTemplateId) ?>">
      <?php if (!is_array($selectedTemplate) || !is_array($selectedPreviewPage)): ?>
      <div class="mc-editor-toolbar">
        <div class="mc-editor-toolbar__summary">
          <span class="sg-pill sg-pill--secondary">Template unavailable</span>
        </div>
        <div class="mc-editor-toolbar__actions">
          <a class="sg-button sg-button--secondary" href="<?= myronEscape($backToTemplatesUrl) ?>">Back to Page Templates</a>
        </div>
      </div>
      <div class="sg-status" role="status">The selected template could not be loaded.</div>
      <?php else: ?>
      <?php
        // STN-012-016: Architectural Guidance sidesheet for the Content operator — same render
        // as the Designer's Site Type Studio sidesheet (shared via Support helper). Read-only on
        // both sides; provides the editorial intent of the template before the operator commits to
        // initiating a new page.
        $contentGuidanceBody = myronRenderTemplateGuidanceSidesheetBody(
            is_array($selectedTemplate['guidance'] ?? null) ? $selectedTemplate['guidance'] : null
        );
      ?>
      <div class="mc-editor-toolbar">
        <div class="mc-editor-toolbar__summary">
          <span class="sg-pill">Read only</span>
        </div>
        <div class="mc-editor-toolbar__actions">
          <a class="sg-button sg-button--secondary" href="<?= myronEscape($backToTemplatesUrl) ?>">Back to Page Templates</a>
          <?php if ($contentGuidanceBody !== ''): ?>
          <button class="sg-button sg-button--secondary" type="button" data-mc-sidesheet-open="content-template-guidance-sheet">Architectural Guidance</button>
          <?php endif; ?>
          <button class="sg-button sg-button--secondary" type="button" data-mc-sidesheet-open="content-template-attributes-sheet">Template Details</button>
          <a class="sg-button sg-button--primary" href="<?= myronEscape($useTemplateUrl($selectedTemplateId)) ?>">Use This Template</a>
        </div>
      </div>
      <div class="mc-editor-viewer__canvas mc-template-manager-viewer__canvas" data-myron-content-template-rendered-viewer>
        <?= myronDefinitionTemplateRenderer()->renderPublishedPage($selectedPreviewPage, myronPublicBasePath(), []) . "\n" ?>
      </div>
      <?php endif; ?>
    </section>

    <?php if (is_array($selectedTemplate)): ?>
    <?php
      $registry = is_array($selectedTemplate['_registry'] ?? null) ? $selectedTemplate['_registry'] : [];
      $templateClass = MyronTemplateDefinitionRepository::templateClassForTemplateId($selectedTemplateId);
      $bodySections = is_array($selectedTemplate['bodySections'] ?? null) ? $selectedTemplate['bodySections'] : [];
      $runtimeTemplates = $runtimeTemplatesBySource[$selectedTemplateId] ?? [];
      $siteTypeFriendly = MyronSiteTypeRegistryRepository::friendlyLabelForCode(
          (string) ($registry['siteType'] ?? $selectedTemplate['siteType'] ?? '')
      );
      $currentUsage = $currentTemplateUsageIndex[$selectedTemplateId] ?? ['pageCount' => 0, 'pages' => []];
      $detailPageCount = (int) ($currentUsage['pageCount'] ?? 0);
      // STN-012-016: Template Details sidesheet sanitized for Content operator —
      // removed Template Key / Bundle / Source Path / raw Chrome Declaration / Status Notes
      // (developer-internal helpers per the pre-R1 sanitization rule). Surfaced operator-meaningful
      // metadata only: page type, site type, section list with friendly names, current usage count.
      ob_start();
    ?>
    <dl class="sg-definition-list">
      <div class="sg-definition-list__row">
        <dt>Page Type</dt>
        <dd><?= myronEscape(ucwords(str_replace('-', ' ', $templateClass))) ?></dd>
      </div>
      <div class="sg-definition-list__row">
        <dt>Site Type</dt>
        <dd><?= myronEscape($siteTypeFriendly) ?></dd>
      </div>
      <div class="sg-definition-list__row">
        <dt>Sections</dt>
        <dd>
          <?php if ($bodySections === []): ?>
          <span class="mc-page-grid__muted">No body sections</span>
          <?php else: ?>
          <ol class="sg-list">
            <?php foreach ($bodySections as $position => $section): ?>
            <?php if (is_array($section)): ?>
            <li>
              <?= myronEscape(ucwords(str_replace('-', ' ', trim((string) ($section['sectionKey'] ?? '')) !== '' ? (string) $section['sectionKey'] : (string) ($section['componentId'] ?? 'section')))) ?>
            </li>
            <?php endif; ?>
            <?php endforeach; ?>
          </ol>
          <?php endif; ?>
        </dd>
      </div>
      <div class="sg-definition-list__row">
        <dt>Current Usage</dt>
        <dd>
          <?= $detailPageCount === 0 ? 'Not yet used by any pages on this site.' : myronEscape((string) $detailPageCount) . ' page' . ($detailPageCount === 1 ? '' : 's') . ' currently use' . ($detailPageCount === 1 ? 's' : '') . ' this template.' ?>
        </dd>
      </div>
    </dl>
    <?php $templateAttributesBody = (string) ob_get_clean(); ?>
    <?php myronRenderAdminSidesheet('content-template-attributes-sheet', 'Template Details', $templateAttributesBody, [
        'description' => 'What the template includes and how it is used on this site.',
        'size' => 'md',
    ]); ?>
    <?php if ($contentGuidanceBody !== ''): ?>
    <?php myronRenderAdminSidesheet('content-template-guidance-sheet', 'Architectural Guidance', $contentGuidanceBody, [
        'description' => 'How this template is structured and the editorial intent behind each section.',
        'size' => 'lg',
    ]); ?>
    <?php endif; ?>
    <?php endif; ?>
    <?php endif; ?>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
