/**
 * Dollie Activity Tracker
 *
 * Captures WordPress admin page context and user clicks, broadcasting them
 * as CustomEvent('dollie-agent') for the Chrome extension content script.
 *
 * Tracks: current page context, clicks on interactive elements.
 */
(function () {
  'use strict';

  if (typeof window.dollieActivityConfig === 'undefined') {
    return;
  }

  var config = window.dollieActivityConfig;

  // Prevent double-init
  if (window.__dollieActivityTrackerLoaded) {
    return;
  }
  window.__dollieActivityTrackerLoaded = true;

  // ---------------------------------------------------------------------------
  // Helpers
  // ---------------------------------------------------------------------------

  function dispatch(event) {
    window.postMessage({ source: 'dollie-activity', payload: event }, '*');
  }

  function buildEvent(type, category, label, meta) {
    return {
      type: type,
      category: category,
      label: label,
      url: window.location.href,
      adminPage: config.pagenow || '',
      meta: meta || {},
      timestamp: Date.now(),
    };
  }

  // ---------------------------------------------------------------------------
  // 1. Page context — tell the agent where the user is
  // ---------------------------------------------------------------------------

  dispatch(buildEvent('navigation', 'navigation', 'Navigated to: ' + config.pagenow, {
    page: config.pagenow,
    title: document.title,
  }));

  // ---------------------------------------------------------------------------
  // 2. Click tracking — capture clicks on interactive elements
  // ---------------------------------------------------------------------------

  document.addEventListener('click', function (e) {
    // Walk up from click target to find the nearest interactive element (max 5 levels)
    var clickable = null;
    var el = e.target;
    for (var i = 0; i < 5 && el; i++) {
      if (el.matches && el.matches('a, button, [role="button"], input[type="submit"]')) {
        clickable = el;
        break;
      }
      el = el.parentElement;
    }

    if (!clickable) {
      return;
    }

    // Get button/link text
    var text = '';
    if (clickable.tagName === 'INPUT') {
      text = clickable.value || '';
    } else {
      text = clickable.textContent || '';
    }
    text = text.trim().replace(/\s+/g, ' ').substring(0, 120);

    if (!text) {
      return;
    }

    var href = clickable.getAttribute('href') || '';

    // Find nearest semantic context (what section of the page was clicked)
    var context = '';
    var contextEl = clickable.closest(
      '#adminmenu, #wpadminbar, .wrap, .edit-post-header, .interface-interface-skeleton__header, ' +
      '#wpbody-content, .row-actions, .tablenav, .postbox'
    );
    if (contextEl) {
      if (contextEl.id) {
        context = '#' + contextEl.id;
      } else {
        context = contextEl.className
          ? '.' + contextEl.className.split(' ')[0]
          : contextEl.tagName.toLowerCase();
      }
    }

    dispatch(buildEvent('click', 'interaction', 'Clicked: ' + text, {
      text: text,
      href: href,
      tagName: clickable.tagName.toLowerCase(),
      id: clickable.id || undefined,
      context: context || undefined,
    }));
  }, true);
})();
