<?php

declare(strict_types=1);

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

$currentUser = myronRequireDesignAccess();
$canManageDesign = myronUserCanManageDesign($currentUser);
$railRepository = myronRailDesignRepository();
$railService = myronRailDesignActionService();
$templateRepository = myronTemplateDefinitionRepository();
$csrfToken = myronCsrfToken();

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (!$canManageDesign) {
            throw new RuntimeException('Your current role cannot update rail design settings.');
        }
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $caller = myronActionCallerContextForUser($currentUser);
        $action = trim((string) ($_POST['action'] ?? ''));
        $railId = trim((string) ($_POST['rail_id'] ?? MyronRailDesignRepository::DEFAULT_RAIL));

        if ($action === 'set-default-rail') {
            $railService->setDefault($railId, $caller);
            myronRedirectWithFlash(myronBuildAdminUrl('design.rails'), 'Updated default rail.', 'success');
        }

        if ($action === 'update-rail-defaults') {
            $railService->updateRail($railId, [
                'name' => (string) ($_POST['name'] ?? ''),
                'placement_default' => (string) ($_POST['placement_default'] ?? 'right'),
                'content' => [
                    'summary' => (string) ($_POST['summary'] ?? ''),
                    'slots' => is_array($_POST['slots'] ?? null) ? $_POST['slots'] : [],
                ],
            ], $caller);
            myronRedirectWithFlash(myronBuildAdminUrl('design.rails'), 'Updated rail configuration.', 'success');
        }

        if ($action === 'update-template-rail-assignment') {
            $sourceTemplateId = trim((string) ($_POST['template_id'] ?? ''));
            $placement = trim((string) ($_POST['placement'] ?? 'right'));
            $railService->setTemplateAssignment($sourceTemplateId, $railId, $placement, $caller);
            $runtimeTemplate = myronContentRepository()->findRuntimeTemplateBySourceTemplateId($sourceTemplateId);
            if (is_array($runtimeTemplate)) {
                myronContentRepository()->updateRuntimeTemplateBlogRailPlacement((string) ($runtimeTemplate['id'] ?? ''), $placement);
            }
            myronRedirectWithFlash(myronBuildAdminUrl('design.rails'), 'Updated template rail assignment.', 'success');
        }

        throw new RuntimeException('Unknown rail design action.');
    } catch (Throwable $exception) {
        myronRedirectWithFlash(myronBuildAdminUrl('design.rails'), $exception->getMessage(), 'error');
    }
}

$rails = $railRepository->listRails();
$activatedRails = $railRepository->listActivatedSorted();
$defaultRail = $railRepository->getDefault();
$assignmentsByTemplate = [];
foreach ($railRepository->listTemplateAssignments() as $assignment) {
    $assignmentsByTemplate[(string) ($assignment['template_id'] ?? '')] = $assignment;
}

$blogTemplates = [];
foreach ($railRepository->supportedBlogTemplateIds() as $templateId) {
    $definition = $templateRepository->findTemplateById($templateId);
    $schema = is_array($definition) ? $definition : [];
    $resolved = $railRepository->resolveForTemplate($templateId, $schema);
    $blogTemplates[] = [
        'id' => $templateId,
        'name' => is_array($definition) ? (string) ($definition['name'] ?? $templateId) : $templateId,
        'resolved' => $resolved,
        'assignment' => $assignmentsByTemplate[$templateId] ?? null,
    ];
}

$validationSignals = [
    [
        'status' => count($activatedRails) > 0 ? 'ready' : 'warning',
        'label' => 'Activated rails',
        'message' => count($activatedRails) . ' rail(s) activated.',
    ],
    [
        'status' => 'ready',
        'label' => 'Default',
        'message' => 'Default: ' . (string) ($defaultRail['name'] ?? 'Standard Blog Rail'),
    ],
    [
        'status' => count($blogTemplates) === 2 ? 'ready' : 'warning',
        'label' => 'Blog assignments',
        'message' => count($blogTemplates) . ' Blog template assignment(s) available.',
    ],
];

myronRenderAdminShellStart($currentUser, [
    'title' => 'Rails Design',
    'titleContext' => 'Rails Design',
    'activeItem' => 'component-studio-rails',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Design', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Component Studio', 'href' => myronBuildAdminUrl('content.sections')],
      ['label' => 'Rails'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Rails Design</h1>
  </div>
  <p class="mc-workspace__subtitle">Manage the reusable site rail used by Blog index and post templates.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main" id="top">
    <section class="sg-section mc-rails-status" id="rail-status">
      <div class="mc-rails-status__grid">
        <?php foreach ($validationSignals as $signal): ?>
        <div class="sg-status sg-status--<?= myronEscape((string) $signal['status']) ?>">
          <strong><?= myronEscape((string) $signal['label']) ?></strong>
          <span><?= myronEscape((string) $signal['message']) ?></span>
        </div>
        <?php endforeach; ?>
      </div>
    </section>

    <section class="sg-section" id="rail-default">
      <form method="post" action="<?= myronEscape(myronBuildAdminUrl('design.rails')) ?>" class="mc-rails-default-form">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="action" value="set-default-rail">
        <label class="sg-field">
          <span class="sg-field__label">Default rail</span>
          <select class="sg-field__control" name="rail_id"<?= count($activatedRails) <= 1 || !$canManageDesign ? ' disabled' : '' ?>>
            <?php foreach ($activatedRails as $rail): ?>
            <option value="<?= myronEscape((string) ($rail['rail_id'] ?? '')) ?>"<?= (string) ($defaultRail['rail_id'] ?? '') === (string) ($rail['rail_id'] ?? '') ? ' selected' : '' ?>><?= myronEscape((string) ($rail['name'] ?? 'Rail')) ?></option>
            <?php endforeach; ?>
          </select>
        </label>
        <button class="sg-button sg-button--primary" type="submit"<?= count($activatedRails) <= 1 || !$canManageDesign ? ' disabled' : '' ?>>Update Default</button>
      </form>
    </section>

    <section class="sg-section" id="rail-library">
      <div class="mc-rails-library" data-myron-rail-library>
        <?php foreach ($rails as $rail): ?>
        <?php
          $railId = (string) ($rail['rail_id'] ?? '');
          $content = is_array($rail['content'] ?? null) ? $rail['content'] : [];
          $slots = array_values(array_filter((array) ($content['slots'] ?? []), 'is_array'));
        ?>
        <article class="mc-rails-card<?= !empty($rail['is_activated']) ? ' mc-rails-card--activated' : ' mc-rails-card--deactivated' ?><?= !empty($rail['is_default']) ? ' mc-rails-card--default' : '' ?>" data-myron-rail-card data-rail-id="<?= myronEscape($railId) ?>">
          <div class="mc-rails-card__header">
            <div>
              <h2 class="mc-rails-card__title"><?= myronEscape((string) ($rail['name'] ?? 'Rail')) ?></h2>
              <p class="mc-rails-card__meta"><?= myronEscape($railId) ?></p>
            </div>
            <div class="mc-rails-card__badges">
              <span class="sg-pill<?= !empty($rail['is_default']) ? ' sg-pill--active' : '' ?>"><?= !empty($rail['is_default']) ? 'default' : 'available' ?></span>
              <span class="sg-pill"><?= myronEscape((string) ($rail['placement_default'] ?? 'right')) ?></span>
            </div>
          </div>

          <div class="mc-rails-card__body">
            <section class="mc-rails-preview" aria-label="<?= myronEscape((string) ($rail['name'] ?? 'Rail')) ?> preview">
              <div class="myron-blog-rail-layout myron-blog-rail-layout--<?= myronEscape((string) ($rail['placement_default'] ?? 'right')) ?> myron-blog-rail-layout--admin-preview" data-myron-blog-rail-layout data-rail-placement="<?= myronEscape((string) ($rail['placement_default'] ?? 'right')) ?>">
                <?php if (($rail['placement_default'] ?? 'right') === 'left'): ?>
                <aside class="myron-blog-rail-layout__rail"><div class="mc-rail-preview-panel"><strong><?= myronEscape((string) ($rail['name'] ?? 'Rail')) ?></strong><p><?= myronEscape((string) ($content['summary'] ?? '')) ?></p></div></aside>
                <div class="myron-blog-rail-layout__main"><div class="mc-rail-preview-panel"><strong>Blog content</strong><p>Archive filters, post cards, article body, and pagination remain the main column.</p></div></div>
                <?php else: ?>
                <div class="myron-blog-rail-layout__main"><div class="mc-rail-preview-panel"><strong>Blog content</strong><p>Archive filters, post cards, article body, and pagination remain the main column.</p></div></div>
                <aside class="myron-blog-rail-layout__rail"><div class="mc-rail-preview-panel"><strong><?= myronEscape((string) ($rail['name'] ?? 'Rail')) ?></strong><p><?= myronEscape((string) ($content['summary'] ?? '')) ?></p></div></aside>
                <?php endif; ?>
              </div>
            </section>

            <?php if ($canManageDesign): ?>
            <form method="post" action="<?= myronEscape(myronBuildAdminUrl('design.rails')) ?>" class="mc-admin-form mc-rails-config-form">
              <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
              <input type="hidden" name="action" value="update-rail-defaults">
              <input type="hidden" name="rail_id" value="<?= myronEscape($railId) ?>">
              <div class="mc-admin-form__section">
                <div class="mc-admin-form__section-header">
                  <h3 class="mc-admin-form__section-title">Rail Settings</h3>
                  <p class="mc-admin-form__section-description">Name the rail and choose the default side used by Blog templates.</p>
                </div>
                <div class="mc-admin-form__grid">
                  <label class="sg-field"><span class="sg-field__label">Name</span><input class="sg-field__control" type="text" name="name" value="<?= myronEscape((string) ($rail['name'] ?? 'Rail')) ?>"></label>
                  <label class="sg-field">
                    <span class="sg-field__label">Default placement</span>
                    <select class="sg-field__control" name="placement_default">
                      <?php foreach ($railRepository->validPlacements() as $placement): ?>
                      <option value="<?= myronEscape($placement) ?>"<?= (string) ($rail['placement_default'] ?? '') === $placement ? ' selected' : '' ?>><?= myronEscape(ucfirst($placement)) ?></option>
                      <?php endforeach; ?>
                    </select>
                  </label>
                </div>
                <label class="sg-field"><span class="sg-field__label">Summary</span><textarea class="sg-field__control" name="summary" rows="3"><?= myronEscape((string) ($content['summary'] ?? '')) ?></textarea></label>
              </div>

              <div class="mc-admin-form__section">
                <div class="mc-admin-form__section-header">
                  <h3 class="mc-admin-form__section-title">Rail Slots</h3>
                  <p class="mc-admin-form__section-description">These Core slots map to the packaged Blog rail composition.</p>
                </div>
                <div class="mc-rails-slot-grid">
                  <?php foreach ($slots as $index => $slot): ?>
                  <label class="sg-field">
                    <span class="sg-field__label"><?= myronEscape((string) ($slot['componentId'] ?? 'Slot ' . ((int) $index + 1))) ?></span>
                    <input type="hidden" name="slots[<?= (int) $index ?>][key]" value="<?= myronEscape((string) ($slot['key'] ?? '')) ?>">
                    <input type="hidden" name="slots[<?= (int) $index ?>][componentId]" value="<?= myronEscape((string) ($slot['componentId'] ?? '')) ?>">
                    <input class="sg-field__control" type="text" name="slots[<?= (int) $index ?>][label]" value="<?= myronEscape((string) ($slot['label'] ?? '')) ?>">
                  </label>
                  <?php endforeach; ?>
                </div>
              </div>
              <div class="sg-card__actions"><button class="sg-button sg-button--primary" type="submit">Update Rail</button></div>
            </form>
            <?php else: ?>
            <div class="mc-admin-form__section">
              <p class="sg-card__text">You have read access to this surface. Editing rails requires Designer or Administrator access.</p>
            </div>
            <?php endif; ?>
          </div>
        </article>
        <?php endforeach; ?>
      </div>
    </section>

    <section class="sg-section mc-rails-assignments" id="rail-template-assignments">
      <h2 class="sg-section__title">Blog Template Assignments</h2>
      <div class="mc-page-grid mc-page-grid--rail-assignments" role="table" aria-label="Blog rail assignments">
        <div class="mc-page-grid__row mc-page-grid__row--head" role="row"><span role="columnheader">Template</span><span role="columnheader">Rail</span><span role="columnheader">Placement</span><span role="columnheader">Source</span><span role="columnheader">Actions</span></div>
        <?php foreach ($blogTemplates as $template): ?>
        <?php $resolved = is_array($template['resolved'] ?? null) ? $template['resolved'] : []; ?>
        <form method="post" action="<?= myronEscape(myronBuildAdminUrl('design.rails')) ?>" class="mc-page-grid__row" role="row" data-myron-rail-template-assignment>
          <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
          <input type="hidden" name="action" value="update-template-rail-assignment">
          <input type="hidden" name="template_id" value="<?= myronEscape((string) ($template['id'] ?? '')) ?>">
          <span class="mc-page-grid__cell" role="cell"><?= myronEscape((string) ($template['name'] ?? $template['id'] ?? 'Template')) ?></span>
          <span class="mc-page-grid__cell" role="cell">
            <select class="sg-field__control" name="rail_id"<?= $canManageDesign ? '' : ' disabled' ?>>
              <?php foreach ($activatedRails as $rail): ?>
              <option value="<?= myronEscape((string) ($rail['rail_id'] ?? '')) ?>"<?= (string) ($resolved['rail_id'] ?? '') === (string) ($rail['rail_id'] ?? '') ? ' selected' : '' ?>><?= myronEscape((string) ($rail['name'] ?? 'Rail')) ?></option>
              <?php endforeach; ?>
            </select>
          </span>
          <span class="mc-page-grid__cell" role="cell">
            <select class="sg-field__control" name="placement"<?= $canManageDesign ? '' : ' disabled' ?>>
              <?php foreach ($railRepository->validPlacements() as $placement): ?>
              <option value="<?= myronEscape($placement) ?>"<?= (string) ($resolved['placement'] ?? '') === $placement ? ' selected' : '' ?>><?= myronEscape(ucfirst($placement)) ?></option>
              <?php endforeach; ?>
            </select>
          </span>
          <span class="mc-page-grid__cell" role="cell"><?= myronEscape((string) ($resolved['source'] ?? 'default')) ?></span>
          <span class="mc-page-grid__cell" role="cell"><button class="sg-button sg-button--primary" type="submit"<?= $canManageDesign ? '' : ' disabled' ?>>Apply</button></span>
        </form>
        <?php endforeach; ?>
      </div>
    </section>
  </div>
</div>
<?php
myronRenderAdminShellEnd();
