"use client";

import { useEffect, useState } from "react";

export function useSingleTabGuard() {
  const [blocked, setBlocked] = useState(false);
  const channel = new BroadcastChannel("makanify_tab_channel");

  useEffect(() => {
    channel.onmessage = (event) => {
      if (event.data === "active") {
        setBlocked(true);
      }
      if (event.data === "takeover") {
        // Another tab has taken control, so block this one
        setBlocked(true);
      }
    };

    // Announce self as active when opening
    channel.postMessage("active");

    return () => {
      channel.close();
    };
  }, []);

  const takeover = () => {
    channel.postMessage("takeover");
    window.location.reload(); // Reload to claim session
  };

  return { blocked, takeover };
}
