'use client';

import { useCallback, useEffect, useRef } from 'react';
import { useConfirm } from '@/components/crm/useConfirm';
import { DISCARD_CONFIRM, leavingHref } from './unsaved';

/**
 * HUB-728: while a form has unsaved changes, asks "Discard unsaved changes?" (the app's confirm
 * dialog) before it is closed (`guard(close)`) or an in-app link is followed, and the browser's
 * own prompt before the page is reloaded or left for another site. `dirty` must be false while
 * the form is closed. Render `dialog` once.
 */
export function useUnsavedGuard(dirty: boolean): {
  guard: (leave: () => void) => void;
  dialog: React.ReactNode;
} {
  const { confirm, dialog } = useConfirm();
  /** The link click let through after "Discard": Next's own handler then opens the page. */
  const allowed = useRef<Element | null>(null);

  useEffect(() => {
    if (!dirty) return;
    const onUnload = (e: BeforeUnloadEvent) => {
      e.preventDefault();
      // Older browsers show the prompt only when a value is set.
      e.returnValue = '';
    };
    window.addEventListener('beforeunload', onUnload);
    return () => window.removeEventListener('beforeunload', onUnload);
  }, [dirty]);

  useEffect(() => {
    if (!dirty) return;
    const onClick = (e: MouseEvent) => {
      const anchor = e.target instanceof Element ? e.target.closest('a[href]') : null;
      if (anchor && allowed.current === anchor) {
        allowed.current = null;
        return;
      }
      if (!anchor || !leavingHref(e, window.location)) return;
      // Before Next's link handler (capture on the document): ask first, then click again.
      e.preventDefault();
      e.stopImmediatePropagation();
      void confirm(DISCARD_CONFIRM).then((ok) => {
        if (!ok) return;
        allowed.current = anchor;
        (anchor as HTMLElement).click();
      });
    };
    document.addEventListener('click', onClick, true);
    return () => document.removeEventListener('click', onClick, true);
  }, [dirty, confirm]);

  const guard = useCallback(
    (leave: () => void) => {
      if (!dirty) {
        leave();
        return;
      }
      void confirm(DISCARD_CONFIRM).then((ok) => {
        if (ok) leave();
      });
    },
    [dirty, confirm],
  );

  return { guard, dialog };
}
