/**
 * Forge Suite dashboard — Disconnect + health-diagnostics client.
 *
 * FC-63 v2: manual license-key activation is removed. The dashboard now drives
 * Connect / Reconnect through Forge_Connect::render_button (its own inline
 * script), so this file only owns the full-site Disconnect button and the
 * health-check / repair panel. Config arrives via wp_localize_script as
 * window.ForgeDashboardCfg:
 *
 * {
 * deactNonce: '...',
 * healthNonce: '...',
 * i18n: { confirmDeact, deactivating, ... },
 * }
 */
(function ($) {
  'use strict';

  if (!window.ForgeDashboardCfg) {
    // Safety net: if PHP didn't localize — typo in handle name / plugin
    // dir — bail out instead of silently breaking click handlers.
    // eslint-disable-next-line no-console
    console.error('[forge-suite] ForgeDashboardCfg missing — skipping.');
    return;
  }

  var CFG = window.ForgeDashboardCfg;
  var I18N = CFG.i18n || {};

  $(function () {
    var $result = $('#forge-suite-license-result');
    var $healthBtn = $('#forge-suite-health-run');
    var $healthResults = $('#forge-suite-health-results');
    var $healthSupport = $('#forge-suite-health-support');
    var $healthRecommendations = $('#forge-suite-health-recommendations');
    var $healthHistory = $('#forge-suite-health-history');

    // Disconnect — full-site teardown via our custom AJAX handler (Reflection
    // into Freemius + Forge_Connect::disconnect_all()).
    var $deactBtn = $('#forge-suite-deactivate-btn');

    $deactBtn.on('click', function () {
      if (!confirm(I18N.confirmDeact)) return;

      $deactBtn.prop('disabled', true).find('.dashicons').removeClass('dashicons-dismiss').addClass('dashicons-update spin');
      $result.html('<span class="forge-suite-result-info">' + I18N.deactivating + '</span>').show();

      $.ajax({
        url: window.ajaxurl,
        type: 'POST',
        dataType: 'json',
        data: {
          action: 'forge_suite_deactivate_bundle',
          _wpnonce: CFG.deactNonce,
        },
        success: function (resp) {
          $deactBtn.prop('disabled', false).find('.dashicons').removeClass('dashicons-update spin').addClass('dashicons-dismiss');
          if (resp && resp.success) {
            $result.html('<span class="forge-suite-result-success">' + resp.data.message + '</span>').show();
            setTimeout(function () { location.reload(); }, 1500);
          } else {
            $result.html('<span class="forge-suite-result-error">' + (resp.data || I18N.deactivationFailed) + '</span>').show();
          }
        },
        error: function () {
          $deactBtn.prop('disabled', false).find('.dashicons').removeClass('dashicons-update spin').addClass('dashicons-dismiss');
          $result.html('<span class="forge-suite-result-error">' + I18N.networkError + '</span>').show();
        },
      });
    });

    $healthBtn.on('click', function () {
      $healthBtn.prop('disabled', true).addClass('is-running');
      $healthResults
        .html('<div class="forge-suite-health-result is-info"><strong>' + I18N.runningHealth + '</strong></div>')
        .show();

      $.ajax({
        url: window.ajaxurl,
        type: 'POST',
        dataType: 'json',
        data: {
          action: 'forge_suite_health_check',
          nonce: CFG.healthNonce,
        },
        success: function (resp) {
          $healthBtn.prop('disabled', false).removeClass('is-running');
          if (!resp || !resp.success || !resp.data || !Array.isArray(resp.data.items)) {
            $healthResults.html('<div class="forge-suite-health-result is-error"><strong>' + I18N.healthFailed + '</strong></div>');
            return;
          }
          renderHealthResults(resp.data.items);
          renderHealthRecommendations(resp.data.recommendations || []);
          renderHealthHistory(resp.data.history || []);
        },
        error: function () {
          $healthBtn.prop('disabled', false).removeClass('is-running');
          $healthResults.html('<div class="forge-suite-health-result is-error"><strong>' + I18N.networkError + '</strong></div>');
        },
      });
    });

    function renderHealthResults(items) {
      var html = '';
      items.forEach(function (item) {
        var status = item.status || 'warn';
        html += '<div class="forge-suite-health-result is-' + escapeAttr(status) + '">';
        html += '<span class="forge-suite-health-result-dot" aria-hidden="true"></span>';
        html += '<div><strong>' + escapeHtml(item.label || '') + '</strong>';
        html += '<span>' + escapeHtml(item.message || '') + '</span>';
        html += renderHealthAction(item.action);
        html += '</div>';
        html += '</div>';
      });
      $healthResults.html(html).show();
    }

    $(document).on('click', '.forge-suite-health-repair', function () {
      var repair = $(this).data('repair');
      if (!repair) return;
      runHealthRepair(String(repair), $(this));
    });

    function runHealthRepair(repair, $trigger) {
      var original = $trigger.text();
      $trigger.prop('disabled', true).text(I18N.runningHealth || 'Running...');
      $healthSupport.prop('hidden', true).empty();

      $.ajax({
        url: window.ajaxurl,
        type: 'POST',
        dataType: 'json',
        data: {
          action: 'forge_suite_health_repair',
          nonce: CFG.healthNonce,
          repair: repair,
        },
        success: function (resp) {
          $trigger.prop('disabled', false).text(original);
          if (!resp || !resp.success || !resp.data) {
            $healthResults.prepend('<div class="forge-suite-health-result is-error"><strong>' + I18N.healthFailed + '</strong></div>');
            return;
          }
          if (Array.isArray(resp.data.items)) renderHealthResults(resp.data.items);
          if (Array.isArray(resp.data.history)) renderHealthHistory(resp.data.history);
          if (resp.data.package) renderSupportPackage(resp.data.package);
          if (resp.data.message) {
            $healthResults.prepend('<div class="forge-suite-health-result is-ok"><span class="forge-suite-health-result-dot" aria-hidden="true"></span><div><strong>' + escapeHtml(resp.data.message) + '</strong></div></div>');
          }
        },
        error: function () {
          $trigger.prop('disabled', false).text(original);
          $healthResults.prepend('<div class="forge-suite-health-result is-error"><strong>' + I18N.networkError + '</strong></div>');
        },
      });
    }

    function renderHealthRecommendations(recommendations) {
      if (!$healthRecommendations.length || !recommendations.length) return;
      var html = '';
      recommendations.forEach(function (rec) {
        html += '<div class="forge-suite-health-recommendation is-medium">';
        html += '<span class="dashicons dashicons-lightbulb" aria-hidden="true"></span>';
        html += '<div><strong>' + escapeHtml(rec.title || '') + '</strong>';
        html += '<span>' + escapeHtml(rec.message || '') + '</span></div>';
        html += renderHealthAction(rec.action);
        html += '</div>';
      });
      $healthRecommendations.html(html).show();
    }

    function renderHealthHistory(history) {
      if (!$healthHistory.length) return;
      var html = '<div class="forge-suite-health-history-head">';
      html += '<strong>' + escapeHtml(I18N.diagnosticHistory || 'Diagnostic history') + '</strong>';
      html += '<button type="button" class="button button-link-delete forge-suite-health-repair" data-repair="clear_history">' + escapeHtml(I18N.clearHistory || 'Clear history') + '</button>';
      html += '</div><div class="forge-suite-health-history-list">';
      if (!history.length) {
        html += '<span class="forge-suite-health-history-empty">' + escapeHtml(I18N.noDiagnosticRuns || 'No diagnostic runs yet.') + '</span>';
      } else {
        history.slice(0, 5).forEach(function (entry) {
          var counts = I18N.healthCounts || '%1$d ok, %2$d warnings, %3$d errors';
          counts = counts
            .replace('%1$d', entry.ok || 0)
            .replace('%2$d', entry.warn || 0)
            .replace('%3$d', entry.error || 0);
          html += '<div class="forge-suite-health-history-row">';
          html += '<span>' + escapeHtml(entry.time || '') + '</span>';
          html += '<span>' + escapeHtml(counts) + '</span>';
          html += '</div>';
        });
      }
      html += '</div>';
      $healthHistory.html(html).show();
    }

    function renderSupportPackage(payload) {
      $healthSupport
        .prop('hidden', false)
        .html('<label><strong>' + escapeHtml(I18N.supportPackage || 'Support package') + '</strong><textarea readonly rows="10">' + escapeHtml(payload) + '</textarea></label>');
    }

    function renderHealthAction(action) {
      if (!action || !action.label) return '';
      if (action.type === 'link' && action.url) {
        return '<a class="button button-secondary forge-suite-health-action" href="' + escapeHtml(action.url) + '">' + escapeHtml(action.label) + '</a>';
      }
      if (action.type === 'repair' && action.repair) {
        return '<button type="button" class="button button-secondary forge-suite-health-action forge-suite-health-repair" data-repair="' + escapeAttr(action.repair) + '">' + escapeHtml(action.label) + '</button>';
      }
      return '';
    }

    function escapeHtml(value) {
      return String(value).replace(/[&<>"']/g, function (ch) {
        return ({
          '&': '&amp;',
          '<': '&lt;',
          '>': '&gt;',
          '"': '&quot;',
          "'": '&#039;',
        })[ch];
      });
    }

    function escapeAttr(value) {
      return String(value).replace(/[^a-z0-9_-]/gi, '');
    }
  });
}(jQuery));
