import { HTML5Backend } from 'react-dnd-html5-backend';
import type { BackendFactory } from 'dnd-core';

// window 객체에 backend 상태를 저장
declare global {
  interface Window {
    __DND_BACKEND_INSTANCE__?: any;
    __DND_SETUP_CALLED__?: boolean;
  }
}

/**
 * Patched HTML5Backend
 * 
 * setup()이 이미 호출되었다면 무시하도록 패치
 */
function createPatchedBackend(manager: any, context: any, options: any) {
  const backend = HTML5Backend(manager, context, options);
  
  // 원래 setup 메서드 저장
  const originalSetup = backend.setup.bind(backend);
  
  // setup 메서드 패치
  backend.setup = function() {
    if (typeof window !== 'undefined') {
      // 이미 setup이 호출되었으면 스킵
      if (window.__DND_SETUP_CALLED__) {
        console.log('[DnD] Setup already called, skipping');
        return;
      }
      
      console.log('[DnD] Calling setup for the first time');
      window.__DND_SETUP_CALLED__ = true;
      
      try {
        return originalSetup();
      } catch (error: any) {
        // "Cannot have two HTML5 backends" 에러가 발생해도 무시
        if (error.message && error.message.includes('two HTML5 backends')) {
          console.warn('[DnD] Caught duplicate backend error, ignoring:', error.message);
          return;
        }
        throw error;
      }
    }
    
    return originalSetup();
  };
  
  // teardown도 패치 (플래그 유지)
  const originalTeardown = backend.teardown.bind(backend);
  backend.teardown = function() {
    console.log('[DnD] Teardown called (keeping setup flag)');
    // __DND_SETUP_CALLED__ 플래그는 유지
    try {
      return originalTeardown();
    } catch (error) {
      console.warn('[DnD] Error during teardown:', error);
    }
  };
  
  return backend;
}

/**
 * Singleton HTML5Backend Factory
 */
export const SingletonHTML5Backend: BackendFactory = (manager, context, options) => {
  if (typeof window !== 'undefined') {
    // 이미 backend 인스턴스가 있으면 재사용
    if (window.__DND_BACKEND_INSTANCE__) {
      console.log('[DnD] Reusing existing backend instance');
      return window.__DND_BACKEND_INSTANCE__;
    }
    
    console.log('[DnD] Creating new patched backend instance');
    const backend = createPatchedBackend(manager, context, options);
    window.__DND_BACKEND_INSTANCE__ = backend;
    return backend;
  }
  
  // window가 없으면 (SSR) 일반 backend 반환
  return HTML5Backend(manager, context, options);
};

export const html5BackendOptions = {};

/**
 * Backend 완전 리셋 (개발용)
 */
export function resetDndBackend() {
  if (typeof window !== 'undefined') {
    const backend = window.__DND_BACKEND_INSTANCE__;
    
    if (backend?.teardown) {
      try {
        // 원래 teardown 호출 (패치된 버전 아님)
        const originalTeardown = Object.getPrototypeOf(backend).teardown;
        if (originalTeardown) {
          originalTeardown.call(backend);
        }
      } catch (e) {
        console.warn('[DnD] Error during reset teardown:', e);
      }
    }
    
    delete window.__DND_BACKEND_INSTANCE__;
    delete window.__DND_SETUP_CALLED__;
    console.log('[DnD] Backend fully reset');
  }
}
