// UES Python <-> JS Bridge Interface
class BackendBridge {
  constructor() {
    this.ready = false;
    this.eventListeners = {};
    
    const onReady = () => {
      if (this.ready) return;
      this.ready = true;
      console.log('⚡ pywebview Bridge Connected Successfully');
      if (window.app) {
        window.app.initBackendState();
      }
    };

    if (window.pywebview && window.pywebview.api) {
      onReady();
    } else {
      window.addEventListener('pywebviewready', onReady);
    }

    // Global listener for Python push events
    window.onBackendEvent = (eventName, payload) => {
      const handlers = this.eventListeners[eventName] || [];
      handlers.forEach(fn => fn(payload));
    };
  }

  on(eventName, callback) {
    if (!this.eventListeners[eventName]) {
      this.eventListeners[eventName] = [];
    }
    this.eventListeners[eventName].push(callback);
  }

  async call(methodName, ...args) {
    // If not ready, wait briefly for bridge to mount
    if (!window.pywebview || !window.pywebview.api) {
      for (let i = 0; i < 20; i++) {
        await new Promise(r => setTimeout(r, 100));
        if (window.pywebview && window.pywebview.api) break;
      }
    }

    if (!window.pywebview || !window.pywebview.api) {
      return { success: false, message: 'Bridge connecting... Please try again in 1 second.' };
    }

    try {
      const fn = window.pywebview.api[methodName];
      if (typeof fn === 'function') {
        const res = await fn(...args);
        return res;
      } else {
        console.error(`Bridge method ${methodName} not found.`);
        return { success: false, message: `Method ${methodName} not found on backend.` };
      }
    } catch (e) {
      console.error(`Error calling bridge method ${methodName}:`, e);
      return { success: false, message: e.toString() };
    }
  }
}

window.bridge = new BackendBridge();
