import { useEffect, useRef } from 'react';

/**
 * Hardens the page during an exam/practice session:
 *  - Blocks copy / cut / paste (mobile + desktop)
 *  - Blocks right-click context menu and text selection
 *  - Blocks common screenshot / save / devtools keyboard shortcuts
 *  - In EXAM mode, detects tab switching / window blur and reports it
 *
 * @param {Object} opts
 * @param {boolean} opts.active        - enable protection
 * @param {boolean} opts.examMode      - stricter, tracks tab switches
 * @param {Function} opts.onTabSwitch  - called when the user leaves the tab/window
 * @param {Function} opts.onBlockedAction - called with a label when an action is blocked
 */
export function useExamSecurity({ active, examMode, onTabSwitch, onBlockedAction }) {
  const switches = useRef(0);

  useEffect(() => {
    if (!active) return undefined;

    const block = (e, label) => {
      e.preventDefault();
      e.stopPropagation();
      if (onBlockedAction) onBlockedAction(label);
      return false;
    };

    const onCopy = (e) => block(e, 'Copying is disabled during the exam');
    const onCut = (e) => block(e, 'Cutting is disabled during the exam');
    const onPaste = (e) => block(e, 'Pasting is disabled during the exam');
    const onContextMenu = (e) => block(e, 'Right-click is disabled');
    const onSelectStart = (e) => {
      // allow selecting inside inputs/textareas (when adding a question), block elsewhere
      const tag = e.target?.tagName;
      if (tag === 'INPUT' || tag === 'TEXTAREA') return undefined;
      e.preventDefault();
      return false;
    };
    const onDragStart = (e) => block(e, 'Dragging content is disabled');

    const onKeyDown = (e) => {
      const k = e.key?.toLowerCase();
      const meta = e.ctrlKey || e.metaKey;
      // Block copy/cut/paste/save/print/screenshot shortcuts
      if (meta && ['c', 'x', 'v', 's', 'p', 'u'].includes(k)) {
        return block(e, 'This shortcut is disabled during the exam');
      }
      // PrintScreen
      if (e.key === 'PrintScreen' || k === 'printscreen') {
        if (navigator.clipboard?.writeText) navigator.clipboard.writeText('');
        return block(e, 'Screenshots are restricted during the exam');
      }
      // DevTools: F12, Ctrl/Cmd+Shift+I/J/C
      if (e.key === 'F12' || (meta && e.shiftKey && ['i', 'j', 'c'].includes(k))) {
        return block(e, 'Developer tools are disabled');
      }
      return undefined;
    };

    const onVisibility = () => {
      if (examMode && document.hidden) {
        switches.current += 1;
        if (onTabSwitch) onTabSwitch(switches.current);
      }
    };
    const onBlur = () => {
      if (examMode) {
        switches.current += 1;
        if (onTabSwitch) onTabSwitch(switches.current);
      }
    };

    document.addEventListener('copy', onCopy, true);
    document.addEventListener('cut', onCut, true);
    document.addEventListener('paste', onPaste, true);
    document.addEventListener('contextmenu', onContextMenu, true);
    document.addEventListener('selectstart', onSelectStart, true);
    document.addEventListener('dragstart', onDragStart, true);
    document.addEventListener('keydown', onKeyDown, true);
    document.addEventListener('visibilitychange', onVisibility);
    window.addEventListener('blur', onBlur);

    // mobile: discourage long-press save / callout
    document.body.classList.add('no-select', 'exam-secure');

    return () => {
      document.removeEventListener('copy', onCopy, true);
      document.removeEventListener('cut', onCut, true);
      document.removeEventListener('paste', onPaste, true);
      document.removeEventListener('contextmenu', onContextMenu, true);
      document.removeEventListener('selectstart', onSelectStart, true);
      document.removeEventListener('dragstart', onDragStart, true);
      document.removeEventListener('keydown', onKeyDown, true);
      document.removeEventListener('visibilitychange', onVisibility);
      window.removeEventListener('blur', onBlur);
      document.body.classList.remove('no-select', 'exam-secure');
    };
  }, [active, examMode, onTabSwitch, onBlockedAction]);
}

export default useExamSecurity;
