<?php

declare(strict_types=1);

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

$currentUser = myronRequireDesignAccess();
$csrfToken = myronCsrfToken();
$repository = myronSectionVariantRepository();
$componentRepository = myronComponentRegistryRepository();
$sectionRepository = myronSectionRegistryRepository();

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $action = trim((string) ($_POST['action'] ?? ''));
        $componentId = (string) ($_POST['component_id'] ?? '');
        $component = $componentRepository->findComponentById($componentId);
        $editableTokens = is_array($component) && is_array($component['editableTokens'] ?? null) ? $component['editableTokens'] : [];
        $creativeRaw = trim((string) ($_POST['creative_json'] ?? ''));
        $creativeDecoded = $creativeRaw !== '' ? json_decode($creativeRaw, true) : null;
        $design = [
            'customCss' => (string) ($_POST['custom_css'] ?? ''),
            'tokenOverrides' => myronNormalizeEditableTokenOverrideInput(is_array($_POST['token_overrides'] ?? null) ? $_POST['token_overrides'] : [], $editableTokens),
            'creative' => is_array($creativeDecoded) ? $creativeDecoded : null,
        ];
        $content = myronNormalizeSectionContentInput(is_array($_POST['content'] ?? null) ? $_POST['content'] : []);

        // APO-193 Card 7 — section variant mutations funnel through
        // MyronSectionVariantActionService. Admin form path + /api/v1/design/section-variants/...
        // share identical service-layer logic.
        $variantService = myronSectionVariantActionService();
        $callerCtx = myronActionCallerContextForUser($currentUser);

        if ($action === 'create-variant') {
            $variantService->create(
                (string) ($_POST['name'] ?? ''),
                (string) ($_POST['section_key'] ?? ''),
                $componentId,
                (string) ($_POST['variant'] ?? 'default'),
                $design,
                $content,
                $callerCtx
            );
            myronRedirectWithFlash(myronBuildAdminUrl('design.sectionVariants'), 'Created section variant.', 'success');
        }

        if ($action === 'update-variant') {
            $variantService->update(
                (string) ($_POST['variant_id'] ?? ''),
                (string) ($_POST['name'] ?? ''),
                (string) ($_POST['section_key'] ?? ''),
                $componentId,
                (string) ($_POST['variant'] ?? 'default'),
                $design,
                $content,
                $callerCtx
            );
            myronRedirectWithFlash(myronBuildAdminUrl('design.sectionVariants', ['variant' => (string) ($_POST['variant_id'] ?? '')]), 'Updated section variant.', 'success');
        }

        if ($action === 'delete-variant') {
            $variantService->delete((string) ($_POST['variant_id'] ?? ''), $callerCtx);
            myronRedirectWithFlash(myronBuildAdminUrl('design.sectionVariants'), 'Deleted section variant.', 'success');
        }

        throw new InvalidArgumentException('Unknown section variant action.');
    } catch (Throwable $exception) {
        myronRedirectWithFlash(myronBuildAdminUrl('design.sectionVariants'), $exception->getMessage(), 'error');
    }
}

$variants = $repository->listVariants();
$selectedVariantId = trim((string) ($_GET['variant'] ?? ''));
$selectedVariant = $selectedVariantId !== '' ? $repository->find($selectedVariantId) : null;
$componentIds = $componentRepository->listComponentIds();
$sectionRows = $sectionRepository->listSections();
$selectedComponentId = is_array($selectedVariant)
    ? (string) ($selectedVariant['componentId'] ?? '')
    : (string) ($componentIds[0] ?? '');
$selectedComponent = $selectedComponentId !== '' ? $componentRepository->findComponentById($selectedComponentId) : null;
$variantEditableTokens = is_array($selectedComponent) && is_array($selectedComponent['editableTokens'] ?? null)
    ? array_values(array_filter($selectedComponent['editableTokens'], 'is_array'))
    : [];
$creativeCatalog = myronCreativeLibraryCatalog();
$motionProfiles = $creativeCatalog->listByCategory('motion');
$sceneBackgrounds = $creativeCatalog->listByCategory('scene');
$heroComponents = $creativeCatalog->listByCategory('hero');

myronRenderAdminShellStart($currentUser, [
    'title' => 'Section Variants',
    'titleContext' => 'Section Variants',
    'activeItem' => 'section-variants',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Design', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Component Studio', 'href' => myronBuildAdminUrl('design.sectionVariants')],
      ['label' => 'Section Variants'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Section Variants</h1>
  </div>
  <p class="mc-workspace__subtitle">Saved section design states captured from Page Templates side sheets and reusable across runtime template sections.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <section class="sg-section">
      <h2 class="sg-section__title"><?= is_array($selectedVariant) ? 'Edit Variant' : 'Create Variant' ?></h2>
      <?php $variantDesign = is_array($selectedVariant['design'] ?? null) ? $selectedVariant['design'] : []; ?>
      <?php $variantContent = is_array($selectedVariant['content'] ?? null) ? $selectedVariant['content'] : []; ?>
      <form method="post" class="sg-form-grid">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <?php if (is_array($selectedVariant)): ?>
        <input type="hidden" name="variant_id" value="<?= myronEscape((string) ($selectedVariant['id'] ?? '')) ?>">
        <?php endif; ?>
        <label class="sg-field">
          <span class="sg-field__label">Name</span>
          <input class="sg-field__control" type="text" name="name" value="<?= myronEscape((string) ($selectedVariant['name'] ?? '')) ?>">
        </label>
        <label class="sg-field">
          <span class="sg-field__label">Component</span>
          <select class="sg-field__control" name="component_id">
            <?php foreach ($componentIds as $componentId): ?>
            <option value="<?= myronEscape($componentId) ?>"<?= $selectedComponentId === $componentId ? ' selected' : '' ?>><?= myronEscape($componentId) ?></option>
            <?php endforeach; ?>
          </select>
        </label>
        <label class="sg-field">
          <span class="sg-field__label">Section Key</span>
          <select class="sg-field__control" name="section_key">
            <option value="">Any matching section</option>
            <?php foreach ($sectionRows as $section): ?>
            <?php $sectionKey = (string) ($section['sectionKey'] ?? ''); ?>
            <?php if ($sectionKey !== ''): ?>
            <option value="<?= myronEscape($sectionKey) ?>"<?= (string) ($selectedVariant['sectionKey'] ?? '') === $sectionKey ? ' selected' : '' ?>><?= myronEscape($sectionKey) ?></option>
            <?php endif; ?>
            <?php endforeach; ?>
          </select>
        </label>
        <label class="sg-field">
          <span class="sg-field__label">Variant</span>
          <input class="sg-field__control" type="text" name="variant" value="<?= myronEscape((string) ($selectedVariant['variant'] ?? 'default')) ?>">
        </label>
        <label class="sg-field">
          <span class="sg-field__label">Headline</span>
          <input class="sg-field__control" type="text" name="content[headline]" value="<?= myronEscape((string) ($variantContent['headline'] ?? '')) ?>">
        </label>
        <label class="sg-field">
          <span class="sg-field__label">Body</span>
          <textarea class="sg-field__control" name="content[body]" rows="3"><?= myronEscape((string) ($variantContent['body'] ?? '')) ?></textarea>
        </label>
        <?php if ($variantEditableTokens !== []): ?>
        <fieldset class="sg-fieldset">
          <legend>Token Overrides</legend>
          <div class="sg-form-grid">
            <?php foreach ($variantEditableTokens as $token): ?>
            <?php
              $cssVar = (string) ($token['cssVar'] ?? $token['token'] ?? '');
              if ($cssVar === '') {
                  continue;
              }
              $controlType = (string) ($token['controlType'] ?? myronTokenControlRenderer()->controlTypeForToken($cssVar));
              $options = array_values(array_map('strval', is_array($token['options'] ?? null) ? $token['options'] : []));
              $value = (string) (($variantDesign['tokenOverrides'][$cssVar] ?? '') ?: '');
            ?>
            <label class="sg-field">
              <span class="sg-field__label"><?= myronEscape((string) ($token['label'] ?? $cssVar)) ?></span>
              <?= myronTokenControlRenderer()->render('token_overrides[' . $cssVar . ']', $value, $controlType, $cssVar, $options) . "\n" ?>
              <span class="mc-page-grid__subtle"><code><?= myronEscape($cssVar) ?></code> · <?= myronEscape($controlType) ?></span>
            </label>
            <?php endforeach; ?>
          </div>
        </fieldset>
        <?php else: ?>
        <div class="sg-status" role="status">The selected component does not expose editable design tokens.</div>
        <?php endif; ?>
        <label class="sg-field">
          <span class="sg-field__label">Custom CSS</span>
          <textarea class="sg-field__control sg-field__control--code" name="custom_css" rows="6" spellcheck="false"><?= myronEscape((string) ($variantDesign['customCss'] ?? '')) ?></textarea>
        </label>
        <?php
          $existingCreative = is_array($variantDesign['creative'] ?? null) ? $variantDesign['creative'] : [];
          $currentMotion = trim((string) ($existingCreative['motionProfile'] ?? ''));
          $currentScene = trim((string) ($existingCreative['sceneBackground'] ?? ''));
          $currentHero = trim((string) ($existingCreative['heroComponent'] ?? ''));
          $currentParams = is_array($existingCreative['params'] ?? null) ? $existingCreative['params'] : [];
        ?>
        <details class="sg-fieldset sg-fieldset--collapsible" id="mc-creative-panel"<?= ($currentMotion !== '' || $currentScene !== '' || $currentHero !== '') ? ' open' : '' ?>>
          <summary class="sg-fieldset__summary">Creative Library</summary>
          <div class="sg-form-grid">
            <label class="sg-field">
              <span class="sg-field__label">Motion Profile</span>
              <select class="sg-field__control" id="mc-motion-select">
                <option value="">None</option>
                <?php foreach ($motionProfiles as $profile): ?>
                <option value="<?= myronEscape((string) ($profile['id'] ?? '')) ?>"<?= $currentMotion === (string) ($profile['id'] ?? '') ? ' selected' : '' ?>><?= myronEscape((string) ($profile['label'] ?? $profile['id'] ?? '')) ?> - <?= myronEscape((string) ($profile['description'] ?? '')) ?></option>
                <?php endforeach; ?>
              </select>
              <span class="mc-page-grid__subtle" id="mc-motion-meta"></span>
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Scene Background</span>
              <select class="sg-field__control" id="mc-scene-select">
                <option value="">None</option>
                <?php foreach ($sceneBackgrounds as $scene): ?>
                <option value="<?= myronEscape((string) ($scene['id'] ?? '')) ?>"<?= $currentScene === (string) ($scene['id'] ?? '') ? ' selected' : '' ?>><?= myronEscape((string) ($scene['label'] ?? $scene['id'] ?? '')) ?> - <?= myronEscape((string) ($scene['description'] ?? '')) ?></option>
                <?php endforeach; ?>
              </select>
              <span class="mc-page-grid__subtle" id="mc-scene-meta"></span>
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Hero Behavior</span>
              <select class="sg-field__control" id="mc-hero-select">
                <option value="">None</option>
                <?php foreach ($heroComponents as $hero): ?>
                <option value="<?= myronEscape((string) ($hero['id'] ?? '')) ?>"<?= $currentHero === (string) ($hero['id'] ?? '') ? ' selected' : '' ?>><?= myronEscape((string) ($hero['label'] ?? $hero['id'] ?? '')) ?> - <?= myronEscape((string) ($hero['description'] ?? '')) ?></option>
                <?php endforeach; ?>
              </select>
              <span class="mc-page-grid__subtle" id="mc-hero-meta"></span>
            </label>
            <div id="mc-params-container" class="sg-form-grid"></div>
          </div>
        </details>
        <input type="hidden" name="creative_json" id="mc-creative-json" value="<?= myronEscape($existingCreative !== [] ? (string) json_encode($existingCreative, JSON_HEX_QUOT | JSON_HEX_APOS) : '') ?>">
        <script>
        (function () {
          var motionCatalog = <?= json_encode($motionProfiles, JSON_HEX_TAG | JSON_HEX_AMP) ?>;
          var sceneCatalog  = <?= json_encode($sceneBackgrounds, JSON_HEX_TAG | JSON_HEX_AMP) ?>;
          var heroCatalog   = <?= json_encode($heroComponents, JSON_HEX_TAG | JSON_HEX_AMP) ?>;
          var currentParams = <?= json_encode($currentParams, JSON_HEX_TAG | JSON_HEX_AMP) ?>;

          var motionSel    = document.getElementById('mc-motion-select');
          var sceneSel     = document.getElementById('mc-scene-select');
          var heroSel      = document.getElementById('mc-hero-select');
          var motionMeta   = document.getElementById('mc-motion-meta');
          var sceneMeta    = document.getElementById('mc-scene-meta');
          var heroMeta     = document.getElementById('mc-hero-meta');
          var paramsBox    = document.getElementById('mc-params-container');
          var creativeJson = document.getElementById('mc-creative-json');
          var form         = creativeJson.closest('form');

          function findEntry(catalog, id) {
            for (var i = 0; i < catalog.length; i++) {
              if (catalog[i].id === id) return catalog[i];
            }
            return null;
          }

          function renderParams() {
            var motionId = motionSel.value;
            var sceneId  = sceneSel.value;
            var heroId   = heroSel.value;
            var motion   = motionId ? findEntry(motionCatalog, motionId) : null;
            var scene    = sceneId  ? findEntry(sceneCatalog, sceneId)   : null;
            var hero     = heroId   ? findEntry(heroCatalog, heroId)     : null;
            var params   = (motion ? motion.supportedParams : []).concat(scene ? scene.supportedParams : []).concat(hero ? hero.supportedParams : []);
            var seen     = {};
            paramsBox.innerHTML = '';
            motionMeta.textContent = motion ? 'Compatible: ' + (motion.compatibleSectionKeys || ['*']).join(', ') : '';
            sceneMeta.textContent = scene ? 'Compatible: ' + (scene.compatibleSectionKeys || ['*']).join(', ') : '';
            heroMeta.textContent = hero ? 'Compatible: ' + (hero.compatibleSectionKeys || ['*']).join(', ') : '';
            params.forEach(function (p) {
              if (seen[p.key]) return;
              seen[p.key] = true;
              var val = currentParams[p.key] !== undefined ? currentParams[p.key] : p.default;
              var label = document.createElement('label');
              label.className = 'sg-field';
              var span = document.createElement('span');
              span.className = 'sg-field__label';
              span.textContent = p.label || p.key;
              label.appendChild(span);
              var control;
              if (p.type === 'select') {
                control = document.createElement('select');
                control.className = 'sg-field__control';
                (p.options || []).forEach(function (opt) {
                  var o = document.createElement('option');
                  o.value = opt;
                  o.textContent = opt;
                  if (opt === val) o.selected = true;
                  control.appendChild(o);
                });
              } else {
                control = document.createElement('input');
                control.className = 'sg-field__control';
                control.type = p.type === 'string' ? 'text' : 'number';
                control.value = val !== undefined ? val : '';
                if (p.min !== undefined) control.min = p.min;
                if (p.max !== undefined) control.max = p.max;
                if (p.step !== undefined) control.step = p.step;
              }
              control.dataset.mcParamKey = p.key;
              control.addEventListener('change', syncJson);
              label.appendChild(control);
              paramsBox.appendChild(label);
            });
            syncJson();
          }

          function syncJson() {
            var motionId = motionSel.value;
            var sceneId  = sceneSel.value;
            var heroId   = heroSel.value;
            if (!motionId && !sceneId && !heroId) {
              creativeJson.value = '';
              return;
            }
            var params = {};
            paramsBox.querySelectorAll('[data-mc-param-key]').forEach(function (ctrl) {
              var key = ctrl.dataset.mcParamKey;
              var raw = ctrl.value;
              params[key] = ctrl.type === 'number' && !isNaN(parseFloat(raw)) ? parseFloat(raw) : raw;
            });
            var obj = {};
            if (motionId) obj.motionProfile = motionId;
            if (sceneId)  obj.sceneBackground = sceneId;
            if (heroId)   obj.heroComponent = heroId;
            if (Object.keys(params).length) obj.params = params;
            creativeJson.value = JSON.stringify(obj);
          }

          motionSel.addEventListener('change', renderParams);
          sceneSel.addEventListener('change',  renderParams);
          heroSel.addEventListener('change',   renderParams);
          renderParams();
        })();
        </script>
        <div class="sg-card__actions">
          <button class="sg-button sg-button--primary" type="submit" name="action" value="<?= is_array($selectedVariant) ? 'update-variant' : 'create-variant' ?>"><?= is_array($selectedVariant) ? 'Update Variant' : 'Create Variant' ?></button>
          <?php if (is_array($selectedVariant)): ?>
          <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('design.sectionVariants')) ?>">New Variant</a>
          <?php endif; ?>
        </div>
      </form>
    </section>

    <section class="sg-section">
      <?php if ($variants === []): ?>
      <div class="sg-empty-state">
        <p class="sg-empty-state__title">No saved section variants</p>
        <p class="sg-empty-state__text">Open a runtime Page Template section and use Save Current as Variant to populate this library.</p>
      </div>
      <?php else: ?>
      <div class="mc-page-grid" role="table" aria-label="Section variants">
        <div class="mc-page-grid__row mc-page-grid__row--head" role="row">
          <span role="columnheader">Variant</span>
          <span role="columnheader">Section</span>
          <span role="columnheader">Design</span>
          <span role="columnheader">Usage</span>
          <span role="columnheader">Actions</span>
        </div>
        <?php foreach ($variants as $variant): ?>
        <?php $usageCount = (int) ($variant['usageCount'] ?? 0); ?>
        <div class="mc-page-grid__row" role="row">
          <span class="mc-page-grid__cell mc-page-grid__cell--name" role="cell">
            <span class="mc-page-grid__name"><?= myronEscape((string) ($variant['name'] ?? 'Variant')) ?></span>
            <span class="mc-page-grid__subtle"><code><?= myronEscape((string) ($variant['id'] ?? '')) ?></code></span>
          </span>
          <span class="mc-page-grid__cell" role="cell">
            <code><?= myronEscape((string) (($variant['sectionKey'] ?? '') ?: ($variant['componentId'] ?? 'section'))) ?></code>
            <span class="mc-page-grid__subtle"><?= myronEscape((string) ($variant['variant'] ?? 'default')) ?></span>
          </span>
          <span class="mc-page-grid__cell" role="cell">
            <?php $design = is_array($variant['design'] ?? null) ? $variant['design'] : []; ?>
            <span class="sg-pill"><?= trim((string) ($design['customCss'] ?? '')) !== '' ? 'CSS' : 'No CSS' ?></span>
            <span class="sg-pill"><?= myronEscape((string) count(is_array($design['tokenOverrides'] ?? null) ? $design['tokenOverrides'] : [])) ?> tokens</span>
          </span>
          <span class="mc-page-grid__cell" role="cell"><?= myronEscape((string) $usageCount) ?> section<?= $usageCount === 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(myronBuildAdminUrl('design.sectionVariants', ['variant' => (string) ($variant['id'] ?? '')])) ?>">Edit</a>
            <form method="post" class="sg-inline-form">
              <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
              <input type="hidden" name="variant_id" value="<?= myronEscape((string) ($variant['id'] ?? '')) ?>">
              <button class="sg-button sg-button--secondary" type="submit" name="action" value="delete-variant"<?= $usageCount > 0 ? ' disabled' : '' ?>>Delete</button>
            </form>
          </span>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>
    </section>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
