<?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 */

$pageTitle = __('long_tail.page_title');
$pageHeading = __('long_tail.heading');
$activeNav = 'long_tail';
$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;
$sort = (string) ($_GET['sort'] ?? 'clicks');
$dir = (string) ($_GET['dir'] ?? 'DESC');
$minTerms = max(1, (int) ($_GET['min_terms'] ?? 4));

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

$buildUrl = static function (array $overrides): string {
    $base = [
        'prop' => (string) ($_GET['prop'] ?? ''),
        'range' => (string) ($_GET['range'] ?? 'last_28_days'),
        'per_page' => (string) ($_GET['per_page'] ?? '10'),
        'sort' => (string) ($_GET['sort'] ?? 'clicks'),
        'dir' => (string) ($_GET['dir'] ?? 'DESC'),
        'min_terms' => (string) ($_GET['min_terms'] ?? '4'),
        'page' => (string) ($_GET['page'] ?? '1'),
    ];
    foreach ($overrides as $k => $v) {
        $base[$k] = (string) $v;
    }
    if (($base['prop'] ?? '') === '') unset($base['prop']);
    return seoscope_url('/long-tail?' . http_build_query($base));
};

ob_start();
?>
<div class="dashboard-card section-card">
    <div class="section-title mb-1"><?= seoscope_h(__('long_tail.title')) ?></div>
    <div class="section-subtitle mb-3">
        <?= seoscope_h(__('long_tail.subtitle', ['start' => $rangeStart, 'end' => $rangeEnd])) ?>
    </div>

    <?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="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) ?>">

            <div class="col-12 col-md-4">
                <label class="form-label small mb-1"><?= seoscope_h(__('long_tail.min_terms')) ?></label>
                <input class="form-control form-control-sm" type="number" name="min_terms" min="2" max="10" value="<?= seoscope_h((string) $minTerms) ?>">
            </div>

            <div class="col-auto">
                <button class="btn btn-sm btn-upgrade" type="submit"><?= seoscope_h(__('common.apply')) ?></button>
            </div>
            <div class="col-auto">
                <a class="btn btn-sm btn-outline-secondary" href="<?= seoscope_h($buildUrl(['min_terms' => '4', 'page' => '1'])) ?>">
                    <?= seoscope_h(__('common.reset')) ?>
                </a>
            </div>
        </form>
    <?php endif; ?>

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

    <?php if (!is_array($activeProp)): ?>
        <div class="text-muted"><?= seoscope_h(__('long_tail.no_property')) ?></div>
    <?php elseif (empty($rows)): ?>
        <div class="text-muted"><?= seoscope_h(__('long_tail.empty')) ?></div>
    <?php else: ?>
        <div class="table-wrap">
            <div class="table-responsive">
                <table class="crm-table">
                    <thead>
                        <tr>
                            <th style="width:44px;"></th>
                            <?php
                                $cols = [
                                    'query' => __('keywords.col_query'),
                                    'terms' => __('long_tail.col_terms'),
                                    '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; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $colspan = 1 + count($cols); ?>
                        <?php foreach ($rows as $idx => $r): ?>
                            <?php if (!is_array($r)) { continue; } ?>
                            <?php
                                $q = (string) ($r['query'] ?? '');
                                $rowId = 'lt-' . (int) $idx;
                                $btnId = $rowId . '-btn';
                                $panelId = $rowId . '-panel';
                            ?>
                            <tr>
                                <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($q) ?>"
                                            <?= $q !== '' ? '' : 'disabled' ?>
                                        >
                                            <i class="fa-solid fa-chevron-right"></i>
                                        </button>
                                    </span>
                                </td>
                                <td><?= seoscope_h($q) ?></td>
                                <td><?= seoscope_h($fmtInt((int) ($r['terms'] ?? 0))) ?></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>
                            </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-lt-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 (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-lt-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'].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">
                <?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 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';

