<?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 $csrf */
/** @var string $questionTermsRaw */

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

$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_30_days'),
        'per_page' => (string) ($_GET['per_page'] ?? '10'),
        'sort' => (string) ($_GET['sort'] ?? 'clicks'),
        'dir' => (string) ($_GET['dir'] ?? 'DESC'),
        'page' => (string) ($_GET['page'] ?? '1'),
    ];
    foreach ($overrides as $k => $v) {
        $base[$k] = (string) $v;
    }
    if (($base['prop'] ?? '') === '') unset($base['prop']);
    return seoscope_url('/question-queries?' . http_build_query($base));
};

ob_start();
?>
<div class="dashboard-card section-card">
    <div class="d-flex align-items-start justify-content-between flex-wrap gap-3 mb-2">
        <div>
            <div class="section-title mb-1"><?= seoscope_h(__('question_queries.title')) ?></div>
            <div class="section-subtitle mb-0"><?= seoscope_h(__('question_queries.subtitle', ['start' => $rangeStart, 'end' => $rangeEnd])) ?></div>
        </div>
    </div>

    <div class="mb-4">
        <div class="text-muted small mb-2">
            <strong><?= seoscope_h(__('question_queries.terms_title')) ?>:</strong>
            <?= seoscope_h(__('question_queries.terms_help')) ?>
        </div>

        <form method="post" action="<?= seoscope_h(seoscope_url('/question-queries/terms')) ?>">
            <input type="hidden" name="_csrf" value="<?= seoscope_h($csrf) ?>">
            <input type="hidden" name="prop" value="<?= seoscope_h((string) ($_GET['prop'] ?? '')) ?>">
            <input type="hidden" name="range" value="<?= seoscope_h((string) ($_GET['range'] ?? '')) ?>">
            <input type="hidden" name="question_terms" id="qq-terms-hidden" value="<?= seoscope_h($questionTermsRaw) ?>">

            <div class="border rounded-3 p-2" style="background: rgba(255,255,255,0.70);">
                <div id="qq-terms-chips" class="d-flex flex-wrap gap-2"></div>
                <input
                    id="qq-terms-input"
                    type="text"
                    class="form-control form-control-sm mt-2"
                    placeholder="Type a term and press Enter (or comma)"
                    autocomplete="off"
                >
            </div>
            <div class="mt-2 d-flex align-items-center justify-content-between flex-wrap gap-2">
                <button type="submit" class="btn btn-sm btn-upgrade"><?= seoscope_h(__('question_queries.save_terms')) ?></button>
                <button type="submit" name="reset" value="1" class="btn btn-sm btn-outline-secondary">
                    <?= seoscope_h(__('question_queries.reset_default')) ?>
                </button>
            </div>
        </form>
    </div>

    <script>
      (function() {
        const hidden = document.getElementById('qq-terms-hidden');
        const chipsEl = document.getElementById('qq-terms-chips');
        const input = document.getElementById('qq-terms-input');
        if (!hidden || !chipsEl || !input) return;

        function parseTerms(raw) {
          return (raw || '')
            .split(/[\n\r,]+/g)
            .map(s => s.trim())
            .filter(Boolean);
        }

        let terms = [];

        function syncHidden() {
          hidden.value = terms.join(', ');
        }

        function render() {
          chipsEl.innerHTML = '';
          terms.forEach((t, idx) => {
            const chip = document.createElement('span');
            chip.className = 'badge bg-secondary-subtle text-dark border d-inline-flex align-items-center gap-2';
            chip.style.padding = '0.45rem 0.6rem';
            chip.style.borderRadius = '999px';

            const label = document.createElement('span');
            label.textContent = t;

            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'btn btn-sm p-0 border-0';
            btn.style.lineHeight = '1';
            btn.style.color = 'inherit';
            btn.setAttribute('aria-label', 'Remove');
            btn.innerHTML = '&times;';
            btn.addEventListener('click', () => {
              terms.splice(idx, 1);
              syncHidden();
              render();
            });

            chip.appendChild(label);
            chip.appendChild(btn);
            chipsEl.appendChild(chip);
          });
        }

        function addTerm(raw) {
          const t = (raw || '').trim();
          if (!t) return;
          const lower = t.toLowerCase();
          if (terms.some(x => x.toLowerCase() === lower)) return;
          terms.push(t);
          syncHidden();
          render();
        }

        // init from hidden value
        terms = parseTerms(hidden.value);
        syncHidden();
        render();

        input.addEventListener('keydown', (e) => {
          if (e.key === 'Enter' || e.key === ',') {
            e.preventDefault();
            addTerm(input.value.replace(/,+$/g, ''));
            input.value = '';
          } else if (e.key === 'Backspace' && input.value === '' && terms.length) {
            // quick remove last
            terms.pop();
            syncHidden();
            render();
          }
        });

        input.addEventListener('blur', () => {
          // if user typed something and clicked elsewhere, keep it
          addTerm(input.value.replace(/,+$/g, ''));
          input.value = '';
        });
      })();
    </script>

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

    <?php if (!is_array($activeProp)): ?>
        <div class="text-muted"><?= seoscope_h(__('question_queries.no_property')) ?></div>
    <?php elseif (empty($rows)): ?>
        <div class="text-muted"><?= seoscope_h(__('question_queries.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'),
                                    '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 = 'qq-' . (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['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-qq-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-qq-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(__('opportunities.prev')) ?></a>
                        </li>
                        <li class="page-item disabled">
                            <span class="page-link"><?= seoscope_h(__('opportunities.page_x_of_y', ['x' => (string) $page, 'y' => (string) $pages])) ?></span>
                        </li>
                        <li class="page-item <?= $page >= $pages ? 'disabled' : '' ?>">
                            <a class="page-link" href="<?= seoscope_h($buildUrl(['page' => (string) $next])) ?>"><?= seoscope_h(__('opportunities.next')) ?></a>
                        </li>
                    </ul>
                </nav>

                <form method="get" class="m-0 d-flex align-items-center gap-2">
                    <span class="text-muted small"><?= seoscope_h(__('pages.rows_per_page')) ?></span>
                    <select class="form-select form-select-sm" name="per_page" style="width:auto;" onchange="this.form.submit()">
                        <option value="10" <?= $perPage === 10 ? 'selected' : '' ?>>10</option>
                        <option value="25" <?= $perPage === 25 ? 'selected' : '' ?>>25</option>
                        <option value="50" <?= $perPage === 50 ? 'selected' : '' ?>>50</option>
                        <option value="100" <?= $perPage === 100 ? 'selected' : '' ?>>100</option>
                    </select>
                    <?php
                        $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';

