<?php

declare(strict_types=1);

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

$currentUser = myronRequireDesignAccess();
$canManageDesign = myronUserCanManageDesign($currentUser);
$csrfToken = myronCsrfToken();
$settingsRepository = myronSiteSettingsRepository();

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (!$canManageDesign) {
            throw new RuntimeException('Your current role cannot update creative library settings.');
        }
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $action = trim((string) ($_POST['action'] ?? ''));
        $currentCreative = $settingsRepository->creativeSettings();
        if ($action === 'activate-nav-style') {
            $navStyle = myronNormalizeSlug((string) ($_POST['nav_style'] ?? ''));
            $entry = $navStyle !== '' ? myronCreativeLibraryCatalog()->find($navStyle) : null;
            if (!is_array($entry) || (string) ($entry['category'] ?? '') !== 'navigation' || (string) ($entry['tier'] ?? '') !== 'site') {
                throw new InvalidArgumentException('Choose a supported site navigation creative.');
            }
            $navParams = [];
            foreach (array_filter(is_array($entry['supportedParams'] ?? null) ? $entry['supportedParams'] : [], 'is_array') as $param) {
                if ((string) ($param['key'] ?? '') !== 'navRadius') {
                    continue;
                }
                $radius = myronNormalizeSlug((string) ($_POST['nav_radius'] ?? ($param['default'] ?? 'pill')));
                $options = array_values(array_map('strval', is_array($param['options'] ?? null) ? $param['options'] : []));
                if (!in_array($radius, $options, true)) {
                    throw new InvalidArgumentException('Choose a supported navigation radius.');
                }
                $navParams['navRadius'] = $radius;
            }
            $settingsRepository->saveCreativeSettings($navStyle, $currentCreative['btnStyle'] ?? null, $navParams);
            myronRedirectWithFlash(myronBuildAdminUrl('design.creativeLibrary'), 'Saved navigation creative.', 'success');
        }
        if ($action === 'clear-nav-style') {
            $settingsRepository->saveCreativeSettings(null, $currentCreative['btnStyle'] ?? null, []);
            myronRedirectWithFlash(myronBuildAdminUrl('design.creativeLibrary'), 'Cleared navigation creative.', 'success');
        }
        if ($action === 'activate-button-style') {
            $buttonStyle = myronNormalizeSlug((string) ($_POST['button_style'] ?? ''));
            $entry = $buttonStyle !== '' ? myronCreativeLibraryCatalog()->find($buttonStyle) : null;
            if (!is_array($entry) || (string) ($entry['category'] ?? '') !== 'button' || (string) ($entry['tier'] ?? '') !== 'site') {
                throw new InvalidArgumentException('Choose a supported site button creative.');
            }
            $settingsRepository->saveCreativeSettings($currentCreative['navStyle'] ?? null, $buttonStyle, $currentCreative['navParams'] ?? []);
            myronRedirectWithFlash(myronBuildAdminUrl('design.creativeLibrary'), 'Activated button creative.', 'success');
        }
        if ($action === 'clear-button-style') {
            $settingsRepository->saveCreativeSettings($currentCreative['navStyle'] ?? null, null, $currentCreative['navParams'] ?? []);
            myronRedirectWithFlash(myronBuildAdminUrl('design.creativeLibrary'), 'Cleared button creative.', 'success');
        }
        throw new InvalidArgumentException('Unknown creative library action.');
    } catch (Throwable $exception) {
        myronRedirectWithFlash(myronBuildAdminUrl('design.creativeLibrary'), $exception->getMessage(), 'error');
    }
}

$creativeSettings = $settingsRepository->creativeSettings();
$activeNavStyle = (string) ($creativeSettings['navStyle'] ?? '');
$activeNavParams = is_array($creativeSettings['navParams'] ?? null) ? $creativeSettings['navParams'] : [];
$activeButtonStyle = (string) ($creativeSettings['btnStyle'] ?? '');
$catalog = myronCreativeLibraryCatalog();
$entries = $catalog->list();
$grouped = [];
foreach ($entries as $entry) {
    $category = trim((string) ($entry['category'] ?? 'other')) ?: 'other';
    $grouped[$category][] = $entry;
}

myronRenderAdminShellStart($currentUser, [
    'title' => 'Creative Library',
    'titleContext' => 'Creative Library',
    'activeItem' => 'creative-library',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Design', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Component Studio', 'href' => myronBuildAdminUrl('design.creativeLibrary')],
      ['label' => 'Creative Library'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Creative Library</h1>
  </div>
  <p class="mc-workspace__subtitle">Browse section and site creative components available to template and public render surfaces.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <?php foreach ($grouped as $category => $items): ?>
    <section class="sg-section">
      <div class="mc-workspace__title-row">
        <h2 class="sg-section__title"><?= myronEscape($category === 'button' ? 'Buttons' : ucwords(str_replace('-', ' ', $category))) ?></h2>
      </div>
      <div class="mc-page-grid mc-page-grid--cards">
        <?php foreach ($items as $entry): ?>
        <?php
          $id = (string) ($entry['id'] ?? '');
          $tier = (string) ($entry['tier'] ?? 'section');
          $compatible = array_values(array_map('strval', is_array($entry['compatibleSectionKeys'] ?? null) ? $entry['compatibleSectionKeys'] : []));
          $params = array_values(array_filter(is_array($entry['supportedParams'] ?? null) ? $entry['supportedParams'] : [], 'is_array'));
          $navRadiusParam = null;
          foreach ($params as $param) {
              if ((string) ($param['key'] ?? '') === 'navRadius') {
                  $navRadiusParam = $param;
                  break;
              }
          }
          $requiresJs = !empty($entry['requiresJs']);
          $isActiveSiteNav = $category === 'navigation' && $tier === 'site' && $id === $activeNavStyle;
          $isActiveSiteButton = $category === 'button' && $tier === 'site' && $id === $activeButtonStyle;
        ?>
        <article class="sg-card mc-creative-library-card">
          <?php if ($category === 'scene'): ?>
          <div class="mc-creative-thumb mc-creative-thumb--<?= myronEscape(myronNormalizeSlug($id)) ?>" aria-hidden="true"></div>
          <?php endif; ?>
          <div class="sg-card__header">
            <div>
              <h3 class="sg-card__title"><?= myronEscape((string) ($entry['label'] ?? $id)) ?></h3>
              <p class="sg-card__text"><?= myronEscape((string) ($entry['description'] ?? 'Creative component.')) ?></p>
            </div>
            <span class="sg-pill"><?= myronEscape($category) ?></span>
          </div>
          <div class="sg-card__body">
            <p class="mc-page-grid__subtle"><code><?= myronEscape($id) ?></code></p>
            <p>
              <span class="sg-pill"><?= myronEscape((string) ($entry['implementationType'] ?? 'js')) ?></span>
              <span class="sg-pill"><?= $requiresJs ? 'Requires JS' : 'Static' ?></span>
              <span class="sg-pill"><?= myronEscape($tier) ?></span>
            </p>
            <?php if ($compatible !== []): ?>
            <p class="mc-page-grid__subtle">Compatible: <?= myronEscape(implode(', ', $compatible)) ?></p>
            <?php endif; ?>
            <?php if ($params !== []): ?>
            <p class="mc-page-grid__subtle">Params: <?= myronEscape(implode(', ', array_map(static fn (array $p): string => (string) ($p['key'] ?? ''), $params))) ?></p>
            <?php endif; ?>
            <?php if ($tier === 'site'): ?>
            <label class="sg-checkbox sg-checkbox--spaced">
              <input type="checkbox" disabled<?= ($isActiveSiteNav || $isActiveSiteButton) ? ' checked' : '' ?>>
              <span>Site-level activation slot</span>
            </label>
            <?php if ($category === 'navigation'): ?>
            <form method="post" class="sg-card__actions">
              <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
              <input type="hidden" name="nav_style" value="<?= myronEscape($id) ?>">
              <input type="hidden" name="action" value="activate-nav-style">
              <?php if (is_array($navRadiusParam)): ?>
              <?php
                $radiusOptions = array_values(array_map('strval', is_array($navRadiusParam['options'] ?? null) ? $navRadiusParam['options'] : []));
                $selectedRadius = $isActiveSiteNav
                    ? (string) ($activeNavParams['navRadius'] ?? ($navRadiusParam['default'] ?? 'pill'))
                    : (string) ($navRadiusParam['default'] ?? 'pill');
              ?>
              <label>
                <span><?= myronEscape((string) ($navRadiusParam['label'] ?? 'Navigation radius')) ?></span>
                <select name="nav_radius"<?= $canManageDesign ? '' : ' disabled' ?>>
                  <?php foreach ($radiusOptions as $radiusOption): ?>
                  <option value="<?= myronEscape($radiusOption) ?>"<?= $radiusOption === $selectedRadius ? ' selected' : '' ?>><?= myronEscape(ucwords($radiusOption)) ?></option>
                  <?php endforeach; ?>
                </select>
              </label>
              <?php endif; ?>
              <button class="sg-button sg-button--primary" type="submit"<?= $canManageDesign ? '' : ' disabled' ?>><?= $isActiveSiteNav ? 'Update' : 'Activate' ?></button>
            </form>
            <?php if ($isActiveSiteNav): ?>
            <form method="post" class="sg-card__actions">
              <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
              <input type="hidden" name="action" value="clear-nav-style">
              <button class="sg-button sg-button--secondary" type="submit"<?= $canManageDesign ? '' : ' disabled' ?>>Clear</button>
            </form>
            <?php endif; ?>
            <?php elseif ($category === 'button'): ?>
            <form method="post" class="sg-card__actions">
              <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
              <input type="hidden" name="button_style" value="<?= myronEscape($id) ?>">
              <?php if ($isActiveSiteButton): ?>
              <input type="hidden" name="action" value="clear-button-style">
              <button class="sg-button sg-button--secondary" type="submit"<?= $canManageDesign ? '' : ' disabled' ?>>Clear</button>
              <?php else: ?>
              <input type="hidden" name="action" value="activate-button-style">
              <button class="sg-button sg-button--primary" type="submit"<?= $canManageDesign ? '' : ' disabled' ?>>Activate</button>
              <?php endif; ?>
            </form>
            <?php endif; ?>
            <?php else: ?>
            <p class="mc-page-grid__subtle">Assign section-tier creative in the Page Template or Section Variants editor.</p>
            <?php endif; ?>
          </div>
        </article>
        <?php endforeach; ?>
      </div>
    </section>
    <?php endforeach; ?>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
