/* =========================================================
   A&B HUB — Phase 2 AJAX helpers
   Loaded on every authenticated page (see layouts/app.php).
   ========================================================= */
(function () {
  "use strict";

  function csrfToken() {
    var meta = document.querySelector('meta[name="csrf-token"]');
    return meta ? meta.getAttribute('content') : '';
  }

  /**
   * abFetch(url, { method, body, ... }) -> Promise<data>
   * - Automatically sends the CSRF token on state-changing requests.
   * - Automatically JSON-encodes a plain object body.
   * - Rejects with the parsed error envelope on !success so callers can
   *   do `.catch(err => abToast(err.message, 'danger'))`.
   */
  window.abFetch = function (url, options) {
    options = options || {};
    var method = (options.method || 'GET').toUpperCase();
    var headers = Object.assign({ 'X-Requested-With': 'XMLHttpRequest' }, options.headers || {});

    if (method !== 'GET' && method !== 'HEAD') {
      headers['X-CSRF-Token'] = csrfToken();
    }

    var body = options.body;
    if (body && typeof body === 'object' && !(body instanceof FormData)) {
      headers['Content-Type'] = 'application/json';
      body = JSON.stringify(body);
    }

    return fetch(url, {
      method: method,
      headers: headers,
      body: method === 'GET' || method === 'HEAD' ? undefined : body,
      credentials: 'same-origin'
    }).then(function (response) {
      return response.json().then(function (data) {
        if (!response.ok || data.success === false) {
          return Promise.reject(data);
        }
        return data;
      });
    });
  };

  /** Renders a small array of field->messages into inline `.invalid-feedback` siblings for a given form element. */
  window.abShowFormErrors = function (formEl, errors) {
    formEl.querySelectorAll('.is-invalid').forEach(function (el) { el.classList.remove('is-invalid'); });
    formEl.querySelectorAll('.invalid-feedback').forEach(function (el) { el.remove(); });

    Object.keys(errors || {}).forEach(function (field) {
      var input = formEl.querySelector('[name="' + field + '"]');
      if (!input) return;
      input.classList.add('is-invalid');
      var msg = document.createElement('div');
      msg.className = 'invalid-feedback d-block';
      msg.textContent = Array.isArray(errors[field]) ? errors[field][0] : errors[field];
      input.insertAdjacentElement('afterend', msg);
    });
  };

  /** Loads the notification bell dropdown contents — called once on page load. */
  function loadNotifications() {
    var list = document.getElementById('abNotifList');
    if (!list) return;

    abFetch('/api/v1/notifications?limit=8').then(function (res) {
      var rows = res.data.rows || [];
      if (rows.length === 0) {
        list.innerHTML = '<div class="p-3 text-center small ab-text-muted">You\'re all caught up.</div>';
        return;
      }

      list.innerHTML = rows.map(function (n) {
        var unreadStyle = n.is_read == 0 ? ' style="background:var(--ab-primary-100);"' : '';
        return '<div class="ab-notif-item"' + unreadStyle + '>' +
          '<div class="ab-notif-icon bg-primary-soft ab-badge"><i class="bi bi-bell"></i></div>' +
          '<div><p>' + n.title + '</p><small>' + n.message + '</small></div>' +
          '</div>';
      }).join('');
    }).catch(function () {
      list.innerHTML = '<div class="p-3 text-center small ab-text-muted">Could not load notifications.</div>';
    });
  }

  /** Debounced global search — leads/customers/companies, rendered as a grouped dropdown under the topbar search box. */
  function initGlobalSearch() {
    var input = document.getElementById('abGlobalSearchInput');
    var results = document.getElementById('abGlobalSearchResults');
    if (!input || !results) return;

    var debounceTimer = null;

    function renderGroup(title, items, urlBase) {
      if (!items.length) return '';
      var rows = items.map(function (item) {
        var sub = item.email || item.phone || item.industry || '';
        return '<a class="dropdown-item small" href="' + urlBase + '/' + item.id + '">' +
          '<strong>' + item.label + '</strong>' + (sub ? '<div class="ab-cell-sub">' + sub + '</div>' : '') + '</a>';
      }).join('');
      return '<h6 class="dropdown-header">' + title + '</h6>' + rows;
    }

    input.addEventListener('input', function () {
      var query = input.value.trim();
      clearTimeout(debounceTimer);

      if (query.length < 2) {
        results.style.display = 'none';
        return;
      }

      debounceTimer = setTimeout(function () {
        abFetch('/search?q=' + encodeURIComponent(query)).then(function (res) {
          var html = renderGroup('Leads', res.data.leads, '/leads') +
            renderGroup('Customers', res.data.customers, '/customers') +
            renderGroup('Companies', res.data.companies, '/companies');

          if (!html) {
            html = '<div class="p-3 text-center small ab-text-muted">No matches for "' + query + '"</div>';
          }
          results.innerHTML = html;
          results.style.display = 'block';
        }).catch(function () { results.style.display = 'none'; });
      }, 300); // debounced — avoids firing a query on every keystroke
    });

    document.addEventListener('click', function (e) {
      if (!results.contains(e.target) && e.target !== input) {
        results.style.display = 'none';
      }
    });
  }

  document.addEventListener('DOMContentLoaded', function () {
    loadNotifications();
    initGlobalSearch();

    var markAllLink = document.getElementById('abMarkAllReadLink');
    if (markAllLink) {
      markAllLink.addEventListener('click', function (e) {
        e.preventDefault();
        abFetch('/api/v1/notifications/read-all', { method: 'POST' }).then(function () {
          var badge = document.getElementById('abNotifBadge');
          if (badge) badge.remove();
          loadNotifications();
        });
      });
    }
  });
})();
