// Exercise 2: cleanup ordering — subscribing to a changing prop
//
// `ChatRoom` subscribes to a room by id. When `roomId` changes, the OLD
// subscription must be cleaned up BEFORE the new one is created — that's
// what the returned cleanup function guarantees automatically. Implement
// the fake `subscribeToRoom`/cleanup wiring and a pure log-order tracker
// so the self-check can verify cleanup-then-resubscribe ordering.
//
// TODO 1: implement subscribeToRoom(roomId, onLog) — returns an unsubscribe
//         function; call onLog(`subscribed:${roomId}`) on subscribe and
//         onLog(`unsubscribed:${roomId}`) inside the returned unsubscribe
// TODO 2: wire the effect in ChatRoom to call subscribeToRoom and return
//         its unsubscribe function as cleanup, depending on [roomId]

import { useEffect, useState } from "react";

function subscribeToRoom(roomId: string, onLog: (entry: string) => void): () => void {
  // TODO 1: log "subscribed:<roomId>" now, return a function that logs
  // "unsubscribed:<roomId>" when called.
  return () => {};
}

function ChatRoom({ roomId }: { roomId: string }) {
  useEffect(() => {
    // TODO 2: subscribe, return the unsubscribe function as cleanup
  }, [roomId]);

  return <p>Room: {roomId}</p>;
}

export { ChatRoom, subscribeToRoom };

// --- self-check: do not modify below this line ---
// Simulates React switching roomId from "general" to "random": it must
// unsubscribe "general" BEFORE subscribing "random" — never the reverse,
// and never both subscribed at once.
const log: string[] = [];
const unsubGeneral = subscribeToRoom("general", (e) => log.push(e));
unsubGeneral(); // React calls cleanup for "general" before running the new effect
const unsubRandom = subscribeToRoom("random", (e) => log.push(e));

const expected = ["subscribed:general", "unsubscribed:general", "subscribed:random"];
const pass = JSON.stringify(log) === JSON.stringify(expected);
console.log(pass ? "PASS (cleanup-before-resubscribe order)" : "FAIL (cleanup-before-resubscribe order)");
console.log("got:", log);

// Verify visually: mount <ChatRoom roomId="general" />, then change the
// roomId prop to "random" (e.g. via a button that calls setRoomId). Add
// console.logs inside subscribeToRoom's subscribe/unsubscribe — you should
// see "unsubscribed:general" logged BEFORE "subscribed:random", proving
// React runs the previous effect's cleanup before the next effect's setup.
