import { useCallback, useContext, useEffect, useId, useRef } from "react";
import { BackNavigationContext } from "./BackNavigationProvider.jsx";

export function useBackLayer(active, onDismiss, name = "layer", { preferTop = false } = {}) {
  const navigation = useContext(BackNavigationContext);
  const reactId = useId();
  const id = `${name}-${reactId}`;
  const dismissRef = useRef(onDismiss);
  dismissRef.current = onDismiss;

  useEffect(() => {
    if (!active || !navigation) return undefined;
    navigation.register(id, () => dismissRef.current());
    return () => navigation.unregister(id);
  }, [active, id, navigation]);

  return useCallback((afterNavigation) => {
    const continuation = typeof afterNavigation === "function" ? afterNavigation : undefined;
    if (navigation) {
      const handled = navigation.dismiss(id, continuation, { preferTop });
      if (handled) return;
    }
    dismissRef.current();
    continuation?.();
  }, [id, navigation, preferTop]);
}

export function useDetailsBackLayer(detailsRef, name = "details") {
  const navigation = useContext(BackNavigationContext);
  const reactId = useId();
  const id = `${name}-${reactId}`;

  useEffect(() => {
    const details = detailsRef.current;
    if (!details || !navigation) return undefined;
    const handleToggle = () => {
      if (details.open) navigation.register(id, () => { details.open = false; });
      else navigation.unregister(id);
    };
    details.addEventListener("toggle", handleToggle);
    if (details.open) handleToggle();
    return () => {
      details.removeEventListener("toggle", handleToggle);
      navigation.unregister(id);
    };
  }, [detailsRef, id, navigation]);
}
