/* global React */
/* hotfix28.2 (Phase 3 D): 공통 모달 셸 — Portal + ESC + body scroll lock + ARIA + focus trap.
 *
 * 26 모달 컴포넌트 중 Portal/a11y 표준화 누락 → 단계적 마이그레이션 entry point.
 * 기존 .modal-overlay / .modal-content / .modal-{sm,md,lg} CSS 컨벤션 그대로 재사용.
 *
 * 사용 1 (title prop):
 *   <ModalShell open onClose={fn} size="md" title="학생 등록">
 *     <div className="modal-body">...</div>
 *     <div className="modal-footer">...</div>
 *   </ModalShell>
 *
 * 사용 2 (header 자유 구성):
 *   <ModalShell open onClose={fn} size="lg">
 *     <div className="modal-header">
 *       <h3>제목 + 액션</h3>
 *       <button className="modal-close" onClick={fn} aria-label="닫기">×</button>
 *     </div>
 *     ...
 *   </ModalShell>
 *
 * 동작:
 *   - createPortal → document.body (조상 transform/filter 영향 차단)
 *   - role="dialog" aria-modal="true" aria-labelledby (title 시 자동 / ariaLabelledBy 명시 가능)
 *   - ESC 닫기 (closeOnEsc=false 로 끔)
 *   - 백드롭 클릭 닫기 (closeOnBackdrop=false 로 끔)
 *   - body overflow:hidden 로 배경 scroll lock (open 시 활성, close 시 복원)
 *   - useFocusTrap 자동 적용 (mount focus + Tab 순환 + cleanup 시 trigger 복귀)
 */
(function () {
  if (typeof window === 'undefined' || !window.React) return;
  const { useEffect, useRef, useMemo } = React;

  /* useFocusTrap 부재 페이지 (script 누락) 대비 noop fallback. */
  const _useFocusTrap = (typeof window.useFocusTrap === 'function')
    ? window.useFocusTrap
    : function _noopUseFocusTrap() {};

  /* createPortal 미로드 시 in-tree fallback. 모든 modal-launching 페이지에 ReactDOM 있음. */
  const _createPortal = (window.ReactDOM && window.ReactDOM.createPortal)
    ? window.ReactDOM.createPortal
    : null;

  let _idCounter = 0;
  function _genId() { _idCounter += 1; return 'modal-title-' + _idCounter; }

  function ModalShell(props) {
    const {
      open,
      onClose,
      size = 'md',
      title,
      ariaLabelledBy,
      closeOnBackdrop = true,
      closeOnEsc = true,
      className = '',
      children,
    } = props || {};

    const dialogRef = useRef(null);
    const titleId = useMemo(() => ariaLabelledBy || (title ? _genId() : undefined), [ariaLabelledBy, title]);

    /* ESC 닫기 — document level keydown. e.stopPropagation 으로 안쪽 input 등 영향 최소화. */
    useEffect(() => {
      if (!open || !closeOnEsc) return undefined;
      function onKey(e) {
        if (e.key === 'Escape') {
          e.stopPropagation();
          if (typeof onClose === 'function') onClose();
        }
      }
      document.addEventListener('keydown', onKey);
      return () => document.removeEventListener('keydown', onKey);
    }, [open, closeOnEsc, onClose]);

    /* body scroll lock — 모달 open 동안 배경 스크롤 차단. 이전 값 복원 (다른 모달 nested 안전). */
    useEffect(() => {
      if (!open) return undefined;
      const prev = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => { document.body.style.overflow = prev; };
    }, [open]);

    /* focus trap — open 시 첫 focusable 자동 focus + Tab 순환 + cleanup 에서 trigger 복귀. */
    _useFocusTrap(dialogRef, !!open);

    if (!open) return null;

    function onBackdropMouseDown(e) {
      if (!closeOnBackdrop) return;
      if (e.target !== e.currentTarget) return;
      if (typeof onClose === 'function') onClose();
    }

    const contentClass = ('modal-content modal-' + size + (className ? ' ' + className : '')).trim();

    const node = React.createElement(
      'div',
      { className: 'modal-overlay', onMouseDown: onBackdropMouseDown },
      React.createElement(
        'div',
        {
          ref: dialogRef,
          className: contentClass,
          role: 'dialog',
          'aria-modal': 'true',
          'aria-labelledby': titleId,
        },
        title
          ? React.createElement(
              'div',
              { className: 'modal-header' },
              React.createElement('h3', { id: titleId }, title),
              React.createElement(
                'button',
                {
                  type: 'button',
                  className: 'modal-close',
                  onClick: onClose,
                  'aria-label': '닫기',
                },
                '×'
              )
            )
          : null,
        children
      )
    );

    return _createPortal ? _createPortal(node, document.body) : node;
  }

  window.ModalShell = ModalShell;
  console.log('[C200] ModalShell loaded (Portal + ESC + scroll lock + ARIA + focus trap)');
})();
