/**
 * 宿主（父窗口）与子端（iframe）之间的桥接创建。
 * - 绑定 iframe 元素，暴露宿主方法给子端调用
 * - 返回 child Promise（解析为子端暴露的方法）与 destroy 销毁函数
 */
import { connectToChild } from 'penpal';
import type { HostApi, ChildApi } from './types.js';
import { log } from './logger.js';

/** Establish Penpal host bridge bound to an iframe and expose Host API to child. */
/**
 * 建立宿主侧 Penpal 桥接并暴露 HostApi。
 * @param params.iframe 目标 iframe 元素
 * @param params.origin 可选，子端 origin（默认当前 window.location.origin）
 * @param params.methods 宿主暴露给子端的方法集合
 * @returns `{ child, destroy }`
 *   - `child`: Promise<ChildApiResolved>，解析后可直接调用子端暴露的方法（如 changeLanguage）
 *   - `destroy`: 断开连接与清理监听器
 */
export function createPenpalHostBridge(params: {
  iframe: HTMLIFrameElement;
  origin?: string;
  methods: HostApi;
}) {
  const childOrigin = params.origin ?? window.location.origin;
  log('createPenpalHostBridge() start', { childOrigin });
  const connection = connectToChild<ChildApi>({ iframe: params.iframe, childOrigin, methods: params.methods as any });
  connection.promise
    .then(() => log('createPenpalHostBridge() child connected'))
    .catch((err) => log('createPenpalHostBridge() connect error', err));
  return {
    child: connection.promise,
    destroy: () => {
      log('createPenpalHostBridge() destroy');
      return connection.destroy?.();
    },
  };
}