<?php
declare(strict_types=1);

/** @var array{ok:?string,err:?string} $flash */
/** @var null|array{id:int,site_url:string,last_sync_at:?string} $activeProp */
/** @var null|array $data */
/** @var string $rangeStart */
/** @var string $rangeEnd */
/** @var ?array $globalFilters */
/** @var bool $seoAiInsightsEnabled */

$pageTitle = __('opportunities.page_title');
$pageHeading = __('opportunities.heading');
$activeNav = 'quick_win';
$hideHero = true;

if (!isset($seoAiInsightsEnabled) || !is_bool($seoAiInsightsEnabled)) {
    $seoAiInsightsEnabled = false;
}

$total = is_array($data) ? (int) ($data['total'] ?? 0) : 0;
$rows = is_array($data) ? ($data['rows'] ?? []) : [];
$thresholds = is_array($data) && isset($data['thresholds']) && is_array($data['thresholds']) ? $data['thresholds'] : [];
$page = max(1, (int) ($_GET['page'] ?? 1));
$perPage = max(10, min(100, (int) ($_GET['per_page'] ?? 10)));
$pages = $total > 0 ? (int) ceil($total / $perPage) : 1;
$sort = (string) ($_GET['sort'] ?? 'score');
$dir = (string) ($_GET['dir'] ?? 'DESC');
$tab = (string) ($_GET['tab'] ?? 'iqqi');
$allowedTabs = ['iqqi', 'ctr_opportunity', 'low_ctr_pages', 'topical_gaps'];
if (!in_array($tab, $allowedTabs, true)) {
    $tab = 'iqqi';
}

$fmtInt = static fn (int $n): string => number_format($n, 0, '.', ',');
$fmtCtr = static fn (float $n): string => number_format($n * 100, 2) . '%';
$fmtPos = static fn (float $n): string => number_format($n, 2);
$fmtScore = static fn (float $n): string => number_format($n, 2);
$fmtCtrGap = static fn (float $n): string => number_format($n * 100, 2) . '%';

$exportUrl = static function (): string {
    $base = $_GET;
    if (!is_array($base)) {
        $base = [];
    }
    unset($base['page'], $base['per_page']);
    return seoscope_url('/export/opportunities.csv' . ($base ? ('?' . http_build_query($base)) : ''));
};

$buildUrl = static function (array $overrides): string {
    $base = [
        'prop' => (string) ($_GET['prop'] ?? ''),
        'range' => (string) ($_GET['range'] ?? 'last_30_days'),
        'per_page' => (string) ($_GET['per_page'] ?? '10'),
        'tab' => (string) ($_GET['tab'] ?? 'iqqi'),
        'sort' => (string) ($_GET['sort'] ?? 'score'),
        'dir' => (string) ($_GET['dir'] ?? 'DESC'),
        'page' => (string) ($_GET['page'] ?? '1'),
    ];
    foreach ($overrides as $k => $v) {
        $base[$k] = (string) $v;
    }
    foreach (['prop'] as $k) {
        if (($base[$k] ?? '') === '') unset($base[$k]);
    }
    // Must link directly to /quick-win: /opportunities is a redirect alias and would drop query params.
    return seoscope_url('/quick-win?' . http_build_query($base));
};

$th = static function (string $k, string $fallback = '') use ($thresholds): string {
    if (array_key_exists($k, $thresholds)) {
        return (string) $thresholds[$k];
    }
    return $fallback;
};

$baseSiteUrl = '';
if (is_array($activeProp) && !empty($activeProp['site_url'])) {
    $baseSiteUrl = rtrim((string) $activeProp['site_url'], '/');
}
$stripBaseUrl = static function (string $url) use ($baseSiteUrl): string {
    $u = trim($url);
    if ($u === '') {
        return '';
    }
    if ($baseSiteUrl !== '' && str_starts_with($u, $baseSiteUrl)) {
        $u = substr($u, strlen($baseSiteUrl));
        if ($u === '') {
            $u = '/';
        }
    }
    // Normalize to a path-like display (avoid empty string).
    if ($u !== '' && $u[0] !== '/' && preg_match('#^https?://#i', $u) !== 1) {
        $u = '/' . $u;
    }
    return $u;
};

ob_start();
?>
<div class="dashboard-card section-card">
    <div class="d-flex align-items-center justify-content-between mb-1">
        <div class="section-title mb-0"><?= seoscope_h(__('opportunities.title')) ?></div>
        <?php if (is_array($activeProp)): ?>
            <a class="btn btn-export-csv" href="<?= seoscope_h($exportUrl()) ?>"><?= seoscope_h(__('common.export_csv')) ?></a>
        <?php endif; ?>
    </div>
    <div class="section-subtitle mb-3">
        <?= seoscope_h(__('opportunities.subtitle', ['start' => $rangeStart, 'end' => $rangeEnd])) ?>
    </div>

    <ul class="nav nav-tabs mb-3" role="tablist">
        <?php
            $tabItems = [
                'iqqi' => 'IQQI',
                'ctr_opportunity' => 'CTR Opportunity',
                'low_ctr_pages' => 'Low CTR Pages',
                'topical_gaps' => 'Topical Gaps',
            ];
            foreach ($tabItems as $k => $label):
                $isActiveTab = $tab === $k;
        ?>
            <li class="nav-item" role="presentation">
                <a
                    class="nav-link <?= $isActiveTab ? 'active' : '' ?>"
                    href="<?= seoscope_h($buildUrl(['tab' => $k, 'page' => '1'])) ?>"
                    role="tab"
                    aria-selected="<?= $isActiveTab ? 'true' : 'false' ?>"
                >
                    <?= seoscope_h($label) ?>
                </a>
            </li>
        <?php endforeach; ?>
    </ul>

    <?php
        $tabDescKey = match ($tab) {
            'ctr_opportunity' => 'quickwin.tab_desc.ctr_opportunity',
            'low_ctr_pages' => 'quickwin.tab_desc.low_ctr_pages',
            'topical_gaps' => 'quickwin.tab_desc.topical_gaps',
            default => 'quickwin.tab_desc.iqqi',
        };
        $tabActionKey = match ($tab) {
            'ctr_opportunity' => 'quickwin.tab_action.ctr_opportunity',
            'low_ctr_pages' => 'quickwin.tab_action.low_ctr_pages',
            'topical_gaps' => 'quickwin.tab_action.topical_gaps',
            default => 'quickwin.tab_action.iqqi',
        };
    ?>
    <div class="text-muted small mb-2">
        <?php if ($tab === 'iqqi'): ?>
            <strong><?= seoscope_h(__('quickwin.iqqi_meaning')) ?></strong> <?= seoscope_h(__($tabDescKey)) ?>
        <?php elseif ($tab === 'ctr_opportunity'): ?>
            <strong><?= seoscope_h(__('quickwin.ctr_opportunity_meaning')) ?></strong> <?= seoscope_h(__($tabDescKey)) ?>
        <?php elseif ($tab === 'low_ctr_pages'): ?>
            <strong><?= seoscope_h(__('quickwin.low_ctr_pages_meaning')) ?></strong> <?= seoscope_h(__($tabDescKey)) ?>
        <?php elseif ($tab === 'topical_gaps'): ?>
            <strong><?= seoscope_h(__('quickwin.topical_gaps_meaning')) ?></strong> <?= seoscope_h(__($tabDescKey)) ?>
        <?php else: ?>
            <?= seoscope_h(__($tabDescKey)) ?>
        <?php endif; ?>
        <div class="mt-1">
            <strong><?= seoscope_h(__('quickwin.suggested_action')) ?></strong>
            <?= seoscope_h(__($tabActionKey)) ?>
        </div>
    </div>

    <?php
    if (!isset($seoAiQwCard)) {
        $seoAiQwCard = null;
    }
    if (is_array($seoAiQwCard) && in_array($tab, ['iqqi', 'ctr_opportunity', 'low_ctr_pages', 'topical_gaps'], true) && !empty($seoAiInsightsEnabled)):
        $ssAiQw = $seoAiQwCard;
        require __DIR__ . '/partials/seo_ai_quickwin_card.php';
    endif;
    ?>

    <?php if (is_array($activeProp)): ?>
        <form method="get" class="row g-2 align-items-end mb-3">
            <input type="hidden" name="prop" value="<?= seoscope_h((string) ($_GET['prop'] ?? '')) ?>">
            <input type="hidden" name="range" value="<?= seoscope_h((string) ($_GET['range'] ?? 'last_28_days')) ?>">
            <input type="hidden" name="tab" value="<?= seoscope_h($tab) ?>">
            <input type="hidden" name="sort" value="<?= seoscope_h($sort) ?>">
            <input type="hidden" name="dir" value="<?= seoscope_h($dir) ?>">
            <input type="hidden" name="per_page" value="<?= seoscope_h((string) $perPage) ?>">

            <?php if ($tab === 'iqqi'): ?>
                <div class="col-12 col-md-3">
                    <label class="form-label small mb-1">min impr</label>
                    <input class="form-control form-control-sm" type="number" name="iqqi_min_impr" value="<?= seoscope_h($th('iqqi_min_impr', '200')) ?>">
                </div>
                <div class="col-6 col-md-3">
                    <label class="form-label small mb-1">pos min</label>
                    <input class="form-control form-control-sm" type="number" step="0.1" name="iqqi_pos_min" value="<?= seoscope_h($th('iqqi_pos_min', '4')) ?>">
                </div>
                <div class="col-6 col-md-3">
                    <label class="form-label small mb-1">pos max</label>
                    <input class="form-control form-control-sm" type="number" step="0.1" name="iqqi_pos_max" value="<?= seoscope_h($th('iqqi_pos_max', '10')) ?>">
                </div>
            <?php elseif ($tab === 'ctr_opportunity'): ?>
                <div class="col-12 col-md-3">
                    <label class="form-label small mb-1">min impr</label>
                    <input class="form-control form-control-sm" type="number" name="ctr_min_impr" value="<?= seoscope_h($th('ctr_min_impr', '200')) ?>">
                </div>
            <?php elseif ($tab === 'low_ctr_pages'): ?>
                <div class="col-12 col-md-3">
                    <label class="form-label small mb-1">min impr</label>
                    <input class="form-control form-control-sm" type="number" name="lowctr_pages_min_impr" value="<?= seoscope_h($th('lowctr_pages_min_impr', '1000')) ?>">
                </div>
                <div class="col-12 col-md-3">
                    <label class="form-label small mb-1">coeff</label>
                    <input class="form-control form-control-sm" type="number" step="0.05" name="lowctr_coeff" value="<?= seoscope_h($th('lowctr_coeff', '0.5')) ?>">
                </div>
            <?php elseif ($tab === 'topical_gaps'): ?>
                <div class="col-12 col-md-3">
                    <label class="form-label small mb-1">min impr</label>
                    <input class="form-control form-control-sm" type="number" name="topical_min_impr" value="<?= seoscope_h($th('topical_min_impr', '200')) ?>">
                </div>
                <div class="col-12 col-md-3">
                    <label class="form-label small mb-1">pos min</label>
                    <input class="form-control form-control-sm" type="number" step="0.1" name="topical_pos_min" value="<?= seoscope_h($th('topical_pos_min', '15')) ?>">
                </div>
                <div class="col-12 col-md-3">
                    <label class="form-label small mb-1">max clicks</label>
                    <input class="form-control form-control-sm" type="number" name="topical_max_clicks" value="<?= seoscope_h($th('topical_max_clicks', '2')) ?>">
                </div>
            <?php endif; ?>

            <div class="col-auto">
                <button class="btn btn-sm btn-upgrade" type="submit">Apply</button>
            </div>
            <div class="col-auto">
                <a class="btn btn-sm btn-outline-secondary" href="<?= seoscope_h($buildUrl(['reset' => '1', 'page' => '1'])) ?>">Reset</a>
            </div>
            <div class="col-auto">
                <button type="button" class="btn btn-sm btn-outline-secondary" id="ss-qw-save-defaults">
                    Save as defaults
                </button>
            </div>
        </form>
        <form method="post" action="<?= seoscope_h(seoscope_url('/settings/google/quick-win')) ?>" id="ss-qw-save-form" class="d-none">
            <input type="hidden" name="_csrf" value="<?= seoscope_h(\SeoScope\Auth\AdminCsrf::token()) ?>">
            <input type="hidden" name="redirect" value="<?= seoscope_h($_SERVER['REQUEST_URI'] ?? '/quick-win') ?>">
            <input type="hidden" name="qw_iqqi_min_impr" value="">
            <input type="hidden" name="qw_iqqi_pos_min" value="">
            <input type="hidden" name="qw_iqqi_pos_max" value="">
            <input type="hidden" name="qw_ctr_min_impr" value="">
            <input type="hidden" name="qw_lowctr_pages_min_impr" value="">
            <input type="hidden" name="qw_lowctr_coeff" value="">
            <input type="hidden" name="qw_topical_min_impr" value="">
            <input type="hidden" name="qw_topical_pos_min" value="">
            <input type="hidden" name="qw_topical_max_clicks" value="">
        </form>
        <script>
          (function () {
            var btn = document.getElementById('ss-qw-save-defaults');
            var form = document.getElementById('ss-qw-save-form');
            if (!btn || !form) return;

            function getVal(name) {
              var el = document.querySelector('input[name="' + name + '"]');
              if (!el) return '';
              return String(el.value || '').trim();
            }
            function setHidden(name, value) {
              var el = form.querySelector('input[name="' + name + '"]');
              if (!el) return;
              el.value = String(value || '').trim();
            }

            btn.addEventListener('click', function () {
              // Read current visible thresholds (tab inputs). If a field isn't present (other tabs),
              // fall back to current defaults from backend-rendered thresholds.
              setHidden('qw_iqqi_min_impr', getVal('iqqi_min_impr') || <?= json_encode((string) ($thresholds['iqqi_min_impr'] ?? '200')) ?>);
              setHidden('qw_iqqi_pos_min', getVal('iqqi_pos_min') || <?= json_encode((string) ($thresholds['iqqi_pos_min'] ?? '4')) ?>);
              setHidden('qw_iqqi_pos_max', getVal('iqqi_pos_max') || <?= json_encode((string) ($thresholds['iqqi_pos_max'] ?? '10')) ?>);

              setHidden('qw_ctr_min_impr', getVal('ctr_min_impr') || <?= json_encode((string) ($thresholds['ctr_min_impr'] ?? '200')) ?>);

              setHidden('qw_lowctr_pages_min_impr', getVal('lowctr_pages_min_impr') || <?= json_encode((string) ($thresholds['lowctr_pages_min_impr'] ?? '1000')) ?>);
              setHidden('qw_lowctr_coeff', getVal('lowctr_coeff') || <?= json_encode((string) ($thresholds['lowctr_coeff'] ?? '0.5')) ?>);

              setHidden('qw_topical_min_impr', getVal('topical_min_impr') || <?= json_encode((string) ($thresholds['topical_min_impr'] ?? '200')) ?>);
              setHidden('qw_topical_pos_min', getVal('topical_pos_min') || <?= json_encode((string) ($thresholds['topical_pos_min'] ?? '15')) ?>);
              setHidden('qw_topical_max_clicks', getVal('topical_max_clicks') || <?= json_encode((string) ($thresholds['topical_max_clicks'] ?? '2')) ?>);

              form.submit();
            });
          })();
        </script>
    <?php endif; ?>

    <?php if (!is_array($activeProp)): ?>
        <div class="text-muted"><?= seoscope_h(__('opportunities.no_property')) ?></div>
    <?php elseif (empty($rows)): ?>
        <div class="text-muted"><?= seoscope_h(__('opportunities.empty')) ?></div>
    <?php else: ?>
        <div class="table-wrap">
            <div class="table-responsive">
                <table class="crm-table">
                    <thead>
                        <tr>
                            <?php if ($tab === 'iqqi' || $tab === 'ctr_opportunity' || $tab === 'topical_gaps'): ?>
                                <th style="width:44px;"></th>
                            <?php endif; ?>
                            <?php
                                $cols = $tab === 'low_ctr_pages'
                                    ? [
                                        'page' => __('pages.col_page'),
                                        'score' => __('opportunities.col_score'),
                                        'impressions' => __('opportunities.col_impressions'),
                                        'ctr' => __('opportunities.col_ctr'),
                                        'position' => __('opportunities.col_position'),
                                        'clicks' => __('opportunities.col_clicks'),
                                      ]
                                    : [
                                        'query' => __('opportunities.col_query'),
                                        'score' => __('opportunities.col_score'),
                                        'impressions' => __('opportunities.col_impressions'),
                                        'ctr' => __('opportunities.col_ctr'),
                                        'position' => __('opportunities.col_position'),
                                        'clicks' => __('opportunities.col_clicks'),
                                      ];
                                foreach ($cols as $key => $label):
                                    $isActive = $sort === $key;
                                    $nextDir = ($isActive && strtoupper($dir) === 'DESC') ? 'ASC' : 'DESC';
                                    $arrow = $isActive ? (strtoupper($dir) === 'DESC' ? ' ↓' : ' ↑') : '';
                            ?>
                                <th>
                                    <a href="<?= seoscope_h($buildUrl(['sort' => $key, 'dir' => $nextDir, 'page' => '1'])) ?>" style="text-decoration:none;">
                                        <?= seoscope_h($label . $arrow) ?>
                                    </a>
                                </th>
                            <?php endforeach; ?>
                            <th><?= seoscope_h(__('opportunities.col_why')) ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $colspan = count($cols) + 1 + (($tab === 'iqqi' || $tab === 'ctr_opportunity' || $tab === 'topical_gaps') ? 1 : 0); ?>
                        <?php foreach ($rows as $r): ?>
                            <?php if (!is_array($r)) { continue; } ?>
                            <?php $rules = (isset($r['rules']) && is_array($r['rules'])) ? $r['rules'] : []; ?>
                            <?php
                                $query = (string) ($r['query'] ?? '');
                                $rowKey = substr(sha1($tab . '|' . $query . '|' . (string) ($r['score'] ?? '')), 0, 12);
                                $panelId = 'ss-qw-pages-' . $rowKey;
                                $btnId = $panelId . '-btn';
                            ?>
                            <tr>
                                <?php if ($tab === 'iqqi' || $tab === 'ctr_opportunity' || $tab === 'topical_gaps'): ?>
                                    <td style="white-space:nowrap;">
                                        <span class="d-inline-block">
                                            <button
                                                type="button"
                                                class="btn btn-sm btn-light-secondary ss-kw-toggle"
                                                id="<?= seoscope_h($btnId) ?>"
                                                data-bs-toggle="collapse"
                                                data-bs-target="#<?= seoscope_h($panelId) ?>"
                                                aria-expanded="false"
                                                aria-controls="<?= seoscope_h($panelId) ?>"
                                                data-kw="<?= seoscope_h($query) ?>"
                                                <?= $query !== '' ? '' : 'disabled' ?>
                                            >
                                                <i class="fa-solid fa-chevron-right"></i>
                                            </button>
                                        </span>
                                    </td>
                                <?php endif; ?>
                                <?php if ($tab === 'low_ctr_pages'): ?>
                                    <?php
                                        $full = (string) ($r['page'] ?? '');
                                        $disp = $stripBaseUrl($full);
                                    ?>
                                    <td>
                                        <a href="<?= seoscope_h($full) ?>" target="_blank" rel="noopener noreferrer">
                                            <?= seoscope_h($disp !== '' ? $disp : $full) ?>
                                        </a>
                                    </td>
                                <?php else: ?>
                                    <td><?= seoscope_h($query) ?></td>
                                <?php endif; ?>
                                <td><?= seoscope_h($fmtScore((float) ($r['score'] ?? 0))) ?></td>
                                <td><?= seoscope_h($fmtInt((int) ($r['impressions'] ?? 0))) ?></td>
                                <td>
                                    <?= seoscope_h($fmtCtr((float) ($r['ctr'] ?? 0))) ?>
                                    <?php if (isset($r['ctr_expected'])): ?>
                                        <div class="text-muted small">exp <?= seoscope_h($fmtCtr((float) ($r['ctr_expected'] ?? 0))) ?></div>
                                    <?php endif; ?>
                                </td>
                                <td><?= seoscope_h($fmtPos((float) ($r['position'] ?? 0))) ?></td>
                                <td><?= seoscope_h($fmtInt((int) ($r['clicks'] ?? 0))) ?></td>
                                <td style="white-space: nowrap;">
                                    <?php foreach ($rules as $rule): ?>
                                        <?php
                                            $rule = (string) $rule;
                                            if ($rule === '') continue;
                                            $badge = 'bg-secondary';
                                            $label = $rule;
                                            if ($rule === 'near_top') { $badge = 'bg-info text-dark'; $label = 'near-top'; }
                                            if ($rule === 'ctr_gap') { $badge = 'bg-warning text-dark'; $label = 'ctr-gap'; }
                                            if ($rule === 'low_ctr_page') { $badge = 'bg-warning text-dark'; $label = 'low-ctr'; }
                                            if ($rule === 'topical_gap') { $badge = 'bg-info text-dark'; $label = 'topical-gap'; }
                                        ?>
                                        <span class="badge <?= seoscope_h($badge) ?> me-1"><?= seoscope_h($label) ?></span>
                                    <?php endforeach; ?>
                                </td>
                            </tr>
                            <?php if ($tab === 'iqqi' || $tab === 'ctr_opportunity' || $tab === 'topical_gaps'): ?>
                                <tr class="ss-kw-pages-row">
                                    <td colspan="<?= (int) $colspan ?>" class="p-0" style="border-top:0;">
                                        <div id="<?= seoscope_h($panelId) ?>" class="collapse" data-bs-parent=".crm-table">
                                            <div class="p-3" style="background: rgba(255,255,255,0.55);">
                                                <div class="text-muted small mb-2"><?= seoscope_h(__('keywords.pages_for_query')) ?></div>
                                                <div class="ss-qw-pages" data-loaded="0">
                                                    <div class="text-muted small"><?= seoscope_h(__('keywords.pages_loading')) ?></div>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <?php if ($tab === 'iqqi' || $tab === 'ctr_opportunity' || $tab === 'topical_gaps'): ?>
            <script>
              (function () {
                var baseSiteUrl = <?= json_encode(is_array($activeProp) ? (string) (($activeProp['site_url'] ?? '') ?: '') : '') ?>;
                function esc(s) {
                  return (s || '').replace(/[&<>"']/g, function (c) {
                    return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c] || c);
                  });
                }
                function stripBase(fullUrl) {
                  var u = String(fullUrl || '');
                  if (!u) return '';
                  if (u[0] === '/') return u;
                  try {
                    var parsed = new URL(u);
                    return (parsed.pathname || '/') + (parsed.search || '') + (parsed.hash || '');
                  } catch (e) {}
                  if (baseSiteUrl && u.indexOf(baseSiteUrl) === 0) {
                    var rest = u.slice(baseSiteUrl.length);
                    return rest && rest[0] === '/' ? rest : '/' + rest;
                  }
                  return u;
                }
                function fmtInt(n) {
                  n = Number(n || 0);
                  try { return new Intl.NumberFormat('en-US', { maximumFractionDigits: 0 }).format(n); } catch (e) { return String(n); }
                }
                function fmtCtr(n) {
                  n = Number(n || 0);
                  return (n * 100).toFixed(2) + '%';
                }
                function fmtPos(n) {
                  n = Number(n || 0);
                  return n.toFixed(2);
                }

                var table = document.querySelector('.crm-table');
                if (!table) return;

                table.addEventListener('shown.bs.collapse', function (ev) {
                  var panel = ev.target;
                  var btn = document.querySelector('[data-bs-target="#' + panel.id + '"]');
                  if (!btn) return;
                  var icon = btn.querySelector('i');
                  if (icon) { icon.classList.remove('fa-chevron-right'); icon.classList.add('fa-chevron-down'); }

                  var wrap = panel.querySelector('.ss-qw-pages');
                  if (!wrap || wrap.getAttribute('data-loaded') === '1') return;

                  var kw = btn.getAttribute('data-kw') || '';
                  var url = new URL(<?= json_encode(seoscope_url('/quick-win/pages')) ?>, window.location.origin);
                  url.searchParams.set('query', kw);
                  url.searchParams.set('limit', '10');
                  try {
                    var cur = new URL(window.location.href);
                    ['prop','range','device','country','compare'].forEach(function (k) {
                      if (cur.searchParams.has(k)) url.searchParams.set(k, cur.searchParams.get(k));
                    });
                  } catch (e) {}

                  fetch(url.toString(), { credentials: 'same-origin' })
                    .then(function (r) { return r.json(); })
                    .then(function (data) {
                      wrap.setAttribute('data-loaded', '1');
                      var rows = (data && data.rows) ? data.rows : [];
                      if (!rows.length) {
                        wrap.innerHTML = '<div class="text-muted small">' + esc(<?= json_encode(__('keywords.pages_empty')) ?>) + '</div>';
                        return;
                      }
                      var html = '';
                      html += '<div class="table-responsive">';
                      html += '<table class="crm-table" style="margin:0;">';
                      html += '<thead><tr>';
                      html += '<th>' + esc(<?= json_encode(__('keywords.pages_col_page')) ?>) + '</th>';
                      html += '<th>' + esc(<?= json_encode(__('keywords.col_clicks')) ?>) + '</th>';
                      html += '<th>' + esc(<?= json_encode(__('keywords.col_impressions')) ?>) + '</th>';
                      html += '<th>' + esc(<?= json_encode(__('keywords.col_ctr')) ?>) + '</th>';
                      html += '<th>' + esc(<?= json_encode(__('keywords.col_position')) ?>) + '</th>';
                      html += '</tr></thead><tbody>';
                      rows.forEach(function (r) {
                        var full = (r && r.page) ? String(r.page) : '';
                        var shortPath = stripBase(full);
                        html += '<tr>';
                        html += '<td><a href="' + esc(full) + '" target="_blank" rel="noopener noreferrer"><code>' + esc(shortPath) + '</code></a></td>';
                        html += '<td>' + esc(fmtInt(r.clicks)) + '</td>';
                        html += '<td>' + esc(fmtInt(r.impressions)) + '</td>';
                        html += '<td>' + esc(fmtCtr(r.ctr)) + '</td>';
                        html += '<td>' + esc(fmtPos(r.position)) + '</td>';
                        html += '</tr>';
                      });
                      html += '</tbody></table></div>';
                      wrap.innerHTML = html;
                    })
                    .catch(function () {
                      wrap.setAttribute('data-loaded', '1');
                      wrap.innerHTML = '<div class="text-muted small">' + esc(<?= json_encode(__('keywords.pages_failed')) ?>) + '</div>';
                    });
                });

                table.addEventListener('hidden.bs.collapse', function (ev) {
                  var panel = ev.target;
                  var btn = document.querySelector('[data-bs-target="#' + panel.id + '"]');
                  if (!btn) return;
                  var icon = btn.querySelector('i');
                  if (icon) { icon.classList.remove('fa-chevron-down'); icon.classList.add('fa-chevron-right'); }
                });
              })();
            </script>
        <?php endif; ?>

        <?php if ($pages > 1): ?>
            <div class="mt-3 d-flex align-items-center justify-content-between gap-3 flex-wrap">
                <nav aria-label="Pagination">
                    <ul class="pagination mb-0">
                        <?php
                            $prev = max(1, $page - 1);
                            $next = min($pages, $page + 1);
                        ?>
                        <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                            <a class="page-link" href="<?= seoscope_h($buildUrl(['page' => (string) $prev])) ?>"><?= seoscope_h(__('opportunities.prev')) ?></a>
                        </li>
                        <li class="page-item disabled">
                            <span class="page-link"><?= seoscope_h(__('opportunities.page_x_of_y', ['x' => (string) $page, 'y' => (string) $pages])) ?></span>
                        </li>
                        <li class="page-item <?= $page >= $pages ? 'disabled' : '' ?>">
                            <a class="page-link" href="<?= seoscope_h($buildUrl(['page' => (string) $next])) ?>"><?= seoscope_h(__('opportunities.next')) ?></a>
                        </li>
                    </ul>
                </nav>

                <form method="get" class="m-0 d-flex align-items-center gap-2">
                    <span class="text-muted small"><?= seoscope_h(__('pages.rows_per_page')) ?></span>
                    <select class="form-select form-select-sm" name="per_page" style="width:auto;" onchange="this.form.submit()">
                        <option value="10" <?= $perPage === 10 ? 'selected' : '' ?>>10</option>
                        <option value="25" <?= $perPage === 25 ? 'selected' : '' ?>>25</option>
                        <option value="50" <?= $perPage === 50 ? 'selected' : '' ?>>50</option>
                        <option value="100" <?= $perPage === 100 ? 'selected' : '' ?>>100</option>
                    </select>
                    <?php
                        // Preserve all current filters/threshold overrides/sort but reset page to 1.
                        $keep = $_GET;
                        if (!is_array($keep)) $keep = [];
                        $keep['page'] = '1';
                        unset($keep['per_page']);
                        foreach ($keep as $k => $v) {
                            if (is_array($v)) continue;
                            if ($v === null) continue;
                            $sv = (string) $v;
                            if ($sv === '') continue;
                            echo '<input type="hidden" name="' . seoscope_h((string) $k) . '" value="' . seoscope_h($sv) . '">';
                        }
                    ?>
                </form>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>
<?php
$content = (string) ob_get_clean();
require __DIR__ . '/layout_admin.php';

