<!doctype html>
<html lang="my">
  <head>
    <meta name="kairos-build-id" content="msikz1qv-kok80k" />
    <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="#1B3670" />
    <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="black-translucent" />
    <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" />
    
    <link rel="dns-prefetch" href="https://api.kairos-global-k.com" />
    <link rel="preconnect" href="https://api.kairos-global-k.com" />
    <link rel="dns-prefetch" href="https://kairos-api.web.app" />
    <link rel="preconnect" href="https://kairos-api.web.app" />
    <link rel="dns-prefetch" href="https://kairos-platform-1ffde.web.app" />
    <link rel="preconnect" href="https://kairos-platform-1ffde.web.app" />
    <link rel="dns-prefetch" href="https://firestore.googleapis.com" />
    <link rel="dns-prefetch" href="https://www.googleapis.com" />
    
    <link rel="apple-touch-icon" href="/apple-touch-icon.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" />

    <!-- Auth fintech typography -->
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" />
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@500;600;700&family=Noto+Sans+Myanmar:wght@400;500;600;700&display=swap" rel="stylesheet" />
    
    <!-- 스플래시 스크린 (iOS) -->
    <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);

        // 설치된 PWA(홈 아이콘)가 / 로 열리면 React 전에 로그인으로 이동
        // (OS 스플래시=흰 배경+로고 상태에서 웰컴 페이지에 멈추는 문제 방지)
        // 단, 하드 업데이트(/?_boot= 또는 pending 플래그) 중에는 가로채지 않음
        try {
          var isStandalonePwa =
            (window.navigator && window.navigator.standalone === true) ||
            (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches);
          var pathOnly = location.pathname || '/';
          var isHardUpdateBoot =
            (location.search && location.search.indexOf('_boot=') !== -1) ||
            (function () {
              try {
                return sessionStorage.getItem('kairos_pending_hard_update') === '1';
              } catch (e2) {
                return false;
              }
            })();
          if (isStandalonePwa && (pathOnly === '/' || pathOnly === '') && !isHardUpdateBoot) {
            console.error('🔥 Standalone PWA → /login 즉시 이동');
            location.replace('/login' + (location.search || '') + (location.hash || ''));
            return;
          }
        } catch (e) {
          console.warn('Standalone redirect skip:', e);
        }
        
        // Capacitor 네이티브 앱 감지
        const isCapacitor = typeof window !== 'undefined' && 
          (window.Capacitor !== undefined || 
           location.protocol === 'file:' ||
           location.hostname === '' ||
           /capacitor/.test(navigator.userAgent));
        
        // Capacitor 네이티브는 webDir이 https://localhost 로 서빙되므로 로컬 개발과 구분
        const isLocalDev = !isCapacitor && /^(localhost|127\.0\.0\.1|\[::1\])$/.test(location.hostname);

        var isStandaloneDisplay = false;
        try {
          isStandaloneDisplay =
            (window.navigator && window.navigator.standalone === true) ||
            (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches);
        } catch (e) { /* ignore */ }
        
        console.error('🔥 Capacitor 감지:', isCapacitor);
        console.error('🔥 로컬 개발 환경:', isLocalDev);
        console.error('🔥 Standalone display:', isStandaloneDisplay);

        // 캐시 강제 초기화: ?clear_sw=1 또는 버전 키 변경 시에만 (매 방문 wipe 금지 — Chrome 첫 화면 지연 원인)
        var SW_BUST_VERSION = '20260720a';
        var forceClearSw = /[?&]clear_sw=1(?:&|$)/.test(location.search || '');
        var needsOneTimeSwClear = false;
        try {
          if (!isLocalDev && !isCapacitor && localStorage.getItem('kairos_sw_bust') !== SW_BUST_VERSION) {
            needsOneTimeSwClear = true;
            localStorage.setItem('kairos_sw_bust', SW_BUST_VERSION);
          }
        } catch (e) { /* ignore */ }

        function waitForSWActive(registration, maxWait) {
          maxWait = maxWait || 10000;
          return new Promise(function (resolve, reject) {
            if (registration.active) {
              resolve(registration);
              return;
            }
            var startTime = Date.now();
            var checkInterval = setInterval(function () {
              if (registration.active) {
                clearInterval(checkInterval);
                resolve(registration);
              } else if (Date.now() - startTime > maxWait) {
                clearInterval(checkInterval);
                reject(new Error('Service Worker activation timeout'));
              }
            }, 100);
            registration.addEventListener('updatefound', function () {
              var newWorker = registration.installing || registration.waiting;
              if (newWorker) {
                newWorker.addEventListener('statechange', function () {
                  if (newWorker.state === 'activated' && registration.active) {
                    clearInterval(checkInterval);
                    resolve(registration);
                  }
                });
              }
            });
          });
        }

        function registerProductionServiceWorkers() {
          var isProduction = location.hostname !== 'localhost' &&
            location.hostname !== '127.0.0.1' &&
            location.hostname.indexOf('localhost') === -1;
          if (!isProduction || !('serviceWorker' in navigator)) return;

          setTimeout(function () {
            navigator.serviceWorker.register('/firebase-messaging-sw.js', { scope: '/' })
              .then(function (registration) {
                console.log('✅ Firebase Messaging SW 등록 완료:', registration.scope);
                return waitForSWActive(registration);
              })
              .catch(function (error) {
                console.error('❌ Firebase Messaging SW 등록 실패:', error);
              });

            fetch('/sw.js', { method: 'HEAD', cache: 'no-store' })
              .then(function (res) {
                var ct = (res.headers.get('content-type') || '').toLowerCase();
                if (!res.ok || ct.indexOf('text/html') !== -1) {
                  console.warn('⚠️ sw.js 없음 또는 HTML 응답 — PWA SW 등록 생략');
                  return null;
                }
                return navigator.serviceWorker.register('/sw.js');
              })
              .then(function (registration) {
                if (!registration) return;
                console.log('✅ PWA Service Worker 등록 완료:', registration.scope);
                return waitForSWActive(registration);
              })
              .catch(function (error) {
                console.warn('⚠️ PWA Service Worker 등록 실패 (비치명적):', error);
              });
          }, 1500);
        }

        async function clearNonFcmServiceWorkersAndCaches() {
          if (!('serviceWorker' in navigator)) return;
          var regs = await navigator.serviceWorker.getRegistrations();
          for (var i = 0; i < regs.length; i++) {
            var reg = regs[i];
            try {
              if (reg.scope && (reg.scope.indexOf('firebase-messaging') !== -1 ||
                  (reg.active && reg.active.scriptURL && reg.active.scriptURL.indexOf('firebase-messaging-sw.js') !== -1))) {
                continue;
              }
              await reg.unregister();
            } catch (e) { /* ignore */ }
          }
          if ('caches' in window) {
            var names = await caches.keys();
            for (var j = 0; j < names.length; j++) {
              try { await caches.delete(names[j]); } catch (e) { /* ignore */ }
            }
          }
        }

        if ('serviceWorker' in navigator) {
          if (isCapacitor || isLocalDev) {
            // 네이티브/로컬: SW 방해 제거
            (async function () {
              try { await clearNonFcmServiceWorkersAndCaches(); } catch (e) { /* ignore */ }
            })();
            window.__restoreSWRegistration = function () {
              console.log('⚠️ 개발/네이티브 — Service Worker 등록 건너뜀');
            };
          } else if (forceClearSw || needsOneTimeSwClear) {
            // 1회성 정리 후에만 wipe (Chrome에서 매 방문 wipe 하면 사이트 열림이 매우 느림)
            console.error('🔥 1회 SW/캐시 정리', { forceClearSw: forceClearSw, needsOneTimeSwClear: needsOneTimeSwClear });
            (async function () {
              try { await clearNonFcmServiceWorkersAndCaches(); } catch (e) { /* ignore */ }
            })();
            window.__restoreSWRegistration = function () {
              registerProductionServiceWorkers();
            };
          } else {
            // 프로덕션 정상 경로: 캐시 유지 → Chrome/PWA 즉시 열림
            console.log('✅ 프로덕션 — 캐시 유지, SW는 React 이후 등록');
            window.__restoreSWRegistration = function () {
              registerProductionServiceWorkers();
            };
          }
        }
        
        if (isCapacitor) {
          console.error('🔥📱 Capacitor 네이티브 앱 감지');
        } else if (isLocalDev) {
          console.error('🔥 로컬 개발 환경');
        } else {
          console.log('✅ 프로덕션 웹 환경');
        }
      })();
    </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-4vLFitdU.js"></script>
    <link rel="stylesheet" href="/assets/index-BOoFMKPY.css">
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!-- 적용/첫 로드 중 흰 화면 방지 (React 마운트 후 제거) -->
    <div id="kairos-boot-splash" style="position:fixed;inset:0;z-index:2147483640;display:flex;align-items:center;justify-content:center;background:#f3f4f6;font-family:system-ui,-apple-system,'Noto Sans Myanmar',sans-serif;">
      <div style="text-align:center;">
        <div style="font-size:28px;font-weight:800;color:#3b82f6;margin-bottom:16px;">Kairos</div>
        <div style="width:36px;height:36px;margin:0 auto;border:3px solid #bfdbfe;border-top-color:#2563eb;border-radius:50%;animation:kairos-spin 0.8s linear infinite;"></div>
      </div>
    </div>
    <style>@keyframes kairos-spin{to{transform:rotate(360deg)}}</style>
    <script>
      (function () {
        function hideSplashIfAppReady() {
          var root = document.getElementById('root');
          var splash = document.getElementById('kairos-boot-splash');
          if (!splash) return;
          if (root && root.children.length > 0) {
            splash.remove();
          }
        }
        setInterval(hideSplashIfAppReady, 300);
        setTimeout(function () {
          // 너무 오래 걸리면 스플래시는 유지하되, 복구 UI가 뜰 수 있게 함
        }, 15000);
      })();
    </script>
    <div id="modal-root"></div>
    <!-- 🔥 프로덕션에서는 디버그 메시지 비활성화 -->
    <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 = '';
        }
        
        // 🔥 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

        // Capacitor 네이티브는 localhost origin이지만 프로덕션 번들
        const isLocalDev = !isCapacitor && (
          window.location.hostname === 'localhost' || 
          window.location.hostname === '127.0.0.1' ||
          window.location.hostname.includes('localhost')
        );
        
        // 프로덕션 환경 감지 (Capacitor 네이티브 포함)
        const isProduction = isCapacitor || (!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 resolveBootLang() {
          try {
            var raw = localStorage.getItem('kairos-language') || localStorage.getItem('i18nextLng') || '';
            var lang = String(raw).split('-')[0].toLowerCase();
            if (lang === 'ko' || lang === 'en' || lang === 'my') return lang;
          } catch (e) {}
          return 'my';
        }

        function bootUiStrings(mode) {
          var lang = resolveBootLang();
          var map = {
            my: {
              brand: 'Kairos',
              updateTitle: 'အက်ပ် အပ်ဒိတ်ရှိပါသည်',
              updateMessage: 'ဗားရှင်းအသစ်ကို သုံးရန် အပ်ဒိတ် ကို နှိပ်ပါ။',
              updateButton: 'အပ်ဒိတ်',
              updating: 'အပ်ဒိတ်လုပ်နေသည်...',
              networkTitle: 'အင်တာနက် ချိတ်ဆက်မှု အမှား',
              networkMessage: 'အင်တာနက်ချိတ်ဆက်မှုကို စစ်ဆေးပြီး ထပ်မံကြိုးစားပါ။',
              retryButton: 'ထပ်မံကြိုးစားမည်'
            },
            ko: {
              brand: '카이로스',
              updateTitle: '업데이트가 있습니다',
              updateMessage: '새 버전을 적용하려면 업데이트를 눌러 주세요.',
              updateButton: '업데이트',
              updating: '업데이트 중...',
              networkTitle: '네트워크 연결 오류',
              networkMessage: '인터넷 연결을 확인하고 다시 시도해주세요.',
              retryButton: '다시 시도'
            },
            en: {
              brand: 'Kairos',
              updateTitle: 'An update is available',
              updateMessage: 'Tap Update to apply the latest version.',
              updateButton: 'Update',
              updating: 'Updating...',
              networkTitle: 'Network connection error',
              networkMessage: 'Check your internet connection and try again.',
              retryButton: 'Try again'
            }
          };
          return map[lang] || map.my;
        }

        function hardApplyBootUpdate() {
          // 현재 페이지에서 SW unregister 금지 → 흰 화면 유발
          // 플래그만 남기고 즉시 루트로 이동, 다음 로드에서 정리
          try {
            sessionStorage.setItem('kairos_pending_hard_update', '1');
            sessionStorage.removeItem('sw_reload_in_progress');
            sessionStorage.removeItem('sw_update_check_blocked');
            localStorage.removeItem('sw_update_available');
          } catch (e) {}
          var splash = document.getElementById('kairos-boot-splash');
          if (splash) splash.style.display = 'flex';
          location.replace(location.origin + '/?_boot=' + Date.now());
        }
        window.__kairosApplyBootUpdate = hardApplyBootUpdate;

        // 적용 직후 로드: SW/캐시 정리 → 완료 후에만 /home 재진입
        // (정리와 React 마운트를 병행하면 메인 청크 로드 실패 → 흰 화면)
        (function runPendingHardUpdateFromHtml() {
          try {
            if (sessionStorage.getItem('kairos_pending_hard_update') !== '1') return;
          } catch (e) { return; }

          // main.jsx가 이 로드에서 앱을 마운트하지 않도록 동기 차단
          window.__KAIROS_BLOCK_REACT_MOUNT__ = true;

          var splash = document.getElementById('kairos-boot-splash');
          if (splash) splash.style.display = 'flex';

          var finishAndReload = function () {
            try {
              sessionStorage.removeItem('kairos_pending_hard_update');
              localStorage.removeItem('kairos-pending-build-id');
              localStorage.removeItem('sw_update_available');
            } catch (e) {}
            // 정리 끝난 뒤 깨끗한 로드로 메인 진입 (청크를 네트워크에서 다시 받음)
            location.replace(location.origin + '/home?_updated=' + Date.now());
          };

          var p = Promise.resolve();
          if ('serviceWorker' in navigator) {
            p = p.then(function () {
              return navigator.serviceWorker.getRegistrations().then(function (regs) {
                return Promise.all(regs.map(function (reg) {
                  try { if (reg.waiting) reg.waiting.postMessage({ type: 'SKIP_WAITING' }); } catch (e) {}
                  return reg.unregister();
                }));
              });
            });
          }
          if ('caches' in window) {
            p = p.then(function () {
              return caches.keys().then(function (keys) {
                return Promise.all(keys.map(function (k) { return caches.delete(k); }));
              });
            });
          }
          p.then(finishAndReload).catch(finishAndReload);
        })();

        function showBootUpdateOverlay(forceUpdate) {
          if (document.getElementById('kairos-boot-recovery')) return true;
          var offline = !navigator.onLine && !forceUpdate;
          var t = bootUiStrings();
          var isUpdate = forceUpdate || navigator.onLine;
          var overlay = document.createElement('div');
          overlay.id = 'kairos-boot-recovery';
          overlay.setAttribute('lang', resolveBootLang());
          overlay.style.cssText = 'position:fixed;inset:0;z-index:2147483646;display:flex;align-items:center;justify-content:center;padding:16px;background:#f3f4f6;font-family:system-ui,-apple-system,sans-serif;';
          overlay.innerHTML = '<div style="max-width:400px;width:100%;text-align:center;background:#fff;padding:40px 28px;border-radius:12px;box-shadow:0 4px 6px rgba(0,0,0,0.1);">'
            + '<h1 style="font-size:24px;margin:0 0 16px;font-weight:700;color:#3b82f6;">' + t.brand + '</h1>'
            + '<p style="font-size:16px;margin:0 0 8px;color:#374151;font-weight:600;">' + (isUpdate ? t.updateTitle : t.networkTitle) + '</p>'
            + '<p style="font-size:13px;margin:0 0 24px;color:#9ca3af;line-height:1.5;">' + (isUpdate ? t.updateMessage : t.networkMessage) + '</p>'
            + '<button type="button" id="kairos-boot-recovery-btn" style="padding:12px 28px;background:#3b82f6;color:#fff;border:none;border-radius:8px;cursor:pointer;font-size:15px;font-weight:700;min-width:140px;">'
            + (isUpdate ? t.updateButton : t.retryButton)
            + '</button></div>';
          document.body.appendChild(overlay);
          var btn = document.getElementById('kairos-boot-recovery-btn');
          if (btn) {
            btn.onclick = function () {
              btn.disabled = true;
              btn.textContent = t.updating;
              hardApplyBootUpdate();
            };
          }
          return true;
        }

        // 네트워크/부팅 실패 UI (업데이트면 업데이트 CTA)
        function showNetworkErrorPage(error) {
          const root = document.getElementById('root');
          if (!root) return false;
          
          const hasReactContent = root.children.length > 0 || 
                                 window.__REACT_RENDERED__ ||
                                 (root.innerHTML.trim().length > 0 && 
                                  !root.innerHTML.includes('noscript') &&
                                  !root.innerHTML.includes('네트워크 연결 오류') &&
                                  !document.getElementById('kairos-boot-recovery'));
          
          if (hasReactContent) {
            console.log('⚠️ React가 이미 렌더링됨 - 복구 UI 표시 스킵');
            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'))) {
            // 온라인인데 스크립트/부팅 실패 → 배포 업데이트 UI
            return showBootUpdateOverlay(navigator.onLine);
          }
          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);
        }
        
        // 모듈 로드 오류 감지
        function isBenignLoadError(event) {
          const target = event.target;
          if (target && target !== window && target.tagName) {
            const tag = String(target.tagName).toUpperCase();
            if (tag === 'LINK' || tag === 'IMG' || tag === 'SCRIPT' || tag === 'STYLE') {
              return true;
            }
          }
          if (!event.message && !event.filename && !event.lineno) {
            return true;
          }
          return false;
        }

        window.addEventListener('error', function(e) {
          if (isBenignLoadError(e)) {
            console.warn('⚠️ 리소스 로드 실패 (앱 동작에는 영향 없음):', e.target?.href || e.target?.src || e.target);
            return;
          }

          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/프로덕션에서는 고정 오류 박스 미표시 (ErrorBoundary·콘솔만)
          if (!isCapacitor && !isProduction) {
            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 (!isCapacitor && !isProduction) {
            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) {
                  // 스크립트 로드 실패(배포 후 청크 불일치 포함) → 업데이트 UI
                  showBootUpdateOverlay(true);
                }
                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++;
              // 하드 업데이트 정리 중에는 React를 의도적으로 마운트하지 않음
              if (window.__KAIROS_BLOCK_REACT_MOUNT__) {
                return;
              }
              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?.dataset?.kairosSidebar || el.id === 'mobile-sidebar' || el.id === 'mobile-sidebar-overlay' || el.id === 'kairos-drawer-overlay' || el.id === 'kairos-drawer-panel') {
                      return;
                    }
                    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 => {
                  if (div?.dataset?.kairosSidebar || div.id === 'mobile-sidebar' || div.id === 'mobile-sidebar-overlay' || div.id === 'kairos-drawer-overlay' || div.id === 'kairos-drawer-panel') {
                    return;
                  }
                  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>
    
  
<script>
(function () {
  if (window.__KAIROS_UPDATE_INLINE__) return;
  window.__KAIROS_UPDATE_INLINE__ = true;
  var LOCAL = "msikz1qv-kok80k";
  var EVENT = 'pwa-update-available';
  var lastNotified = null;

  function notify(remoteId) {
    if (!remoteId || remoteId === LOCAL) return;
    if (lastNotified === remoteId) return;
    lastNotified = remoteId;
    try {
      localStorage.setItem('sw_update_available', '1');
      localStorage.setItem('kairos-pending-build-id', remoteId);
    } catch (e) {}
    try {
      window.dispatchEvent(new CustomEvent(EVENT, {
        detail: { source: 'version-json', version: 'build:' + remoteId }
      }));
    } catch (e) {}
    showFallbackBanner(remoteId);
  }

  function resolveLang() {
    try {
      var raw = localStorage.getItem('kairos-language') || localStorage.getItem('i18nextLng') || '';
      var lang = String(raw).split('-')[0].toLowerCase();
      if (lang === 'ko' || lang === 'en' || lang === 'my') return lang;
    } catch (e) {}
    return 'my';
  }

  function strings() {
    var map = {
      my: {
        title: 'အက်ပ် အပ်ဒိတ်ရှိပါသည်',
        message: 'ဗားရှင်းအသစ်ကို သုံးရန် အပ်ဒိတ် ကို နှိပ်ပါ။',
        apply: 'အပ်ဒိတ်',
        applying: 'အပ်ဒိတ်လုပ်နေသည်...'
      },
      ko: {
        title: '업데이트가 있습니다',
        message: '새 버전을 적용하려면 업데이트를 눌러 주세요.',
        apply: '업데이트',
        applying: '업데이트 중...'
      },
      en: {
        title: 'An update is available',
        message: 'Tap Update to apply the latest version.',
        apply: 'Update',
        applying: 'Updating...'
      }
    };
    return map[resolveLang()] || map.my;
  }

  function hardApplyUpdate() {
    try {
      sessionStorage.setItem('kairos_pending_hard_update', '1');
      sessionStorage.removeItem('sw_reload_in_progress');
      sessionStorage.removeItem('sw_update_check_blocked');
      localStorage.removeItem('sw_update_available');
    } catch (e) {}
    var splash = document.getElementById('kairos-boot-splash');
    if (splash) splash.style.display = 'flex';
    location.replace(location.origin + '/?_boot=' + Date.now());
  }

  function showFallbackBanner(remoteId) {
    var t = strings();
    var existing = document.getElementById('kairos-update-fallback');
    if (existing) {
      existing.style.display = 'flex';
      return;
    }
    var bar = document.createElement('div');
    bar.id = 'kairos-update-fallback';
    bar.setAttribute('role', 'status');
    bar.setAttribute('lang', resolveLang());
    bar.style.cssText = 'position:fixed;left:12px;right:12px;top:calc(12px + env(safe-area-inset-top,0px));z-index:2147483000;display:flex;gap:10px;align-items:center;padding:14px 16px;border-radius:14px;background:rgba(15,23,42,.97);color:#fff;box-shadow:0 12px 32px rgba(0,0,0,.35);max-width:520px;margin:0 auto;font-family:system-ui,-apple-system,sans-serif;';
    bar.innerHTML = '<div style="flex:1;min-width:0"><div style="font-size:14px;font-weight:700;margin-bottom:4px">' + t.title + '</div><div style="font-size:13px;opacity:.85">' + t.message + '</div></div><button type="button" id="kairos-update-apply" style="border:none;border-radius:10px;padding:10px 14px;font-weight:700;font-size:14px;background:#2563eb;color:#fff;cursor:pointer">' + t.apply + '</button>';
    (document.body || document.documentElement).appendChild(bar);
    document.getElementById('kairos-update-apply').onclick = function () {
      var btn = document.getElementById('kairos-update-apply');
      if (btn) {
        btn.disabled = true;
        btn.textContent = t.applying;
      }
      if (typeof window.__kairosApplyBootUpdate === 'function') {
        window.__kairosApplyBootUpdate();
        return;
      }
      hardApplyUpdate();
    };
  }

  async function check() {
    try {
      var res = await fetch('/version.json?_=' + Date.now(), { cache: 'no-store' });
      if (!res.ok) return;
      var data = await res.json();
      if (data && data.buildId) notify(data.buildId);
    } catch (e) {}
  }

  if (navigator.serviceWorker) {
    navigator.serviceWorker.addEventListener('message', function (event) {
      var data = event && event.data;
      if (data && data.type === 'KAIROS_APP_UPDATE' && data.buildId) {
        notify(data.buildId);
      }
    });
  }

  setTimeout(check, 2000);
  setInterval(function () {
    if (document.hidden) return;
    check();
  }, 30000);
  document.addEventListener('visibilitychange', function () {
    if (!document.hidden) check();
  });
  window.addEventListener('focus', check);
})();
</script>
</body>
</html>