<?php

declare(strict_types=1);

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

$currentUser = myronRequireContentAccess();
$currentSiteUsage = myronCurrentSiteUsageReadModel();
$primitiveRenderer = myronPrimitiveRenderer();
$sections = $currentSiteUsage->governedSectionInventoryRows();

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

$selectedJtbdGroups = $filterValues($_GET['jtbd'] ?? '');
$selectedSectionTypes = $filterValues($_GET['type'] ?? '');
$selectedSectionKey = trim((string) ($_GET['section'] ?? ''));

$jtbdGroups = [];
$sectionTypes = [];
foreach ($sections as $section) {
    $group = trim((string) ($section['jtbdGroup'] ?? ''));
    $type = trim((string) ($section['sectionType'] ?? ''));
    if ($group !== '') {
        $jtbdGroups[$group] = $group;
    }
    if ($type !== '') {
        $sectionTypes[$type] = $type;
    }
}
ksort($jtbdGroups);
ksort($sectionTypes);

$selectedJtbdGroups = array_values(array_filter($selectedJtbdGroups, static fn (string $value): bool => isset($jtbdGroups[$value])));
$selectedSectionTypes = array_values(array_filter($selectedSectionTypes, static fn (string $value): bool => isset($sectionTypes[$value])));
$listQuery = [];
if ($selectedJtbdGroups !== []) {
    $listQuery['jtbd'] = implode(',', $selectedJtbdGroups);
}
if ($selectedSectionTypes !== []) {
    $listQuery['type'] = implode(',', $selectedSectionTypes);
}

$selectedSection = $selectedSectionKey !== ''
    ? $currentSiteUsage->findGovernedSectionByKey($selectedSectionKey)
    : null;
$isDetailMode = is_array($selectedSection);
$backToSectionsUrl = myronBuildAdminUrl('content.sections', $listQuery);
$sectionDetailUrl = static fn (array $row): string => myronBuildAdminUrl('content.sections', array_merge($listQuery, ['section' => (string) ($row['sectionKey'] ?? '')]));

$title = $isDetailMode ? (string) ($selectedSection['label'] ?? $selectedSectionKey) : 'Sections';

myronRenderAdminShellStart($currentUser, [
    'title' => $title,
    'titleContext' => 'Content',
    'activeItem' => 'content-sections',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs($isDetailMode ? [
      ['label' => 'Content', 'href' => myronBuildAdminUrl('content.pages')],
      ['label' => 'Sections', 'href' => myronBuildAdminUrl('content.sections')],
      ['label' => 'Section'],
  ] : [
      ['label' => 'Content', 'href' => myronBuildAdminUrl('content.pages')],
      ['label' => 'Sections'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title"><?= myronEscape($title) ?></h1>
  </div>
  <p class="mc-workspace__subtitle"><?= $isDetailMode ? 'Read-only rendered inspection for a section currently used by site pages.' : 'Read-only inspection for rendered sections currently used by site pages.' ?></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="Job to Be Done filters" data-mc-filter-group data-mc-filter-param="jtbd">
        <span class="mc-filter-group__label">Job to Be Done</span>
        <div class="mc-filter-pill-row">
          <button class="sg-pill mc-filter-pill<?= $selectedJtbdGroups === [] ? ' sg-pill--active' : '' ?>" type="button" data-mc-filter-all aria-pressed="<?= $selectedJtbdGroups === [] ? 'true' : 'false' ?>">All</button>
          <?php foreach ($jtbdGroups as $group): ?>
          <button class="sg-pill mc-filter-pill<?= in_array($group, $selectedJtbdGroups, true) ? ' sg-pill--active' : '' ?>" type="button" data-mc-filter-value="<?= myronEscape($group) ?>" aria-pressed="<?= in_array($group, $selectedJtbdGroups, true) ? 'true' : 'false' ?>"><?= myronEscape($group) ?></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<?= $selectedSectionTypes === [] ? ' sg-pill--active' : '' ?>" type="button" data-mc-filter-all aria-pressed="<?= $selectedSectionTypes === [] ? 'true' : 'false' ?>">All</button>
          <?php foreach ($sectionTypes as $sectionType): ?>
          <button class="sg-pill mc-filter-pill<?= in_array($sectionType, $selectedSectionTypes, true) ? ' sg-pill--active' : '' ?>" type="button" data-mc-filter-value="<?= myronEscape($sectionType) ?>" aria-pressed="<?= in_array($sectionType, $selectedSectionTypes, true) ? 'true' : 'false' ?>"><?= myronEscape($sectionType) ?></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($sections)) ?> matching</span>
        <span class="sg-pill"><?= myronEscape((string) count($sections)) ?> current-site sections</span>
      </div>

      <div class="sg-status" role="status" data-mc-filter-empty hidden>No current-site sections match the current filters.</div>
      <div class="mc-page-grid" role="table" aria-label="Rendered section inventory" 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="jtbd"><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">Render Component</button></span>
          <span role="columnheader" data-mc-sort-key="usage" data-mc-sort-type="number"><button class="mc-page-grid__sort" type="button">Page Usage</button></span>
          <span role="columnheader" data-mc-sort-key="status"><button class="mc-page-grid__sort" type="button">Status</button></span>
          <span role="columnheader">Inspect</span>
        </div>

        <?php foreach ($sections as $section): ?>
        <?php
          $componentId = (string) ($section['componentId'] ?? '');
          $variant = (string) ($section['variant'] ?? '');
          $label = (string) ($section['label'] ?? $componentId);
          $usageItems = is_array($section['usages'] ?? null) ? $section['usages'] : [];
          $renderComponents = array_values(array_map('strval', is_array($section['primaryComponents'] ?? null) ? $section['primaryComponents'] : []));
          if ($renderComponents === [] && $componentId !== '') {
              $renderComponents = [$componentId . ($variant !== '' ? ' / ' . $variant : '')];
          }
        ?>
        <div
          class="mc-page-grid__row"
          role="row"
          data-mc-filter-row
          data-filter-jtbd="<?= myronEscape((string) ($section['jtbdGroup'] ?? '')) ?>"
          data-filter-type="<?= myronEscape((string) ($section['sectionType'] ?? '')) ?>"
          data-sort-section="<?= myronEscape($label . ' ' . (string) ($section['sectionKey'] ?? $section['identityKey'] ?? $componentId)) ?>"
          data-sort-jtbd="<?= myronEscape((string) ($section['jtbdGroup'] ?? '')) ?>"
          data-sort-type="<?= myronEscape((string) ($section['sectionType'] ?? '')) ?>"
          data-sort-components="<?= myronEscape(implode(', ', $renderComponents)) ?>"
          data-sort-usage="<?= myronEscape((string) count($usageItems)) ?>"
          data-sort-status="<?= myronEscape((string) ($section['remediationStatus'] ?? '')) ?>"
        >
          <span class="mc-page-grid__cell mc-page-grid__cell--name" role="cell">
            <span class="mc-page-grid__name"><?= myronEscape($label) ?></span>
            <span class="mc-page-grid__subtle"><code><?= myronEscape((string) ($section['sectionKey'] ?? $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"><span class="sg-pill"><?= myronEscape((string) ($section['sectionType'] ?? '')) ?></span></span>
          <span class="mc-page-grid__cell" role="cell"><?= myronEscape(implode(', ', $renderComponents)) ?></span>
          <span class="mc-page-grid__cell" role="cell">
            <span class="sg-pill <?= $usageItems !== [] ? 'sg-pill--active' : 'sg-pill--secondary' ?>"><?= myronEscape((string) count($usageItems)) ?> occurrences</span>
          </span>
          <span class="mc-page-grid__cell" role="cell">
            <span class="sg-pill sg-pill--active"><?= myronEscape((string) ($section['remediationStatus'] ?? '')) ?></span>
          </span>
          <span class="mc-page-grid__cell mc-page-grid__cell--actions" role="cell">
            <a class="sg-button sg-button--secondary" href="<?= myronEscape($sectionDetailUrl($section)) ?>">Open</a>
          </span>
        </div>
        <?php endforeach; ?>
      </div>
    </section>
    <?php else: ?>
    <?php
      $componentId = (string) ($selectedSection['componentId'] ?? '');
      $variant = (string) ($selectedSection['variant'] ?? '');
      $defaultContent = is_array($selectedSection['defaultContent'] ?? null) ? $selectedSection['defaultContent'] : [];
      $sourceTemplates = is_array($selectedSection['sourceTemplateIds'] ?? null) ? $selectedSection['sourceTemplateIds'] : [];
      $sourceTemplateId = (string) ($sourceTemplates[0] ?? '');
      $renderedSection = $primitiveRenderer->renderById($componentId, [
          'variant' => $variant,
          'title' => (string) ($defaultContent['headline'] ?? $selectedSection['label'] ?? ''),
          'body' => (string) ($defaultContent['body'] ?? ''),
          'content' => $defaultContent,
      ], [
          'templateId' => $sourceTemplateId,
          'basePath' => myronPublicBasePath(),
      ]);
    ?>
    <section class="sg-section mc-template-manager-viewer" data-myron-content-section-detail data-component-id="<?= myronEscape($componentId) ?>" data-section-identity="<?= myronEscape((string) ($selectedSection['identityKey'] ?? $componentId)) ?>">
      <div class="mc-editor-toolbar">
        <div class="mc-editor-toolbar__summary">
          <span class="sg-pill">read only</span>
          <span class="mc-editor-toolbar__meta"><code><?= myronEscape((string) ($selectedSection['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-inspector-sheet">Section Details</button>
        </div>
      </div>

      <div class="mc-section-render-preview" data-myron-rendered-section-preview>
        <?= $renderedSection ?>
      </div>
    </section>

    <?php ob_start(); ?>
    <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) ($selectedSection['sectionKey'] ?? '')) !== '' ? '<code>' . myronEscape((string) $selectedSection['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) ($selectedSection['usageCount'] ?? 0)) ?> live occurrences</dd>
      </div>
    </dl>
    <?php $sheetBody = (string) ob_get_clean(); ?>
    <?php myronRenderAdminSidesheet('section-inspector-sheet', 'Section Details', $sheetBody, [
        'description' => 'Read-only rendered section identity and usage.',
        'size' => 'lg',
    ]); ?>
    <?php endif; ?>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
