/**
 * Jalpi Support Center — module script.
 *
 * Self-contained: no jQuery, no shared helpers, no dependency on the editor
 * bundle or the frontend engine. Enqueued only on the Support screen, and every
 * handler self-guards on its own element so a missing tab is a no-op rather
 * than an error.
 *
 * Config arrives via wp_localize_script as `jalpiSupport`.
 */
(function () {
  'use strict';

  var cfg = window.jalpiSupport || {};
  var i18n = cfg.i18n || {};

  /* ── System Info: copy to clipboard ──────────────────────────────────── */

  function initCopy() {
    var btn = document.querySelector('.jalpi-support__copy');
    var src = document.querySelector('.jalpi-support__report');
    var out = document.querySelector('.jalpi-support__copied');
    if (!btn || !src) return;

    btn.addEventListener('click', function () {
      var done = function (msg) {
        if (out) {
          out.textContent = msg;
          // Clear the status so a second copy is announced again rather than
          // reading as stale text.
          setTimeout(function () { out.textContent = ''; }, 2500);
        }
      };

      // navigator.clipboard needs a secure context; plenty of local installs
      // are plain http, so fall back to the textarea selection path.
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(src.value).then(
          function () { done(i18n.copied || 'Copied'); },
          function () { fallback(); }
        );
      } else {
        fallback();
      }

      function fallback() {
        src.hidden = false;
        src.select();
        var ok = false;
        try { ok = document.execCommand('copy'); } catch (e) { ok = false; }
        if (ok) {
          src.hidden = true;
          done(i18n.copied || 'Copied');
        } else {
          // Leave the textarea visible — the user can still copy by hand.
          done(i18n.copyFailed || 'Could not copy — select the text manually.');
        }
      }
    });
  }

  /* ── Diagnostics: run checks ─────────────────────────────────────────── */

  function initDiagnostics() {
    var btn = document.querySelector('.jalpi-support__run-checks');
    var out = document.querySelector('.jalpi-support__results');
    if (!btn || !out) return;

    btn.addEventListener('click', function () {
      btn.disabled = true;
      out.innerHTML = '';
      var note = document.createElement('p');
      note.className = 'jalpi-support__spinner';
      note.textContent = i18n.running || 'Running checks…';
      out.appendChild(note);

      var body = new URLSearchParams();
      body.append('action', 'jalpi_support_diagnostics');
      body.append('nonce', cfg.nonce || '');

      fetch(cfg.ajaxUrl, {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: body.toString()
      })
        .then(function (r) { return r.json(); })
        .then(function (res) {
          btn.disabled = false;
          out.innerHTML = '';
          if (!res || !res.success || !res.data || !res.data.checks) {
            fail();
            return;
          }
          res.data.checks.forEach(function (c) { out.appendChild(row(c)); });
        })
        .catch(function () {
          btn.disabled = false;
          out.innerHTML = '';
          fail();
        });

      function fail() {
        var p = document.createElement('p');
        p.className = 'jalpi-support__spinner';
        p.textContent = i18n.checksFailed || 'Could not complete the checks.';
        out.appendChild(p);
      }
    });

    // Built with createElement/textContent rather than innerHTML so server
    // strings are never parsed as markup.
    function row(check) {
      var status = check.status === 'pass' || check.status === 'warn' || check.status === 'fail'
        ? check.status
        : 'warn';

      var wrap = document.createElement('div');
      wrap.className = 'jalpi-support__check';

      var badge = document.createElement('span');
      badge.className = 'jalpi-support__badge jalpi-support__badge--' + status;
      badge.textContent = status;
      wrap.appendChild(badge);

      var body = document.createElement('div');

      var label = document.createElement('div');
      label.className = 'jalpi-support__check-label';
      label.textContent = check.label || '';
      body.appendChild(label);

      if (check.detail) {
        var detail = document.createElement('div');
        detail.className = 'jalpi-support__check-detail';
        detail.textContent = check.detail;
        body.appendChild(detail);
      }

      wrap.appendChild(body);
      return wrap;
    }
  }

  /* ── Contact: copy the support address ───────────────────────────────── */

  function initCopyEmail() {
    var btn = document.getElementById('jalpi-support-copy-btn');
    if (!btn) return;

    var label = btn.querySelector('.jalpi-support-copy-text');

    btn.addEventListener('click', function () {
      var email = btn.getAttribute('data-email');
      if (!email) return;

      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(email).then(
          function () { flash(); },
          function () { legacyCopy(email); }
        );
      } else {
        legacyCopy(email);
      }
    });

    // execCommand is deprecated but remains the only option on plain-http
    // admin screens, where navigator.clipboard is unavailable.
    function legacyCopy(text) {
      var ta = document.createElement('textarea');
      ta.value = text;
      ta.style.position = 'fixed';
      ta.style.opacity = '0';
      document.body.appendChild(ta);
      ta.select();
      try { document.execCommand('copy'); flash(); } catch (e) { /* nothing to do */ }
      document.body.removeChild(ta);
    }

    function flash() {
      btn.classList.add('is-copied');
      if (label) label.textContent = i18n.copied || 'Copied!';
      setTimeout(function () {
        btn.classList.remove('is-copied');
        if (label) label.textContent = i18n.copy || 'Copy Email';
      }, 2000);
    }
  }

  /* ── Contact: help request form ──────────────────────────────────────── */

  function initSupportForm() {
    var form = document.getElementById('jalpi-support-form');
    var btn = document.getElementById('jalpi-support-submit');
    var status = document.getElementById('jalpi-support-status');
    if (!form || !btn || !status) return;

    // Pre-fill with the logged-in user's address; they can still change it.
    var emailInput = document.getElementById('jalpi-support-email-input');
    if (emailInput && !emailInput.value && cfg.adminEmail) {
      emailInput.value = cfg.adminEmail;
    }

    form.addEventListener('submit', function (e) {
      e.preventDefault();

      hideStatus();
      clearErrors();

      var category = form.querySelector('[name="category"]');
      var message = form.querySelector('[name="message"]');
      var email = form.querySelector('[name="email"]');

      if (!category.value || !message.value.trim() || !email.value.trim()) {
        [category, message, email].forEach(function (f) {
          if (!f.value.trim()) f.classList.add('has-error');
        });
        showStatus('error', i18n.fillFields || 'Please fill in all required fields.');
        return;
      }

      // Deliberately loose — the server does the authoritative check with
      // is_email(); this only catches obvious typos before a round trip.
      if (email.value.indexOf('@') === -1 || email.value.indexOf('.') === -1) {
        email.classList.add('has-error');
        showStatus('error', i18n.invalidEmail || 'Please enter a valid email address.');
        return;
      }

      var original = btn.innerHTML;
      btn.disabled = true;
      btn.innerHTML = '<span class="dashicons dashicons-update jalpi-support-spinning"></span> ' +
        (i18n.sending || 'Sending…');

      var body = new URLSearchParams();
      body.append('action', 'jalpi_support_submit');
      body.append('nonce', cfg.nonce || '');
      body.append('category', category.value);
      body.append('message', message.value);
      body.append('email', email.value);

      fetch(cfg.ajaxUrl, {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: body.toString()
      })
        .then(function (r) { return r.json(); })
        .then(function (res) { done(res); })
        .catch(function () {
          restore();
          showStatus('error', i18n.error || 'Something went wrong. Please try again.');
        });

      function done(res) {
        restore();

        if (res && res.success) {
          showStatus('success', (res.data && res.data.message) || i18n.sent || 'Your message has been sent.');
          // Keep the address so a follow-up message needs less retyping.
          var keep = email.value;
          form.reset();
          email.value = keep;
          return;
        }

        var msg = (res && res.data && res.data.message) || i18n.error || 'Something went wrong.';
        if (res && res.data && res.data.code === 'rate_limited') {
          msg = i18n.rateLimited || msg;
          showStatus('warning', msg);
          return;
        }
        showStatus('error', msg);
      }

      function restore() {
        btn.disabled = false;
        btn.innerHTML = original;
      }
    });

    // Clearing the error outline as soon as the user edits the field keeps
    // the warning tied to the current state rather than a stale attempt.
    form.addEventListener('input', function (e) {
      if (e.target.classList) e.target.classList.remove('has-error');
    });

    function clearErrors() {
      Array.prototype.forEach.call(
        form.querySelectorAll('.has-error'),
        function (el) { el.classList.remove('has-error'); }
      );
    }

    function showStatus(type, msg) {
      status.className = 'jalpi-support-status is-' + type;
      status.textContent = msg;
      status.style.display = 'block';
      status.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }

    function hideStatus() {
      status.style.display = 'none';
      status.className = 'jalpi-support-status';
      status.textContent = '';
    }
  }

  function init() {
    initCopy();
    initDiagnostics();
    initCopyEmail();
    initSupportForm();
  }

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