/*
  --------------------------------------------------------------------------
  PRIMEBRIDGE LIVE NOTIFICATION ENGINE v6
  --------------------------------------------------------------------------
  Refactored to use PrimeBridge utility modules:
    - PrimeBridge.random   for random selections
    - PrimeBridge.time     for time formatting
    - PrimeBridge.modal    for modal dialogs
  Exports controlled API via PrimeBridge.notifications for engine.js
  --------------------------------------------------------------------------
*/

(function () {
  'use strict';

  /* ------------------------------------------------------------------ */
  /*  DOM References                                                     */
  /* ------------------------------------------------------------------ */

  var liveLeft = document.getElementById('liveLeft');
  var liveRight = document.getElementById('liveRight');

  if (!liveLeft || !liveRight) {
    console.error('PrimeBridge Live Engine failed to initialize.');
    return;
  }

  /* ------------------------------------------------------------------ */
  /*  Internal State                                                     */
  /* ------------------------------------------------------------------ */

  var currentSide = 'left';
  var _intervalId = null;

  /* ------------------------------------------------------------------ */
  /*  AVATAR COLOR MAP                                                   */
  /* ------------------------------------------------------------------ */

  var AVATAR_COLORS = {
    deposit: '#10b981',
    withdrawal: '#ef4444',
    registration: '#f59e0b',
    managedPortfolio: '#8b5cf6',
    selfTrading: '#06b6d4',
    sectors: '#ec4899',
    capitalInstruments: '#eab308',
    bonus: '#f97316'
  };

  function _getInitial(name) {
    return (name || 'C').charAt(0).toUpperCase();
  }

  function _avatarSvg(name, type) {
    var color = AVATAR_COLORS[type] || '#6366f1';
    var initial = _getInitial(name);
    return '<svg width="28" height="28" viewBox="0 0 28 28" xmlns="http://www.w3.org/2000/svg" ' +
      'style="flex-shrink:0;border-radius:50%">' +
      '<circle cx="14" cy="14" r="14" fill="' + color + '" opacity="0.85"/>' +
      '<text x="14" y="14" text-anchor="middle" dominant-baseline="central" fill="white" ' +
      'font-family="Inter,-apple-system,sans-serif" font-weight="700" font-size="12">' +
      initial + '</text></svg>';
  }

  /* ------------------------------------------------------------------ */
  /*  CREATE LIVE NOTIFICATION CARD                                      */
  /* ------------------------------------------------------------------ */

  function createLiveNotification(data) {
    var card = document.createElement('div');
    card.className = 'live-notification';

    card.innerHTML =
      _avatarSvg(data.user, data.type) +
      '<div class="live-content">' +
        '<div class="live-name">' + (data.user || 'Client') + '</div>' +
        '<div class="live-title">' + (data.title || 'Transaction') + '</div>' +
        '<div class="live-meta">' +
          '<span class="live-country">' + (data.meta || '') + '</span>' +
          '<span class="live-time" data-ts="' + Date.now() + '">' +
            PrimeBridge.time.timeAgo(Date.now()) +
          '</span>' +
        '</div>' +
      '</div>';

    /* -- Open modal on click (dedup: one click per card) -- */
    card.addEventListener('click', function () {
      if (card.getAttribute('data-modal-opened')) return;
      card.setAttribute('data-modal-opened', '1');
      // Augment data for the polished modal layout
      data.fullName = data.fullName || data.user || (data.title ? data.title.split(/ deposited| withdrew| registered| activated| invested| purchased| received| went/)[0] : '') || 'Unknown User';
      data.timeAgo = data.timeAgo || PrimeBridge.time.timeAgo(Date.now());
      data.country = data.country || data.flag || '';
      data.amount = data.amount || (data.title ? data.title.match(/\$[\d,]+/)?.[0] : '') || '';
      PrimeBridge.modal.setTitle(data.modalTitle || 'Live Transaction');
      PrimeBridge.modal.renderTransaction(data);
      PrimeBridge.modal.open();
    });

    /* -- Alternating sides -- */
    var container = currentSide === 'left' ? liveLeft : liveRight;

    /* -- Max 3 cards per column (legacy pattern) -- */
    if (container.children.length >= 3) {
      container.firstChild.remove();
    }

    container.appendChild(card);
    currentSide = (currentSide === 'left') ? 'right' : 'left';

    /* -- Auto-remove after 6.5s -- */
    setTimeout(function () {
      card.style.opacity = '0';
      card.style.transform = 'translateY(-12px) scale(.96)';
      setTimeout(function () {
        card.remove();
      }, 350);
    }, 6500);
  }

  /* ------------------------------------------------------------------ */
  /*  OPEN TRANSACTION MODAL (delegates to PrimeBridge.modal)            */
  /* ------------------------------------------------------------------ */

  function openTxnModal(data) {
    var contentHtml =
      '<div class="txn-user-wrap">' +
        _avatarSvg(data.user, data.type) +
        '<div>' +
          '<div class="txn-user">' + data.user + '</div>' +
          '<div class="txn-sub">' + data.country + '</div>' +
        '</div>' +
      '</div>' +
      '<div class="txn-grid">' +
        '<div class="txn-box">' +
          '<span>Amount</span>' +
          '<b>' + data.amount + '</b>' +
        '</div>' +
        '<div class="txn-box">' +
          '<span>Method</span>' +
          '<b>' + data.method + '</b>' +
        '</div>' +
      '</div>' +
      '<div class="txn-status">' + data.status + '</div>';

    PrimeBridge.modal.open(contentHtml, data.modalTitle || 'Live Transaction');
  }

  /* ------------------------------------------------------------------ */
  /*  CLOSE MODAL (backward-compatible delegate)                         */
  /* ------------------------------------------------------------------ */

  window.closeTxnModal = function (event) {
    if (event && event.target && event.target.id !== 'txnModal') return;
    PrimeBridge.modal.close();
  };

  /* ------------------------------------------------------------------ */
  /*  LIVE FEED CONTROLS                                                 */
  /* ------------------------------------------------------------------ */

  function startLiveFeed() {
    if (_intervalId) return;

    var weightedTypes = [
      'deposit', 'deposit', 'deposit', 'deposit', 'deposit',
      'withdrawal', 'withdrawal', 'withdrawal', 'withdrawal',
      'registration', 'registration',
      'managedPortfolio',
      'selfTrading',
      'sectors',
      'capitalInstruments', 'capitalInstruments',
      'bonus', 'bonus'
    ];

    /**
     * Generate the next interval with traffic-wave timing.
     * Creates natural bursts and pauses instead of fixed rhythm.
     * Examples: 8s, 12s, 45s, 21s, 90s, 17s
     */
    function _nextInterval() {
      var roll = Math.random();
      if (roll < 0.25) {
        // Burst phase — rapid activity (1.5-5.5s)
        return Math.floor(Math.random() * 4000 + 1500);
      } else if (roll < 0.85) {
        // Normal phase (5-17s)
        return Math.floor(Math.random() * 12000 + 5000);
      } else {
        // Quiet phase — lull in activity (20-90s)
        return Math.floor(Math.random() * 70000 + 20000);
      }
    }

    /**
     * Single tick — create one notification, schedule the next.
     */
    function _tick() {
      var eventType = PrimeBridge.random.pickWeighted(weightedTypes);
      var eventData = PrimeBridge.generator.composeEvent(eventType);
      // Run through event-guard for validation + auto-repair
      if (PrimeBridge.eventGuard) {
        eventData = PrimeBridge.eventGuard.guard(eventData);
      }
      createLiveNotification(eventData);
      _intervalId = setTimeout(_tick, _nextInterval());
    }

    // Start the feed with the first tick
    _intervalId = setTimeout(_tick, _nextInterval());
  }

  function stopLiveFeed() {
    if (_intervalId) {
      clearTimeout(_intervalId);
      _intervalId = null;
    }
  }

  /* ------------------------------------------------------------------ */
  /*  EXPORT API                                                         */
  /* ------------------------------------------------------------------ */

  window.PrimeBridge = window.PrimeBridge || {};
  PrimeBridge.notifications = {
    createCard: createLiveNotification,
    startFeed: startLiveFeed,
    stop: stopLiveFeed,
    isRunning: function () {
      return _intervalId !== null;
    }
  };

  /* ------------------------------------------------------------------ */
  /*  AUTO-START with random 10-20s delay for realistic feel             */
  /* ------------------------------------------------------------------ */

  // Don't start immediately — users need time to read the page first.
  // Random delay between 10 and 20 seconds creates a natural feel.
  var delay = PrimeBridge.random ? PrimeBridge.random.randomInt(10000, 20000) : 12000;
  setTimeout(startLiveFeed, delay);

  // Refresh time labels every 30s for realistic time progression
  // "just now" → "1 min ago" → "2 mins ago" → "5 mins ago"
  setInterval(function () {
    var timeEls = document.querySelectorAll('.live-time[data-ts]');
    for (var i = 0; i < timeEls.length; i++) {
      var el = timeEls[i];
      var ts = parseInt(el.getAttribute('data-ts'), 10);
      if (ts) {
        el.textContent = PrimeBridge.time.timeAgo(ts);
      }
    }
  }, 30000);
})();
