/**
 * VSR License Page — Activation / Deactivation
 */
(function () {
  'use strict';

  const nonce   = (typeof vlensAdmin !== 'undefined') ? vlensAdmin.nonce   : '';
  const restUrl = (typeof vlensAdmin !== 'undefined') ? vlensAdmin.restUrl : '';

  function msgEl()    { return document.getElementById('vsrLicMsg'); }
  function inputEl()  { return document.getElementById('vsrLicKey'); }
  function actBtn()   { return document.getElementById('vsrLicActivate'); }
  function deactBtn() { return document.getElementById('vsrLicDeactivate'); }

  /* ── Display result message ──────────────────────────────────── */
  function showMsg(text, type /* 'success' | 'error' | 'info' */) {
    const el = msgEl();
    if (!el) return;
    el.textContent  = text;
    el.className    = 'vsr-lic-msg vsr-lic-msg--' + type;
    el.style.display = '';
  }

  /* ── Set loading state ───────────────────────────────────────── */
  function setLoading(btn, loading) {
    if (!btn) return;
    btn.disabled = loading;
    btn.classList.toggle('vsr-lic-btn--loading', loading);
    if (loading) {
      btn._origText = btn.innerHTML;
      btn.innerHTML = '<span class="vsr-lic-spinner"></span> Please wait…';
    } else if (btn._origText) {
      btn.innerHTML = btn._origText;
    }
  }

  /* ── POST to our REST endpoint ──────────────────────────────── */
  async function post(action, body) {
    const url = restUrl.replace(/\/$/, '') + '/vlens/v1/license/' + action;
    const res = await fetch(url, {
      method:  'POST',
      headers: {
        'Content-Type':    'application/json',
        'X-WP-Nonce':      nonce,
      },
      body: JSON.stringify(body),
    });
    return res.json();
  }

  /* ── Activate ────────────────────────────────────────────────── */
  function onActivate() {
    const btn = actBtn();
    const key = (inputEl() ? inputEl().value.trim() : '');

    if (!key) {
      showMsg('Please enter your license key.', 'error');
      if (inputEl()) inputEl().focus();
      return;
    }

    setLoading(btn, true);
    msgEl() && (msgEl().style.display = 'none');

    post('activate', { license_key: key })
      .then(data => {
        setLoading(btn, false);
        if (data && data.success) {
          showMsg(data.message || 'License activated!', 'success');
          // Reload after 1.5 s to show the active state
          setTimeout(() => location.reload(), 1500);
        } else {
          showMsg((data && data.message) ? data.message : 'Activation failed. Please try again.', 'error');
        }
      })
      .catch(err => {
        setLoading(btn, false);
        showMsg('Network error: ' + err.message, 'error');
      });
  }

  /* ── Deactivate ──────────────────────────────────────────────── */
  function onDeactivate() {
    if (!confirm('Deactivate this license? Premium features will be removed from this site.')) return;

    const btn = deactBtn();
    setLoading(btn, true);
    msgEl() && (msgEl().style.display = 'none');

    post('deactivate', {})
      .then(data => {
        setLoading(btn, false);
        if (data && data.success) {
          showMsg(data.message || 'License deactivated.', 'info');
          setTimeout(() => location.reload(), 1500);
        } else {
          showMsg((data && data.message) ? data.message : 'Deactivation failed.', 'error');
        }
      })
      .catch(err => {
        setLoading(btn, false);
        showMsg('Network error: ' + err.message, 'error');
      });
  }

  /* ── Init ────────────────────────────────────────────────────── */
  function init() {
    const ab = actBtn();
    const db = deactBtn();
    if (ab) ab.addEventListener('click', onActivate);
    if (db) db.addEventListener('click', onDeactivate);

    // Allow Enter key in the input field to submit
    const inp = inputEl();
    if (inp) {
      inp.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') onActivate();
      });
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }

})();
