import { useEffect } from "react";
import { log } from "../util/logger";
import { routeMessage } from "../util/postMessage";

export function usePostMessage() {
  useEffect(() => {
    const handler = (event: MessageEvent) => {
      log("Received postMessage:", event.data);
      const response = routeMessage(event.data);
      window.parent?.postMessage(response, "*");
    };
    window.addEventListener("message", handler);
    return () => {
      window.removeEventListener("message", handler);
    };
  }, []);
}
