<?php

declare(strict_types=1);

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

$currentUser = myronRequireAdministrationAccess();
$csrfToken = myronCsrfToken();
$service = myronMarketplaceExtensionInstallService();
$filters = [];
foreach (['q', 'sort', 'capability', 'compatibility', 'publisherId', 'namespace', 'category', 'collection'] as $filterKey) {
    $value = trim((string) ($_GET[$filterKey] ?? ''));
    if ($value !== '') {
        $filters[$filterKey] = $value;
    }
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $packageVersionId = trim((string) ($_POST['package_version_id'] ?? ''));
        $result = $service->install($packageVersionId, (string) ($currentUser['id'] ?? ''));
        $namespace = (string) ($result['candidate']['namespace'] ?? '');
        myronRedirectWithFlash(
            myronBuildAdminUrl('extensions.register', $namespace !== '' ? ['vendor' => $namespace] : []),
            'Extension package installed. Register scopes before enabling.',
            'success'
        );
    } catch (Throwable $exception) {
        myronRedirectWithFlash(myronBuildAdminUrl('extensions.marketplace'), $exception->getMessage(), 'error');
    }
}

$state = $service->listCandidates($filters);
$items = is_array($state['items'] ?? null) ? $state['items'] : [];

myronRenderAdminShellStart($currentUser, [
    'title' => 'Extension Marketplace',
    'titleContext' => 'Extensions',
    'activeItem' => 'extensions-marketplace',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Extensions', 'href' => myronBuildAdminUrl('extensions.installed')],
      ['label' => 'Marketplace'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Extension Marketplace</h1>
  </div>
  <p class="mc-workspace__subtitle">Review signed Extension packages and install them into the local extensions directory.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <section class="sg-section">
      <h2 class="sg-section__title">Available Extensions</h2>
      <form class="mc-form" method="get" action="<?= myronEscape(myronBuildAdminUrl('extensions.marketplace')) ?>">
        <div class="mc-form__grid">
          <label class="mc-form__field">
            <span>Search</span>
            <input class="mc-input" type="search" name="q" value="<?= myronEscape((string) ($filters['q'] ?? '')) ?>">
          </label>
          <label class="mc-form__field">
            <span>Sort</span>
            <select class="mc-select" name="sort">
              <?php foreach (['recent' => 'Recent', 'rating' => 'Rating', 'support-health' => 'Support Health', 'capability-match' => 'Capability Match', 'curated' => 'Curated'] as $value => $label): ?>
              <option value="<?= myronEscape($value) ?>"<?= (($filters['sort'] ?? '') === $value) ? ' selected' : '' ?>><?= myronEscape($label) ?></option>
              <?php endforeach; ?>
            </select>
          </label>
          <label class="mc-form__field">
            <span>Capability</span>
            <input class="mc-input" type="text" name="capability" value="<?= myronEscape((string) ($filters['capability'] ?? '')) ?>">
          </label>
          <label class="mc-form__field">
            <span>Category</span>
            <input class="mc-input" type="text" name="category" value="<?= myronEscape((string) ($filters['category'] ?? '')) ?>">
          </label>
          <label class="mc-form__field">
            <span>Namespace</span>
            <input class="mc-input" type="text" name="namespace" value="<?= myronEscape((string) ($filters['namespace'] ?? '')) ?>">
          </label>
          <label class="mc-form__field">
            <span>Collection</span>
            <input class="mc-input" type="text" name="collection" value="<?= myronEscape((string) ($filters['collection'] ?? '')) ?>">
          </label>
        </div>
        <div class="mc-form__actions">
          <button class="sg-button sg-button--secondary" type="submit">Apply</button>
          <a class="sg-button sg-button--ghost" href="<?= myronEscape(myronBuildAdminUrl('extensions.marketplace')) ?>">Reset</a>
        </div>
      </form>
      <?php if (($state['ok'] ?? false) !== true): ?>
      <div class="sg-empty-state">
        <p class="sg-empty-state__title">Marketplace unavailable.</p>
        <p class="sg-empty-state__text"><?= myronEscape((string) ($state['error'] ?? 'extension_marketplace_unavailable')) ?></p>
      </div>
      <?php elseif ($items === []): ?>
      <div class="sg-empty-state">
        <p class="sg-empty-state__title">No Extension packages available.</p>
        <p class="sg-empty-state__text">Published third-party Extensions will appear here.</p>
      </div>
      <?php else: ?>
      <table class="mc-page-grid">
        <thead>
          <tr>
            <th>Extension</th>
            <th>Publisher</th>
            <th>Compatibility</th>
            <th>Review</th>
            <th>Status</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($items as $item): ?>
          <?php
          $packageVersionId = (string) ($item['packageVersionId'] ?? '');
          $namespace = (string) ($item['namespace'] ?? '');
          $review = is_array($item['review'] ?? null) ? $item['review'] : [];
          $compatibility = is_array($item['compatibility'] ?? null) ? $item['compatibility'] : [];
          $discovery = is_array($item['discovery'] ?? null) ? $item['discovery'] : [];
          $signals = is_array($discovery['signals'] ?? null) ? $discovery['signals'] : [];
          $facets = is_array($discovery['facets'] ?? null) ? $discovery['facets'] : [];
          $installed = !empty($item['installed']);
          ?>
          <tr>
            <td>
              <strong><?= myronEscape((string) ($item['displayName'] ?? $item['packageId'] ?? 'Extension')) ?></strong><br>
              <small><code><?= myronEscape((string) ($item['packageId'] ?? '')) ?></code> · <?= myronEscape((string) ($item['version'] ?? '')) ?></small>
              <?php if ((string) ($discovery['summary'] ?? '') !== ''): ?>
              <br><small><?= myronEscape((string) $discovery['summary']) ?></small>
              <?php endif; ?>
            </td>
            <td><code><?= myronEscape($namespace) ?></code></td>
            <td>
              <?= myronEscape((string) ($compatibility['myroncmsVersionRange'] ?? '')) ?><br>
              <small>API <?= myronEscape((string) ($compatibility['extensionApiVersion'] ?? '')) ?></small>
            </td>
            <td>
              <code><?= myronEscape((string) ($review['reviewId'] ?? '')) ?></code><br>
              <small><?= myronEscape((string) ($review['policyVersion'] ?? '')) ?></small>
            </td>
            <td>
              <?php if ($installed): ?>
              <span class="sg-pill sg-pill--active">Installed</span>
              <?php else: ?>
              <span class="sg-pill">Ready</span>
              <?php endif; ?>
              <?php if ($signals !== []): ?>
              <br><small><?= myronEscape(number_format((float) ($signals['averageRating'] ?? 0), 1)) ?> stars · <?= myronEscape((string) ((int) ($signals['reviewCount'] ?? 0))) ?> reviews</small>
              <br><small>Support: <?= myronEscape((string) ($signals['supportHealth'] ?? 'unknown')) ?></small>
              <?php endif; ?>
              <?php if ($facets !== []): ?>
              <br><small>
                <?php foreach (array_slice($facets, 0, 3) as $facet): ?>
                <span class="sg-pill"><?= myronEscape((string) ($facet['value'] ?? '')) ?></span>
                <?php endforeach; ?>
              </small>
              <?php endif; ?>
            </td>
            <td>
              <?php if ($installed): ?>
              <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('extensions.register', ['vendor' => $namespace])) ?>">Register Scopes</a>
              <?php else: ?>
              <form method="post" action="<?= myronEscape(myronBuildAdminUrl('extensions.marketplace')) ?>">
                <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
                <input type="hidden" name="package_version_id" value="<?= myronEscape($packageVersionId) ?>">
                <button class="sg-button sg-button--primary" type="submit">Install</button>
              </form>
              <?php endif; ?>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
      <?php endif; ?>
    </section>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
