import { WSClient } from "./modules/zJsWebSocketClient.js";

// Affichage de la page en cours ou par défaut, de la page d'accueil
var page = sessionStorage.getItem('Splendor');
if(!page) { page = 'lobby.php' }

const mainFrame =  document.getElementById("mainFrame")
mainFrame.setAttribute('title', "Splendor");
mainFrame.setAttribute('src', `./pages/${page}`);

// Connexion au WebSocket Serveur
const ws = new WSClient('ws://127.0.0.1:8002');

const knownIframes = new Set();       // ↙︎ iframes qui nous parlent
const statusSubscribers = new Set();  // ↙︎ iframes qui veulent les statuts

function broadcastStatus(status) {
  for (const frame of statusSubscribers) {
    frame.postMessage({ action: "ws-status", payload: { status } }, "*");
  }
}

/* 1️⃣  Intercepter les demandes des iframes */
window.addEventListener("message", (event) => {
	//console.log(event);
	
	const { source, data } = event;
	if (!data || typeof data !== "object") return;
	const { action, payload } = data;

	knownIframes.add(source); // note : on pourrait vérifier event.origin ici

	switch (action) {
		case "ws-status-subscribe":
			statusSubscribers.add(source);          // l’iframe veut les statuts
			source.postMessage(                     // on lui envoie l’état courant tout de suite
				{ action: "ws-status", payload: { status: ws.isOpen ? "open" : "closed" } }, "*"
			);
			break;

		case "ws-status-unsubscribe":
			statusSubscribers.delete(source);
			break;

   	case "ws-send":
      	ws.send(payload.type, payload.payload);
			break;

		case "ws-subscribe":
			// Subscribe et redirige les messages à l’iframe
			ws.on(payload.type, (data) => {
				source.postMessage({ action: "ws-message", payload: { type: payload.type, data } }, "*");
			});
			break;

		case "ws-unsubscribe":
			ws.off(payload.type);
			break;

	}
});

/* 2️⃣  Relayer les changements d’état du WS */
ws.onOpen(() => broadcastStatus("open"));
ws.onClose(() => broadcastStatus("closed"));
ws.onError(() => broadcastStatus("error"));
ws.onReconnecting?.(() => broadcastStatus("reconnecting")); // si implémenté