/**
 * VisitorLens — Settings Page JS
 * Loads settings from REST API, populates form, saves on click.
 */
(function () {
  'use strict';

  // Tab switching
  document.querySelectorAll('.vsr-tab').forEach(function (tab) {
    tab.addEventListener('click', function () {
      document.querySelectorAll('.vsr-tab').forEach(function (t) { t.classList.remove('active'); });
      document.querySelectorAll('.vsr-tab-content').forEach(function (c) { c.classList.remove('active'); });
      tab.classList.add('active');
      var target = document.getElementById('tab-' + tab.getAttribute('data-tab'));
      if (target) target.classList.add('active');
    });
  });

  // Field mapping: element ID → setting key
  var toggleFields = {
    'vsr-tracking-enabled':     'tracking_enabled',
    'vsr-recording-enabled':    'recording_enabled',
    'vsr-geoip-enabled':        'geoip_enabled',
    'vsr-skip-idle':            'skip_idle',
    'vsr-mask-inputs':          'mask_inputs',
    'vsr-respect-dnt':          'respect_dnt',
    'vsr-exclude-wp-admin':     'exclude_wp_admin',
    'vsr-exclude-logged-admins':'exclude_logged_admins',
    'vsr-exclude-bots':         'exclude_bots',
    'vsr-consent-required':     'consent_required',
  };

  var valueFields = {
    'vsr-dashboard-theme':      'dashboard_theme',
    'vsr-retention-days':       'retention_days',
    'vsr-session-limit':        'session_limit',
    'vsr-sampling-rate':        'sampling_rate',
    'vsr-flush-interval':       'flush_interval',
    'vsr-consent-mode':         'consent_mode',
    'vsr-consent-cookie-name':  'consent_cookie_name',
  };

  /* ── Tags UI for exclude URLs / IPs ── */

  var excludeUrlsList = [];
  var excludeIpsList  = [];

  function renderTags(containerId, list, onRemove) {
    var container = document.getElementById(containerId);
    if (!container) return;
    container.innerHTML = '';
    list.forEach(function (val, idx) {
      var tag = document.createElement('span');
      tag.className = 'vsr-tag';
      tag.textContent = val;
      var btn = document.createElement('button');
      btn.className = 'vsr-tag-remove';
      btn.type = 'button';
      btn.innerHTML = '&times;';
      btn.title = 'Remove';
      btn.addEventListener('click', function () { onRemove(idx); });
      tag.appendChild(btn);
      container.appendChild(tag);
    });
  }

  function renderUrlTags() { renderTags('vsr-exclude-urls-tags', excludeUrlsList, function (i) { excludeUrlsList.splice(i, 1); renderUrlTags(); }); }
  function renderIpTags()  { renderTags('vsr-exclude-ips-tags',  excludeIpsList,  function (i) { excludeIpsList.splice(i, 1);  renderIpTags(); }); }

  function addTag(inputId, list, render) {
    var input = document.getElementById(inputId);
    if (!input) return;
    var vals = input.value.split(',').map(function (s) { return s.trim(); }).filter(Boolean);
    vals.forEach(function (v) {
      if (list.indexOf(v) === -1) list.push(v);
    });
    input.value = '';
    render();
  }

  // Add button clicks
  var addUrlBtn = document.getElementById('vsr-exclude-urls-add');
  if (addUrlBtn) addUrlBtn.addEventListener('click', function () { addTag('vsr-exclude-urls-input', excludeUrlsList, renderUrlTags); });

  var addIpBtn = document.getElementById('vsr-exclude-ips-add');
  if (addIpBtn) addIpBtn.addEventListener('click', function () { addTag('vsr-exclude-ips-input', excludeIpsList, renderIpTags); });

  // Enter key in tag inputs
  var urlInput = document.getElementById('vsr-exclude-urls-input');
  if (urlInput) urlInput.addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); addTag('vsr-exclude-urls-input', excludeUrlsList, renderUrlTags); } });

  var ipInput = document.getElementById('vsr-exclude-ips-input');
  if (ipInput) ipInput.addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); addTag('vsr-exclude-ips-input', excludeIpsList, renderIpTags); } });

  /* ── Consent UI toggling ── */

  function updateConsentUI() {
    var required = document.getElementById('vsr-consent-required');
    var options  = document.getElementById('vsr-consent-options');
    var modeEl   = document.getElementById('vsr-consent-mode');
    var customGrp = document.getElementById('vsr-custom-cookie-group');

    if (options) options.style.display = required && required.checked ? '' : 'none';
    if (customGrp && modeEl) customGrp.style.display = modeEl.value === 'custom' ? '' : 'none';
  }

  var consentReq = document.getElementById('vsr-consent-required');
  if (consentReq) consentReq.addEventListener('change', updateConsentUI);

  var consentMode = document.getElementById('vsr-consent-mode');
  if (consentMode) consentMode.addEventListener('change', updateConsentUI);

  /**
   * Load settings from API and populate form.
   */
  async function loadSettings() {
    try {
      var settings = await VSR.get('settings');

      // Toggles
      Object.keys(toggleFields).forEach(function (id) {
        var el = document.getElementById(id);
        if (el) {
          var val = settings[toggleFields[id]];
          el.checked = (val === '1' || val === true || val === 1);
        }
      });

      // Value fields
      Object.keys(valueFields).forEach(function (id) {
        var el = document.getElementById(id);
        if (el) el.value = settings[valueFields[id]] || '';
      });

      // Tag lists
      if (Array.isArray(settings.exclude_urls)) {
        excludeUrlsList = settings.exclude_urls.slice();
      }
      renderUrlTags();

      if (Array.isArray(settings.exclude_ips)) {
        excludeIpsList = settings.exclude_ips.slice();
      }
      renderIpTags();

      // Last cleanup timestamp
      var cleanupEl = document.getElementById('vsr-last-cleanup');
      if (cleanupEl) {
        cleanupEl.textContent = settings.last_cleanup
          ? 'Last cleanup: ' + settings.last_cleanup
          : 'No cleanup has run yet';
      }

      // Update consent UI visibility
      updateConsentUI();
    } catch (e) {
      console.error('VSR: Failed to load settings', e);
    }
  }

  /**
   * Collect form values and save via API.
   */
  async function saveSettings() {
    var data = {};

    // Toggles → '1' or '0'
    Object.keys(toggleFields).forEach(function (id) {
      var el = document.getElementById(id);
      if (el) data[toggleFields[id]] = el.checked ? '1' : '0';
    });

    // Value fields
    Object.keys(valueFields).forEach(function (id) {
      var el = document.getElementById(id);
      if (el) data[valueFields[id]] = el.value;
    });

    // Tag lists → arrays
    data.exclude_urls = excludeUrlsList.slice();
    data.exclude_ips  = excludeIpsList.slice();

    var statusEl = document.getElementById('vsr-save-status');
    var btn = document.getElementById('vsr-save-settings');

    try {
      btn.disabled = true;
      btn.textContent = 'Saving…';
      await VSR.post('settings', data);
      statusEl.textContent = '✓ Settings saved';
      statusEl.style.color = '#22c55e';
      setTimeout(function () { statusEl.textContent = ''; }, 3000);
    } catch (e) {
      statusEl.textContent = '✗ Save failed';
      statusEl.style.color = '#ef4444';
      console.error('VSR: Failed to save settings', e);
    } finally {
      btn.disabled = false;
      btn.textContent = 'Save Settings';
    }
  }

  // Save button
  var saveBtn = document.getElementById('vsr-save-settings');
  if (saveBtn) {
    saveBtn.addEventListener('click', saveSettings);
  }

  // Purge recordings
  var purgeRecBtn = document.getElementById('vsr-purge-recordings');
  if (purgeRecBtn) {
    purgeRecBtn.addEventListener('click', async function () {
      if (!confirm('Permanently delete ALL session recordings? This cannot be undone.')) return;
      try {
        purgeRecBtn.disabled = true;
        purgeRecBtn.textContent = 'Purging…';
        await VSR.del('replay/clear');
        alert('All recording data purged successfully.');
      } catch (e) {
        alert('Purge failed. Check console for details.');
        console.error(e);
      } finally {
        purgeRecBtn.disabled = false;
        purgeRecBtn.textContent = 'Purge Recordings';
      }
    });
  }

  // Purge stats
  var purgeStatsBtn = document.getElementById('vsr-purge-stats');
  if (purgeStatsBtn) {
    purgeStatsBtn.addEventListener('click', function () {
      alert('Statistics purge will be available in a future update.');
    });
  }

  /* ── 19b: Storage Usage ── */

  function fmtBytes(b) {
    b = parseInt(b) || 0;
    if (b < 1024)        return b + ' B';
    if (b < 1048576)     return (b / 1024).toFixed(1) + ' KB';
    if (b < 1073741824)  return (b / 1048576).toFixed(2) + ' MB';
    return (b / 1073741824).toFixed(2) + ' GB';
  }

  async function loadStorage() {
    var totalEl = document.getElementById('vsr-storage-total');
    var barsEl  = document.getElementById('vsr-storage-bars');
    if (!totalEl || !barsEl) return;

    totalEl.textContent = 'Loading…';
    barsEl.innerHTML    = '';

    try {
      var data = await VSR.get('settings/storage');
      var tables      = data.tables || [];
      var totalBytes  = data.total_bytes || 0;

      totalEl.textContent = 'Total: ' + fmtBytes(totalBytes) + ' across ' + tables.length + ' table(s)';

      if (!tables.length) {
        barsEl.innerHTML = '<div style="color:var(--vsr-muted,#888);font-size:13px;">No data found.</div>';
        return;
      }

      var html = '<table style="width:100%;border-collapse:collapse;font-size:13px;">';
      html += '<thead><tr>'
            + '<th style="text-align:left;padding:4px 8px 4px 0;color:var(--vsr-muted,#888);font-weight:500;">Table</th>'
            + '<th style="text-align:right;padding:4px 0;color:var(--vsr-muted,#888);font-weight:500;">Rows</th>'
            + '<th style="text-align:right;padding:4px 0 4px 12px;color:var(--vsr-muted,#888);font-weight:500;">Size</th>'
            + '<th style="width:35%;padding:4px 0 4px 12px;"></th>'
            + '</tr></thead><tbody>';

      tables.forEach(function (t) {
        var pct = totalBytes > 0 ? Math.max(2, Math.round((t.bytes / totalBytes) * 100)) : 0;
        html += '<tr>'
              + '<td style="padding:5px 8px 5px 0;"><code style="font-size:12px;">' + t.name + '</code></td>'
              + '<td style="text-align:right;padding:5px 0;color:var(--vsr-muted,#888);">' + (t.row_count || 0).toLocaleString() + '</td>'
              + '<td style="text-align:right;padding:5px 0 5px 12px;white-space:nowrap;">' + fmtBytes(t.bytes) + '</td>'
              + '<td style="padding:5px 0 5px 12px;">'
              + '<div style="background:var(--vsr-border,#e5e7eb);border-radius:4px;height:6px;overflow:hidden;">'
              + '<div style="background:#6366f1;height:6px;width:' + pct + '%;border-radius:4px;transition:width .4s;"></div>'
              + '</div></td>'
              + '</tr>';
      });

      html += '</tbody></table>';
      barsEl.innerHTML = html;
    } catch (e) {
      totalEl.textContent = 'Failed to load storage data.';
      console.error('VSR: storage load error', e);
    }
  }

  var refreshStorageBtn = document.getElementById('vsr-refresh-storage');
  if (refreshStorageBtn) {
    refreshStorageBtn.addEventListener('click', loadStorage);
  }

  // Init
  loadSettings();
  loadStorage();

  /* ── License Tab ─────────────────────────────────────────────────────────── */

  var licenseLoaded = false;

  var STATUS_LABELS = {
    active:   { text: 'Active',      cls: 'vsr-badge-green'  },
    inactive: { text: 'Inactive',    cls: 'vsr-badge-grey'   },
    expired:  { text: 'Expired',     cls: 'vsr-badge-red'    },
    invalid:  { text: 'Invalid Key', cls: 'vsr-badge-red'    },
    revoked:  { text: 'Revoked',     cls: 'vsr-badge-red'    },
  };

  function renderLicenseBadge(status) {
    var badge = document.getElementById('vsr-license-badge');
    if (!badge) return;
    var def = STATUS_LABELS[status] || { text: status, cls: 'vsr-badge-grey' };
    badge.textContent   = def.text;
    badge.className     = 'vsr-license-badge ' + def.cls;
  }

  function renderLicenseRows(info) {
    var rows = document.getElementById('vsr-license-rows');
    if (!rows) return;

    var pairs = [];
    if (info.key_masked)   pairs.push(['License Key',   '<code style="font-size:12px;letter-spacing:.04em;">' + esc(info.key_masked) + '</code>']);
    if (info.status)       pairs.push(['Status',        esc(info.status.charAt(0).toUpperCase() + info.status.slice(1))]);
    if (info.expires)      pairs.push(['Expires',       esc(info.expires)]);
    else if (info.status === 'active') pairs.push(['Expires', 'Lifetime / no expiry']);
    if (info.domain)       pairs.push(['Registered Domain', esc(info.domain)]);
    if (info.file_count)   pairs.push(['Premium Files',     info.file_count + ' files active on disk']);
    if (info.activated_at) pairs.push(['Activated',         esc(info.activated_at)]);

    if (!pairs.length) {
      rows.innerHTML = '<p style="color:#6b7280;font-size:13px;margin:0;">No license activated yet.</p>';
      return;
    }

    rows.innerHTML = pairs.map(function(p) {
      return '<div class="vsr-setting-row" style="padding:8px 0;border-bottom:1px solid #f3f4f6;">'
        + '<div class="vsr-setting-info"><div class="vsr-setting-label" style="font-size:13px;">' + p[0] + '</div></div>'
        + '<div style="font-size:13px;color:#374151;">' + p[1] + '</div>'
        + '</div>';
    }).join('');
  }

  function renderLicenseActions(info) {
    var actions = document.getElementById('vsr-license-actions');
    if (!actions) return;
    actions.innerHTML = '';

    var fs = vlensAdmin.hasFreemius;
    var accountUrl = vlensAdmin.freemiusAccountUrl || '';

    if (info.status === 'active') {
      // Re-download button
      var btnRe = document.createElement('button');
      btnRe.className = 'button';
      btnRe.textContent = 'Re-download Files';
      btnRe.addEventListener('click', function () { doRedownload(btnRe); });
      actions.appendChild(btnRe);

      // Deactivate button
      var btnDe = document.createElement('button');
      btnDe.className = 'button';
      btnDe.style.color = '#b91c1c';
      btnDe.textContent = 'Deactivate License';
      btnDe.addEventListener('click', function () { doDeactivate(btnDe); });
      actions.appendChild(btnDe);

    } else {
      // Activate via Freemius button (if pro plugin is installed)
      if (fs && accountUrl) {
        var btnAct = document.createElement('a');
        btnAct.className   = 'button button-primary';
        btnAct.href        = accountUrl;
        btnAct.textContent = 'Activate License';
        actions.appendChild(btnAct);
      }

      // Show how-to card if Freemius not loaded
      var helpCard = document.getElementById('vsr-license-help-card');
      if (helpCard && !fs) {
        helpCard.style.display = '';
      }
    }
  }

  function setLicenseMsg(msg, isError) {
    var el = document.getElementById('vsr-license-msg');
    if (!el) return;
    el.textContent = msg;
    el.style.color = isError ? '#b91c1c' : '#059669';
  }

  function loadLicenseStatus() {
    // Use data preloaded in vlensAdmin if available, then refresh via REST
    var preloaded = (vlensAdmin.license && vlensAdmin.license.status) ? vlensAdmin.license : null;
    if (preloaded && !licenseLoaded) {
      renderLicenseBadge(preloaded.status);
      renderLicenseRows(preloaded);
      renderLicenseActions(preloaded);
      licenseLoaded = true;
    }

    // Always refresh from REST for up-to-date state
    VSR.get('license/status').then(function (info) {
      renderLicenseBadge(info.status);
      renderLicenseRows(info);
      renderLicenseActions(info);
      licenseLoaded = true;
    }).catch(function () {
      if (!licenseLoaded) {
        setLicenseMsg('Could not load license status. Please refresh the page.', true);
      }
    });
  }

  function doRedownload(btn) {
    btn.disabled = true;
    btn.textContent = 'Downloading…';
    setLicenseMsg('', false);

    VSR.post('license/redownload', {}).then(function (res) {
      btn.disabled    = false;
      btn.textContent = 'Re-download Files';
      if (res.success) {
        setLicenseMsg('Files downloaded successfully. Please reload the page to activate premium features.', false);
        loadLicenseStatus();
      } else {
        setLicenseMsg(res.message || 'Re-download failed.', true);
      }
    }).catch(function () {
      btn.disabled    = false;
      btn.textContent = 'Re-download Files';
      setLicenseMsg('Network error. Please try again.', true);
    });
  }

  function doDeactivate(btn) {
    if (!confirm('Deactivate your license? Premium files will be removed from this site.')) return;
    btn.disabled    = true;
    btn.textContent = 'Deactivating…';
    setLicenseMsg('', false);

    VSR.post('license/deactivate', {}).then(function (res) {
      if (res.success) {
        setLicenseMsg('License deactivated. Premium files have been removed.', false);
        loadLicenseStatus();
      } else {
        btn.disabled    = false;
        btn.textContent = 'Deactivate License';
        setLicenseMsg(res.message || 'Deactivation failed.', true);
      }
    }).catch(function () {
      btn.disabled    = false;
      btn.textContent = 'Deactivate License';
      setLicenseMsg('Network error. Please try again.', true);
    });
  }

  function esc(str) {
    return String(str)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;');
  }

  // Load when License tab is clicked
  document.querySelectorAll('.vsr-tab').forEach(function (tab) {
    if (tab.getAttribute('data-tab') === 'license') {
      tab.addEventListener('click', function () {
        loadLicenseStatus();
      });
    }
  });

  // Pre-load if URL hash says #license
  if (window.location.hash === '#license') {
    var licTab = document.querySelector('[data-tab="license"]');
    if (licTab) licTab.click();
  }

})();
