<?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 $keywordsShow all|tracked */
/** @var list<string> $trackedQueriesList */
/** @var list<array{id:int,name:string}> $trackedCategoriesList */
/** @var array<string, int|null> $trackedQueryCategoryMap */
/** @var null|int $keywordsTrackCategoryFilter null = all tracked; 0 = uncategorized; >0 = category id */
/** @var bool $keywordsTrackAtLimit */
/** @var int $keywordsTrackMax */

if (!isset($keywordsShow) || !is_string($keywordsShow)) {
    $keywordsShow = 'all';
}
if (!isset($trackedQueriesList) || !is_array($trackedQueriesList)) {
    $trackedQueriesList = [];
}
if (!isset($trackedCategoriesList) || !is_array($trackedCategoriesList)) {
    $trackedCategoriesList = [];
}
if (!isset($trackedQueryCategoryMap) || !is_array($trackedQueryCategoryMap)) {
    $trackedQueryCategoryMap = [];
}
if (!isset($keywordsTrackCategoryFilter)) {
    $keywordsTrackCategoryFilter = null;
}
if (!isset($keywordsTrackAtLimit)) {
    $keywordsTrackAtLimit = false;
}
if (!isset($keywordsTrackMax) || !is_int($keywordsTrackMax)) {
    $keywordsTrackMax = 500;
}

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

$pageTitle = __('keywords.page_title');
$pageHeading = __('keywords.heading');
$activeNav = 'keywords';
$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;

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

$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);

$exportUrl = static function (): string {
    $base = $_GET;
    if (!is_array($base)) {
        $base = [];
    }
    unset($base['page'], $base['per_page']);
    return seoscope_url('/export/keywords.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'] ?? '25'),
        '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('/keywords?' . 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(__('keywords.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(__('keywords.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(__('keywords.show_label')) ?></span>
            <a class="<?= $keywordsShow !== 'tracked' ? 'fw-semibold text-decoration-none' : 'text-decoration-none' ?>" href="<?= seoscope_h($buildUrl(['show' => '', 'page' => '1'])) ?>">
                <?= seoscope_h(__('keywords.show_all')) ?>
            </a>
            <span class="text-muted" aria-hidden="true">|</span>
            <a class="<?= $keywordsShow === 'tracked' ? 'fw-semibold text-decoration-none' : 'text-decoration-none' ?>" href="<?= seoscope_h($buildUrl(['show' => 'tracked', 'page' => '1'])) ?>">
                <?= seoscope_h(__('keywords.show_tracked')) ?>
            </a>
        </div>
        <?php if ($keywordsShow === 'tracked' && $kwPropId > 0): ?>
            <?php
                $kwCurCatParam = trim((string) ($_GET['track_cat'] ?? ''));
                $kwCatIsAll = $kwCurCatParam === '';
                $kwCatIsNone = $kwCurCatParam === '0';
                $kwStCatQs = ['tab' => 'categories', 'prop' => (string) $kwPropId];
            ?>
            <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="<?= $kwCatIsAll ? '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="<?= $kwCatIsNone ? '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 ($trackedCategoriesList 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="<?= (!$kwCatIsAll && !$kwCatIsNone && $kwCurCatParam === (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($kwStCatQs))) ?>"><?= seoscope_h(__('tracked_cat.manage_link_settings')) ?></a>
            </div>
        <?php endif; ?>
        <?php if ($keywordsTrackAtLimit && $keywordsShow !== 'tracked' && is_array($activeProp)): ?>
            <div class="alert alert-secondary small py-2 mb-2 mb-md-3">
                <?= seoscope_h(__('keywords.track_limit_banner', ['max' => (string) $keywordsTrackMax])) ?>
            </div>
        <?php endif; ?>
        <div class="mb-3">
            <input
                type="search"
                class="form-control topbar-select"
                id="ss-kw-search"
                placeholder="<?= seoscope_h(__('keywords.filter_search_ph')) ?>"
                value="<?= seoscope_h($q) ?>"
                autocomplete="off"
                spellcheck="false"
            >
        </div>
        <script>
          (function () {
            var el = document.getElementById('ss-kw-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();
                // Avoid hammering the server on short inputs; allow clearing immediately.
                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(__('keywords.prev_range', ['start' => (string) ($prevRange['start'] ?? ''), 'end' => (string) ($prevRange['end'] ?? '')])) ?>
        </div>
    <?php endif; ?>

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

    <?php if (!is_array($activeProp)): ?>
        <div class="text-muted"><?= seoscope_h(__('keywords.no_property')) ?></div>
    <?php elseif (empty($rows)): ?>
        <div class="text-muted">
            <?php if ($keywordsShow === 'tracked' && $trackedQueriesList === []): ?>
                <?= seoscope_h(__('keywords.tracked_empty_none')) ?>
            <?php elseif ($keywordsShow === 'tracked'): ?>
                <?= seoscope_h(__('keywords.tracked_empty_range')) ?>
            <?php else: ?>
                <?= seoscope_h(__('keywords.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(__('keywords.col_track_actions')) ?></span>
                            </th>
                            <?php
                                $cols = [
                                    'query' => __('keywords.col_query'),
                                    'clicks' => __('keywords.col_clicks'),
                                    'impressions' => __('keywords.col_impressions'),
                                    'ctr' => __('keywords.col_ctr'),
                                    'position' => __('keywords.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 ($keywordsShow === 'tracked'): ?>
                                <th><?= seoscope_h(__('tracked_cat.col_category')) ?></th>
                            <?php endif; ?>
                            <?php if ($compare): ?>
                                <th><?= seoscope_h(__('keywords.col_delta_clicks')) ?></th>
                                <th><?= seoscope_h(__('keywords.col_delta_impr')) ?></th>
                                <th><?= seoscope_h(__('keywords.col_delta_ctr')) ?></th>
                                <th><?= seoscope_h(__('keywords.col_delta_pos')) ?></th>
                            <?php endif; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $kwExtraCols = $keywordsShow === 'tracked' ? 1 : 0; ?>
                        <?php $colspan = 2 + 5 + ($compare ? 4 : 0) + $kwExtraCols; ?>
                        <?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
                                $kw = (string) ($r['query'] ?? '');
                                $rowId = 'kw-' . (int) $idx;
                                $btnId = $rowId . '-btn';
                                $panelId = $rowId . '-panel';
                            ?>
                            <tr id="<?= seoscope_h('ss-kw-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-kw="<?= seoscope_h($kw) ?>"
                                    >
                                        <i class="fa-solid fa-chevron-right"></i>
                                    </button>
                                </td>
                                <td class="text-center align-middle">
                                    <?php if ($keywordsShow === 'tracked'): ?>
                                        <form method="post" action="<?= seoscope_h(seoscope_url('/keywords/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) $kwPropId ?>">
                                            <input type="hidden" name="query" value="<?= seoscope_h($kw) ?>">
                                            <?= $kwRetFieldsHtml ?>
                                            <button
                                                type="submit"
                                                class="btn btn-sm btn-link text-danger p-0"
                                                title="<?= seoscope_h(__('keywords.untrack_aria_remove')) ?>"
                                                aria-label="<?= seoscope_h(__('keywords.untrack_aria_remove')) ?>"
                                            >
                                                <i class="fa-solid fa-trash-can" aria-hidden="true"></i>
                                            </button>
                                        </form>
                                    <?php elseif ($keywordsTrackAtLimit && !isset($trackedLookup[$kw])): ?>
                                        <span
                                            class="text-muted"
                                            title="<?= seoscope_h(__('keywords.track_limit_hint', ['max' => (string) $keywordsTrackMax])) ?>"
                                            aria-label="<?= seoscope_h(__('keywords.track_limit_hint', ['max' => (string) $keywordsTrackMax])) ?>"
                                        >
                                            <i class="fa-regular fa-star" aria-hidden="true"></i>
                                        </span>
                                    <?php elseif (!isset($trackedLookup[$kw])): ?>
                                        <form method="post" action="<?= seoscope_h(seoscope_url('/keywords/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) $kwPropId ?>">
                                            <input type="hidden" name="query" value="<?= seoscope_h($kw) ?>">
                                            <?= $kwRetFieldsHtml ?>
                                            <?php if ($keywordsShow !== 'tracked' && $trackedCategoriesList !== []): ?>
                                                <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(__('keywords.track_category_aria')) ?>" aria-label="<?= seoscope_h(__('keywords.track_category_aria')) ?>">
                                                    <option value="0" selected><?= seoscope_h(__('tracked_cat.uncategorized')) ?></option>
                                                    <?php foreach ($trackedCategoriesList 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(__('keywords.track_aria_add')) ?>"
                                                aria-label="<?= seoscope_h(__('keywords.track_aria_add')) ?>"
                                            >
                                                <i class="fa-regular fa-star" aria-hidden="true"></i>
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <span
                                            class="text-warning"
                                            title="<?= seoscope_h(__('keywords.track_aria_tracked')) ?>"
                                            aria-label="<?= seoscope_h(__('keywords.track_aria_tracked')) ?>"
                                        >
                                            <i class="fa-solid fa-star" aria-hidden="true"></i>
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td><?= seoscope_h((string) ($r['query'] ?? '')) ?></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 ($keywordsShow === 'tracked'): ?>
                                    <?php
                                        $kwCatId = array_key_exists($kw, $trackedQueryCategoryMap) ? $trackedQueryCategoryMap[$kw] : null;
                                    ?>
                                    <td class="small">
                                        <form method="post" action="<?= seoscope_h(seoscope_url('/keywords/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) $kwPropId ?>">
                                            <input type="hidden" name="query" value="<?= seoscope_h($kw) ?>">
                                            <?= $kwRetFieldsHtml ?>
                                            <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" <?= $kwCatId === null ? 'selected' : '' ?>><?= seoscope_h(__('tracked_cat.uncategorized')) ?></option>
                                                <?php foreach ($trackedCategoriesList as $tco): ?>
                                                    <?php if (!is_array($tco)) {
                                                        continue;
                                                    } ?>
                                                    <?php $oid = (int) ($tco['id'] ?? 0); ?>
                                                    <?php if ($oid > 0): ?>
                                                        <option value="<?= $oid ?>" <?= ($kwCatId !== null && $oid === (int) $kwCatId) ? '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-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-kw-pages" data-loaded="0">
                                                <div class="text-muted small"><?= seoscope_h(__('keywords.pages_loading')) ?></div>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <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 it's already a path, keep it.
              if (u[0] === '/') return u;
              try {
                var parsed = new URL(u);
                return (parsed.pathname || '/') + (parsed.search || '') + (parsed.hash || '');
              } catch (e) {}
              // Fallback: try to remove base site url prefix
              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-kw-pages');
              if (!wrap || wrap.getAttribute('data-loaded') === '1') return;

              var kw = btn.getAttribute('data-kw') || '';
              var url = new URL(<?= json_encode(seoscope_url('/keywords/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','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) {
                  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 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(__('keywords.prev')) ?></a>
                        </li>
                        <li class="page-item disabled">
                            <span class="page-link"><?= seoscope_h(__('keywords.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(__('keywords.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
                        $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' => 'keyword',
    'show' => $keywordsShow,
    'labels' => ['tracked' => (string) __('keywords.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';

