"use client";

import { useEffect } from "react";

export function PreventBrowserBackspace() {
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key !== "Backspace" || event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey) return;

      const target = event.target as HTMLElement | null;
      const editableTarget = target?.closest("input, textarea, select, [contenteditable='true'], [contenteditable=''], [role='textbox']") as HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | HTMLElement | null;
      if (editableTarget && !("readOnly" in editableTarget && editableTarget.readOnly) && !("disabled" in editableTarget && editableTarget.disabled)) return;

      event.preventDefault();
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, []);

  return null;
}
