/**
 * Composable hook for managing unsaved changes and exit warnings.
 *
 * Usage in a Svelte component:
 * ```svelte
 * <script lang="ts">
 *   import { unsavedChangesGuard } from '$lib/dirtyStateGuard';
 *
 *   let formData = { name: '', description: '' };
 *   const { isDirty, markDirty, markClean, checkBeforeClose } = unsavedChangesGuard();
 *
 *   function handleInputChange() {
 *     markDirty();
 *   }
 *
 *   function handleSave() {
 *     // ... api call ...
 *     markClean();
 *   }
 *
 *   async function handleClose() {
 *     if (await checkBeforeClose()) {
 *       // Show confirmation dialog if dirty
 *       // User can choose to discard or keep editing
 *     } else {
 *       // No unsaved changes, safe to close
 *       isOpen = false;
 *     }
 *   }
 * </script>
 *
 * <UnsavedChangesDialog
 *   bind:isOpen={showConfirmation}
 *   onDiscard={() => { isOpen = false; }}
 *   onCancel={() => { showConfirmation = false; }}
 * />
 * ```
 */

export interface UnsavedChangesGuardOptions {
  title?: string;
  message?: string;
}

export function unsavedChangesGuard(options: UnsavedChangesGuardOptions = {}) {
  let isDirtyValue = false;
  let confirmationCallback: (() => void) | null = null;

  const defaults = {
    title: 'Unsaved Changes',
    message: 'You have unsaved changes. Are you sure you want to leave?',
    ...options,
  };

  return {
    get isDirty() {
      return isDirtyValue;
    },

    markDirty() {
      isDirtyValue = true;
    },

    markClean() {
      isDirtyValue = false;
    },

    reset() {
      isDirtyValue = false;
    },

    /**
     * Call this when the user tries to close/exit.
     * If there are unsaved changes, it will trigger the confirmation callback.
     * Returns true if confirmation is needed, false if safe to close.
     */
    async checkBeforeClose(onConfirm?: () => void) {
      if (isDirtyValue) {
        if (onConfirm) {
          confirmationCallback = onConfirm;
          onConfirm();
        }
        return true;
      }
      return false;
    },

    /**
     * Get the confirmation options (for use with UnsavedChangesDialog).
     */
    getConfirmationOptions() {
      return defaults;
    },
  };
}
