import React, { useEffect, useRef } from 'react';
import { useLocation, useNavigate, useBlocker } from 'react-router-dom';

export interface UnsavedChangesGuardProps {
  isDirty: boolean;
  message?: string;
  onConfirm?: () => void;
}

export function UnsavedChangesGuard({ isDirty, message = 'Sie haben ungespeicherte Änderungen. Möchten Sie die Seite wirklich verlassen?', onConfirm }: UnsavedChangesGuardProps) {
  const blocker = useBlocker(isDirty);
  const messageRef = useRef(message);
  messageRef.current = message;

  useEffect(() => {
    if (blocker.state === 'blocked') {
      const confirmed = window.confirm(messageRef.current);
      if (confirmed) {
        onConfirm?.();
        blocker.proceed();
      } else {
        blocker.reset();
      }
    }
  }, [blocker, onConfirm]);

  return null;
}
