(() => {
  'use strict';

  function pageState(frame, descriptor) {
    if (!descriptor || descriptor.kind !== 'elementor' || !Number(descriptor.post_id) || !descriptor.edit_url) return null;
    try {
      const expected = new URL(descriptor.edit_url, window.location.origin);
      const actual = new URL(frame.contentWindow.location.href, window.location.origin);
      if (
        expected.origin !== window.location.origin
        || actual.origin !== expected.origin
        || actual.pathname !== expected.pathname
        || actual.searchParams.get('post') !== String(descriptor.post_id)
        || actual.searchParams.get('action') !== 'elementor'
      ) return null;
      return {
        kind: 'elementor',
        post_id: Number(descriptor.post_id),
        title: String(descriptor.title || ''),
        path: actual.pathname,
        ready: true,
        dirty: false,
        state_hash: '',
      };
    } catch (_) {
      return null;
    }
  }

  function isTerminalResult(result) {
    return ['completed', 'failed', 'denied', 'recovery_required'].includes(String(result?.status || ''));
  }

  function shouldResumePolling(isElementorCommand, result) {
    return !isElementorCommand || isTerminalResult(result);
  }

  window.wpagentlyLiveEditorElementor = { pageState, isTerminalResult, shouldResumePolling };
})();
