<?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 array{min_impressions:int,clicks_drop_pct:float,impr_drop_pct:float,position_worsen:float} $cfg */

$pageTitle = __('decay.page_title');
$pageHeading = __('decay.heading');
$activeNav = 'decay';
$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'] ?? 'd_clicks');
$dir = (string) ($_GET['dir'] ?? 'ASC');
$prevRange = (is_array($data) && isset($data['prev_range']) && is_array($data['prev_range'])) ? $data['prev_range'] : null;

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

$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'),
        'sort' => (string) ($_GET['sort'] ?? 'd_clicks'),
        'dir' => (string) ($_GET['dir'] ?? 'ASC'),
        'min_impressions' => (string) ($_GET['min_impressions'] ?? ''),
        'clicks_drop_pct' => (string) ($_GET['clicks_drop_pct'] ?? ''),
        'impr_drop_pct' => (string) ($_GET['impr_drop_pct'] ?? ''),
        'position_worsen' => (string) ($_GET['position_worsen'] ?? ''),
        'page' => (string) ($_GET['page'] ?? '1'),
    ];
    foreach ($overrides as $k => $v) {
        $base[$k] = (string) $v;
    }
    if (($base['prop'] ?? '') === '') unset($base['prop']);
    foreach (['min_impressions','clicks_drop_pct','impr_drop_pct','position_worsen'] as $k) {
        if (($base[$k] ?? '') === '') unset($base[$k]);
    }
    return seoscope_url('/decay?' . http_build_query($base));
};

ob_start();
?>
<div class="dashboard-card section-card">
    <div class="section-title mb-1"><?= seoscope_h(__('decay.title')) ?></div>
    <div class="section-subtitle mb-3">
        <?= seoscope_h(__('decay.subtitle', ['start' => $rangeStart, 'end' => $rangeEnd])) ?>
        <?php if ($prevRange): ?>
            <span class="ms-2 text-muted small"><?= seoscope_h(__('decay.prev_range', ['start' => (string) ($prevRange['start'] ?? ''), 'end' => (string) ($prevRange['end'] ?? '')])) ?></span>
        <?php endif; ?>
    </div>

    <?php if (is_array($activeProp)): ?>
        <?php
            $minImpr = (int) ($cfg['min_impressions'] ?? 500);
            $clicksDropPct = (int) round(((float) ($cfg['clicks_drop_pct'] ?? 0.2)) * 100);
            $imprDropPct = (int) round(((float) ($cfg['impr_drop_pct'] ?? 0.2)) * 100);
            $posWorsen = (float) ($cfg['position_worsen'] ?? 1.0);
        ?>
        <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-lg-3">
                <label class="form-label small mb-1"><?= seoscope_h(__('settings.decay.min_impressions')) ?></label>
                <input class="form-control form-control-sm" type="number" name="min_impressions" min="0" step="1" value="<?= seoscope_h((string) $minImpr) ?>">
            </div>
            <div class="col-12 col-lg-3">
                <label class="form-label small mb-1"><?= seoscope_h(__('settings.decay.clicks_drop_pct')) ?></label>
                <input class="form-control form-control-sm" type="number" name="clicks_drop_pct" min="0" max="100" step="1" value="<?= seoscope_h((string) $clicksDropPct) ?>">
            </div>
            <div class="col-12 col-lg-3">
                <label class="form-label small mb-1"><?= seoscope_h(__('settings.decay.impr_drop_pct')) ?></label>
                <input class="form-control form-control-sm" type="number" name="impr_drop_pct" min="0" max="100" step="1" value="<?= seoscope_h((string) $imprDropPct) ?>">
            </div>
            <div class="col-12 col-lg-3">
                <label class="form-label small mb-1"><?= seoscope_h(__('settings.decay.position_worsen')) ?></label>
                <input class="form-control form-control-sm" type="number" name="position_worsen" min="0" step="0.1" value="<?= seoscope_h((string) $posWorsen) ?>">
            </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_impressions' => '', 'clicks_drop_pct' => '', 'impr_drop_pct' => '', 'position_worsen' => '', 'page' => '1'])) ?>">
                    <?= seoscope_h(__('common.reset')) ?>
                </a>
            </div>
        </form>
    <?php endif; ?>

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

    <?php if (!is_array($activeProp)): ?>
        <div class="text-muted"><?= seoscope_h(__('decay.no_property')) ?></div>
    <?php elseif (empty($rows)): ?>
        <div class="text-muted"><?= seoscope_h(__('decay.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' => __('decay.col_query'),
                                    'd_clicks' => __('decay.col_delta_clicks'),
                                    'd_impr' => __('decay.col_delta_impr'),
                                    'd_pos' => __('decay.col_delta_pos'),
                                    'cur_clicks' => __('decay.col_clicks'),
                                ];
                                foreach ($cols as $key => $label):
                                    $isActive = $sort === $key;
                                    $nextDir = ($isActive && strtoupper($dir) === 'DESC') ? 'ASC' : 'DESC';
                                    $arrow = $isActive ? (strtoupper($dir) === 'DESC' ? ' ↓' : ' ↑') : '';
                            ?>
                                <th>
                                    <a href="<?= seoscope_h($buildUrl(['sort' => $key, 'dir' => $nextDir, 'page' => '1'])) ?>" style="text-decoration:none;">
                                        <?= seoscope_h($label . $arrow) ?>
                                    </a>
                                </th>
                            <?php endforeach; ?>
                            <th><?= seoscope_h(__('decay.col_why')) ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $colspan = 1 + count($cols) + 1; ?>
                        <?php foreach ($rows as $idx => $r): ?>
                            <?php if (!is_array($r)) { continue; } ?>
                            <?php $flags = (isset($r['flags']) && is_array($r['flags'])) ? $r['flags'] : []; ?>
                            <?php
                                $q = (string) ($r['query'] ?? '');
                                $rowId = 'dc-' . (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 class="<?= ((float) ($r['d_clicks'] ?? 0)) < 0 ? 'text-danger' : 'text-muted' ?>"><?= seoscope_h($fmtDeltaPct((float) ($r['d_clicks'] ?? 0))) ?></td>
                                <td class="<?= ((float) ($r['d_impr'] ?? 0)) < 0 ? 'text-danger' : 'text-muted' ?>"><?= seoscope_h($fmtDeltaPct((float) ($r['d_impr'] ?? 0))) ?></td>
                                <td class="<?= ((float) ($r['d_pos'] ?? 0)) > 0 ? 'text-danger' : 'text-muted' ?>"><?= seoscope_h($fmtDeltaPos((float) ($r['d_pos'] ?? 0))) ?></td>
                                <td><?= seoscope_h($fmtInt((int) ($r['cur_clicks'] ?? 0))) ?></td>
                                <td style="white-space: nowrap;">
                                    <?php if (in_array('clicks', $flags, true)): ?>
                                        <span class="badge bg-danger me-1"><?= seoscope_h(__('decay.why_clicks')) ?></span>
                                    <?php endif; ?>
                                    <?php if (in_array('impressions', $flags, true)): ?>
                                        <span class="badge bg-danger me-1"><?= seoscope_h(__('decay.why_impr')) ?></span>
                                    <?php endif; ?>
                                    <?php if (in_array('position', $flags, true)): ?>
                                        <span class="badge bg-warning text-dark"><?= seoscope_h(__('decay.why_pos')) ?></span>
                                    <?php endif; ?>
                                </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-decay-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-decay-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">
                <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(__('decay.prev')) ?></a>
                        </li>
                        <li class="page-item disabled">
                            <span class="page-link"><?= seoscope_h(__('decay.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(__('decay.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>
<?php
$content = (string) ob_get_clean();
require __DIR__ . '/layout_admin.php';

