import { createSignal, onCleanup, onMount } from "solid-js";
import type { View } from "../lib/model";
import { isHostMessage, type HostSharedState, type PageCommand } from "../sdk/protocol";
import { notifyReady, sendCommand } from "../sdk/page";

/**
 * Connects one iframe document to the persistent Host Shell.
 *
 * The listener and state belong to the iframe's Solid owner. Navigating or
 * removing the iframe runs `onCleanup`, so the old document cannot continue to
 * receive Host snapshots.
 */
export function createFrameBridge(view: View) {
  const [state, setState] = createSignal<HostSharedState | null>(null);

  const receive = (event: MessageEvent<unknown>) => {
    if (event.origin !== window.location.origin || event.source !== window.parent) return;
    if (!isHostMessage(event.data)) return;
    if (event.data.type === "state" && event.data.state.view === view) {
      setState(event.data.state);
    }
    if (event.data.type === "dispose") {
      window.dispatchEvent(new Event("wasmeld:dispose"));
    }
  };

  onMount(() => {
    window.addEventListener("message", receive);
    notifyReady(view);
  });

  onCleanup(() => window.removeEventListener("message", receive));

  return {
    state,
    command(command: PageCommand) {
      sendCommand(view, command);
    },
  };
}
