import type { View } from "../pages/registry";
import {
  SDK_CHANNEL,
  SDK_VERSION,
  type HostMessage,
  type HostSharedState,
  type PageLifecyclePhase,
} from "./protocol";

export function sendState(target: Window, state: HostSharedState): void {
  send(target, {
    channel: SDK_CHANNEL,
    version: SDK_VERSION,
    source: "host",
    type: "state",
    state,
  });
}

export function sendLifecycle(target: Window, phase: PageLifecyclePhase): void {
  send(target, {
    channel: SDK_CHANNEL,
    version: SDK_VERSION,
    source: "host",
    type: "lifecycle",
    phase,
  });
}

export function pageUrl(view: View, instance: number): string {
  const url = new URL("/page.html", window.location.origin);
  url.searchParams.set("view", view);
  url.searchParams.set("instance", instance.toString());
  return `${url.pathname}${url.search}`;
}

function send(target: Window, message: HostMessage): void {
  target.postMessage(message, window.location.origin);
}
