"use client";

import { useEffect } from "react";
import { useRouter } from "@/i18n/routing";
import type { CafeNotification } from "@/lib/api/notifications";
import { permissionsOf } from "@/lib/permissions";
import { useAuthStore } from "@/lib/stores/auth.store";

type RoutableNotification = Pick<CafeNotification, "type" | "referenceId">;

/** Fired when a toast/desktop notification is clicked; the bridge below navigates. */
export const OPEN_NOTIFICATION_EVENT = "meezi:open-notification";

/**
 * The in-panel page a notification should open (locale-agnostic path), or null
 * when there's nothing actionable to open (e.g. a platform broadcast — show its
 * text instead). Permission-aware: a new-order alert sends a kitchen user to the
 * KDS, a cashier to the POS, and a floor user to the tables board — never to a
 * page their role can't open (which the route guard would just block).
 */
export function resolveNotificationDestination(
  n: RoutableNotification,
  permissions: Set<string> | null
): string | null {
  const can = (p: string) => permissions === null || permissions.has(p);

  // Best available "live orders" surface for this user.
  const orderPage = (): string | null =>
    can("ViewKitchen") ? "/kds"
      : can("ProcessOrders") ? "/pos"
      : can("ViewTables") ? "/tables"
      : null;

  switch (n.type) {
    case "table_call_waiter":
      return can("ViewTables") ? "/tables" : null;
    case "guest_order_new":
    case "guest_order_ready":
      return orderPage();
    case "platform_broadcast":
      return null; // announcement — no page to open
    default:
      if (n.type.startsWith("guest_order")) return orderPage();
      if (n.type.includes("table")) return can("ViewTables") ? "/tables" : null;
      return null;
  }
}

/** Resolve the destination using the current user's permissions from the store.
 *  Safe to call outside React render (e.g. inside a SignalR/toast callback). */
export function notificationDestinationFromStore(n: RoutableNotification): string | null {
  return resolveNotificationDestination(n, permissionsOf(useAuthStore.getState().user));
}

/**
 * Listens for {@link OPEN_NOTIFICATION_EVENT} (dispatched when a toast or native
 * desktop notification is clicked) and navigates client-side. Mount once in the
 * dashboard shell.
 */
export function useNotificationNavBridge() {
  const router = useRouter();
  useEffect(() => {
    const handler = (e: Event) => {
      const path = (e as CustomEvent<string>).detail;
      if (path) router.push(path);
    };
    window.addEventListener(OPEN_NOTIFICATION_EVENT, handler);
    return () => window.removeEventListener(OPEN_NOTIFICATION_EVENT, handler);
  }, [router]);
}

/** Dispatch a navigation request from a non-React context (toast/desktop click). */
export function requestNotificationNav(path: string): void {
  if (typeof window !== "undefined") {
    window.dispatchEvent(new CustomEvent(OPEN_NOTIFICATION_EVENT, { detail: path }));
  }
}
