<?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 string $pagesShow all|tracked */
/** @var list<string> $trackedPagesList */
/** @var list<array{id:int,name:string}> $pagesTrackedCategoriesList */
/** @var array<string, int|null> $trackedPageCategoryMap */
/** @var null|int $pagesTrackCategoryFilter */
/** @var bool $pagesTrackAtLimit */
/** @var int $pagesTrackMax */

if (!isset($pagesShow) || !is_string($pagesShow)) {
    $pagesShow = 'all';
}
if (!isset($trackedPagesList) || !is_array($trackedPagesList)) {
    $trackedPagesList = [];
}
if (!isset($pagesTrackedCategoriesList) || !is_array($pagesTrackedCategoriesList)) {
    $pagesTrackedCategoriesList = [];
}
if (!isset($trackedPageCategoryMap) || !is_array($trackedPageCategoryMap)) {
    $trackedPageCategoryMap = [];
}
if (!isset($pagesTrackCategoryFilter)) {
    $pagesTrackCategoryFilter = null;
}
if (!isset($pagesTrackAtLimit)) {
    $pagesTrackAtLimit = false;
}
if (!isset($pagesTrackMax) || !is_int($pagesTrackMax)) {
    $pagesTrackMax = 500;
}

$csrf = \SeoScope\Auth\AdminCsrf::token();
$trackedLookup = [];
foreach ($trackedPagesList as $tp) {
    if (is_string($tp) && $tp !== '') {
        $trackedLookup[$tp] = true;
    }
}

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

$total = is_array($data) ? (int) ($data['total'] ?? 0) : 0;
$rows = is_array($data) ? ($data['rows'] ?? []) : [];
$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;
$preset = (string) ($_GET['range'] ?? 'last_30_days');
$q = trim((string) ($_GET['q'] ?? ''));
$sort = (string) ($_GET['sort'] ?? 'clicks');
$dir = (string) ($_GET['dir'] ?? 'DESC');
$compare = (string) ($_GET['compare'] ?? '') === '1';
$prevRange = (is_array($data) && isset($data['prev_range']) && is_array($data['prev_range'])) ? $data['prev_range'] : null;

$pgPropId = is_array($activeProp) ? (int) ($activeProp['id'] ?? 0) : 0;
$pgRetFieldsHtml = '';
if ($pgPropId > 0) {
    $retPropVal = (string) (int) ($_GET['prop'] ?? 0);
    if ($retPropVal === '0') {
        $retPropVal = (string) $pgPropId;
    }
    $pairs = [
        'ret_prop' => $retPropVal,
        'ret_range' => $preset,
        'ret_sort' => $sort,
        'ret_dir' => $dir,
        'ret_page' => (string) $page,
        'ret_per_page' => (string) $perPage,
    ];
    if ($pagesShow === 'tracked') {
        $pairs['ret_show'] = 'tracked';
    }
    if ($q !== '') {
        $pairs['ret_q'] = $q;
    }
    foreach ($pairs as $nk => $nv) {
        if ($nv === '') {
            continue;
        }
        $pgRetFieldsHtml .= '<input type="hidden" name="' . seoscope_h($nk) . '" value="' . seoscope_h((string) $nv) . '">';
    }
    if ($compare) {
        $pgRetFieldsHtml .= '<input type="hidden" name="ret_compare" value="1">';
    }
    if ($pagesShow === 'tracked' && $pagesTrackCategoryFilter !== null) {
        $pgRetFieldsHtml .= '<input type="hidden" name="ret_track_cat" value="' . seoscope_h((string) ($pagesTrackCategoryFilter === 0 ? '0' : (string) $pagesTrackCategoryFilter)) . '">';
    }
}

$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);
$fmtDeltaPct = static fn (float $n): string => ($n >= 0 ? '+' : '') . number_format($n * 100, 1) . '%';
$fmtDeltaPos = static fn (float $n): string => ($n >= 0 ? '+' : '') . number_format($n, 2);

$stripBase = static function (string $fullUrl, ?array $activeProp): string {
    $fullUrl = trim($fullUrl);
    if ($fullUrl === '' || !is_array($activeProp)) {
        return $fullUrl;
    }
    $base = (string) ($activeProp['site_url'] ?? '');
    $base = rtrim($base, '/');
    if ($base === '') {
        return $fullUrl;
    }
    if (stripos($fullUrl, $base) === 0) {
        $rest = substr($fullUrl, strlen($base));
        return $rest !== '' ? $rest : '/';
    }
    // Fallback: try parse host match (handles http/https or missing trailing slash).
    $b = parse_url($base);
    $u = parse_url($fullUrl);
    $bHost = is_array($b) ? (string) ($b['host'] ?? '') : '';
    $uHost = is_array($u) ? (string) ($u['host'] ?? '') : '';
    if ($bHost !== '' && $uHost !== '' && strcasecmp($bHost, $uHost) === 0) {
        $path = is_array($u) ? (string) ($u['path'] ?? '') : '';
        $query = is_array($u) ? (string) ($u['query'] ?? '') : '';
        $out = ($path !== '' ? $path : '/');
        if ($query !== '') $out .= '?' . $query;
        return $out;
    }
    return $fullUrl;
};

$exportUrl = static function (): string {
    $base = $_GET;
    if (!is_array($base)) {
        $base = [];
    }
    unset($base['page'], $base['per_page']);
    return seoscope_url('/export/pages.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'),
        'q' => (string) ($_GET['q'] ?? ''),
        'compare' => (string) ($_GET['compare'] ?? ''),
        'sort' => (string) ($_GET['sort'] ?? 'clicks'),
        'dir' => (string) ($_GET['dir'] ?? 'DESC'),
        'page' => (string) ($_GET['page'] ?? '1'),
    ];
    $tcGet = trim((string) ($_GET['track_cat'] ?? ''));
    if ($tcGet !== '') {
        $base['track_cat'] = $tcGet;
    }
    $showCur = strtolower((string) ($_GET['show'] ?? 'all'));
    if ($showCur === 'tracked') {
        $base['show'] = 'tracked';
    }
    foreach ($overrides as $k => $v) {
        if ($k === 'track_cat' && (string) $v === '') {
            unset($base['track_cat']);
            continue;
        }
        $base[$k] = (string) $v;
    }
    foreach (['prop', 'compare', 'show', 'track_cat'] as $k) {
        if (($base[$k] ?? '') === '') {
            unset($base[$k]);
        }
    }
    if (($base['q'] ?? '') === '') {
        unset($base['q']);
    }
    return seoscope_url('/pages?' . http_build_query($base));
};

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(__('pages.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(__('pages.subtitle', ['start' => $rangeStart, 'end' => $rangeEnd])) ?>
    </div>

    <?php if (is_array($activeProp)): ?>
        <div class="d-flex align-items-center gap-2 flex-wrap mb-2 small">
            <span class="text-muted"><?= seoscope_h(__('pages.show_label')) ?></span>
            <a class="<?= $pagesShow !== 'tracked' ? 'fw-semibold text-decoration-none' : 'text-decoration-none' ?>" href="<?= seoscope_h($buildUrl(['show' => '', 'page' => '1'])) ?>">
                <?= seoscope_h(__('pages.show_all')) ?>
            </a>
            <span class="text-muted" aria-hidden="true">|</span>
            <a class="<?= $pagesShow === 'tracked' ? 'fw-semibold text-decoration-none' : 'text-decoration-none' ?>" href="<?= seoscope_h($buildUrl(['show' => 'tracked', 'page' => '1'])) ?>">
                <?= seoscope_h(__('pages.show_tracked')) ?>
            </a>
        </div>
        <?php if ($pagesShow === 'tracked' && $pgPropId > 0): ?>
            <?php
                $pgCurCatParam = trim((string) ($_GET['track_cat'] ?? ''));
                $pgCatIsAll = $pgCurCatParam === '';
                $pgCatIsNone = $pgCurCatParam === '0';
                $pgStCatQs = ['tab' => 'categories', 'prop' => (string) $pgPropId];
            ?>
            <div class="mb-3 small">
                <div class="d-flex flex-wrap align-items-center gap-2 mb-2">
                    <span class="text-muted"><?= seoscope_h(__('tracked_cat.filter_label')) ?>:</span>
                    <a class="<?= $pgCatIsAll ? 'fw-semibold text-decoration-none' : 'text-decoration-none' ?>" href="<?= seoscope_h($buildUrl(['track_cat' => '', 'page' => '1'])) ?>"><?= seoscope_h(__('tracked_cat.filter_all')) ?></a>
                    <span class="text-muted" aria-hidden="true">|</span>
                    <a class="<?= $pgCatIsNone ? 'fw-semibold text-decoration-none' : 'text-decoration-none' ?>" href="<?= seoscope_h($buildUrl(['track_cat' => '0', 'page' => '1'])) ?>"><?= seoscope_h(__('tracked_cat.filter_none')) ?></a>
                    <?php foreach ($pagesTrackedCategoriesList as $tcat): ?>
                        <?php if (!is_array($tcat)) {
                            continue;
                        } ?>
                        <?php
                            $tcatId = (int) ($tcat['id'] ?? 0);
                            $tcatName = (string) ($tcat['name'] ?? '');
                        ?>
                        <?php if ($tcatId > 0 && $tcatName !== ''): ?>
                            <span class="text-muted" aria-hidden="true">|</span>
                            <a class="<?= (!$pgCatIsAll && !$pgCatIsNone && $pgCurCatParam === (string) $tcatId) ? 'fw-semibold text-decoration-none' : 'text-decoration-none' ?>" href="<?= seoscope_h($buildUrl(['track_cat' => (string) $tcatId, 'page' => '1'])) ?>"><?= seoscope_h($tcatName) ?></a>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
                <p class="text-muted small mb-2"><?= seoscope_h(__('tracked_cat.filter_hint_reports')) ?></p>
                <a class="small" href="<?= seoscope_h(seoscope_url('/settings?' . http_build_query($pgStCatQs))) ?>"><?= seoscope_h(__('tracked_cat.manage_link_settings')) ?></a>
            </div>
        <?php endif; ?>
        <?php if ($pagesTrackAtLimit && $pagesShow !== 'tracked' && is_array($activeProp)): ?>
            <div class="alert alert-secondary small py-2 mb-2 mb-md-3">
                <?= seoscope_h(__('pages.track_limit_banner', ['max' => (string) $pagesTrackMax])) ?>
            </div>
        <?php endif; ?>
        <div class="mb-3">
            <input
                type="search"
                class="form-control topbar-select"
                id="ss-pages-search"
                placeholder="<?= seoscope_h(__('pages.filter_search_ph')) ?>"
                value="<?= seoscope_h($q) ?>"
                autocomplete="off"
                spellcheck="false"
            >
        </div>
        <script>
          (function () {
            var el = document.getElementById('ss-pages-search');
            if (!el) return;
            var t = null;
            var lastSent = null;
            el.addEventListener('input', function () {
              if (t) window.clearTimeout(t);
              t = window.setTimeout(function () {
                var url = new URL(window.location.href);
                var v = (el.value || '').trim();
                if (v !== '' && v.length < 2) return;
                if (lastSent === v) return;
                lastSent = v;
                if (v) url.searchParams.set('q', v);
                else url.searchParams.delete('q');
                url.searchParams.set('page', '1');
                window.location.href = url.toString();
              }, 650);
            });
          })();
        </script>
    <?php endif; ?>
    <?php if ($compare && is_array($prevRange)): ?>
        <div class="text-muted small mb-3">
            <?= seoscope_h(__('pages.prev_range', ['start' => (string) ($prevRange['start'] ?? ''), 'end' => (string) ($prevRange['end'] ?? '')])) ?>
        </div>
    <?php endif; ?>

    <?php
    if (!isset($seoAiPgCard)) {
        $seoAiPgCard = null;
    }
    if (!isset($seoAiInsightsEnabled)) {
        $seoAiInsightsEnabled = false;
    }
    if (is_array($seoAiPgCard) && !empty($seoAiInsightsEnabled)):
        $ssAiQw = $seoAiPgCard;
        require __DIR__ . '/partials/seo_ai_quickwin_card.php';
    endif;
    ?>

    <?php if (!is_array($activeProp)): ?>
        <div class="text-muted"><?= seoscope_h(__('pages.no_property')) ?></div>
    <?php elseif (empty($rows)): ?>
        <div class="text-muted">
            <?php if ($pagesShow === 'tracked' && $trackedPagesList === []): ?>
                <?= seoscope_h(__('pages.tracked_empty_none')) ?>
            <?php elseif ($pagesShow === 'tracked'): ?>
                <?= seoscope_h(__('pages.tracked_empty_range')) ?>
            <?php else: ?>
                <?= seoscope_h(__('pages.empty')) ?>
            <?php endif; ?>
        </div>
    <?php else: ?>
        <div class="table-wrap">
            <div class="table-responsive">
                <table class="crm-table">
                    <thead>
                        <tr>
                            <th style="width:44px;"></th>
                            <th class="text-center align-middle" style="min-width: 11rem;">
                                <span class="visually-hidden"><?= seoscope_h(__('pages.col_track_actions')) ?></span>
                            </th>
                            <?php
                                $cols = [
                                    'page' => __('pages.col_page'),
                                    'clicks' => __('pages.col_clicks'),
                                    'impressions' => __('pages.col_impressions'),
                                    'ctr' => __('pages.col_ctr'),
                                    'position' => __('pages.col_position'),
                                ];
                                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; ?>
                            <?php if ($pagesShow === 'tracked'): ?>
                                <th><?= seoscope_h(__('tracked_cat.col_category')) ?></th>
                            <?php endif; ?>
                            <?php if ($compare): ?>
                                <th><?= seoscope_h(__('pages.col_delta_clicks')) ?></th>
                                <th><?= seoscope_h(__('pages.col_delta_impr')) ?></th>
                                <th><?= seoscope_h(__('pages.col_delta_ctr')) ?></th>
                                <th><?= seoscope_h(__('pages.col_delta_pos')) ?></th>
                            <?php endif; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $pgExtraCols = $pagesShow === 'tracked' ? 1 : 0; ?>
                        <?php $colspan = 2 + 5 + ($compare ? 4 : 0) + $pgExtraCols; ?>
                        <?php foreach ($rows as $idx => $r): ?>
                            <?php if (!is_array($r)) { continue; } ?>
                            <?php
                                $prev = (is_array($r['prev'] ?? null)) ? $r['prev'] : ['clicks'=>0,'impressions'=>0,'ctr'=>0.0,'position'=>0.0];
                                $dc = 0.0; $di = 0.0; $dctr = 0.0; $dpos = 0.0;
                                if ($compare) {
                                    $pc = (float) ($prev['clicks'] ?? 0);
                                    $pi = (float) ($prev['impressions'] ?? 0);
                                    $pctr = (float) ($prev['ctr'] ?? 0);
                                    $ppos = (float) ($prev['position'] ?? 0);
                                    $cc = (float) ($r['clicks'] ?? 0);
                                    $ci = (float) ($r['impressions'] ?? 0);
                                    $cctr = (float) ($r['ctr'] ?? 0);
                                    $cpos = (float) ($r['position'] ?? 0);
                                    $dc = $pc > 0 ? (($cc - $pc) / $pc) : ($cc > 0 ? 1.0 : 0.0);
                                    $di = $pi > 0 ? (($ci - $pi) / $pi) : ($ci > 0 ? 1.0 : 0.0);
                                    $dctr = $pctr > 0 ? (($cctr - $pctr) / $pctr) : ($cctr > 0 ? 1.0 : 0.0);
                                    $dpos = $cpos - $ppos;
                                }
                            ?>
                            <?php
                                $pageUrl = (string) ($r['page'] ?? '');
                                $pageLabel = $stripBase($pageUrl, $activeProp);
                                $rowId = 'pg-' . (int) $idx;
                                $btnId = $rowId . '-btn';
                                $panelId = $rowId . '-panel';
                            ?>
                            <tr id="<?= seoscope_h('ss-pg-row-' . (int) $idx) ?>">
                                <td style="white-space:nowrap;">
                                    <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-page="<?= seoscope_h($pageUrl) ?>"
                                    >
                                        <i class="fa-solid fa-chevron-right"></i>
                                    </button>
                                </td>
                                <td class="text-center align-middle">
                                    <?php if ($pagesShow === 'tracked'): ?>
                                        <form method="post" action="<?= seoscope_h(seoscope_url('/pages/untrack')) ?>" class="d-inline ss-track-async-form" data-ss-action="untrack">
                                            <input type="hidden" name="_csrf" value="<?= seoscope_h($csrf) ?>">
                                            <input type="hidden" name="property_id" value="<?= (int) $pgPropId ?>">
                                            <input type="hidden" name="page_url" value="<?= seoscope_h($pageUrl) ?>">
                                            <?= $pgRetFieldsHtml ?>
                                            <button
                                                type="submit"
                                                class="btn btn-sm btn-link text-danger p-0"
                                                title="<?= seoscope_h(__('pages.untrack_aria_remove')) ?>"
                                                aria-label="<?= seoscope_h(__('pages.untrack_aria_remove')) ?>"
                                            >
                                                <i class="fa-solid fa-trash-can" aria-hidden="true"></i>
                                            </button>
                                        </form>
                                    <?php elseif ($pagesTrackAtLimit && !isset($trackedLookup[$pageUrl])): ?>
                                        <span
                                            class="text-muted"
                                            title="<?= seoscope_h(__('pages.track_limit_hint', ['max' => (string) $pagesTrackMax])) ?>"
                                            aria-label="<?= seoscope_h(__('pages.track_limit_hint', ['max' => (string) $pagesTrackMax])) ?>"
                                        >
                                            <i class="fa-regular fa-star" aria-hidden="true"></i>
                                        </span>
                                    <?php elseif (!isset($trackedLookup[$pageUrl])): ?>
                                        <form method="post" action="<?= seoscope_h(seoscope_url('/pages/track')) ?>" class="d-inline-flex flex-wrap align-items-center gap-1 justify-content-center mb-0 ss-track-async-form" data-ss-action="track">
                                            <input type="hidden" name="_csrf" value="<?= seoscope_h($csrf) ?>">
                                            <input type="hidden" name="property_id" value="<?= (int) $pgPropId ?>">
                                            <input type="hidden" name="page_url" value="<?= seoscope_h($pageUrl) ?>">
                                            <?= $pgRetFieldsHtml ?>
                                            <?php if ($pagesShow !== 'tracked' && $pagesTrackedCategoriesList !== []): ?>
                                                <select name="track_category_id" class="form-select form-select-sm py-0" style="width: auto; min-width: 6.5rem; max-width: 10rem;" title="<?= seoscope_h(__('pages.track_category_aria')) ?>" aria-label="<?= seoscope_h(__('pages.track_category_aria')) ?>">
                                                    <option value="0" selected><?= seoscope_h(__('tracked_cat.uncategorized')) ?></option>
                                                    <?php foreach ($pagesTrackedCategoriesList as $tco): ?>
                                                        <?php if (!is_array($tco)) {
                                                            continue;
                                                        } ?>
                                                        <?php $tcid = (int) ($tco['id'] ?? 0); ?>
                                                        <?php if ($tcid > 0): ?>
                                                            <option value="<?= $tcid ?>"><?= seoscope_h((string) ($tco['name'] ?? '')) ?></option>
                                                        <?php endif; ?>
                                                    <?php endforeach; ?>
                                                </select>
                                            <?php endif; ?>
                                            <button
                                                type="submit"
                                                class="btn btn-sm btn-link text-secondary p-0"
                                                title="<?= seoscope_h(__('pages.track_aria_add')) ?>"
                                                aria-label="<?= seoscope_h(__('pages.track_aria_add')) ?>"
                                            >
                                                <i class="fa-regular fa-star" aria-hidden="true"></i>
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <span
                                            class="text-warning"
                                            title="<?= seoscope_h(__('pages.track_aria_tracked')) ?>"
                                            aria-label="<?= seoscope_h(__('pages.track_aria_tracked')) ?>"
                                        >
                                            <i class="fa-solid fa-star" aria-hidden="true"></i>
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td><a href="<?= seoscope_h($pageUrl) ?>" target="_blank" rel="noopener noreferrer"><?= seoscope_h($pageLabel) ?></a></td>
                                <td><?= seoscope_h($fmtInt((int) ($r['clicks'] ?? 0))) ?></td>
                                <td><?= seoscope_h($fmtInt((int) ($r['impressions'] ?? 0))) ?></td>
                                <td><?= seoscope_h($fmtCtr((float) ($r['ctr'] ?? 0))) ?></td>
                                <td><?= seoscope_h($fmtPos((float) ($r['position'] ?? 0))) ?></td>
                                <?php if ($pagesShow === 'tracked'): ?>
                                    <?php
                                        $pgCatId = array_key_exists($pageUrl, $trackedPageCategoryMap) ? $trackedPageCategoryMap[$pageUrl] : null;
                                    ?>
                                    <td class="small">
                                        <form method="post" action="<?= seoscope_h(seoscope_url('/pages/category/assign')) ?>" class="d-inline-block ss-track-async-form" data-ss-action="assign">
                                            <input type="hidden" name="_csrf" value="<?= seoscope_h($csrf) ?>">
                                            <input type="hidden" name="property_id" value="<?= (int) $pgPropId ?>">
                                            <input type="hidden" name="page_url" value="<?= seoscope_h($pageUrl) ?>">
                                            <?= $pgRetFieldsHtml ?>
                                            <select name="category_id" class="form-select form-select-sm ss-track-category-select" style="min-width:10rem; max-width:14rem;" title="<?= seoscope_h(__('tracked_cat.assign_placeholder')) ?>" aria-label="<?= seoscope_h(__('tracked_cat.assign_placeholder')) ?>">
                                                <option value="0" <?= $pgCatId === null ? 'selected' : '' ?>><?= seoscope_h(__('tracked_cat.uncategorized')) ?></option>
                                                <?php foreach ($pagesTrackedCategoriesList as $tco): ?>
                                                    <?php if (!is_array($tco)) {
                                                        continue;
                                                    } ?>
                                                    <?php $poid = (int) ($tco['id'] ?? 0); ?>
                                                    <?php if ($poid > 0): ?>
                                                        <option value="<?= $poid ?>" <?= ($pgCatId !== null && $poid === (int) $pgCatId) ? 'selected' : '' ?>><?= seoscope_h((string) ($tco['name'] ?? '')) ?></option>
                                                    <?php endif; ?>
                                                <?php endforeach; ?>
                                            </select>
                                        </form>
                                    </td>
                                <?php endif; ?>
                                <?php if ($compare): ?>
                                    <td class="<?= $dc >= 0 ? 'text-success' : 'text-danger' ?>"><?= seoscope_h($fmtDeltaPct($dc)) ?></td>
                                    <td class="<?= $di >= 0 ? 'text-success' : 'text-danger' ?>"><?= seoscope_h($fmtDeltaPct($di)) ?></td>
                                    <td class="<?= $dctr >= 0 ? 'text-success' : 'text-danger' ?>"><?= seoscope_h($fmtDeltaPct($dctr)) ?></td>
                                    <td class="<?= $dpos <= 0 ? 'text-success' : 'text-danger' ?>"><?= seoscope_h($fmtDeltaPos($dpos)) ?></td>
                                <?php endif; ?>
                            </tr>
                            <tr class="ss-page-kws-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="d-flex align-items-center justify-content-between gap-3 mb-2">
                                                <div class="text-muted small"><?= seoscope_h(__('pages.keywords_for_page')) ?></div>
                                                <div class="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 ss-page-kws-limit" style="width:auto;">
                                                        <option value="10" selected>10</option>
                                                        <option value="25">25</option>
                                                        <option value="50">50</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="ss-page-kws">
                                                <div class="text-muted small"><?= seoscope_h(__('pages.keywords_loading')) ?></div>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <script>
          (function () {
            function esc(s) {
              return (s || '').replace(/[&<>"']/g, function (c) {
                return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c] || c);
              });
            }
            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;

            function loadKeywords(panel, pageUrl, limit) {
              var wrap = panel.querySelector('.ss-page-kws');
              if (!wrap) return;
              wrap.innerHTML = '<div class="text-muted small">' + esc(<?= json_encode(__('pages.keywords_loading')) ?>) + '</div>';

              var url = new URL(<?= json_encode(seoscope_url('/pages/keywords')) ?>, window.location.origin);
              url.searchParams.set('page', pageUrl);
              url.searchParams.set('limit', String(limit || 25));
              try {
                var cur = new URL(window.location.href);
                ['prop','range','device','country','compare','show'].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) {
                  var rows = (data && data.rows) ? data.rows : [];
                  if (!rows.length) {
                    wrap.innerHTML = '<div class="text-muted small">' + esc(<?= json_encode(__('pages.keywords_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(__('pages.keywords_col_query')) ?>) + '</th>';
                  html += '<th>' + esc(<?= json_encode(__('pages.col_clicks')) ?>) + '</th>';
                  html += '<th>' + esc(<?= json_encode(__('pages.col_impressions')) ?>) + '</th>';
                  html += '<th>' + esc(<?= json_encode(__('pages.col_ctr')) ?>) + '</th>';
                  html += '<th>' + esc(<?= json_encode(__('pages.col_position')) ?>) + '</th>';
                  html += '</tr></thead><tbody>';
                  rows.forEach(function (r) {
                    html += '<tr>';
                    html += '<td>' + esc(r.query || '') + '</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.innerHTML = '<div class="text-muted small">' + esc(<?= json_encode(__('pages.keywords_failed')) ?>) + '</div>';
                });
            }

            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'); }

              if (panel.getAttribute('data-loaded') === '1') return;
              panel.setAttribute('data-loaded', '1');
              var pageUrl = btn.getAttribute('data-page') || '';
              var sel = panel.querySelector('.ss-page-kws-limit');
              var limit = sel ? Number(sel.value || 25) : 25;
              loadKeywords(panel, pageUrl, limit);
            });

            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'); }
            });

            table.addEventListener('change', function (ev) {
              var target = ev.target;
              if (!target || !target.classList || !target.classList.contains('ss-page-kws-limit')) return;
              var panel = target.closest('.collapse');
              if (!panel) return;
              var btn = document.querySelector('[data-bs-target="#' + panel.id + '"]');
              if (!btn) return;
              var pageUrl = btn.getAttribute('data-page') || '';
              loadKeywords(panel, pageUrl, Number(target.value || 25));
            });
          })();
        </script>

        <?php if ($pages > 1): ?>
            <div class="mt-3 d-flex align-items-center justify-content-between gap-3 flex-wrap">
                <?php
                    $prev = max(1, $page - 1);
                    $next = min($pages, $page + 1);
                ?>
                <nav aria-label="Pagination">
                    <ul class="pagination mb-0">
                        <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                            <a class="page-link" href="<?= seoscope_h($buildUrl(['page' => (string) $prev])) ?>">
                                <?= seoscope_h(__('pages.prev')) ?>
                            </a>
                        </li>
                        <li class="page-item disabled">
                            <span class="page-link"><?= seoscope_h(__('pages.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(__('pages.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/sort/search 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>
<script>
window.seoscopeTrackConfig = <?= json_encode([
    'entity' => 'page',
    'show' => $pagesShow,
    'labels' => ['tracked' => (string) __('pages.track_aria_tracked')],
    'networkError' => (string) __('common.async_request_failed'),
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) ?>;
</script>
<?php
$content = (string) ob_get_clean();
require __DIR__ . '/layout_admin.php';

