/**
 * BoostBot - Pre-Uninstall Export Suggestion Popup
 *
 * Injected on the WordPress plugins.php page. Intercepts the "Delete"
 * action for BoostBot and shows a modal offering to export configuration
 * and data before deletion.
 *
 * @since 1.0.3
 */
(function () {
  'use strict';

  // Only run on the plugins page
  if (typeof boostbotUninstall === 'undefined') return;

  var apiUrl = boostbotUninstall.apiUrl;
  var nonce = boostbotUninstall.nonce;
  var pluginSlug = 'boostbot/boostbot.php';
  var i18n = boostbotUninstall.i18n || {};

  // Translations with fallbacks
  var t = {
    title:          i18n.title          || 'Before you go...',
    subtitle:       i18n.subtitle       || 'Would you like to export your BoostBot data before deleting? You can re-import it later if you reinstall.',
    configTitle:    i18n.configTitle    || 'Plugin Configuration',
    configDesc:     i18n.configDesc     || 'Settings, widgets, bots, personalities, appearance presets, and all customizations.',
    dataTitle:      i18n.dataTitle      || 'Collected Data',
    dataDesc:       i18n.dataDesc       || 'Leads, conversations, meetings, contacts, analytics, and usage statistics.',
    exportConfig:   i18n.exportConfig   || 'Export Configuration',
    exportData:     i18n.exportData     || 'Export Data',
    skipDelete:     i18n.skipDelete     || 'Skip & Delete Plugin',
    cancel:         i18n.cancel         || 'Cancel',
    exporting:      i18n.exporting      || 'Exporting...',
    downloaded:     i18n.downloaded     || 'Downloaded!',
    error:          i18n.error          || 'Export failed. You can still delete the plugin.',
  };

  /**
   * Intercept the "Delete" link for BoostBot.
   */
  function init() {
    // Find the BoostBot row in the plugins table
    var pluginRow = document.querySelector('tr[data-plugin="' + pluginSlug + '"]');
    if (!pluginRow) return;

    // Find the "Delete" link
    var deleteLink = pluginRow.querySelector('.delete a, a.delete');
    if (!deleteLink) return;

    var originalHref = deleteLink.href;

    deleteLink.addEventListener('click', function (e) {
      e.preventDefault();
      e.stopPropagation();
      showExportModal(originalHref);
    });
  }

  /**
   * Show the export suggestion modal.
   */
  function showExportModal(deleteUrl) {
    // Prevent duplicates
    var existing = document.getElementById('boostbot-uninstall-modal');
    if (existing) existing.remove();

    var overlay = document.createElement('div');
    overlay.id = 'boostbot-uninstall-modal';
    overlay.style.cssText =
      'position:fixed;top:0;left:0;right:0;bottom:0;z-index:100100;' +
      'background:rgba(0,0,0,0.6);display:flex;align-items:center;' +
      'justify-content:center;animation:bbFadeIn 0.2s ease;';

    var isRtl = document.documentElement.dir === 'rtl';
    var textAlign = isRtl ? 'right' : 'left';

    overlay.innerHTML =
      '<style>' +
      '@keyframes bbFadeIn{from{opacity:0}to{opacity:1}}' +
      '@keyframes bbSlideUp{from{transform:translateY(20px);opacity:0}to{transform:translateY(0);opacity:1}}' +
      '.bb-modal{background:#fff;border-radius:12px;max-width:520px;width:90%;padding:32px;' +
      'box-shadow:0 20px 60px rgba(0,0,0,0.3);animation:bbSlideUp 0.3s ease;text-align:' + textAlign + ';}' +
      '.bb-modal h2{margin:0 0 8px;font-size:20px;color:#1d2327;}' +
      '.bb-modal p.bb-sub{margin:0 0 24px;color:#646970;font-size:14px;line-height:1.5;}' +
      '.bb-export-card{border:1px solid #ddd;border-radius:8px;padding:16px;margin-bottom:12px;' +
      'display:flex;align-items:center;gap:12px;transition:border-color 0.2s;}' +
      '.bb-export-card:hover{border-color:#2271b1;}' +
      '.bb-export-card .bb-icon{width:40px;height:40px;border-radius:8px;display:flex;align-items:center;' +
      'justify-content:center;flex-shrink:0;font-size:20px;}' +
      '.bb-export-card .bb-icon.config{background:#e8f0fe;color:#2271b1;}' +
      '.bb-export-card .bb-icon.data{background:#fef3e8;color:#d63638;}' +
      '.bb-export-card .bb-info{flex:1;min-width:0;}' +
      '.bb-export-card .bb-info h4{margin:0 0 4px;font-size:14px;color:#1d2327;}' +
      '.bb-export-card .bb-info p{margin:0;font-size:12px;color:#787c82;line-height:1.4;}' +
      '.bb-export-btn{padding:8px 16px;border-radius:6px;border:1px solid #2271b1;background:#2271b1;' +
      'color:#fff;cursor:pointer;font-size:13px;white-space:nowrap;transition:all 0.2s;flex-shrink:0;}' +
      '.bb-export-btn:hover{background:#135e96;}' +
      '.bb-export-btn:disabled{opacity:0.6;cursor:not-allowed;}' +
      '.bb-export-btn.done{background:#00a32a;border-color:#00a32a;}' +
      '.bb-actions{display:flex;gap:12px;margin-top:24px;justify-content:flex-end;}' +
      '.bb-actions .bb-skip{padding:8px 20px;border-radius:6px;border:1px solid #d63638;background:#fff;' +
      'color:#d63638;cursor:pointer;font-size:13px;transition:all 0.2s;}' +
      '.bb-actions .bb-skip:hover{background:#d63638;color:#fff;}' +
      '.bb-actions .bb-cancel{padding:8px 20px;border-radius:6px;border:1px solid #ddd;background:#fff;' +
      'color:#646970;cursor:pointer;font-size:13px;transition:all 0.2s;}' +
      '.bb-actions .bb-cancel:hover{background:#f6f7f7;}' +
      '</style>' +
      '<div class="bb-modal">' +
      '  <h2>' + t.title + '</h2>' +
      '  <p class="bb-sub">' + t.subtitle + '</p>' +
      '  <div class="bb-export-card" id="bb-config-card">' +
      '    <div class="bb-icon config">&#x2699;</div>' +
      '    <div class="bb-info">' +
      '      <h4>' + t.configTitle + '</h4>' +
      '      <p>' + t.configDesc + '</p>' +
      '    </div>' +
      '    <button class="bb-export-btn" id="bb-export-config-btn">' + t.exportConfig + '</button>' +
      '  </div>' +
      '  <div class="bb-export-card" id="bb-data-card">' +
      '    <div class="bb-icon data">&#x1F4CA;</div>' +
      '    <div class="bb-info">' +
      '      <h4>' + t.dataTitle + '</h4>' +
      '      <p>' + t.dataDesc + '</p>' +
      '    </div>' +
      '    <button class="bb-export-btn" id="bb-export-data-btn">' + t.exportData + '</button>' +
      '  </div>' +
      '  <div class="bb-actions">' +
      '    <button class="bb-cancel" id="bb-cancel-btn">' + t.cancel + '</button>' +
      '    <button class="bb-skip" id="bb-skip-btn">' + t.skipDelete + '</button>' +
      '  </div>' +
      '</div>';

    document.body.appendChild(overlay);

    // Event handlers
    document.getElementById('bb-export-config-btn').addEventListener('click', function () {
      doExport('config', this);
    });
    document.getElementById('bb-export-data-btn').addEventListener('click', function () {
      doExport('data', this);
    });
    document.getElementById('bb-skip-btn').addEventListener('click', function () {
      overlay.remove();
      window.location.href = deleteUrl;
    });
    document.getElementById('bb-cancel-btn').addEventListener('click', function () {
      overlay.remove();
    });

    // Close on backdrop click
    overlay.addEventListener('click', function (e) {
      if (e.target === overlay) {
        overlay.remove();
      }
    });

    // Close on Escape
    document.addEventListener('keydown', function onEsc(e) {
      if (e.key === 'Escape') {
        overlay.remove();
        document.removeEventListener('keydown', onEsc);
      }
    });
  }

  /**
   * Perform the export API call and trigger download.
   */
  function doExport(type, button) {
    var originalText = button.textContent;
    button.textContent = t.exporting;
    button.disabled = true;

    var url = apiUrl + 'backup/export/' + type;

    fetch(url, {
      method: 'GET',
      headers: {
        'X-WP-Nonce': nonce,
        'Accept': 'application/json',
      },
      credentials: 'same-origin',
    })
      .then(function (response) {
        if (!response.ok) throw new Error('HTTP ' + response.status);
        return response.json();
      })
      .then(function (json) {
        if (!json.success || !json.data) throw new Error('Invalid response');

        // Create downloadable JSON file
        var blob = new Blob([JSON.stringify(json.data, null, 2)], {
          type: 'application/json',
        });
        var filename =
          'boostbot-' + type + '-' + new Date().toISOString().slice(0, 10) + '.json';

        var a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(a.href);

        button.textContent = '✓ ' + t.downloaded;
        button.classList.add('done');
      })
      .catch(function () {
        button.textContent = t.error;
        button.disabled = false;
        setTimeout(function () {
          button.textContent = originalText;
        }, 3000);
      });
  }

  // Initialize when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();
