<?php
declare(strict_types=1);

/**
 * Shared SEO AI Assistant card for supported Quick Win tabs.
 *
 * @var array{
 *   slug:string,
 *   tab:string,
 *   csrf:string,
 *   cached_body:?array{executive_summary:string,seo_interpretation:string,priority_recommendation:string},
 *   has_cached:bool,
 *   no_property:bool,
 *   no_rows:bool,
 *   configure:bool,
 *   idle:bool,
 *   show_cached:bool,
 *   session_storage_key:string,
 *   url_query_params:list<string>,
 *   intro_hint:string,
 *   not_ready:string,
 *   generate_tooltip:string,
 *   endpoint?:string,
 *   append_tab_param?:bool,
 * } $ssAiQw
 */

if (!isset($ssAiQw) || !is_array($ssAiQw)) {
    return;
}

$slug = preg_replace('/[^a-z0-9_-]/', '', (string) ($ssAiQw['slug'] ?? 'qw')) ?: 'qw';
$tab = (string) ($ssAiQw['tab'] ?? 'iqqi');
$csrf = (string) ($ssAiQw['csrf'] ?? \SeoScope\Auth\AdminCsrf::token());
$cachedBody = isset($ssAiQw['cached_body']) && is_array($ssAiQw['cached_body']) ? $ssAiQw['cached_body'] : null;
$hasCached = !empty($ssAiQw['has_cached']);
$noProperty = !empty($ssAiQw['no_property']);
$noRows = !empty($ssAiQw['no_rows']);
$configure = !empty($ssAiQw['configure']);
$idle = !empty($ssAiQw['idle']);
$showCached = !empty($ssAiQw['show_cached']) || $hasCached;
$sessionKey = (string) ($ssAiQw['session_storage_key'] ?? 'ss_seo_ai_qw_has_result');
$urlParams = is_array($ssAiQw['url_query_params'] ?? null) ? $ssAiQw['url_query_params'] : ['prop', 'range', 'compare', 'device', 'country', 'tab'];
$appendTabParam = !array_key_exists('append_tab_param', $ssAiQw) || !empty($ssAiQw['append_tab_param']);
$endpointPath = trim((string) ($ssAiQw['endpoint'] ?? ''));
$endpointUrl = $endpointPath !== '' ? seoscope_url($endpointPath) : seoscope_url('/quick-win/seo-ai-assistant');
$settingsUrl = seoscope_url('/settings?' . http_build_query(['tab' => 'ai']));

$ssAiQwNl = static function (string $text): string {
    return nl2br(seoscope_h($text), false);
};
?>
<section class="mt-3 mb-4">
    <div
        class="dashboard-card section-card ss-seo-ai-assistant-card"
        id="ss-seo-ai-<?= seoscope_h($slug) ?>-card"
        aria-labelledby="ss-seo-ai-<?= seoscope_h($slug) ?>-heading"
        data-ss-seo-ai-endpoint="<?= seoscope_h($endpointUrl) ?>"
        data-ss-seo-ai-csrf="<?= seoscope_h($csrf) ?>"
        data-ss-seo-ai-prefilled="<?= $showCached ? '1' : '0' ?>"
    >
        <div class="mb-3">
            <div class="section-title mb-0" id="ss-seo-ai-<?= seoscope_h($slug) ?>-heading">
                <span><?= seoscope_h(__('seo_ai.card.title')) ?></span>
            </div>
            <p class="section-subtitle mb-0 mt-2"><?= seoscope_h((string) ($ssAiQw['intro_hint'] ?? '')) ?></p>
        </div>

        <div id="ss-seo-ai-<?= seoscope_h($slug) ?>-state-no-property" class="section-subtitle mb-0<?= $noProperty ? '' : ' d-none' ?>">
            <?= seoscope_h(__('seo_ai.card.state_no_property')) ?>
        </div>

        <div id="ss-seo-ai-<?= seoscope_h($slug) ?>-state-no-rows" class="section-subtitle mb-0<?= $noRows ? '' : ' d-none' ?>">
            <?= seoscope_h((string) ($ssAiQw['not_ready'] ?? '')) ?>
        </div>

        <div id="ss-seo-ai-<?= seoscope_h($slug) ?>-state-configure" class="<?= $configure ? '' : 'd-none' ?>">
            <p class="section-subtitle mb-2"><?= seoscope_h(__('seo_ai.card.configure_hint')) ?></p>
            <a class="btn btn-sm btn-outline-primary" href="<?= seoscope_h($settingsUrl) ?>"><?= seoscope_h(__('seo_ai.card.open_settings_ai')) ?></a>
        </div>

        <div id="ss-seo-ai-<?= seoscope_h($slug) ?>-state-idle" class="<?= $idle ? '' : 'd-none' ?>">
            <div class="d-flex flex-wrap align-items-center gap-2">
                <button type="button" class="btn btn-sm ss-seo-ai-btn-generate" id="ss-seo-ai-<?= seoscope_h($slug) ?>-btn-generate" disabled title="<?= seoscope_h((string) ($ssAiQw['generate_tooltip'] ?? '')) ?>">
                    <?= seoscope_h(__('seo_ai.card.generate')) ?>
                </button>
                <span id="ss-seo-ai-<?= seoscope_h($slug) ?>-regenerate-wrap" class="ms-2<?= $hasCached ? '' : ' d-none' ?>">
                    <button type="button" class="btn btn-sm btn-outline-secondary" id="ss-seo-ai-<?= seoscope_h($slug) ?>-btn-regenerate" disabled title="<?= seoscope_h(__('seo_ai.card.regenerate_tooltip')) ?>">
                        <?= seoscope_h(__('seo_ai.card.regenerate')) ?>
                    </button>
                </span>
            </div>
        </div>

        <div id="ss-seo-ai-<?= seoscope_h($slug) ?>-state-loading" class="d-none mt-2 text-muted" aria-live="polite">
            <div class="d-flex align-items-center gap-2">
                <div class="spinner-border spinner-border-sm text-primary" role="status" aria-hidden="true"></div>
                <span><?= seoscope_h(__('seo_ai.card.analyzing')) ?></span>
            </div>
        </div>

        <div id="ss-seo-ai-<?= seoscope_h($slug) ?>-state-error" class="alert alert-danger mt-3 mb-0 py-2 small d-none" role="alert"></div>

        <div id="ss-seo-ai-<?= seoscope_h($slug) ?>-state-success" class="<?= $showCached ? 'mt-3' : 'd-none mt-3' ?>" role="status" aria-live="polite">
            <div class="mb-3">
                <div class="fw-semibold small text-uppercase text-muted mb-1"><?= seoscope_h(__('seo_ai.card.summary_heading')) ?></div>
                <div id="ss-seo-ai-<?= seoscope_h($slug) ?>-out-summary" class="small"><?php
                    if ($cachedBody !== null) {
                        $t = trim((string) ($cachedBody['executive_summary'] ?? ''));
                        echo $t !== '' ? $ssAiQwNl($t) : '<span class="text-muted">—</span>';
                    }
                ?></div>
            </div>
            <div class="mb-3">
                <div class="fw-semibold small text-uppercase text-muted mb-1"><?= seoscope_h(__('seo_ai.card.insight_heading')) ?></div>
                <div id="ss-seo-ai-<?= seoscope_h($slug) ?>-out-insight" class="small"><?php
                    if ($cachedBody !== null) {
                        $t = trim((string) ($cachedBody['seo_interpretation'] ?? ''));
                        echo $t !== '' ? $ssAiQwNl($t) : '<span class="text-muted">—</span>';
                    }
                ?></div>
            </div>
            <div class="mb-0">
                <div class="fw-semibold small text-uppercase text-muted mb-1"><?= seoscope_h(__('seo_ai.card.action_heading')) ?></div>
                <div id="ss-seo-ai-<?= seoscope_h($slug) ?>-out-action" class="small"><?php
                    if ($cachedBody !== null) {
                        $t = trim((string) ($cachedBody['priority_recommendation'] ?? ''));
                        echo $t !== '' ? $ssAiQwNl($t) : '<span class="text-muted">—</span>';
                    }
                ?></div>
            </div>
        </div>
    </div>
</section>
<?php
$ssSeoAiQwJsCfg = [
    'networkError' => __('seo_ai.card.network_error'),
    'badResponse' => __('seo_ai.card.bad_response'),
    'csrfFailed' => __('seo_ai.card.csrf_failed'),
];
?>
<script>
(function (SLUG, TAB, SESSION_KEY, URL_PARAMS, CFG) {
  var wrap = document.getElementById('ss-seo-ai-' + SLUG + '-regenerate-wrap');
  if (!wrap || wrap.classList.contains('d-none') === false) return;
  try {
    if (window.sessionStorage && window.sessionStorage.getItem(SESSION_KEY) === '1') {
      wrap.classList.remove('d-none');
    }
  } catch (e) {}
})(<?= json_encode($slug, JSON_THROW_ON_ERROR) ?>, <?= json_encode($tab, JSON_THROW_ON_ERROR) ?>, <?= json_encode($sessionKey, JSON_THROW_ON_ERROR) ?>, <?= json_encode($urlParams, JSON_THROW_ON_ERROR) ?>, <?= json_encode($ssSeoAiQwJsCfg, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) ?>, <?= json_encode($appendTabParam, JSON_THROW_ON_ERROR) ?>);
(function (SLUG, TAB, SESSION_KEY, URL_PARAMS, CFG, APPEND_TAB) {
  var card = document.getElementById('ss-seo-ai-' + SLUG + '-card');
  var idle = document.getElementById('ss-seo-ai-' + SLUG + '-state-idle');
  var gen = document.getElementById('ss-seo-ai-' + SLUG + '-btn-generate');
  var reg = document.getElementById('ss-seo-ai-' + SLUG + '-btn-regenerate');
  var loading = document.getElementById('ss-seo-ai-' + SLUG + '-state-loading');
  var errBox = document.getElementById('ss-seo-ai-' + SLUG + '-state-error');
  var okBox = document.getElementById('ss-seo-ai-' + SLUG + '-state-success');
  var outSum = document.getElementById('ss-seo-ai-' + SLUG + '-out-summary');
  var outIns = document.getElementById('ss-seo-ai-' + SLUG + '-out-insight');
  var outAct = document.getElementById('ss-seo-ai-' + SLUG + '-out-action');
  var wrap = document.getElementById('ss-seo-ai-' + SLUG + '-regenerate-wrap');
  if (!card || !idle || idle.classList.contains('d-none')) return;

  var endpoint = card.getAttribute('data-ss-seo-ai-endpoint') || '';
  var csrf = card.getAttribute('data-ss-seo-ai-csrf') || '';
  if (!endpoint || !csrf) return;

  var inFlight = false;

  function escHtml(s) {
    var d = document.createElement('div');
    d.textContent = s;
    return d.innerHTML;
  }

  function formatBlock(s) {
    s = String(s || '').trim();
    if (!s) return '<span class="text-muted">—</span>';
    return escHtml(s).replace(/\r\n|\r|\n/g, '<br>');
  }

  function setLoading(on) {
    if (loading) loading.classList.toggle('d-none', !on);
    if (gen) gen.disabled = on;
    if (reg) reg.disabled = on;
  }

  function hideError() {
    if (!errBox) return;
    errBox.classList.add('d-none');
    errBox.textContent = '';
  }

  function showError(msg) {
    if (!errBox) return;
    errBox.textContent = String(msg || '');
    errBox.classList.remove('d-none');
  }

  function applySuccess(data) {
    hideError();
    if (outSum) outSum.innerHTML = formatBlock(data.executive_summary);
    if (outIns) outIns.innerHTML = formatBlock(data.seo_interpretation);
    if (outAct) outAct.innerHTML = formatBlock(data.priority_recommendation);
    if (okBox) okBox.classList.remove('d-none');
    if (wrap) wrap.classList.remove('d-none');
    card.setAttribute('data-ss-seo-ai-prefilled', '1');
    try {
      if (window.sessionStorage) window.sessionStorage.setItem(SESSION_KEY, '1');
    } catch (e) {}
  }

  function run(regenerate) {
    if (inFlight || !endpoint || !csrf) return;
    inFlight = true;
    hideError();
    setLoading(true);

    var body = new URLSearchParams();
    body.set('_csrf', csrf);
    if (regenerate) body.set('regenerate', '1');

    var postUrl = endpoint;
    try {
      var u = new URL(endpoint, window.location.origin);
      var cur = new URL(window.location.href);
      URL_PARAMS.forEach(function (k) {
        var v = cur.searchParams.get(k);
        if (v !== null && v !== '') u.searchParams.set(k, v);
      });
      if (APPEND_TAB && !u.searchParams.get('tab')) u.searchParams.set('tab', TAB);
      postUrl = u.toString();
    } catch (e) {}

    fetch(postUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
      body: body.toString(),
      credentials: 'same-origin',
    })
      .then(function (res) {
        var ct = (res.headers.get('content-type') || '').toLowerCase();
        return res.text().then(function (raw) {
          var data = null;
          if (ct.indexOf('application/json') !== -1) {
            try { data = JSON.parse(raw); } catch (e) { data = null; }
          }
          return { res: res, data: data };
        });
      })
      .then(function (pack) {
        if (pack.res.status === 403 && !pack.data) {
          showError(CFG.csrfFailed);
          return;
        }
        if (!pack.data || typeof pack.data !== 'object') {
          showError(CFG.badResponse);
          return;
        }
        if (!pack.data.ok) {
          showError(typeof pack.data.message === 'string' && pack.data.message ? pack.data.message : CFG.badResponse);
          return;
        }
        applySuccess(pack.data);
      })
      .catch(function () {
        showError(CFG.networkError);
      })
      .finally(function () {
        inFlight = false;
        setLoading(false);
      });
  }

  if (gen) gen.disabled = false;
  if (reg) reg.disabled = false;
  if (gen) gen.addEventListener('click', function () { run(false); });
  if (reg) reg.addEventListener('click', function () { run(true); });
})(<?= json_encode($slug, JSON_THROW_ON_ERROR) ?>, <?= json_encode($tab, JSON_THROW_ON_ERROR) ?>, <?= json_encode($sessionKey, JSON_THROW_ON_ERROR) ?>, <?= json_encode($urlParams, JSON_THROW_ON_ERROR) ?>, <?= json_encode($ssSeoAiQwJsCfg, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) ?>, <?= json_encode($appendTabParam, JSON_THROW_ON_ERROR) ?>);
</script>
