<?php

declare(strict_types=1);

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

$currentUser = myronRequireDesignAccess();
$csrfToken = myronCsrfToken();
$repository = myronCustomCssRepository();
$activeTab = trim((string) ($_GET['tab'] ?? 'css'));
$activeTab = in_array($activeTab, ['css', 'js', 'fonts'], true) ? $activeTab : 'css';

/**
 * @param array<string, mixed> $post
 * @return list<array<string, mixed>>
 */
function myronCustomInteractionsExternalLibrariesFromPost(array $post): array
{
    $names = is_array($post['external_name'] ?? null) ? array_values((array) $post['external_name']) : [];
    $urls = is_array($post['external_url'] ?? null) ? array_values((array) $post['external_url']) : [];
    $integrities = is_array($post['external_integrity'] ?? null) ? array_values((array) $post['external_integrity']) : [];
    $crossorigins = is_array($post['external_crossorigin'] ?? null) ? array_values((array) $post['external_crossorigin']) : [];
    $enabled = is_array($post['external_enabled'] ?? null) ? array_map('strval', (array) $post['external_enabled']) : [];
    $orders = is_array($post['external_order'] ?? null) ? array_values((array) $post['external_order']) : [];

    $libraries = [];
    $count = max(count($names), count($urls), count($integrities), count($crossorigins), count($orders), 1);
    for ($i = 0; $i < $count; $i++) {
        $url = trim((string) ($urls[$i] ?? ''));
        if ($url === '') {
            continue;
        }
        $libraries[] = [
            'name' => trim((string) ($names[$i] ?? '')),
            'url' => $url,
            'integrity' => trim((string) ($integrities[$i] ?? '')),
            'crossorigin' => trim((string) ($crossorigins[$i] ?? '')),
            'enabled' => in_array((string) $i, $enabled, true),
            'order' => (int) ($orders[$i] ?? ($i + 1)),
        ];
    }

    return $libraries;
}

/**
 * @param array<string, mixed> $post
 * @return list<array<string, mixed>>
 */
function myronCustomInteractionsExternalFontsFromPost(array $post): array
{
    $names = is_array($post['font_external_name'] ?? null) ? array_values((array) $post['font_external_name']) : [];
    $urls = is_array($post['font_external_url'] ?? null) ? array_values((array) $post['font_external_url']) : [];
    $integrities = is_array($post['font_external_integrity'] ?? null) ? array_values((array) $post['font_external_integrity']) : [];
    $crossorigins = is_array($post['font_external_crossorigin'] ?? null) ? array_values((array) $post['font_external_crossorigin']) : [];
    $enabled = is_array($post['font_external_enabled'] ?? null) ? array_map('strval', (array) $post['font_external_enabled']) : [];
    $orders = is_array($post['font_external_order'] ?? null) ? array_values((array) $post['font_external_order']) : [];

    $fonts = [];
    $count = max(count($names), count($urls), count($integrities), count($crossorigins), count($orders), 1);
    for ($i = 0; $i < $count; $i++) {
        $url = trim((string) ($urls[$i] ?? ''));
        if ($url === '') {
            continue;
        }
        $fonts[] = [
            'name' => trim((string) ($names[$i] ?? '')),
            'url' => $url,
            'integrity' => trim((string) ($integrities[$i] ?? '')),
            'crossorigin' => trim((string) ($crossorigins[$i] ?? '')),
            'enabled' => in_array((string) $i, $enabled, true),
            'order' => (int) ($orders[$i] ?? ($i + 1)),
        ];
    }

    return $fonts;
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        // APO-193 Card 6 — admin form path + PATCH /api/v1/design/custom-css/site
        // share MyronCustomCssActionService::saveSiteCss.
        $action = trim((string) ($_POST['action'] ?? 'save-site-custom-css'));
        $callerCtx = myronActionCallerContextForUser($currentUser);
        if ($action === 'save-site-custom-css' || $action === '') {
            myronCustomCssActionService()->saveSiteCss((string) ($_POST['site_css'] ?? ''), $callerCtx);
            myronRedirectWithFlash(myronBuildAdminUrl('design.customInteractions'), 'Updated site-wide custom CSS.', 'success');
        }
        if ($action === 'save-custom-interactions-js') {
            myronCustomCssActionService()->saveCustomInteractions(
                myronCustomInteractionsExternalLibrariesFromPost($_POST),
                (string) ($_POST['custom_js'] ?? ''),
                $callerCtx
            );
            myronRedirectWithFlash(myronBuildAdminUrl('design.customInteractions', ['tab' => 'js']), 'Updated site-wide custom interactions.', 'success');
        }
        if ($action === 'upload-custom-interaction-library') {
            myronCustomCssActionService()->uploadInteractionLibraryFromMultipart(
                $_FILES['interaction_library'] ?? [],
                (string) ($_POST['library_label'] ?? ''),
                $callerCtx
            );
            myronRedirectWithFlash(myronBuildAdminUrl('design.customInteractions', ['tab' => 'js']), 'Uploaded JavaScript interaction library.', 'success');
        }
        if ($action === 'delete-custom-interaction-library') {
            myronCustomCssActionService()->deleteInteractionLibrary(
                (string) ($_POST['library_id'] ?? ''),
                $callerCtx
            );
            myronRedirectWithFlash(myronBuildAdminUrl('design.customInteractions', ['tab' => 'js']), 'Deleted JavaScript interaction library.', 'success');
        }
        if ($action === 'save-custom-interaction-fonts') {
            myronCustomCssActionService()->saveCustomInteractionFonts(
                myronCustomInteractionsExternalFontsFromPost($_POST),
                null,
                $callerCtx
            );
            myronRedirectWithFlash(myronBuildAdminUrl('design.customInteractions', ['tab' => 'fonts']), 'Updated custom font includes.', 'success');
        }
        if ($action === 'upload-custom-interaction-font') {
            myronCustomCssActionService()->uploadInteractionFontFromMultipart(
                $_FILES['interaction_font'] ?? [],
                (string) ($_POST['font_label'] ?? ''),
                (string) ($_POST['font_family'] ?? ''),
                (string) ($_POST['font_weight'] ?? '400'),
                (string) ($_POST['font_style'] ?? 'normal'),
                (string) ($_POST['font_display'] ?? 'swap'),
                $callerCtx
            );
            myronRedirectWithFlash(myronBuildAdminUrl('design.customInteractions', ['tab' => 'fonts']), 'Uploaded web font.', 'success');
        }
        if ($action === 'delete-custom-interaction-font') {
            myronCustomCssActionService()->deleteInteractionFont(
                (string) ($_POST['font_id'] ?? ''),
                $callerCtx
            );
            myronRedirectWithFlash(myronBuildAdminUrl('design.customInteractions', ['tab' => 'fonts']), 'Deleted uploaded web font.', 'success');
        }
        throw new InvalidArgumentException('Unknown custom interactions action.');
    } catch (Throwable $exception) {
        myronRedirectWithFlash(myronBuildAdminUrl('design.customInteractions', ['tab' => $activeTab]), $exception->getMessage(), 'error');
    }
}

$siteCss = $repository->siteCss();
$interactions = $repository->customInteractions();
$externalLibraries = $interactions['externalLibraries'];
$uploadedLibraries = $interactions['uploadedLibraries'];
$customJs = (string) $interactions['customJs'];
$externalFonts = $interactions['externalFonts'];
$uploadedFonts = $interactions['uploadedFonts'];
$externalRows = $externalLibraries !== [] ? $externalLibraries : [[
    'name' => '',
    'url' => '',
    'integrity' => '',
    'crossorigin' => '',
    'enabled' => true,
    'order' => 1,
]];
$externalFontRows = $externalFonts !== [] ? $externalFonts : [[
    'name' => '',
    'url' => '',
    'integrity' => '',
    'crossorigin' => '',
    'enabled' => true,
    'order' => 1,
]];

myronRenderAdminShellStart($currentUser, [
    'title' => 'Custom Interactions',
    'titleContext' => 'Custom Interactions',
    'activeItem' => 'custom-css',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Design', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Design Studio', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Custom Interactions'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Custom Interactions</h1>
  </div>
  <p class="mc-workspace__subtitle">Author site-wide CSS and JavaScript interaction layers that render after MyronCMS runtime assets.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <div class="mc-workspace__tabs" role="tablist" aria-label="Custom Interactions views">
      <a class="mc-workspace__tab<?= $activeTab === 'css' ? ' mc-workspace__tab--active' : '' ?>" href="<?= myronEscape(myronBuildAdminUrl('design.customInteractions')) ?>">CSS</a>
      <a class="mc-workspace__tab<?= $activeTab === 'js' ? ' mc-workspace__tab--active' : '' ?>" href="<?= myronEscape(myronBuildAdminUrl('design.customInteractions', ['tab' => 'js'])) ?>">JS</a>
      <a class="mc-workspace__tab<?= $activeTab === 'fonts' ? ' mc-workspace__tab--active' : '' ?>" href="<?= myronEscape(myronBuildAdminUrl('design.customInteractions', ['tab' => 'fonts'])) ?>">Fonts</a>
    </div>
    <?php if ($activeTab === 'js'): ?>
    <section class="sg-section">
      <h2 class="sg-section__title">JavaScript Libraries</h2>
      <p class="sg-section__subtitle">Custom JavaScript is executable operator-authored code. External library URLs must use HTTPS.</p>
      <form method="post" class="sg-form-grid" data-custom-interactions-js-form>
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="action" value="save-custom-interactions-js">

        <div class="myron-data-table-wrapper">
          <table class="myron-data-table">
            <thead>
              <tr>
                <th scope="col">Enabled</th>
                <th scope="col">Name</th>
                <th scope="col">HTTPS URL</th>
                <th scope="col">Integrity</th>
                <th scope="col">Crossorigin</th>
                <th scope="col">Order</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($externalRows as $index => $library): ?>
              <tr>
                <td><input type="checkbox" name="external_enabled[]" value="<?= myronEscape((string) $index) ?>" <?= (bool) ($library['enabled'] ?? true) ? 'checked' : '' ?>></td>
                <td><input class="sg-field__control" type="text" name="external_name[]" value="<?= myronEscape((string) ($library['name'] ?? '')) ?>" placeholder="Library name"></td>
                <td><input class="sg-field__control" type="url" name="external_url[]" value="<?= myronEscape((string) ($library['url'] ?? $library['cdnUrl'] ?? '')) ?>" placeholder="https://cdn.example.com/library.js"></td>
                <td><input class="sg-field__control" type="text" name="external_integrity[]" value="<?= myronEscape((string) ($library['integrity'] ?? $library['sri'] ?? '')) ?>" placeholder="sha384-..."></td>
                <td>
                  <select class="sg-field__control" name="external_crossorigin[]">
                    <?php $crossorigin = (string) ($library['crossorigin'] ?? ''); ?>
                    <option value="" <?= $crossorigin === '' ? 'selected' : '' ?>>None</option>
                    <option value="anonymous" <?= $crossorigin === 'anonymous' ? 'selected' : '' ?>>anonymous</option>
                    <option value="use-credentials" <?= $crossorigin === 'use-credentials' ? 'selected' : '' ?>>use-credentials</option>
                  </select>
                </td>
                <td><input class="sg-field__control" type="number" min="1" step="1" name="external_order[]" value="<?= myronEscape((string) ($library['order'] ?? ($index + 1))) ?>"></td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>

        <label class="sg-field">
          <span class="sg-field__label">Custom JS</span>
          <textarea class="sg-field__control sg-field__control--code" name="custom_js" rows="16" spellcheck="false"><?= myronEscape($customJs) ?></textarea>
        </label>

        <div class="sg-card__actions">
          <button class="sg-button sg-button--primary" type="submit">Save JS Interactions</button>
        </div>
      </form>
    </section>

    <section class="sg-section">
      <h2 class="sg-section__title">Uploaded Libraries</h2>
      <form method="post" enctype="multipart/form-data" class="sg-form-grid">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="action" value="upload-custom-interaction-library">
        <label class="sg-field">
          <span class="sg-field__label">Library Label</span>
          <input class="sg-field__control" type="text" name="library_label" placeholder="Three.js custom build">
        </label>
        <label class="sg-field">
          <span class="sg-field__label">Upload JS Library</span>
          <input class="sg-field__control" type="file" name="interaction_library" accept=".js,application/javascript,text/javascript">
          <span class="sg-field__hint">JavaScript libraries must be `.js` files up to 1 MB. Uploads are stored in the design-scoped interaction library path.</span>
        </label>
        <div class="sg-card__actions">
          <button class="sg-button sg-button--secondary" type="submit">Upload Library</button>
        </div>
      </form>

      <?php if ($uploadedLibraries !== []): ?>
      <div class="myron-data-table-wrapper">
        <table class="myron-data-table">
          <thead><tr><th>Name</th><th>URL</th><th>SHA-256</th><th>Size</th><th>Actions</th></tr></thead>
          <tbody>
            <?php foreach ($uploadedLibraries as $library): ?>
            <tr>
              <td><?= myronEscape((string) ($library['name'] ?? 'Uploaded library')) ?></td>
              <td><code><?= myronEscape((string) ($library['url'] ?? '')) ?></code></td>
              <td><code><?= myronEscape((string) ($library['sha256'] ?? '')) ?></code></td>
              <td><?= myronEscape(myronFormatFileSize((int) ($library['sizeBytes'] ?? 0))) ?></td>
              <td>
                <form method="post" onsubmit="return window.confirm('Delete this uploaded JavaScript library?');">
                  <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
                  <input type="hidden" name="action" value="delete-custom-interaction-library">
                  <input type="hidden" name="library_id" value="<?= myronEscape((string) ($library['id'] ?? '')) ?>">
                  <button class="sg-button sg-button--danger" type="submit">Delete</button>
                </form>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <?php endif; ?>
    </section>
    <?php elseif ($activeTab === 'fonts'): ?>
    <section class="sg-section">
      <h2 class="sg-section__title">Font Stylesheets</h2>
      <p class="sg-section__subtitle">External font stylesheet URLs must use HTTPS. Self-hosted uploads render from the first-party font path below.</p>
      <form method="post" class="sg-form-grid" data-custom-interactions-fonts-form>
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="action" value="save-custom-interaction-fonts">

        <div class="myron-data-table-wrapper">
          <table class="myron-data-table">
            <thead>
              <tr>
                <th scope="col">Enabled</th>
                <th scope="col">Name</th>
                <th scope="col">HTTPS CSS URL</th>
                <th scope="col">Integrity</th>
                <th scope="col">Crossorigin</th>
                <th scope="col">Order</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($externalFontRows as $index => $font): ?>
              <tr>
                <td><input type="checkbox" name="font_external_enabled[]" value="<?= myronEscape((string) $index) ?>" <?= (bool) ($font['enabled'] ?? true) ? 'checked' : '' ?>></td>
                <td><input class="sg-field__control" type="text" name="font_external_name[]" value="<?= myronEscape((string) ($font['name'] ?? '')) ?>" placeholder="Font stylesheet name"></td>
                <td><input class="sg-field__control" type="url" name="font_external_url[]" value="<?= myronEscape((string) ($font['url'] ?? '')) ?>" placeholder="https://fonts.googleapis.com/css2?family=Inter"></td>
                <td><input class="sg-field__control" type="text" name="font_external_integrity[]" value="<?= myronEscape((string) ($font['integrity'] ?? '')) ?>" placeholder="sha384-..."></td>
                <td>
                  <select class="sg-field__control" name="font_external_crossorigin[]">
                    <?php $fontCrossorigin = (string) ($font['crossorigin'] ?? ''); ?>
                    <option value="" <?= $fontCrossorigin === '' ? 'selected' : '' ?>>None</option>
                    <option value="anonymous" <?= $fontCrossorigin === 'anonymous' ? 'selected' : '' ?>>anonymous</option>
                    <option value="use-credentials" <?= $fontCrossorigin === 'use-credentials' ? 'selected' : '' ?>>use-credentials</option>
                  </select>
                </td>
                <td><input class="sg-field__control" type="number" min="1" step="1" name="font_external_order[]" value="<?= myronEscape((string) ($font['order'] ?? ($index + 1))) ?>"></td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>

        <div class="sg-card__actions">
          <button class="sg-button sg-button--primary" type="submit">Save Font Includes</button>
        </div>
      </form>
    </section>

    <section class="sg-section">
      <h2 class="sg-section__title">Uploaded Fonts</h2>
      <form method="post" enctype="multipart/form-data" class="sg-form-grid">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="action" value="upload-custom-interaction-font">
        <label class="sg-field">
          <span class="sg-field__label">Font Label</span>
          <input class="sg-field__control" type="text" name="font_label" placeholder="Inter variable">
        </label>
        <label class="sg-field">
          <span class="sg-field__label">Font Family</span>
          <input class="sg-field__control" type="text" name="font_family" placeholder="Inter">
        </label>
        <label class="sg-field">
          <span class="sg-field__label">Weight</span>
          <input class="sg-field__control" type="text" name="font_weight" value="400" placeholder="400 or 100 900">
        </label>
        <label class="sg-field">
          <span class="sg-field__label">Style</span>
          <select class="sg-field__control" name="font_style">
            <option value="normal">normal</option>
            <option value="italic">italic</option>
            <option value="oblique">oblique</option>
          </select>
        </label>
        <label class="sg-field">
          <span class="sg-field__label">Display</span>
          <select class="sg-field__control" name="font_display">
            <option value="swap" selected>swap</option>
            <option value="auto">auto</option>
            <option value="block">block</option>
            <option value="fallback">fallback</option>
            <option value="optional">optional</option>
          </select>
        </label>
        <label class="sg-field">
          <span class="sg-field__label">Upload Web Font</span>
          <input class="sg-field__control" type="file" name="interaction_font" accept=".woff2,.woff,.ttf,.otf,font/woff2,font/woff,font/ttf,font/otf">
          <span class="sg-field__hint">Web font uploads must be `.woff2`, `.woff`, `.ttf`, or `.otf` files up to 2 MB.</span>
        </label>
        <div class="sg-card__actions">
          <button class="sg-button sg-button--secondary" type="submit">Upload Font</button>
        </div>
      </form>

      <?php if ($uploadedFonts !== []): ?>
      <div class="myron-data-table-wrapper">
        <table class="myron-data-table">
          <thead><tr><th>Font</th><th>URL</th><th>SHA-256</th><th>Size</th><th>Actions</th></tr></thead>
          <tbody>
            <?php foreach ($uploadedFonts as $font): ?>
            <tr>
              <td>
                <?= myronEscape((string) ($font['label'] ?? 'Uploaded font')) ?><br>
                <code><?= myronEscape((string) ($font['familyName'] ?? '')) ?> / <?= myronEscape((string) ($font['weight'] ?? '')) ?> / <?= myronEscape((string) ($font['style'] ?? '')) ?> / <?= myronEscape((string) ($font['display'] ?? '')) ?></code>
              </td>
              <td><code><?= myronEscape((string) ($font['url'] ?? '')) ?></code></td>
              <td><code><?= myronEscape((string) ($font['sha256'] ?? '')) ?></code></td>
              <td><?= myronEscape(myronFormatFileSize((int) ($font['sizeBytes'] ?? 0))) ?></td>
              <td>
                <form method="post" onsubmit="return window.confirm('Delete this uploaded web font?');">
                  <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
                  <input type="hidden" name="action" value="delete-custom-interaction-font">
                  <input type="hidden" name="font_id" value="<?= myronEscape((string) ($font['id'] ?? '')) ?>">
                  <button class="sg-button sg-button--danger" type="submit">Delete</button>
                </form>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <?php endif; ?>
    </section>
    <?php else: ?>
    <section class="sg-section">
      <form method="post" class="sg-form-grid">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="action" value="save-site-custom-css">
        <label class="sg-field">
          <span class="sg-field__label">Site-wide CSS</span>
          <textarea class="sg-field__control sg-field__control--code" name="site_css" rows="18" spellcheck="false"><?= myronEscape($siteCss) ?></textarea>
        </label>
        <div class="sg-card__actions">
          <button class="sg-button sg-button--primary" type="submit">Save CSS</button>
        </div>
      </form>
    </section>
    <section class="sg-section">
      <h2 class="sg-section__title">Emission Preview</h2>
      <pre class="sg-code-block"><code><?= myronEscape($repository->cssLayer($siteCss)) ?></code></pre>
    </section>
    <?php endif; ?>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
