<!doctype html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/png" href="/logo192.png" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
    <meta name="theme-color" content="#10b981" />
    <meta name="description" content="미얀마 근로자를 위한 송금, 상담, 복지 지원 통합 플랫폼" />
    
    <!-- PWA 메타 태그 -->
    <meta name="mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="default" />
    <meta name="apple-mobile-web-app-title" content="Kairos" />
    <meta name="application-name" content="Kairos" />
    <meta name="msapplication-TileColor" content="#10b981" />
    <meta name="msapplication-tap-highlight" content="no" />
    
    <!-- 🔥 초기 로딩 최적화: DNS prefetch 및 preconnect -->
    <link rel="dns-prefetch" href="https://kairos-platform-1ffde.web.app" />
    <link rel="preconnect" href="https://kairos-platform-1ffde.web.app" />
    
    <!-- 아이콘 -->
    <link rel="apple-touch-icon" href="/logo192.png" />
    <link rel="icon" type="image/png" sizes="192x192" href="/logo192.png" />
    <link rel="icon" type="image/png" sizes="512x512" href="/logo512.png" />
    <link rel="manifest" href="/manifest.json" />
    
    <!-- 스플래시 스크린 (iOS) -->
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
    <link rel="apple-touch-startup-image" href="/logo512.png" />
    <title>Kairos - 미얀마 근로자 복지 지원 플랫폼</title>
    
    <!-- Service Worker handling: disable in Capacitor native app -->
    <script>
      (function () {
        // 🔥 즉시 실행되는 디버깅 로그
        console.error('🔥🔥🔥 index.html 스크립트 시작 🔥🔥🔥');
        console.error('🔥 현재 시간:', new Date().toISOString());
        console.error('🔥 User Agent:', navigator.userAgent);
        console.error('🔥 Location:', location.href);
        
        // Capacitor 네이티브 앱 감지
        const isCapacitor = typeof window !== 'undefined' && 
          (window.Capacitor !== undefined || 
           location.protocol === 'file:' ||
           location.hostname === '' ||
           /capacitor/.test(navigator.userAgent));
        
        // 로컬 개발 환경 감지
        const isLocalDev = /^(localhost|127\.0\.0\.1|\[::1\])$/.test(location.hostname);
        
        console.error('🔥 Capacitor 감지:', isCapacitor);
        console.error('🔥 로컬 개발 환경:', isLocalDev);
        
        // 🔥🔥🔥 모든 환경에서 Service Worker 강제 제거 및 캐시 삭제
        // 🔥 핵심: 초기 스크립트 로드 전에 모든 Service Worker를 완전히 비활성화
        if ('serviceWorker' in navigator) {
          (async () => {
            try {
              // 1. Service Worker 등록을 차단하되, FCM용 Service Worker는 예외 처리
              const originalRegister = navigator.serviceWorker.register;
              navigator.serviceWorker.register = function(...args) {
                const swPath = args[0];
                // 🔥 FCM용 Service Worker는 허용 (Firebase Messaging이 필요로 함)
                if (swPath && (swPath.includes('firebase-messaging-sw.js') || swPath.includes('firebase-messaging'))) {
                  if (process.env.NODE_ENV === 'development') {
                    console.log('✅ FCM용 Service Worker 등록 허용:', swPath);
                  }
                  return originalRegister.apply(navigator.serviceWorker, args);
                }
                // 그 외의 Service Worker는 차단
                console.warn('🚫 Service Worker 등록 차단 (초기 로딩 중)', swPath);
                return Promise.reject(new Error('Service Worker registration blocked during initial load'));
              };
              
              // 2. FCM용 Service Worker를 제외한 모든 Service Worker 등록 해제
              const regs = await navigator.serviceWorker.getRegistrations();
              console.error('🔥 Service Worker 등록 해제 시작:', regs.length, '개');
              for (const reg of regs) {
                try {
                  // 🔥 FCM용 Service Worker는 유지
                  if (reg.scope && (reg.scope.includes('firebase-messaging') || reg.active?.scriptURL?.includes('firebase-messaging-sw.js'))) {
                    if (process.env.NODE_ENV === 'development') {
                      console.log('✅ FCM용 Service Worker 유지:', reg.scope);
                    }
                    continue;
                  }
                  await reg.unregister();
                  console.error('✅ SW unregistered:', reg.scope);
                } catch (e) {
                  console.error('❌ SW unregister 실패:', e);
                }
              }
              
              // 3. 모든 캐시 삭제
              if ('caches' in window) {
                const names = await caches.keys();
                console.error('🔥 캐시 삭제 시작:', names.length, '개');
                for (const name of names) {
                  try {
                    await caches.delete(name);
                    console.error('✅ Cache deleted:', name);
                  } catch (e) {
                    console.error('❌ Cache delete 실패:', e);
                  }
                }
              }
              
              // 4. Service Worker 컨트롤러 제거
              if (navigator.serviceWorker.controller) {
                navigator.serviceWorker.controller.postMessage({ type: 'SKIP_WAITING' });
                console.error('🔥 Service Worker 컨트롤러에 SKIP_WAITING 메시지 전송');
              }
              
              console.error('✅ Service Worker 및 캐시 완전 제거 완료');
              
              // 5. Service Worker 등록 복원 함수 (전역에서 접근 가능하도록)
              window.__restoreSWRegistration = function() {
                // 🔥 원본 함수 복원
                navigator.serviceWorker.register = originalRegister;
                console.log('✅ Service Worker 등록 복원 (React 렌더링 완료 후)');
                
                // 프로덕션 환경 확인 (localhost가 아닌 경우)
                const isProduction = location.hostname !== 'localhost' && 
                                   location.hostname !== '127.0.0.1' &&
                                   !location.hostname.includes('localhost');
                
                if (isProduction) {
                  // 🔥 Service Worker가 완전히 활성화될 때까지 기다리는 함수
                  const waitForSWActive = (registration, maxWait = 10000) => {
                    return new Promise((resolve, reject) => {
                      if (registration.active) {
                        resolve(registration);
                        return;
                      }
                      
                      const startTime = Date.now();
                      const checkInterval = setInterval(() => {
                        if (registration.active) {
                          clearInterval(checkInterval);
                          resolve(registration);
                        } else if (Date.now() - startTime > maxWait) {
                          clearInterval(checkInterval);
                          reject(new Error('Service Worker activation timeout'));
                        }
                      }, 100);
                      
                      // installing 이벤트 리스너
                      registration.addEventListener('updatefound', () => {
                        const newWorker = registration.installing || registration.waiting;
                        if (newWorker) {
                          newWorker.addEventListener('statechange', () => {
                            if (newWorker.state === 'activated' && registration.active) {
                              clearInterval(checkInterval);
                              resolve(registration);
                            }
                          });
                        }
                      });
                    });
                  };
                  
                  // 🔥 핵심: Firebase Messaging SW 먼저 등록 (푸시 알림 필수)
                  setTimeout(() => {
                    // 1. Firebase Messaging SW 등록 (푸시 알림 핵심 기능)
                    navigator.serviceWorker.register('/firebase-messaging-sw.js', { scope: '/' })
                      .then(registration => {
                        console.log('✅ Firebase Messaging SW 등록 완료:', registration.scope);
                        // 🔥 Service Worker가 활성화될 때까지 대기
                        return waitForSWActive(registration).then(() => {
                          console.log('✅ Firebase Messaging SW 활성화 완료 - 푸시 알림 서비스 활성화됨');
                        });
                      })
                      .catch(error => {
                        console.error('❌ Firebase Messaging SW 등록 실패 (푸시 알림 비활성화):', error);
                      });
                    
                    // 2. PWA Service Worker 등록 (오프라인 지원, 캐싱)
                    navigator.serviceWorker.register('/sw.js')
                      .then(registration => {
                        console.log('✅ PWA Service Worker 등록 완료:', registration.scope);
                        // 🔥 Service Worker가 활성화될 때까지 대기
                        return waitForSWActive(registration).then(() => {
                          console.log('✅ PWA Service Worker 활성화 완료');
                        });
                      })
                      .catch(error => {
                        console.warn('⚠️ PWA Service Worker 등록 실패 (비치명적):', error);
                      });
                  }, 2000); // React 완전 초기화 후 2초 대기
                } else {
                  console.log('⚠️ 개발 환경 - Service Worker 등록 건너뜀');
                }
              };
            } catch (e) {
              console.error('❌ Service Worker 제거 중 오류:', e);
            }
          })();
        }
        
        if (isCapacitor) {
          // Capacitor 네이티브 앱: 추가 처리 불필요 (위에서 이미 처리됨)
          console.error('🔥📱 Capacitor 네이티브 앱 감지 - Service Worker 비활성화 완료');
        } else if (isLocalDev) {
          // 로컬 개발 환경: 추가 처리 불필요 (위에서 이미 처리됨)
          console.error('🔥 로컬 개발 환경 - Service Worker 비활성화 완료');
        } else {
          // 프로덕션 웹: Service Worker 등록은 React 렌더링 완료 후 restoreSWRegistration에서 처리
          // 초기 로딩 시에는 등록하지 않음 (JavaScript 모듈 로드 방해 방지)
          console.log('✅ 프로덕션 웹 환경 - Service Worker 등록은 React 렌더링 완료 후 수행됨');
        }
      })();
    </script>
    <!-- Capacitor 환경에서 Service Worker 스크립트 로드 차단 -->
    <script>
      (function() {
        const isCapacitor = typeof window !== 'undefined' && 
          (window.Capacitor !== undefined || 
           location.protocol === 'file:' ||
           location.hostname === '' ||
           /capacitor/.test(navigator.userAgent));
        
        if (isCapacitor) {
          // Service Worker 스크립트 로드 차단
          const originalRegister = navigator.serviceWorker?.register;
          if (originalRegister) {
            navigator.serviceWorker.register = function() {
              console.log('🚫 Capacitor 환경: Service Worker 등록 차단');
              return Promise.reject(new Error('Service Worker disabled in Capacitor'));
            };
          }
          
          // 기존 등록 해제
          if ('serviceWorker' in navigator) {
            navigator.serviceWorker.getRegistrations().then(async (regs) => {
              for (const reg of regs) {
                try { 
                  await reg.unregister(); 
                  console.log('✅ SW unregistered:', reg.scope); 
                } catch (e) {
                  console.warn('SW unregister error:', e);
                }
              }
              if ('caches' in window) {
                const names = await caches.keys();
                for (const name of names) {
                  try { 
                    await caches.delete(name); 
                    console.log('✅ Cache deleted:', name); 
                  } catch (e) {
                    console.warn('Cache delete error:', e);
                  }
                }
              }
              });
          }
        }
      })();
    </script>
    <script type="module" src="/js/index-D3DbAVEO.js"></script>
    <link rel="stylesheet" href="/assets/index-CE2C3vWp.css">
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script>
      // 🔥 루트 경로에서 즉시 로그인 페이지로 리다이렉트 (React 렌더링 전)
      if (window.location.pathname === '/' || window.location.pathname === '') {
        console.log('🔥 index.html에서 루트 경로 감지 - 즉시 /login으로 리다이렉트');
        window.location.replace('/login');
      }
    </script>
    <!-- 🔥 프로덕션에서는 디버그 메시지 비활성화 -->
    <script>
      (function() {
        // 즉시 실행되는 기본 디버깅 (콘솔만)
        console.log('✅ index.html 스크립트 실행됨');
        // 🔥 CRITICAL FIX: body와 root 요소 배경색을 CSS에서 설정한 값으로 유지
        // 인라인 스타일을 제거하여 CSS가 정상적으로 적용되도록 함
        document.body.style.backgroundColor = '';
        const rootElement = document.getElementById('root');
        if (rootElement) {
          rootElement.style.backgroundColor = '';
        }
        
        // 로컬 개발 환경 감지
        const isLocalDev = window.location.hostname === 'localhost' || 
                          window.location.hostname === '127.0.0.1' ||
                          window.location.hostname.includes('localhost');
        
        // 🔥 Capacitor 환경 감지 (한 번만) - 더 엄격한 체크
        const isCapacitor = typeof window !== 'undefined' && 
          (window.Capacitor !== undefined || 
           location.protocol === 'file:' ||
           location.hostname === '' ||
           location.href === 'https://localhost/' ||
           location.href.startsWith('https://localhost') ||
           /capacitor/.test(navigator.userAgent) ||
           (navigator.userAgent && /wv/.test(navigator.userAgent)) || // WebView 감지
           (navigator.userAgent && /Android.*wv/.test(navigator.userAgent))); // Android WebView
        
        // 프로덕션 환경 감지
        const isProduction = !isLocalDev && !isCapacitor;
        
        console.log('🔍 환경 감지:', {
          isCapacitor: isCapacitor,
          protocol: location.protocol,
          hostname: location.hostname,
          userAgent: navigator.userAgent,
          hasCapacitor: typeof window !== 'undefined' && window.Capacitor !== undefined
        });
        
        // 스크립트 로드 추적
        let scriptLoaded = false;
        let moduleLoadError = false;
        
        // 🔥 메인 스크립트 로드 감지
        const originalAppendChild = document.head.appendChild.bind(document.head);
        document.head.appendChild = function(node) {
          if (node.tagName === 'SCRIPT' && node.src) {
            console.error('🔥 스크립트 태그 추가됨:', node.src);
            node.addEventListener('load', function() {
              console.error('🔥 스크립트 로드 완료:', node.src);
              scriptLoaded = true;
            });
            node.addEventListener('error', function(e) {
              console.error('🔥 스크립트 로드 실패:', node.src, e);
              moduleLoadError = true;
            });
          }
          return originalAppendChild(node);
        };
        
        // 네트워크 연결 테스트
        async function testNetworkConnection() {
          try {
            // Firebase Hosting URL에 접근 가능한지 테스트
            const response = await fetch('https://kairos-platform-1ffde.web.app', {
              method: 'HEAD',
              mode: 'no-cors',
              cache: 'no-cache'
            });
            return true;
          } catch (error) {
            console.error('❌ 네트워크 연결 테스트 실패:', error);
            return false;
          }
        }
        
        // 네트워크 오류 감지 및 사용자 친화적 오류 페이지 표시
        function showNetworkErrorPage(error) {
          const root = document.getElementById('root');
          if (!root) return false;
          
          // 🔥 CRITICAL: React가 이미 렌더링된 경우 root 요소를 덮어쓰지 않음
          // React 렌더링이 완료되었는지 확인
          const hasReactContent = root.children.length > 0 || 
                                 window.__REACT_RENDERED__ ||
                                 (root.innerHTML.trim().length > 0 && 
                                  !root.innerHTML.includes('noscript') &&
                                  !root.innerHTML.includes('네트워크 연결 오류'));
          
          if (hasReactContent) {
            console.log('⚠️ React가 이미 렌더링됨 - 네트워크 오류 페이지 표시 스킵');
            return false;
          }
          
          const isNetworkError = error?.message?.includes('Failed to fetch') ||
                                 error?.message?.includes('ERR_QUIC') ||
                                 error?.message?.includes('ERR_NETWORK') ||
                                 error?.message?.includes('ERR_NAME_NOT_RESOLVED') ||
                                 error?.message?.includes('network') ||
                                 error?.message?.includes('timeout') ||
                                 error?.message?.includes('웹 페이지를 사용할 수 없음') ||
                                 error?.type === 'networkerror';
          
          if (isNetworkError || (!error && location.href.includes('about:blank'))) {
            root.innerHTML = `
              <div style="
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                padding: 20px;
                color: white;
                text-align: center;
                z-index: 999999;
              ">
                <div style="font-size: 64px; margin-bottom: 20px;">📡</div>
                <h1 style="font-size: 24px; margin-bottom: 16px; font-weight: bold;">네트워크 연결 오류</h1>
                <p style="font-size: 16px; margin-bottom: 16px; opacity: 0.9; max-width: 400px;">
                  인터넷 연결을 확인하고 다시 시도해주세요.
                </p>
                <p style="font-size: 14px; margin-bottom: 24px; opacity: 0.7; max-width: 400px;">
                  현재 위치: ${location.href}<br/>
                  네트워크 상태: ${navigator.onLine ? '온라인' : '오프라인'}
                </p>
                <button onclick="window.location.reload()" style="
                  background: white;
                  color: #667eea;
                  border: none;
                  padding: 12px 32px;
                  border-radius: 8px;
                  font-size: 16px;
                  font-weight: bold;
                  cursor: pointer;
                  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
                  margin-bottom: 12px;
                ">
                  다시 시도
                </button>
                <p style="font-size: 12px; margin-top: 12px; opacity: 0.7;">
                  문제가 지속되면 앱을 재시작하거나 VPN 연결을 확인해주세요.
                </p>
              </div>
            `;
            return true;
          }
          return false;
        }
        
        // 페이지 로드 시 네트워크 상태 확인
        if (isCapacitor && location.href.includes('about:blank')) {
          setTimeout(() => {
            // 🔥 React 렌더링이 완료되지 않은 경우에만 오류 페이지 표시
            const root = document.getElementById('root');
            const hasReactContent = root && (root.children.length > 0 || window.__REACT_RENDERED__);
            if (!hasReactContent) {
            showNetworkErrorPage({ message: '웹 페이지를 사용할 수 없음', type: 'networkerror' });
            }
          }, 1000);
        }
        
        // 모듈 로드 오류 감지
        window.addEventListener('error', function(e) {
          console.error('❌ JavaScript 오류:', e.message, e.filename, e.lineno);
          
          // 🔥 CRITICAL: React 렌더링이 완료된 후에는 root 요소를 덮어쓰지 않음
          const root = document.getElementById('root');
          const hasReactContent = root && (root.children.length > 0 || window.__REACT_RENDERED__);
          
          if (hasReactContent) {
            // React가 이미 렌더링된 경우 오류는 ErrorBoundary가 처리하도록 함
            console.log('⚠️ React가 이미 렌더링됨 - 오류는 ErrorBoundary가 처리');
            return;
          }
          
          // 네트워크 오류인 경우 사용자 친화적 오류 페이지 표시
          if (showNetworkErrorPage(e)) {
            return;
          }
          
          // 모듈 로드 오류인지 확인
          if (e.filename && (e.filename.includes('.js') || e.filename.includes('main.jsx'))) {
            moduleLoadError = true;
          }
          
          // 🔥 Capacitor 환경에서는 오류 박스 표시 안 함 (무한 루프 방지)
          if (!isProduction || isCapacitor) {
            const errorDiv = document.createElement('div');
            errorDiv.style.cssText = 'padding:20px;color:red;background:white;z-index:99999;position:fixed;top:80px;left:10px;right:10px;border:2px solid red;max-height:300px;overflow-y:auto;';
            errorDiv.innerHTML = '<h2 style="color:red;">오류 발생</h2><p><strong>메시지:</strong> ' + e.message + '</p><p><strong>파일:</strong> ' + (e.filename || 'unknown') + '</p><p><strong>라인:</strong> ' + (e.lineno || 'unknown') + '</p>';
            document.body.appendChild(errorDiv);
          }
        }, true); // capture phase에서도 감지
        
        window.addEventListener('unhandledrejection', function(e) {
          console.error('❌ Promise 오류:', e.reason);
          
          // 🔥 CRITICAL: React 렌더링이 완료된 후에는 root 요소를 덮어쓰지 않음
          const root = document.getElementById('root');
          const hasReactContent = root && (root.children.length > 0 || window.__REACT_RENDERED__);
          
          if (hasReactContent) {
            // React가 이미 렌더링된 경우 오류는 ErrorBoundary가 처리하도록 함
            console.log('⚠️ React가 이미 렌더링됨 - Promise 오류는 ErrorBoundary가 처리');
            return;
          }
          
          // 네트워크 오류인 경우 사용자 친화적 오류 페이지 표시
          if (showNetworkErrorPage({ message: e.reason?.message || String(e.reason), type: 'networkerror' })) {
            return;
          }
          
          // 🔥 Capacitor 환경에서는 오류 박스 표시 안 함 (무한 루프 방지)
          if (!isProduction || isCapacitor) {
            const errorDiv = document.createElement('div');
            errorDiv.style.cssText = 'padding:20px;color:red;background:white;z-index:99999;position:fixed;top:80px;left:10px;right:10px;border:2px solid red;max-height:300px;overflow-y:auto;';
            errorDiv.innerHTML = '<h2 style="color:red;">Promise 오류</h2><p>' + (e.reason?.message || String(e.reason)) + '</p>';
            document.body.appendChild(errorDiv);
          }
        });
        
        // 스크립트 로드 확인 (프로덕션 빌드 경로도 감지)
        const mainScript = document.querySelector('script[type="module"][src*="index"]') || 
                           document.querySelector('script[type="module"][src="/src/main.jsx"]');
        if (mainScript) {
          const scriptSrc = mainScript.getAttribute('src');
          console.log('🔍 메인 스크립트 발견:', scriptSrc);
          
          // 🔥 Preload 링크 실패 감지 및 즉시 제거
          let preloadFailureDetected = false;
          const preloadLinks = document.querySelectorAll('link[rel="modulepreload"]');
          preloadLinks.forEach((link, index) => {
            // Preload 링크에 에러 리스너 추가 (간접적 감지)
            link.addEventListener('error', function(e) {
              if (!preloadFailureDetected) {
                preloadFailureDetected = true;
                console.warn('⚠️ Preload 링크 실패 감지:', link.href);
                console.warn('⚠️ 모든 preload 링크 제거 후 직접 로드 시도');
                // 모든 preload 링크 제거
                document.querySelectorAll('link[rel="modulepreload"]').forEach(l => l.remove());
              }
            });
          });
          
          // 🔥 메인 스크립트 로드 지연 감지 및 preload 제거 (3초 후)
          // 네트워크가 불안정하면 preload가 오히려 방해가 될 수 있음
          const preloadTimeout = setTimeout(() => {
            if (!scriptLoaded && !preloadFailureDetected) {
              const preloadLinksCheck = document.querySelectorAll('link[rel="modulepreload"]');
              if (preloadLinksCheck.length > 0) {
                console.warn('⚠️ 메인 스크립트 로드 지연 감지 (3초) - preload 링크 제거 후 직접 로드 시도');
                preloadLinksCheck.forEach(l => {
                  console.log('🗑️ Preload 링크 제거 (타임아웃):', l.href);
                  l.remove();
                });
                preloadFailureDetected = true;
              }
            }
          }, 3000);
          
          // 🔥 Preload 링크 실패 시에도 메인 스크립트 로드 계속 진행
          // 브라우저가 자동으로 의존성을 로드하므로, preload 실패는 치명적이지 않음
          
            mainScript.addEventListener('load', function() {
              // 타임아웃 클리어
              clearTimeout(preloadTimeout);
              
              // 스크립트 로드 완료 처리
              scriptLoaded = true;
              console.error('✅ 메인 스크립트 로드 완료:', scriptSrc);
              
              // 🔥 메인 스크립트 로드 후 즉시 main.jsx 실행 확인
              setTimeout(function() {
                console.error('🔥 메인 스크립트 로드 후 상태 확인:');
                console.error('🔥 window.__MAIN_JSX_LOADED__:', window.__MAIN_JSX_LOADED__);
                console.error('🔥 window.__MAIN_JSX_START_TIME__:', window.__MAIN_JSX_START_TIME__);
                
                if (!window.__MAIN_JSX_LOADED__) {
                  console.error('❌ main.jsx가 실행되지 않았습니다!');
                } else {
                  console.error('✅ main.jsx 실행 확인됨!');
                  
                  // 🔥 메인 스크립트 로드 완료 후 React 렌더링 대기 후 Service Worker 등록
                  // React 렌더링 완료를 감지하기 위해 주기적으로 체크
                  let reactCheckCount = 0;
                  const checkReactAndRegisterSW = setInterval(() => {
                    reactCheckCount++;
                    
                    // 1. window.__REACT_RENDERED__ 플래그 확인 (가장 확실한 방법)
                    if (window.__REACT_RENDERED__) {
                      clearInterval(checkReactAndRegisterSW);
                      console.log('✅ React 렌더링 확인 (플래그) - Service Worker 등록 준비');
                      // React 렌더링 완료 후 5초 대기 (동적 import 완료 보장)
                      setTimeout(() => {
                        if (typeof window.__restoreSWRegistration === 'function') {
                          window.__restoreSWRegistration();
                        }
                      }, 5000);
                      return;
                    }
                    
                    // 2. root 요소 내용 확인 (백업 방법)
                    const root = document.getElementById('root');
                    const hasReactContent = root && (
                      root.children.length > 0 || 
                      (root.innerHTML.trim().length > 0 && root.innerHTML !== '<noscript>You need to enable JavaScript to run this app.</noscript>') ||
                      (root.textContent.trim().length > 0 && !root.textContent.includes('You need to enable JavaScript'))
                    );
                    
                    if (hasReactContent) {
                      clearInterval(checkReactAndRegisterSW);
                      console.log('✅ React 렌더링 확인 (DOM 체크) - Service Worker 등록 준비');
                      // React 렌더링 완료 후 5초 대기 (동적 import 완료 보장)
                      setTimeout(() => {
                        if (typeof window.__restoreSWRegistration === 'function') {
                          window.__restoreSWRegistration();
                        }
                      }, 5000);
                      return;
                    }
                    
                    // 3. 타임아웃 처리 (10초 후 강제 실행)
                    if (reactCheckCount >= 10) {
                      clearInterval(checkReactAndRegisterSW);
                      console.warn('⚠️ React 렌더링 타임아웃 - Service Worker 등록 강제 실행');
                      if (typeof window.__restoreSWRegistration === 'function') {
                        window.__restoreSWRegistration();
                      }
                    }
                  }, 1000);
                }
              }, 100);
            });
            
            // 스크립트 재시도 로직 (네트워크 불안정 대응)
            let retryCount = 0;
            const maxRetries = 5; // 재시도 횟수 증가
            const retryDelays = [500, 1000, 2000, 3000, 5000]; // 점진적 지연
            
            // 🔥 FIXED: Blob URL 방식 제거 - 모듈 상대 경로 import가 작동하지 않음
            // 네트워크 오류 시 캐시 버스팅 파라미터를 추가한 script 태그로 재시도만 수행
            
            const retryLoadScript = async () => {
              if (retryCount >= maxRetries) {
                console.error('❌ 스크립트 재시도 횟수 초과:', scriptSrc);
                moduleLoadError = true;
                
                // 🔥 React가 이미 렌더링된 경우 오류 페이지 표시하지 않음
                const root = document.getElementById('root');
                const hasReactContent = root && (root.children.length > 0 || window.__REACT_RENDERED__);
                if (!hasReactContent) {
                showNetworkErrorPage({ 
                  message: '네트워크 연결이 불안정합니다. 페이지를 새로고침해주세요.',
                  type: 'networkerror',
                  filename: scriptSrc
                });
                }
                return;
              }
              
              retryCount++;
              const retryDelay = retryDelays[retryCount - 1] || 5000;
              console.log(`🔄 스크립트 재시도 (${retryCount}/${maxRetries}):`, scriptSrc, `지연: ${retryDelay}ms`);
              
              // 네트워크 상태 확인
              if (!navigator.onLine) {
                console.warn('⚠️ 오프라인 상태 - 네트워크 연결 대기');
                setTimeout(retryLoadScript, retryDelay);
                return;
              }
              
              setTimeout(async () => {
                // 🔥 FIXED: Blob URL 방식 제거 - 일반 script 태그 재시도만 수행
                // 기존 스크립트 제거
                const existingScript = document.querySelector(`script[src*="${scriptSrc.split('/').pop()}"]`);
                if (existingScript && existingScript.parentNode) {
                  existingScript.parentNode.removeChild(existingScript);
                }
                
                // 새 스크립트 생성 및 로드 (캐시 무시)
                const newScript = document.createElement('script');
                newScript.type = 'module';
                newScript.crossOrigin = 'anonymous';
                
                // 🔥 QUIC 오류 방지를 위해 HTTP/1.1로 강제 (URL 파라미터 추가)
                const scriptUrl = scriptSrc + '?retry=' + retryCount + '&t=' + Date.now() + '&nocache=' + Math.random() + '&http=1';
                newScript.src = scriptUrl;
                
                newScript.addEventListener('load', function() {
                  scriptLoaded = true;
                  console.log('✅ 스크립트 재시도 성공:', scriptSrc);
                });
                
                newScript.addEventListener('error', function(e) {
                  console.error('❌ 스크립트 재시도 실패:', scriptSrc, e);
                  // 다음 재시도
                  retryLoadScript();
                });
                
                document.head.appendChild(newScript);
              }, retryDelay);
            };
            
            mainScript.addEventListener('error', async function(e) {
              console.error('❌ 메인 스크립트 로드 실패:', scriptSrc, e);
              
              // 네트워크 오류 감지 강화 (ERR_CONNECTION_CLOSED 등)
              const errorMsg = String(e.message || e.type || '');
              const errorSrc = String(e.target?.src || '');
              const errorString = JSON.stringify(e).toLowerCase();
              
              // 🔥 Preload 링크 실패로 인한 오류인지 확인
              // Preload 실패는 메인 스크립트 로드에 영향을 줄 수 있음
              const isPreloadRelated = errorMsg.includes('Failed to resolve module') ||
                                      errorMsg.includes('module specifier') ||
                                      errorSrc.includes('vendor-react-core') ||
                                      errorSrc.includes('vendor-firebase');
              
              // 🔥 QUIC 프로토콜 오류 특별 처리
              const isQuicError = errorMsg.includes('ERR_QUIC_PROTOCOL_ERROR') ||
                                 errorSrc.includes('ERR_QUIC_PROTOCOL_ERROR') ||
                                 errorString.includes('quic');
              
              // 🔥 ERR_CONNECTION_CLOSED 명시적 감지 (네트워크 불안정)
              // 이 오류는 브라우저 콘솔에만 나타나고 이벤트 객체에는 포함되지 않을 수 있음
              const isConnectionClosed = errorMsg.includes('ERR_CONNECTION_CLOSED') ||
                                        errorSrc.includes('ERR_CONNECTION_CLOSED') ||
                                        errorString.includes('connection_closed') ||
                                        errorString.includes('err_connection_closed');
              
              // ERR_CONNECTION_CLOSED는 보통 이벤트 객체에 직접 포함되지 않으므로
              // 모든 네트워크 관련 오류를 재시도 대상으로 처리
              const isNetworkError = (
                isConnectionClosed ||
                isQuicError ||
                isPreloadRelated ||
                errorMsg.includes('ERR_NETWORK') ||
                errorMsg.includes('ERR_CONNECTION_RESET') ||
                errorMsg.includes('connection') ||
                errorMsg.includes('network') ||
                errorSrc.includes('ERR_CONNECTION_CLOSED') ||
                errorSrc.includes('ERR_CONNECTION_RESET') ||
                errorString.includes('connection_closed') ||
                errorString.includes('connection_reset') ||
                errorString.includes('network') ||
                e.type === 'error' // 모든 error 타입은 네트워크 오류 가능성
              );
              
              if (isNetworkError && retryCount < maxRetries) {
                console.log('🔄 네트워크 오류 감지 - 자동 재시도 시작');
                
                // 🔥 네트워크 오류 시 무조건 preload 링크 제거 (preload가 오히려 방해될 수 있음)
                // ERR_CONNECTION_CLOSED는 preload 링크 실패의 신호일 수 있음
                const preloadLinks = document.querySelectorAll('link[rel="modulepreload"]');
                if (preloadLinks.length > 0) {
                  console.log('⚠️ 네트워크 오류 감지 - 모든 preload 링크 제거 후 직접 로드 시도');
                  preloadLinks.forEach(link => {
                    console.log('🗑️ Preload 링크 제거:', link.href);
                    link.remove();
                  });
                }
                
                // 🔥 FIXED: Blob URL 방식 제거 - 일반 script 태그 재시도만 수행
                retryLoadScript();
                return;
              }
              
              moduleLoadError = true;
              scriptLoaded = false;
            });
            
            // 스크립트가 이미 로드되었을 수도 있음
            if (mainScript.readyState === 'complete' || mainScript.readyState === 'loaded') {
              scriptLoaded = true;
            }
            
            // 스크립트 로드 상태 주기적 확인 (네트워크 오류로 이벤트가 발생하지 않을 수 있음)
            let scriptCheckCount = 0;
            const scriptCheckInterval = setInterval(() => {
              scriptCheckCount++;
              
              // React가 렌더링되었으면 스크립트는 로드된 것으로 간주
              const root = document.getElementById('root');
              if (root && (root.children.length > 0 || root.innerHTML.trim().length > 0)) {
                scriptLoaded = true;
                clearInterval(scriptCheckInterval);
                console.log('✅ React 렌더링 확인 - 스크립트 로드 상태 업데이트');
                return;
              }
              
              // 5초 후에도 확인되지 않으면 중단
              if (scriptCheckCount >= 5) {
                clearInterval(scriptCheckInterval);
              }
            }, 1000);
          } else {
            console.warn('⚠️ 메인 스크립트를 찾을 수 없습니다');
          }
        
            // React 로드 확인 (빠른 확인)
            let checkCount = 0;
            const checkInterval = setInterval(function() {
              checkCount++;
              const root = document.getElementById('root');
              
              // 🔥 디버깅: root 요소 상태 확인
              if (checkCount % 5 === 0) {
                console.log('🔍 root 요소 상태 체크:', {
                  exists: !!root,
                  childrenCount: root?.children.length || 0,
                  innerHTMLLength: root?.innerHTML.trim().length || 0,
                  textContentLength: root?.textContent.trim().length || 0,
                  hasReactRendered: window.__REACT_RENDERED__,
                  checkCount
                });
              }
              
              // 🔥 React 렌더링 확인 (더 엄격한 체크)
              const hasReactContent = root && (
                root.children.length > 0 || 
                (root.innerHTML.trim().length > 0 && !root.innerHTML.includes('noscript')) ||
                (root.textContent.trim().length > 0 && !root.textContent.includes('You need to enable JavaScript'))
              );
              
              if (hasReactContent || window.__REACT_RENDERED__) {
                console.error('✅ React 렌더링 확인됨', {
                  hasReactContent,
                  __REACT_RENDERED__: window.__REACT_RENDERED__,
                  rootChildren: root?.children.length,
                  rootHTML: root?.innerHTML.substring(0, 100)
                });
                window.__REACT_RENDERED__ = true;
                
                clearInterval(checkInterval);
              } else if (checkCount >= 20) {
                // 20초 후에도 React가 렌더링되지 않으면 (원격 모드에서 네트워크 지연 고려)
                console.error('❌ React가 렌더링되지 않았습니다 (20초 경과)');
                
                // 개발 환경에서만 타임아웃 박스 표시
                if (!isProduction) {
                  const timeoutDiv = document.createElement('div');
                  timeoutDiv.style.cssText = 'padding:20px;color:orange;background:white;z-index:99999;position:fixed;top:100px;left:10px;right:10px;border:2px solid orange;';
                  const networkStatus = navigator.onLine ? '✅ 온라인' : '❌ 오프라인';
                  timeoutDiv.innerHTML = '<h2 style="color:orange;">로딩 시간 초과</h2><p>React가 20초 내에 렌더링되지 않았습니다.</p><p>네트워크 상태: ' + networkStatus + '</p><p>스크립트 로드: ' + (scriptLoaded ? '✅' : '❌') + '</p><p>위치: ' + location.href + '</p><p>콘솔을 확인하세요.</p>';
                  document.body.appendChild(timeoutDiv);
                }
                clearInterval(checkInterval);
              } else if (checkCount >= 10 && !scriptLoaded) {
                // 10초 후에도 스크립트가 로드되지 않으면 경고
                console.warn('⚠️ 스크립트 로드 지연 (10초 경과)');
                
                // 스크립트가 실제로 존재하는지 확인
                if (mainScript) {
                  const scriptUrl = mainScript.getAttribute('src');
                  fetch(scriptUrl, { method: 'HEAD', cache: 'no-cache' })
                    .then(response => {
                      if (!response.ok) {
                        console.error('❌ 스크립트 파일을 찾을 수 없습니다:', scriptUrl, response.status);
                        // 🔥 React가 이미 렌더링된 경우 오류 페이지 표시하지 않음
                        const root = document.getElementById('root');
                        const hasReactContent = root && (root.children.length > 0 || window.__REACT_RENDERED__);
                        if (!hasReactContent) {
                        showNetworkErrorPage({ 
                          message: '스크립트 파일을 찾을 수 없습니다: ' + scriptUrl,
                          type: 'networkerror'
                        });
                        }
                      }
                    })
                    .catch(err => {
                      console.error('❌ 스크립트 파일 접근 실패:', scriptUrl, err);
                      // 🔥 React가 이미 렌더링된 경우 오류 페이지 표시하지 않음
                      const root = document.getElementById('root');
                      const hasReactContent = root && (root.children.length > 0 || window.__REACT_RENDERED__);
                      if (!hasReactContent) {
                      showNetworkErrorPage({ 
                        message: '네트워크 오류: ' + err.message,
                        type: 'networkerror'
                      });
                      }
                    });
                }
                
              }
        }, 1000);
      })();
    </script>
    
    <!-- 🔥🔥🔥 스플래시 화면 강제 숨김 (빌드 과정과 무관하게 항상 실행) -->
    <script>
      (function() {
        'use strict';
        
        console.log('🔥🔥🔥 index.html 스플래시 숨김 코드 실행 시작 🔥🔥🔥');
        
        // 🔥 WebView 감지
        const isWebView = /wv/.test(navigator.userAgent) || 
                          /Android.*wv/.test(navigator.userAgent) ||
                          location.href === 'https://localhost/' ||
                          location.href.startsWith('https://localhost');
        
        console.log('🔥 index.html 스플래시 숨김 체크:', { 
          isWebView, 
          location: location.href,
          userAgent: navigator.userAgent 
        });
        
        if (isWebView) {
          console.log('✅ index.html에서 스플래시 숨김 로직 실행');
          
          // 🔥 방법 1: DOM 직접 조작으로 스플래시 숨김
          const hideSplashByDOM = () => {
            try {
              const splashSelectors = [
                '#splash',
                '[data-splash]',
                '.splash-screen',
                '.splash',
                '[class*="splash"]',
                '[id*="splash"]',
                'capacitor-splash-screen',
                '[data-capacitor-splash]'
              ];
              
              let hiddenCount = 0;
              splashSelectors.forEach(selector => {
                try {
                  const elements = document.querySelectorAll(selector);
                  elements.forEach(el => {
                    if (el) {
                      el.style.display = 'none';
                      el.style.visibility = 'hidden';
                      el.style.opacity = '0';
                      el.style.pointerEvents = 'none';
                      el.style.zIndex = '-9999';
                      hiddenCount++;
                    }
                  });
                } catch (e) {
                  // selector 오류 무시
                }
              });
              
              // 전체 화면을 덮는 div 찾기
              try {
                const allDivs = document.querySelectorAll('div');
                allDivs.forEach(div => {
                  const style = window.getComputedStyle(div);
                  const bgImage = style.backgroundImage;
                  const zIndex = parseInt(style.zIndex, 10);
                  
                  if (bgImage && bgImage !== 'none' && zIndex > 1000) {
                    const rect = div.getBoundingClientRect();
                    if (rect.width >= window.innerWidth * 0.9 && rect.height >= window.innerHeight * 0.9) {
                      div.style.display = 'none';
                      div.style.visibility = 'hidden';
                      div.style.opacity = '0';
                      hiddenCount++;
                    }
                  }
                });
              } catch (e) {
                // 무시
              }
              
              if (hiddenCount > 0) {
                console.log(`✅ index.html DOM 조작으로 ${hiddenCount}개 스플래시 요소 숨김`);
              }
            } catch (err) {
              console.warn('⚠️ index.html DOM 조작 실패:', err);
            }
          };
          
          // 🔥 방법 2: CSS 주입으로 스플래시 숨김
          const hideSplashByCSS = () => {
            try {
              const styleId = 'force-hide-splash-index-html';
              let styleElement = document.getElementById(styleId);
              if (!styleElement) {
                styleElement = document.createElement('style');
                styleElement.id = styleId;
                styleElement.textContent = `
                  #splash, [data-splash], .splash-screen, .splash,
                  [class*="splash"], [id*="splash"], capacitor-splash-screen,
                  [data-capacitor-splash] {
                    display: none !important;
                    visibility: hidden !important;
                    opacity: 0 !important;
                    pointer-events: none !important;
                    z-index: -9999 !important;
                  }
                `;
                document.head.appendChild(styleElement);
                console.log('✅ index.html CSS 주입으로 스플래시 숨김');
              }
            } catch (err) {
              console.warn('⚠️ index.html CSS 주입 실패:', err);
            }
          };
          
          // 🔥 방법 3: Capacitor 플러그인 호출 (window.Capacitor 직접 사용)
          const hideSplashByPlugin = () => {
            try {
              // window.Capacitor가 로드될 때까지 대기
              if (typeof window.Capacitor !== 'undefined' && window.Capacitor?.Plugins?.SplashScreen) {
                try {
                  window.Capacitor.Plugins.SplashScreen.hide();
                  console.log('✅ index.html SplashScreen.hide() 성공 (직접 호출)');
                } catch (err) {
                  console.warn('⚠️ index.html SplashScreen.hide() 실패:', err);
                }
              } else {
                // Capacitor가 아직 로드되지 않았으면 나중에 시도
                setTimeout(() => {
                  if (typeof window.Capacitor !== 'undefined' && window.Capacitor?.Plugins?.SplashScreen) {
                    try {
                      window.Capacitor.Plugins.SplashScreen.hide();
                      console.log('✅ index.html SplashScreen.hide() 성공 (지연 호출)');
                    } catch (err) {
                      console.warn('⚠️ index.html SplashScreen.hide() 실패:', err);
                    }
                  }
                }, 500);
              }
            } catch (err) {
              console.warn('⚠️ index.html 플러그인 호출 실패:', err);
            }
          };
          
          // 🔥 즉시 실행 (DOM 조작 + CSS 주입)
          hideSplashByDOM();
          hideSplashByCSS();
          
          // 🔥 추가 시도: 50ms 후
          setTimeout(() => {
            console.log('🔥 index.html 50ms 후 스플래시 숨김 재시도');
            hideSplashByDOM();
            hideSplashByCSS();
            hideSplashByPlugin();
          }, 50);
          
          // 🔥 추가 시도: 100ms 후
          setTimeout(() => {
            console.log('🔥 index.html 100ms 후 스플래시 숨김 재시도');
            hideSplashByDOM();
            hideSplashByCSS();
            hideSplashByPlugin();
          }, 100);
          
          // 🔥 추가 시도: 300ms 후
          setTimeout(() => {
            console.log('🔥 index.html 300ms 후 스플래시 숨김 재시도');
            hideSplashByDOM();
            hideSplashByCSS();
            hideSplashByPlugin();
          }, 300);
          
          // 🔥 추가 시도: 500ms 후
          setTimeout(() => {
            console.log('🔥 index.html 500ms 후 스플래시 숨김 재시도');
            hideSplashByDOM();
            hideSplashByCSS();
            hideSplashByPlugin();
          }, 500);
          
          // 🔥 추가 시도: 1초 후
          setTimeout(() => {
            console.log('🔥 index.html 1초 후 스플래시 숨김 재시도');
            hideSplashByDOM();
            hideSplashByCSS();
            hideSplashByPlugin();
          }, 1000);
          
          // 🔥 추가 시도: 2초 후
          setTimeout(() => {
            console.log('🔥 index.html 2초 후 스플래시 숨김 재시도');
            hideSplashByDOM();
            hideSplashByCSS();
            hideSplashByPlugin();
          }, 2000);
        } else {
          console.log('⚠️ index.html 스플래시 숨김 스킵 (WebView가 아님)');
        }
      })();
    </script>
    
  </body>
</html>