<?php

declare(strict_types=1);

require_once dirname(__DIR__, 3) . '/system/bootstrap.php';
// DesignSystemRegistry is loaded by bootstrap's app-local JSONM runtime.

$currentUser = myronRequireDesignAccess(true);

$registry = new DesignSystemRegistry();
$registry->ensureStorage();

function myronDesignLayoutEscape(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

function myronDesignLayoutRedirect(string $type, string $message): never
{
    myronRedirectWithFlash(myronBuildAdminUrl('design.layout'), $message, $type);
}

function myronDesignLayoutValue(array $layout, string $group, string $key): string
{
    $values = is_array($layout[$group] ?? null) ? $layout[$group] : [];
    return (string) ($values[$key] ?? '');
}

function myronDesignLayoutWidthValue(array $layout, string $scope, string $field): string
{
    $widthModes = is_array($layout['widthModes'] ?? null) ? $layout['widthModes'] : [];
    $intent = is_array($widthModes[$scope] ?? null) ? $widthModes[$scope] : [];
    return (string) ($intent[$field] ?? ($field === 'mode' ? 'contained' : 'lg'));
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $action = (string) ($_POST['action'] ?? '');

    try {
        if ($action === 'update-layout') {
            $layout = $_POST['layout'] ?? null;
            if (!is_array($layout)) {
                throw new RuntimeException('Layout settings payload is required.');
            }
            // APO-193 Card 8 — admin form path + PATCH /api/v1/design/layout
            // share MyronLayoutActionService::updateLayout.
            $callerCtx = myronActionCallerContextForUser($currentUser);
            $outcome = myronLayoutActionService()->updateLayout($layout, $callerCtx);
            myronDesignLayoutRedirect('success', 'Updated layout settings for `' . $outcome['recordName'] . '`.');
        }

        throw new RuntimeException('Unknown action.');
    } catch (Throwable $e) {
        myronDesignLayoutRedirect('error', $e->getMessage());
    }
}

$currentLayout = $registry->currentLayoutTokens();

myronRenderAdminShellStart($currentUser, [
    'title' => 'Layout Settings',
    'titleContext' => 'Layout Settings',
    'activeItem' => 'design-layout',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Design', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Design Studio', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Layout'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Layout Settings</h1>
  </div>
  <p class="mc-workspace__subtitle">Govern public site width, gutters, and responsive breakpoints through the active JSONM layout token contract.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main" id="top">
    <section class="sg-section" id="layout-settings">
      <form method="post" action="<?= myronEscape(myronBuildAdminUrl('design.layout')) ?>" class="sg-form-grid mc-layout-settings-form">
        <input type="hidden" name="action" value="update-layout">

        <?php foreach ([
            'containers' => ['label' => 'Container Widths', 'hint' => 'Maximum content widths for compact, standard, and wide public layouts.'],
            'gutters' => ['label' => 'Gutters', 'hint' => 'Inline page padding used by public layout containers.'],
            'breakpoints' => ['label' => 'Breakpoints', 'hint' => 'Responsive thresholds used by compiled and static layout rules.'],
        ] as $group => $meta): ?>
        <fieldset class="sg-field sg-field--full mc-layout-settings-group">
          <legend class="sg-field__label"><?= myronDesignLayoutEscape($meta['label']) ?></legend>
          <span class="sg-field__hint"><?= myronDesignLayoutEscape($meta['hint']) ?></span>
          <div class="mc-layout-settings-grid">
            <?php foreach (['sm' => 'Small', 'md' => 'Medium', 'lg' => 'Large'] as $key => $label): ?>
            <label class="sg-field">
              <span class="sg-field__label"><?= myronDesignLayoutEscape($label) ?></span>
              <input class="sg-field__control" type="text" name="layout[<?= myronDesignLayoutEscape($group) ?>][<?= myronDesignLayoutEscape($key) ?>]" value="<?= myronDesignLayoutEscape(myronDesignLayoutValue($currentLayout, $group, $key)) ?>" required pattern="[0-9]+px">
            </label>
            <?php endforeach; ?>
          </div>
        </fieldset>
        <?php endforeach; ?>

        <fieldset class="sg-field sg-field--full mc-layout-settings-group">
          <legend class="sg-field__label">Width Modes</legend>
          <span class="sg-field__hint">Constrained page and section width intent. Breakpoints remain governed by the global layout tokens above.</span>
          <div class="mc-layout-settings-grid">
            <?php foreach (['page' => 'Page Default', 'section' => 'Section Default'] as $scope => $label): ?>
            <label class="sg-field">
              <span class="sg-field__label"><?= myronDesignLayoutEscape($label) ?> Mode</span>
              <select class="sg-field__control" name="layout[widthModes][<?= myronDesignLayoutEscape($scope) ?>][mode]" required>
                <?php foreach (['contained' => 'Contained', 'full-bleed' => 'Full Width', 'fixed' => 'Fixed', 'mixed' => 'Mixed'] as $value => $text): ?>
                <option value="<?= myronDesignLayoutEscape($value) ?>"<?= myronDesignLayoutWidthValue($currentLayout, $scope, 'mode') === $value ? ' selected' : '' ?>><?= myronDesignLayoutEscape($text) ?></option>
                <?php endforeach; ?>
              </select>
            </label>
            <label class="sg-field">
              <span class="sg-field__label"><?= myronDesignLayoutEscape($label) ?> Container</span>
              <select class="sg-field__control" name="layout[widthModes][<?= myronDesignLayoutEscape($scope) ?>][container]" required>
                <?php foreach (['sm' => 'Small', 'md' => 'Medium', 'lg' => 'Large'] as $value => $text): ?>
                <option value="<?= myronDesignLayoutEscape($value) ?>"<?= myronDesignLayoutWidthValue($currentLayout, $scope, 'container') === $value ? ' selected' : '' ?>><?= myronDesignLayoutEscape($text) ?></option>
                <?php endforeach; ?>
              </select>
            </label>
            <?php endforeach; ?>
          </div>
        </fieldset>

        <div class="sg-card__actions">
          <button class="sg-button sg-button--primary" type="submit">Apply Layout Settings</button>
          <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('design.tokenDesigner')) ?>#tokens-layout-containers">Review Token Designer</a>
        </div>
      </form>
    </section>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
