/**
 * AtomX Bridge — integração completa MotionVault ↔ AtomX
 * 
 * AtomX roda em iframe oculto com seu próprio CSInterface.
 * MotionVault manda comandos via postMessage. Zero modificação no AtomX.
 */
(function() {
  'use strict';
  console.log('[AtomX Bridge] 🚀 Starting...');

  var bridge = { iframe: null, ready: false, _queue: [] };
  window._atomxBridge = bridge;

  window.addEventListener('message', function(e) {
    if (e.data && e.data.type === 'ATOMX_READY') {
      console.log('[AtomX Bridge] ✅ AtomX engine ready');
      bridge.ready = true;
      while (bridge._queue.length) { bridge._queue.shift()(); }
    }
  });

  // Hidden iframe with full AtomX
  var iframe = document.createElement('iframe');
  iframe.src = 'atomx/index.html';
  Object.assign(iframe.style, { display:'none', position:'absolute', left:'-9999px', width:'400px', height:'400px', border:'0' });
  iframe.onload = function() { console.log('[AtomX Bridge] iframe loaded'); };
  document.body.appendChild(iframe);
  bridge.iframe = iframe;

  // Public API
  window.applyAtomxAssetViaBridge = function(item) {
    console.log('[AtomX Bridge] apply:', item && item.atomxasset_path);
    if (!item || !item.atomxasset_path) return false;
    if (!bridge.iframe) { console.error('[AtomX Bridge] ❌ no iframe'); return false; }

    var msg = {
      source: 'motionvault',
      type: 'MV_APPLY',
      file: item.atomxasset_path,
      subType: item.subType || '',
      name: item.name || '',
      packprint: item.packprint || ''
    };

    function send() {
      try { bridge.iframe.contentWindow.postMessage(msg, '*'); }
      catch(e) { console.error('[AtomX Bridge] postMessage error:', e); }
    }

    if (bridge.ready) send();
    else bridge._queue.push(send);

    return true; // Accepted
  };
})();
