From 05db17887df5834b0de439371196728256c71582 Mon Sep 17 00:00:00 2001 From: HeuJung Date: Thu, 23 Apr 2026 17:36:31 +0900 Subject: [PATCH] v7.0.0-beta.3 release --- .env.example | 2 +- .env.testing.example | 2 +- CHANGELOG.md | 15 + INSTALL.md | 2 +- README.md | 2 +- .../Commands/Core/CoreUpdateCommand.php | 123 +++++++- .../Core/ExecuteUpgradeStepsCommand.php | 26 ++ app/Exceptions/UpgradeHandoffException.php | 63 ++++ .../Helpers/FilePermissionHelper.php | 82 ++++++ app/Services/CoreUpdateService.php | 39 +++ app/Support/UmaskHelper.php | 64 +++++ bootstrap/app.php | 18 ++ config/app.php | 28 +- docs/extension/plugin-development.md | 99 +++++++ docs/extension/upgrade-step-guide.md | 92 ++++++ docs/frontend/state-management.md | 44 +++ docs/requirements.md | 49 ++++ lang/en/exceptions.php | 5 + lang/ko/exceptions.php | 5 + phpunit.xml | 7 +- .../_bundled/sirsoft-ckeditor5/CHANGELOG.md | 6 + .../_bundled/sirsoft-ckeditor5/composer.json | 2 +- .../sirsoft-ckeditor5/dist/js/plugin.iife.js | 6 +- .../dist/js/plugin.iife.js.map | 2 +- .../_bundled/sirsoft-ckeditor5/package.json | 2 +- .../_bundled/sirsoft-ckeditor5/plugin.json | 4 +- .../resources/js/handlers/initEditor.ts | 6 +- public/build/core/template-engine.min.js | 58 ++-- public/build/core/template-engine.min.js.map | 2 +- public/build/manifest.json | 2 +- resources/js/core/TemplateApp.ts | 4 + resources/js/core/devtools/G7DevToolsCore.ts | 82 ++++++ .../js/core/template-engine/CHANGELOG.md | 14 + .../core/template-engine/DynamicRenderer.tsx | 103 ++++++- .../js/core/template-engine/G7CoreGlobals.ts | 63 +++- .../troubleshooting-state-setstate.test.ts | 271 ++++++++++++++++++ .../ExecuteUpgradeStepsCommandHandoffTest.php | 213 ++++++++++++++ .../Console/CoreUpdateCommandHandoffTest.php | 240 ++++++++++++++++ .../UpgradeHandoffExceptionTest.php | 120 ++++++++ .../Unit/Helpers/FilePermissionHelperTest.php | 130 +++++++++ ...oreUpdateServiceHandoffPropagationTest.php | 139 +++++++++ tests/Unit/Support/UmaskHelperTest.php | 142 +++++++++ .../Upgrades/Upgrade_7_0_0_beta_3Test.php | 213 ++++++++++++++ tests/bootstrap.php | 43 +++ upgrades/Upgrade_7_0_0_beta_3.php | 246 ++++++++++++++++ 45 files changed, 2822 insertions(+), 58 deletions(-) create mode 100644 app/Exceptions/UpgradeHandoffException.php create mode 100644 app/Support/UmaskHelper.php create mode 100644 tests/Feature/Console/Commands/ExecuteUpgradeStepsCommandHandoffTest.php create mode 100644 tests/Feature/Console/CoreUpdateCommandHandoffTest.php create mode 100644 tests/Unit/Exceptions/UpgradeHandoffExceptionTest.php create mode 100644 tests/Unit/Services/CoreUpdateServiceHandoffPropagationTest.php create mode 100644 tests/Unit/Support/UmaskHelperTest.php create mode 100644 tests/Unit/Upgrades/Upgrade_7_0_0_beta_3Test.php create mode 100644 upgrades/Upgrade_7_0_0_beta_3.php diff --git a/.env.example b/.env.example index df659a60..db8b5847 100644 --- a/.env.example +++ b/.env.example @@ -3,7 +3,7 @@ APP_ENV=production APP_KEY= APP_DEBUG=false APP_URL=http://localhost -APP_VERSION=7.0.0-beta.2 +APP_VERSION=7.0.0-beta.3 APP_LOCALE=ko APP_FALLBACK_LOCALE=ko diff --git a/.env.testing.example b/.env.testing.example index 3f0ae2f1..812b54a5 100644 --- a/.env.testing.example +++ b/.env.testing.example @@ -3,7 +3,7 @@ APP_ENV=testing APP_KEY= APP_DEBUG=false APP_URL=http://localhost -APP_VERSION=7.0.0-beta.2 +APP_VERSION=7.0.0-beta.3 APP_LOCALE=ko APP_FALLBACK_LOCALE=ko diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c66edc2..e3de0e47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,21 @@ 형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며, [Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다. +## [7.0.0-beta.3] - 2026-04-23 + +### Fixed + +- CKEditor5 플러그인 활성 상태에서 게시판 글쓰기 저장 시 "제목은 필수입니다" 422 오류가 발생하던 호환성 문제 수정 — 제목·내용 입력 순서와 무관하게 정상 저장되도록 개선 +- 코어 업데이트가 sudo 로 실행된 환경에서 캐시·세션·확장 디렉토리의 그룹 쓰기 권한이 일부 손실되어 업데이트 직후 "Permission denied" 또는 플러그인 제거 검증 실패가 발생하던 문제 수정 — 업데이트 종료 시점에 그룹 쓰기 권한을 자동 정상화하며 기존 손실 분은 1회성 복구 스텝으로 회수 +- 업데이트 완료 후 Laravel 런타임이 새로 만드는 캐시·세션 하위 디렉토리가 기본 umask(022) 때문에 다시 그룹 쓰기 권한을 잃어 재차 "Permission denied" 가 발생하던 문제 수정 — 업그레이드 스텝이 업데이트 진행 프로세스의 umask 를 그룹 쓰기 친화적으로 전환하고, 이후 부팅 시점에도 `storage/` 의 현재 그룹 쓰기 설정을 감지해 프로세스 umask 를 자동 동조 (운영자가 그룹 공유를 비활성화한 환경은 그대로 보존) +- 코어 업데이트 마지막 단계의 진행 표시줄이 끝난 뒤 줄바꿈 없이 다음 셸 프롬프트가 같은 줄에 붙어 표시되던 출력 문제 수정 + +### Notes + +- 7.0.0-beta.1 에서 7.0.0-beta.3 로 직접 업그레이드하는 경우, 환경(opcache CLI 활성 등)에 따라 권한 복구 스텝이 자동 실행되지 않고 건너뛰어질 수 있습니다. 업데이트 후 `storage/framework/cache` 등에서 Permission denied 가 발생하면 아래 명령을 수동 실행해 주세요 — 7.0.0-beta.2 에서 올라오는 경로에서는 해당 없음 + - `php artisan core:execute-upgrade-steps --from=7.0.0-beta.2 --to=7.0.0-beta.3 --force` +- 시스템 레벨에서도 일관된 그룹 공유 권한을 원하면 php-fpm pool 설정에 `umask = 002` (또는 systemd unit 의 `UMask=0002`) 추가를 권장합니다. 코드 레벨 동조와 병행하면 외부 프로세스(cron, composer 등) 도 동일 권한으로 파일을 생성합니다 + ## [7.0.0-beta.2] - 2026-04-20 ### Added diff --git a/INSTALL.md b/INSTALL.md index d285f1d5..febc011e 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -238,7 +238,7 @@ unzip g7-release.zip # 압축 해제 결과 확인 — 루트 디렉토리가 g7이 아니면 이름 변경 ls -la -# (필요 시) mv g7-7.0.0-beta.2 g7 +# (필요 시) mv g7-7.0.0-beta.3 g7 # ZIP 파일 정리 (선택) rm g7-release.zip diff --git a/README.md b/README.md index b90b0ebd..0eed119e 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@

- Version + Version PHP Laravel React diff --git a/app/Console/Commands/Core/CoreUpdateCommand.php b/app/Console/Commands/Core/CoreUpdateCommand.php index a5fde397..42d32503 100644 --- a/app/Console/Commands/Core/CoreUpdateCommand.php +++ b/app/Console/Commands/Core/CoreUpdateCommand.php @@ -3,6 +3,7 @@ namespace App\Console\Commands\Core; use App\Console\Commands\Core\Concerns\BundledExtensionUpdatePrompt; +use App\Exceptions\UpgradeHandoffException; use App\Extension\CoreVersionChecker; use App\Extension\Helpers\CoreBackupHelper; use App\Extension\ModuleManager; @@ -438,11 +439,85 @@ class CoreUpdateCommand extends Command $this->newLine(); $this->info('일괄 업데이트로 생성된 파일의 소유권을 복원하는 중...'); $service->restoreOwnership($ownershipSnapshot, $onProgress); + // restoreOwnership 의 진행 표시($onProgress → $bar->display())가 + // 개행 없이 끝나므로 다음 셸 프롬프트가 같은 줄에 붙는 것을 방지. + $this->newLine(2); $log('일괄 확장 업데이트 후 소유권 재복원 완료'); } return Command::SUCCESS; + } catch (UpgradeHandoffException $e) { + // 업그레이드 스텝이 새 PHP 프로세스 재진입을 요청한 경우. + // + // 롤백하지 않음 — 파일 교체 / migration / composer 결과까지는 이미 `toVersion` 상태로 유효. + // Step 11 cleanup 을 축소 실행하여 중간 상태를 확정하고, 사용자에게 스텝 전용 재실행 안내. + // + // - updateVersionInEnv(toVersion): 디스크가 이미 toVersion 이므로 .env 도 toVersion 으로 + // 일치시킨다. afterVersion 이 아님 — afterVersion 으로 두면 사용자가 다시 core:update + // 를 돌릴 때 GitHub 재다운로드부터 전체가 반복된다. toVersion 으로 고정 + 사용자에게는 + // execute-upgrade-steps 만 실행하도록 안내하여 재다운로드를 회피한다. + // - clearAllCaches: 신규 코드·config 반영 + // - restoreOwnership: sudo 생성 파일 소유권 복원 + // - cleanupPending: _pending 정리 + // - 백업은 유지 (재실행 중 실패해도 복구 가능) + // - maintenance 해제: 서비스 재개 + // + // resumeCommand 는 예외에 명시되지 않았으면 `execute-upgrade-steps --from= + // --to= --force` 로 자동 생성. step 만 단독 실행되어 재다운로드 없음. + $bar->finish(); + $this->newLine(2); + + $log("업그레이드 핸드오프 수신: {$e->afterVersion} 까지 완료 — {$e->reason}"); + + $resumeCommand = $e->resumeCommand ?? sprintf( + 'php artisan core:execute-upgrade-steps --from=%s --to=%s --force', + $e->afterVersion, + $toVersion, + ); + + try { + $service->updateVersionInEnv($toVersion); + $service->clearAllCaches(); + $service->restoreOwnership($ownershipSnapshot, $onProgress); + $log('핸드오프 cleanup 완료 (버전 toVersion 고정 + 캐시 clear + 소유권 복원)'); + + if (! empty($pendingPath)) { + $service->cleanupPending($pendingPath); + } + + if ($maintenanceEnabled) { + $service->disableMaintenanceMode(); + $maintenanceEnabled = false; + $log('유지보수 모드 해제'); + } + } catch (\Throwable $cleanupError) { + $log("핸드오프 cleanup 중 오류: {$cleanupError->getMessage()}"); + $this->warn("핸드오프 cleanup 중 오류 발생 — 수동 점검 필요: {$cleanupError->getMessage()}"); + } + + $this->saveUpdateLog($logEntries, $fromVersion, $toVersion, true); + + $this->newLine(); + $this->warn('업그레이드 파일 반영은 완료되었으나, 일부 업그레이드 스텝이 현재 프로세스에서 실행될 수 없어 중단되었습니다.'); + $this->newLine(); + $this->line(" 완료 스텝 지점: {$e->afterVersion}"); + $this->line(" 파일·설정 버전: {$toVersion} (이미 반영됨)"); + $this->line(" 사유: {$e->reason}"); + $this->newLine(); + $this->info('나머지 스텝을 적용하려면 아래 명령을 실행하세요 (재다운로드 없이 스텝만 실행):'); + $this->line(" {$resumeCommand}"); + $this->newLine(); + $this->warn('⚠ 위 명령을 실행하지 않으면 버전 표시는 최신이지만 일부 스텝이 미실행 상태로 남습니다.'); + $this->newLine(); + + if ($backupPath) { + $this->line("백업이 유지되었습니다: {$backupPath}"); + $this->newLine(); + } + + return Command::SUCCESS; + } catch (\Throwable $e) { $bar->finish(); $this->newLine(2); @@ -538,11 +613,17 @@ class CoreUpdateCommand extends Command * 일 때만 성공으로 판정한다. proc_open 미지원 환경·커맨드 미존재·비정상 종료는 * false 반환하여 호출자가 in-process fallback 으로 전환할 수 있게 한다. * + * 핸드오프 신호: 자식이 exit=UpgradeHandoffException::EXIT_CODE 로 종료하면서 + * stdout 에 `[HANDOFF] ` 라인을 남기면, 본 메서드는 UpgradeHandoffException 을 + * 재구성하여 상위로 던진다 (CoreUpdateCommand::handle 의 catch 블록이 처리). + * * @param string $fromVersion 시작 버전 * @param string $toVersion 대상 버전 * @param bool $force 동일 버전 강제 실행 여부 * @param \Closure $log 로그 엔트리 수집 콜백 * @return bool spawn 성공 여부 (false 면 fallback 실행 필요) + * + * @throws UpgradeHandoffException 자식이 핸드오프 신호를 보낸 경우 */ private function spawnUpgradeStepsProcess(string $fromVersion, string $toVersion, bool $force, \Closure $log): bool { @@ -602,14 +683,37 @@ class CoreUpdateCommand extends Command fclose($pipes[0]); // stdout 실시간 전달 — 상위 콘솔에서 진행 상황 확인 가능 + // 단, [HANDOFF] 접두사 라인은 상위 콘솔로 노출하지 않고 페이로드만 보관한다 + // (exit=UpgradeHandoffException::EXIT_CODE 감지 시 UpgradeHandoffException 재구성용). + $handoffPayload = null; while (! feof($pipes[1])) { $line = fgets($pipes[1]); if ($line !== false) { $trimmed = rtrim($line); - if ($trimmed !== '') { - $this->line($trimmed); - $log('[spawn] '.$trimmed); + if ($trimmed === '') { + continue; } + + if (str_starts_with($trimmed, '[HANDOFF] ')) { + $json = substr($trimmed, strlen('[HANDOFF] ')); + $decoded = json_decode($json, true); + // resumeCommand 는 null 허용 (자식이 null 로 전달한 경우 부모가 + // CoreUpdateCommand catch 분기에서 from/to 기반으로 자동 생성) + if (is_array($decoded) + && array_key_exists('afterVersion', $decoded) + && array_key_exists('reason', $decoded) + && array_key_exists('resumeCommand', $decoded) + ) { + $handoffPayload = $decoded; + $log('[spawn] 핸드오프 신호 수신: after='.$decoded['afterVersion']); + + continue; + } + // 구조가 깨진 핸드오프 라인 — 정상 출력으로 간주해 그대로 전달 + } + + $this->line($trimmed); + $log('[spawn] '.$trimmed); } } @@ -617,6 +721,19 @@ class CoreUpdateCommand extends Command fclose($pipes[2]); $exitCode = proc_close($process); + if ($exitCode === UpgradeHandoffException::EXIT_CODE && $handoffPayload !== null) { + $log("spawn 핸드오프 종료 (exit={$exitCode})"); + + // resumeCommand 가 null 이면 null 그대로 전달 — 상위 catch 에서 자동 생성. + $resume = $handoffPayload['resumeCommand']; + + throw new UpgradeHandoffException( + afterVersion: (string) $handoffPayload['afterVersion'], + reason: (string) $handoffPayload['reason'], + resumeCommand: is_string($resume) ? $resume : null, + ); + } + if ($exitCode === 0) { $log('spawn 완료 (exit=0)'); diff --git a/app/Console/Commands/Core/ExecuteUpgradeStepsCommand.php b/app/Console/Commands/Core/ExecuteUpgradeStepsCommand.php index 477c5239..bf0e9a32 100644 --- a/app/Console/Commands/Core/ExecuteUpgradeStepsCommand.php +++ b/app/Console/Commands/Core/ExecuteUpgradeStepsCommand.php @@ -2,6 +2,7 @@ namespace App\Console\Commands\Core; +use App\Exceptions\UpgradeHandoffException; use App\Services\CoreUpdateService; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; @@ -52,6 +53,31 @@ class ExecuteUpgradeStepsCommand extends Command fn (string $version) => $this->info("upgrade step 실행: {$version}"), $force, ); + } catch (UpgradeHandoffException $e) { + // 업그레이드 스텝이 새 PHP 프로세스 재진입을 요청했다. + // 부모 프로세스(spawnUpgradeStepsProcess)가 [HANDOFF] 라인을 stdout 에서 + // 읽어 페이로드를 복원하고 UpgradeHandoffException 재구성 후 상위로 던지도록, + // JSON 페이로드를 표식과 함께 출력한다. 표식 문자열은 구분자 역할이므로 일반 + // step 출력과 충돌하지 않게 고정된 접두사를 사용한다. + // + // resumeCommand 는 step 작성자가 null 로 두는 것을 권장(CoreUpdateCommand 가 + // from/to 버전을 사용해 자동 생성). null 도 JSON 으로 그대로 전달. + $payload = json_encode([ + 'afterVersion' => $e->afterVersion, + 'reason' => $e->reason, + 'resumeCommand' => $e->resumeCommand, + ], JSON_UNESCAPED_UNICODE); + + $this->line('[HANDOFF] '.$payload); + + Log::info('core:execute-upgrade-steps 핸드오프', [ + 'from' => $from, + 'to' => $to, + 'after' => $e->afterVersion, + 'reason' => $e->reason, + ]); + + return UpgradeHandoffException::EXIT_CODE; } catch (\Throwable $e) { Log::error('core:execute-upgrade-steps 실패', [ 'from' => $from, diff --git a/app/Exceptions/UpgradeHandoffException.php b/app/Exceptions/UpgradeHandoffException.php new file mode 100644 index 00000000..acaef53a --- /dev/null +++ b/app/Exceptions/UpgradeHandoffException.php @@ -0,0 +1,63 @@ + --to= --force` + * 형식으로 자동 생성한다. + * 대부분의 step 작성자는 null 기본값 사용 권장 — + * 전체 `core:update` 재다운로드를 피하고 스텝만 재실행. + */ + public function __construct( + public readonly string $afterVersion, + public readonly string $reason, + public readonly ?string $resumeCommand = null, + ) { + parent::__construct(__('exceptions.core_update.handoff', [ + 'after_version' => $afterVersion, + 'reason' => $reason, + 'resume_command' => $resumeCommand ?? '(auto)', + ])); + } +} diff --git a/app/Extension/Helpers/FilePermissionHelper.php b/app/Extension/Helpers/FilePermissionHelper.php index 66c7471b..a5720c56 100644 --- a/app/Extension/Helpers/FilePermissionHelper.php +++ b/app/Extension/Helpers/FilePermissionHelper.php @@ -312,6 +312,88 @@ class FilePermissionHelper return $report['changed']; } + /** + * 루트 디렉토리가 그룹 쓰기 권한을 가질 때, 하위 디렉토리·파일에 동일 권한을 승격합니다. + * + * 배경: sudo root 로 실행된 코어 업데이트가 umask 022 환경에서 신규 디렉토리/파일을 + * `0755/0644` 로 생성한 뒤 `chownRecursive` 로 소유자만 원본(`jjh:www-data`) 으로 + * 복원하면, 그룹(`www-data`) 에 쓰기 권한이 없는 비대칭이 영구 잔존한다. 결과적으로 + * php-fpm(www-data) 이 `storage/framework/cache/...` 같은 경로에 쓰기 실패. + * + * 본 메서드는 다음 정책으로 비대칭을 해소한다: + * - 루트가 `g+w` 면 하위 항목 중 `g-w` 인 디렉토리·파일을 `g+w` 로 승격 + * - 루트가 `g-w` 면 no-op (운영자가 의도적으로 그룹 쓰기 차단한 정책 보존) + * - 다른 비트(other, owner, sticky, setgid 등) 무변경 — `g+w` 만 OR + * - symbolic link 는 링크 자체만 처리 (대상 미추적) + * - 멱등 — 이미 정상인 항목은 changed 카운트에 포함 안 함 + * - silent fail — 권한 부족·chmod 미지원 환경에서도 예외 미발생 + * + * @param string $root 대상 루트 (재귀 순회) + * @return int 실제 chmod 한 항목 수 + */ + public static function syncGroupWritability(string $root): int + { + if (! function_exists('chmod') || ! is_dir($root)) { + return 0; + } + + $rootPerms = @fileperms($root); + if ($rootPerms === false) { + return 0; + } + + // 루트가 g+w 가 아니면 정책 보존 (no-op) + if (($rootPerms & 0020) === 0) { + return 0; + } + + $report = ['changed' => 0]; + self::syncGroupWritabilityInternal($root, $report, true); + + if ($report['changed'] > 0) { + Log::info('syncGroupWritability: 그룹 쓰기 권한 정상화', [ + 'root' => $root, + 'changed' => $report['changed'], + ]); + } + + return $report['changed']; + } + + /** + * syncGroupWritability 내부 재귀. + * + * @param string $path 대상 경로 + * @param array{changed:int} $report 집계 (참조) + * @param bool $isRoot 루트 자체는 정책 판정용으로만 사용 (chmod 안 함) + */ + private static function syncGroupWritabilityInternal(string $path, array &$report, bool $isRoot = false): void + { + // symbolic link 는 대상 추적 금지 + if (is_link($path)) { + return; + } + + if (! $isRoot) { + $perms = @fileperms($path); + if ($perms !== false && ($perms & 0020) === 0) { + // g+w 만 추가, 다른 비트 무변경 + if (@chmod($path, $perms | 0020)) { + $report['changed']++; + } + } + } + + if (! is_dir($path)) { + return; + } + + $items = new \FilesystemIterator($path, \FilesystemIterator::SKIP_DOTS); + foreach ($items as $item) { + self::syncGroupWritabilityInternal($item->getPathname(), $report, false); + } + } + /** * chownRecursive 의 내부 재귀 구현. 실패 카운터를 참조 전달로 집계한다. * diff --git a/app/Services/CoreUpdateService.php b/app/Services/CoreUpdateService.php index 960febd4..a1a75850 100644 --- a/app/Services/CoreUpdateService.php +++ b/app/Services/CoreUpdateService.php @@ -1182,6 +1182,12 @@ class CoreUpdateService * 코어 업그레이드 스텝을 실행합니다. * 각 스텝에서 환경설정 파일 생성, 데이터 마이그레이션 등을 수행합니다. * + * 예외 전파 정책: + * - 일반 예외 (\Throwable): 그대로 상위 전파. CoreUpdateCommand 가 catch 후 롤백. + * - UpgradeHandoffException: 그대로 상위 전파. CoreUpdateCommand 가 catch 후 롤백 없이 + * .env APP_VERSION 을 afterVersion 으로 고정, maintenance 해제, 사용자에게 재실행 안내. + * 즉 "해당 스텝 직전까지의 상태를 확정 + 재진입 지점 지정" 시나리오에 사용. + * * @param string $fromVersion 시작 버전 * @param string $toVersion 종료 버전 * @param \Closure|null $onStep 각 스텝 실행 시 콜백 (버전 문자열 전달) @@ -1532,9 +1538,13 @@ class CoreUpdateService continue; } + // 7.0.0-beta.3+: target 루트 퍼미션을 perms 필드로 추가 스냅샷. + // restoreOwnership 이 sudo 업데이트로 인한 그룹 쓰기 권한 비대칭을 + // 정상화할 때 사용 (Laravel 런타임 쓰기 경로에 한해). $snapshot[$target] = [ 'owner' => @fileowner($path), 'group' => @filegroup($path), + 'perms' => (@fileperms($path) & 0777) ?: null, ]; } @@ -1618,6 +1628,35 @@ class CoreUpdateService } } + // 7.0.0-beta.3+: Laravel 런타임 쓰기 경로(storage/, bootstrap/cache/) 에 한해 + // 그룹 쓰기 권한 비대칭 정상화. sudo root 업데이트가 umask 022 로 신규 생성한 + // 하위 디렉토리(g-w) 가 chownRecursive 후에도 g-w 로 남아 php-fpm(www-data 그룹) + // 이 cache 쓰기 실패하는 문제를 구조적으로 차단. + // + // 정책: 루트가 g+w 면 하위 g-w 항목을 g+w 로 승격, 그 외 비트 무변경. + // 운영자가 의도적으로 그룹 쓰기를 차단한 경로는 보존됨. + $groupWritableTargets = config('app.update.restore_ownership_group_writable', [ + 'storage', + 'bootstrap/cache', + ]); + $groupWritableChanged = 0; + foreach ($groupWritableTargets as $target) { + $path = base_path($target); + if (! File::isDirectory($path)) { + continue; + } + + $onProgress?->__invoke('group_writable', $target); + $groupWritableChanged += FilePermissionHelper::syncGroupWritability($path); + } + + if ($groupWritableChanged > 0) { + Log::info('코어 업데이트: 그룹 쓰기 권한 정상화', [ + 'targets' => $groupWritableTargets, + 'changed_entries' => $groupWritableChanged, + ]); + } + if ($restoredCount > 0) { Log::info('코어 업데이트: 소유권 복원 완료', [ 'restored_entries_total' => $restoredCount, diff --git a/app/Support/UmaskHelper.php b/app/Support/UmaskHelper.php new file mode 100644 index 00000000..2a1e937a --- /dev/null +++ b/app/Support/UmaskHelper.php @@ -0,0 +1,64 @@ +`) 도 g+w 를 +| 유지하도록 프로세스 umask 를 0002 로 조정한다. 이 동조가 없으면 기본 umask 022 +| 로 인해 `0755` (drwxr-xr-x) 로 만들어져 php-fpm(www-data) 그룹 쓰기가 실패한다. +| +| `storage/` 에 g-w 가 설정된 경우(일부 공유 호스팅 특수 환경) 에는 운영자 +| 의도를 존중하여 umask 를 건드리지 않는다. `umask` 함수 자체가 비활성인 +| 환경에서도 조용히 스킵한다. 상세: App\Support\UmaskHelper. +| +*/ +UmaskHelper::configureForGroupSharing(dirname(__DIR__).'/storage'); + /* |-------------------------------------------------------------------------- | Disable putenv() for Thread Safety diff --git a/config/app.php b/config/app.php index 16037389..952f7c19 100644 --- a/config/app.php +++ b/config/app.php @@ -211,7 +211,7 @@ return [ | */ - 'version' => env('APP_VERSION', '7.0.0-beta.2'), + 'version' => env('APP_VERSION', '7.0.0-beta.3'), /* |-------------------------------------------------------------------------- @@ -266,6 +266,32 @@ return [ 'G7_UPDATE_RESTORE_OWNERSHIP', 'storage,bootstrap/cache,vendor,modules,modules/_pending,plugins,plugins/_pending,templates,templates/_pending,storage/app/core_pending' )))), + // 7.0.0-beta.3+: 그룹 쓰기 권한 비대칭 정상화 대상. + // sudo root 로 실행된 업데이트가 umask 022 로 신규 생성한 하위 디렉토리/파일이 + // chownRecursive 후에도 g-w 로 남아 php-fpm(www-data 그룹) 이 쓰기 실패하는 + // 문제를 차단하기 위해, restoreOwnership 종료 직후 본 경로들에 한해 + // FilePermissionHelper::syncGroupWritability 를 호출한다. + // + // 정책: 루트가 g+w 면 하위 g-w 항목을 g+w 로 승격, 다른 비트 무변경. + // 운영자가 의도적으로 그룹 쓰기를 차단한 경로(0755 등) 는 자동 보존됨. + // + // Laravel 런타임 그룹 쓰기 필요 경로 — 인스톨러 SSoT(public/install/includes/config.php + // REQUIRED_DIRECTORIES) 와 1:1 정렬: + // - storage, bootstrap/cache: 캐시·세션·로그 + // - vendor: composer/sudo 가 root 로 재생성한 후 일반 권한 사용자/php-fpm 이 후속 작업 + // - modules, plugins, templates: 확장 설치/업데이트/제거 시 php-fpm 이 디렉토리 조작 + // - modules/_pending, plugins/_pending, templates/_pending: 다운로드 대기소 + // - storage/app/core_pending: 코어 업데이트 _pending 영역 (storage 재귀로도 커버되지만 + // SSoT 정렬 위해 명시) + // + // _bundled/ 는 개발 시점 원본 배포본이므로 런타임 쓰기 불필요 — SSoT 에도 미포함. + // + // 자식 디렉토리(예: plugins/sirsoft-*)는 syncGroupWritability 가 재귀 순회하여 + // 자동 정상화되므로 상위 루트만 지정하면 충분. 환경변수로 재정의 가능. + 'restore_ownership_group_writable' => array_filter(array_map('trim', explode(',', env( + 'G7_UPDATE_RESTORE_OWNERSHIP_GROUP_WRITABLE', + 'storage,bootstrap/cache,vendor,modules,modules/_pending,plugins,plugins/_pending,templates,templates/_pending,storage/app/core_pending' + )))), ], ]; diff --git a/docs/extension/plugin-development.md b/docs/extension/plugin-development.md index ca3c6cff..04d1412f 100644 --- a/docs/extension/plugin-development.md +++ b/docs/extension/plugin-development.md @@ -1206,6 +1206,105 @@ public function seoVariables(): array --- +## 폼 상태 정합성 — 이중 저장소 전제와 자동 동기화 (engine-v1.43.0+) + +플러그인이 폼(Form) 내부에서 `G7Core.state.setLocal({render: false})` 패턴을 사용하는 경우, 엔진의 **이중 저장소 구조**를 이해하고 있어야 한다. 이 구조는 "단일화 실패 이력"의 결과이며 엔진 설계 전제이다. + +### 이중 저장소 구조 개요 + +엔진은 폼 데이터를 두 저장소에 분리 관리한다: + +| 저장소 | 실체 | 쓰는 곳 | 읽는 곳 | +| ------ | ---- | ------- | ------- | +| **A** | React `localDynamicState` (useState) | Form 자동바인딩 (Input/Textarea onChange) | DOM value, 부분 리렌더 | +| **B** | `globalState._local` (TemplateApp 싱글톤) | `G7Core.state.setLocal/getLocal` | apiCall body 바인딩, 플러그인 동기화 | + +두 저장소는 engine-v1.43.0부터 엔진이 자동으로 동기화한다. 일반 플러그인은 이 구조를 의식할 필요가 없다. + +### 왜 저장소를 하나로 통합하지 않는가 + +B로 단일화하면 매 keystroke마다 TemplateApp 전체 리렌더가 발생해 대형 폼에서 타이핑 지연이 생긴다. 이를 완화할 구독 기반 선택적 리렌더(`StateSubscriptionManager`)는 2026-01에 필터 체크박스 253~295ms 지연으로 롤백된 실패 경로다. 이중 저장소 전제는 엔진 설계 결과이지 개선 대상이 아니다. + +### 엔진 자동 동기화 메커니즘 + +1. **A→B 방향**: 자동바인딩의 `performStateUpdate`가 A에 쓸 때 B에도 `setLocal({render: false})`로 동기 기록 +2. **B→A 방향**: 엔진이 자동바인딩 활성 경로를 `__g7AutoBindingPaths: Map`에 추적. 플러그인이 `setLocal({render: false})`로 그 경로를 건드리면 엔진이 **자동으로 `render: true`로 승격**하여 A 동기화 유도 +3. **예외**: `selfManaged: true`를 명시한 호출은 자동 승격에서 제외 (CKEditor5 등 자체 DOM 관리 플러그인용) + +### `G7Core.state.setLocal` 옵션 레퍼런스 + +```typescript +G7Core.state.setLocal(updates, options?: { + scope?: 'current' | 'parent' | 'root'; // 스코프 지정 + merge?: 'replace' | 'shallow' | 'deep'; // 병합 방식 (기본 'deep') + debounce?: number; // 디바운스 ms + debounceKey?: string; // 디바운스 키 + render?: boolean; // React 리렌더 여부 (기본 true) + selfManaged?: boolean; // 자동 승격 opt-out (기본 undefined/false) +}); +``` + +### `selfManaged: true` 옵션 사용 규칙 (중요) + +**역할**: 엔진의 자동 리렌더 승격 보호를 끄는 opt-out 스위치. "이 플러그인은 React 없이 자기가 DOM을 직접 관리하니 엔진은 자동 승격 오지랖을 끄고 원래 `render: false`를 유지해 달라"는 의도적 선언. + +**기본값**: `undefined` (사실상 `false`). **옵션을 생략하면 엔진이 자동 승격 보호를 적용**한다. + +**언제 `true`로 설정하는가**: + +- 플러그인이 React 컴포넌트가 아니라 JavaScript로 직접 DOM 요소를 조작하는 독립 위젯을 쓸 때 (CKEditor5, Monaco Editor 등) +- 매 keystroke마다 전체 트리 리렌더가 성능상 허용 안 되는 경우 +- 플러그인이 자체 `setData()`/`setValue()` 방식으로 UI를 직접 갱신하고 React 재렌더에 의존하지 않는 구조 + +**언제 생략하는가 (기본)**: + +- 일반적인 모든 플러그인. 엔진이 자동으로 정합성 확보 +- **초보자는 `selfManaged`를 몰라도 되고 모르는 편이 안전** (safe-by-default) + +### 플러그인 개발 체크리스트 + +새 플러그인이 폼 내부에서 `setLocal`을 쓰는 경우 다음을 확인: + +- [ ] `setLocal({render: false})`를 호출하는가? +- [ ] 해당 경로의 React 컴포넌트(자동바인딩 대상 Input/Textarea 등)가 폼 안에 존재하는가? +- [ ] 플러그인이 React 밖에서 자체 DOM을 직접 관리하는가? +- [ ] 위 세 질문 모두 YES → `selfManaged: true` 명시 (엔진 승격 예외, 성능 보존) +- [ ] 위 중 하나라도 NO/모르겠음 → **옵션 생략** (엔진이 자동 승격으로 정합성 확보 — 안전한 기본값) +- [ ] `merge: 'replace'` 사용 시 자동바인딩 값 유실 가능성 있음 → 필요 시 `getLocal()` 후 병합하여 `merge: 'deep'` 사용 +- [ ] `requires.g7_version`을 engine-v1.43.0 이상 내포 코어 버전으로 상향 + +### 예시 + +**일반 플러그인 (대다수)**: + +```typescript +G7Core.state.setLocal({ "form.category": "news" }); +// render 옵션 생략 → 엔진이 A↔B 동기화 자동 처리 +``` + +**WYSIWYG 에디터 등 자체 DOM 관리 플러그인**: + +```typescript +G7Core.state.setLocal( + { "form.content": editorInstance.getData() }, + { + debounce: 300, + debounceKey: `editor-sync-${name}`, + render: false, + selfManaged: true, // ← 자체 DOM 관리 명시. 자동 승격 제외 + } +); +``` + +### 절대 금지 사항 + +- `parentFormContext.setState`를 커스텀 핸들러에서 직접 호출하는 경로 우회 금지 — 엔진이 자동바인딩으로 호출하는 내부 API +- 자동 승격 무력화를 위해 `selfManaged: true`를 남용 금지 — 의도적으로 자체 DOM 관리하는 경우에만 사용 + +> 상세 배경: [`docs/frontend/state-management.md`](../frontend/state-management.md) "이중 저장소 구조" 섹션 참조 + +--- + ## 관련 문서 - [index.md](index.md) - 확장 시스템 전체 개요 diff --git a/docs/extension/upgrade-step-guide.md b/docs/extension/upgrade-step-guide.md index faadd866..88d63d7a 100644 --- a/docs/extension/upgrade-step-guide.md +++ b/docs/extension/upgrade-step-guide.md @@ -10,6 +10,7 @@ 3. 인프라 재설계 릴리즈의 특수 경로 = 경로 C → docblock 에 `@upgrade-path C` 선언 + 로컬 로직 필수 4. 경로 A (모듈/플러그인) · 경로 C 규율: 기존 클래스의 신규 메서드 호출 금지, 로컬 private 헬퍼 우선 5. 모든 분기에 upgrade.log 출력 — 로그 없음 = 디버깅 단서 없음 +6. beta.3+ 타깃 step 이 중간에 새 프로세스 재진입이 필요하면 `UpgradeHandoffException` throw (섹션 10.5) ``` --- @@ -25,6 +26,9 @@ 7. [생명주기와 제거 시점](#7-생명주기와-제거-시점) 8. [실전 사례](#8-실전-사례) 9. [업그레이드 경로별 규율 (모듈/플러그인 · 코어 beta.3+ · 코어 beta.2 특수)](#9-업그레이드-경로별-규율) +10. [경로 C 내부 inline spawn 패턴](#10-경로-c-내부-inline-spawn-패턴) +10.5. [업그레이드 핸드오프 (beta.3+ 인프라)](#105-업그레이드-핸드오프-beta3-인프라) +11. [업그레이드 후 데이터 정합성 (완전 동기화)](#11-업그레이드-후-데이터-정합성-완전-동기화) --- @@ -388,6 +392,94 @@ PHP; --- +## 10.5 업그레이드 핸드오프 (beta.3+ 인프라) + +일부 릴리즈는 "여기서부터는 새 PHP 프로세스가 필요하다" 는 경계 지점을 가진다. 예컨대 upgrade step A 까지는 현재 프로세스에서 안전하지만, step B 는 이미 로드된 이전 클래스와 충돌한다면, A 까지 확정하고 B 는 사용자가 `core:update` 를 재실행할 때 새 프로세스에서 처리하도록 위임하는 편이 안전하다. + +이를 위해 coreunit beta.3 에서 `UpgradeHandoffException` 인프라를 도입했다. + +### 동작 흐름 + +```text +Upgrade_X_Y_Z::run() + └─ throw UpgradeHandoffException(afterVersion, reason) + ↓ +[spawn 경로] [in-process 경로] +ExecuteUpgradeStepsCommand CoreUpdateService::runUpgradeSteps + └─ catch → stdout "[HANDOFF] " └─ 그대로 전파 + └─ exit 75 ↓ + CoreUpdateCommand::handle +spawnUpgradeStepsProcess └─ catch (UpgradeHandoffException) + └─ [HANDOFF] 페이로드 파싱 └─ updateVersionInEnv(toVersion) + └─ exit 75 → UpgradeHandoffException └─ clearAllCaches + └─ throw └─ restoreOwnership + ↓ └─ cleanupPending +CoreUpdateCommand::handle └─ disableMaintenanceMode + └─ (in-process 분기와 동일한 처리) └─ resumeCommand 자동 생성 + └─ 사용자에게 스텝 전용 재실행 안내 + └─ return Command::SUCCESS +``` + +핸드오프 catch 는 `.env APP_VERSION` 을 `afterVersion` 이 아닌 **`toVersion`** 으로 올린다. 디스크의 파일·vendor·migration 은 이미 `toVersion` 상태이므로 .env 를 `toVersion` 으로 맞춰야 상태가 일치한다. 만약 `afterVersion` 으로 되돌리면 사용자가 다시 `core:update` 를 실행했을 때 GitHub 재다운로드부터 전체 프로세스가 반복된다. + +대신 사용자에게는 **스텝 전용** 명령 (`php artisan core:execute-upgrade-steps --from= --to= --force`) 만 실행하도록 안내한다. 이 명령은 재다운로드·vendor 재설치 없이 남은 upgrade step 만 실행한다. + +### 사용 시점 + +upgrade step 파일에서 아래 조건이 모두 성립할 때 사용한다: + +1. 현재 PHP 프로세스가 본 step 을 안전하게 실행할 수 없다고 판단 가능 (예: 필요한 클래스/메서드 미로드) +2. **직전 step 까지의 상태는 유효** 하며 이 상태를 확정해도 무방 +3. 사용자가 `core:update` 를 한 번 더 실행하는 불편이 허용 범위 + +조건 2 가 충족되지 않으면 핸드오프 대신 일반 예외를 던져 롤백시키는 편이 안전하다. + +### 사용 예 + +```php +use App\Exceptions\UpgradeHandoffException; +use App\Extension\Helpers\FilePermissionHelper; + +public function run(UpgradeContext $context): void +{ + if (! method_exists(FilePermissionHelper::class, 'syncGroupWritability')) { + // resumeCommand 를 지정하지 않으면 CoreUpdateCommand 가 catch 시점에 + // `php artisan core:execute-upgrade-steps --from= --to= --force` + // 로 자동 생성한다. 대부분의 step 은 이 기본 동작을 사용하면 된다. + throw new UpgradeHandoffException( + afterVersion: '7.0.0-beta.2', + reason: '신설 메서드 FilePermissionHelper::syncGroupWritability 가 현재 프로세스에 로드되지 않음', + ); + } + + // ... 정상 로직 +} +``` + +커스텀 재실행 명령을 안내하고 싶다면 `resumeCommand` 를 명시 전달한다. 그러나 기본 자동 생성 명령이 표준 시나리오에 최적이므로 특별한 이유가 없는 한 생략이 권장된다. + +### 주의: 이전 버전 상위 계층 호환성 + +`UpgradeHandoffException` 은 beta.3 에서 신설된 클래스다. 이전 버전 (beta.1, beta.2) 의 `CoreUpdateService` / `CoreUpdateCommand` 는 이 클래스를 모른다. 따라서 **이전 버전 in-process 에서 throw 하면 uncaught exception 취급되어 `catch (\Throwable)` 롤백 경로로 빠진다**. + +즉, 본 인프라가 의도대로 작동하는 것은 **beta.3 이후 코어가 실행 주체인 경우** — 즉 beta.3 이후 업데이트에서 사용 가능. beta.1 / beta.2 로부터 beta.3 로 올라오는 시점의 step 은 이 인프라를 사용할 수 없다 (graceful skip 등 다른 전략 필요). + +다음 표로 정리: + +| 실행 주체 코어 | spawn 가능 | 핸드오프 인프라 사용 | +| -------------- | ---------- | -------------------- | +| beta.1 | ✗ | ✗ (uncaught → 롤백) | +| beta.2 | ✓ (spawn) | ✗ (자식 catch 없음) | +| beta.3+ | ✓ | ✓ | + +beta.3+ 타깃을 가정할 수 있는 경우에만 사용한다. + +### 인프라 도입 시점 + +- 인프라 자체는 beta.3 에서 도입. 첫 실사용은 beta.3+ 후속 릴리즈부터 (beta.3 본 릴리즈의 `Upgrade_7_0_0_beta_3.php` 는 graceful skip 사용 — beta.1 하위 호환 사유) + +--- + ## 11. 업그레이드 후 데이터 정합성 (완전 동기화) upgrade step 이 수행하는 데이터 변경은 단순 "마이그레이션" 이 아니라 **완전 동기화** 를 지향한다. 즉: diff --git a/docs/frontend/state-management.md b/docs/frontend/state-management.md index 61951ada..43a66aa7 100644 --- a/docs/frontend/state-management.md +++ b/docs/frontend/state-management.md @@ -141,6 +141,50 @@ G7이 자동으로 주입하는 `_global` 속성입니다. 레이아웃에서 ✅ API 에러 저장: onError 핸들러에서 에러 데이터 저장에 활용 ``` +### 이중 저장소 구조 (engine-v1.43.0+) + +```text +⚠️ CRITICAL (엔진 유지보수자 필독): _local은 내부적으로 두 저장소로 관리된다. + 이 구조는 "단일화 시도 실패" 이력의 결과이며 엔진 설계 전제이다. + 변경 제안 전 반드시 과거 경로 기반 구독 시스템 롤백 이력 검토. +``` + +| 저장소 | 실체 | 쓰는 곳 | 읽는 곳 | +| ------ | ---- | ------- | ------- | +| **A** | React `localDynamicState` (useState) | Form 자동바인딩 (Input/Textarea onChange) | DOM value, 부분 리렌더 | +| **B** | `globalState._local` (TemplateApp 싱글톤) | `G7Core.state.setLocal/getLocal` | apiCall body 바인딩, 플러그인 동기화 | + +레이아웃 JSON·일반 플러그인 개발자는 이 구조를 **의식할 필요가 없다**. 엔진이 양방향 동기화를 자동 처리한다. + +**엔진 자동 동기화 메커니즘 (요약)**: + +- **A→B 방향**: 자동바인딩 `performStateUpdate`가 A에 쓸 때 B에도 `setLocal({render:false})`로 동기 기록 +- **B→A 방향**: 자동바인딩 활성 경로를 `__g7AutoBindingPaths: Map`에 추적. 플러그인이 `setLocal({render:false})`로 그 경로를 건드리면 엔진이 **자동으로 `render:true`로 승격** +- **예외**: `selfManaged: true` 명시한 호출은 자동 승격 제외 (CKEditor5 등 자체 DOM 관리 플러그인 전용) + +### 엔진 수정 시 금지 사항 (CRITICAL) + +```text +❌ _local에 쓰는 새 경로를 추가하면서 A 또는 B 한쪽만 갱신 +❌ `parentFormContext.setState`를 직접 호출하는 우회 경로 추가 (자동바인딩 내부 API) +❌ `__g7AutoBindingPaths` 레지스트리를 건드리지 않고 자동바인딩 변형 구현 +❌ setLocal의 `render:false` 자동 승격 분기를 임의로 제거하거나 조건 완화 +❌ 구독 기반 선택적 리렌더 재시도 (과거에 도입 후 롤백된 실패 경로 — 반드시 검토 후 논의) +``` + +### 엔진 수정 시 필수 확인 사항 + +```text +✅ _local 쓰기 경로 추가 시 A+B 양쪽 동기화 확인 +✅ 새 `setLocal({render:false})` 사용처가 자동바인딩 경로와 겹치는지 확인 (겹치면 selfManaged 필요) +✅ DynamicRenderer의 레지스트리 useEffect 조건 변경 시 iteration/Strict Mode 이중 마운트 영향 검토 +✅ SPA 네비게이션 시 레지스트리 재초기화 (new Map()) 유지 +✅ 수정 후 이중 저장소 동기화 관련 회귀 테스트 전수 통과 확인 +``` + +- 상세 설명: [`docs/extension/plugin-development.md`](../extension/plugin-development.md) "폼 상태 정합성" 섹션 +- 구현 참고: [`DynamicRenderer.tsx`](../../resources/js/core/template-engine/DynamicRenderer.tsx) `performStateUpdate` 상단 주석 (~50줄) + ### 라이프사이클 (SPA 네비게이션) SPA navigate 시 `_local` 상태는 **레이아웃 이름 기준으로 선택적 초기화**됩니다: diff --git a/docs/requirements.md b/docs/requirements.md index c791d341..0b174dd7 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -87,6 +87,55 @@ | `max_execution_time` | 60 | 120+ | 대량 데이터 처리 시 | | `max_input_vars` | 1000 | 5000+ | 복잡한 폼 데이터 처리 | +### 1.6 파일 권한 및 umask 운영 방식 + +G7 은 배포 환경에 따라 세 가지 대표 운영 방식을 지원한다. 본 섹션은 각 방식에서 `storage/` 등 런타임 쓰기 대상 디렉토리의 권한 설정과 umask 권장값을 정리한다. + +#### 운영 방식 분류 + +| 운영 방식 | 소유자 : 그룹 | 권장 퍼미션 | 전형적 환경 | +|-----------|--------------|-------------|-------------| +| **A. 그룹 공유** | `사용자 : www-data` (서로 다른 UID) | `drwxrwxr-x` (0775) + g+w | SSH 로그인 사용자와 php-fpm 프로세스가 UID 가 다르고 `www-data` 같은 공용 그룹으로 파일 쓰기 권한을 공유하는 일반적인 Ubuntu/Debian 구성 | +| **B. 단일 소유자** | `사용자 : 사용자` 또는 `www-data : www-data` (동일 UID) | `drwxr-xr-x` (0755) | suexec / mod_userdir / 단순 Apache 환경에서 파일 소유자·웹서버 프로세스가 같은 UID | +| **C. suexec / cPanel** | 계정별 UID 격리 | `drwxr-xr-x` (0755) | 공유 호스팅, 계정마다 독립 UID/GID | + +`storage/` 디렉토리의 실제 퍼미션을 확인: + +```bash +stat -c '%a %U:%G' storage +``` + +#### 권장 설정 + +**방식 A (그룹 공유)**: + +```bash +# 인스톨러 완료 후 운영자가 1회 실행 +sudo chown -R $USER:www-data storage bootstrap/cache vendor modules plugins templates +sudo chmod -R 775 storage bootstrap/cache vendor modules plugins templates +``` + +추가로 php-fpm / systemd 의 umask 를 `002` 로 설정하면 cron·composer·수동 SSH artisan 등 외부 프로세스도 동일 권한으로 파일을 만든다. + +| 설정 지점 | 값 | 위치 예시 | +|-----------|----|-----------| +| php-fpm pool | `umask = 002` | `/etc/php/8.x/fpm/pool.d/www.conf` | +| systemd unit | `UMask=0002` | `/lib/systemd/system/php8.x-fpm.service` `[Service]` 섹션 | + +시스템 레벨 설정이 없어도 코어 부팅 시 `storage/` 의 g+w 여부를 감지하여 프로세스 umask 를 자동으로 `0002` 로 동조하므로 Laravel 부팅 경로를 거치는 파일 생성은 정상 동작한다 (`public/index.php`, `artisan`, queue worker, scheduler 등). 시스템 레벨 설정은 **부팅 경로를 거치지 않는 외부 프로세스 대응용 권장 사항**. + +**방식 B/C (단일 소유자)**: + +```bash +sudo chmod -R 755 storage bootstrap/cache vendor modules plugins templates +``` + +그룹 쓰기 비트가 없으므로 코어 자동 umask 동조는 발동하지 않는다 (운영자 의도 존중). 추가 설정 불필요. + +#### 인스톨러가 안내하는 기본 권한 + +인스톨러의 기본 안내 명령은 보수적으로 `chmod -R 755` 를 제시한다. 방식 A 로 운영하려면 인스톨 완료 후 `775` 로 재조정 + 소유자/그룹을 본인 계정 + `www-data` 로 변경. 인스톨러는 `chmod` 를 직접 호출하지 않으므로 운영자가 쉘에서 1회 실행. + --- ## 2. 데이터베이스 diff --git a/lang/en/exceptions.php b/lang/en/exceptions.php index b7b3226d..6048f56a 100644 --- a/lang/en/exceptions.php +++ b/lang/en/exceptions.php @@ -42,6 +42,11 @@ return [ 'save_failed' => 'Failed to save settings: :category', ], + // Core update related exceptions + 'core_update' => [ + 'handoff' => 'Upgrade handoff: completed up to :after_version — :reason (resume with: :resume_command)', + ], + // Vendor bundle / installation related exceptions 'vendor' => [ 'composer_not_available' => 'Composer cannot be executed in this environment. Use bundled mode instead.', diff --git a/lang/ko/exceptions.php b/lang/ko/exceptions.php index 989280b6..be481c6d 100644 --- a/lang/ko/exceptions.php +++ b/lang/ko/exceptions.php @@ -42,6 +42,11 @@ return [ 'save_failed' => '설정 저장에 실패했습니다: :category', ], + // 코어 업데이트 관련 예외 + 'core_update' => [ + 'handoff' => '업그레이드 핸드오프: :after_version 까지 완료 — :reason (재실행: :resume_command)', + ], + // Vendor 번들/설치 관련 예외 'vendor' => [ 'composer_not_available' => 'Composer를 실행할 수 없는 환경입니다. 번들 모드를 사용하세요.', diff --git a/phpunit.xml b/phpunit.xml index 67181053..4152d9f4 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -34,9 +34,10 @@ - - - + diff --git a/plugins/_bundled/sirsoft-ckeditor5/CHANGELOG.md b/plugins/_bundled/sirsoft-ckeditor5/CHANGELOG.md index 4ded76ba..5457b03f 100644 --- a/plugins/_bundled/sirsoft-ckeditor5/CHANGELOG.md +++ b/plugins/_bundled/sirsoft-ckeditor5/CHANGELOG.md @@ -4,6 +4,12 @@ 형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며, [Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다. +## [1.0.0-beta.2] - 2026-04-22 + +### Fixed + +- CKEditor5 사용 게시판 글쓰기 화면에서 제목과 내용을 함께 입력해 저장할 때 "제목이 비어있다" 오류가 나던 문제 수정 + ## [1.0.0-beta.1] - 2026-04-09 ### Added diff --git a/plugins/_bundled/sirsoft-ckeditor5/composer.json b/plugins/_bundled/sirsoft-ckeditor5/composer.json index 916c8d29..ccd19680 100644 --- a/plugins/_bundled/sirsoft-ckeditor5/composer.json +++ b/plugins/_bundled/sirsoft-ckeditor5/composer.json @@ -2,7 +2,7 @@ "name": "plugins/sirsoft-ckeditor5", "description": "CKEditor 5 WYSIWYG Editor Plugin for Gnuboard7 platform", "type": "library", - "version": "1.0.0-beta.1", + "version": "1.0.0-beta.2", "authors": [ { "name": "sirsoft", diff --git a/plugins/_bundled/sirsoft-ckeditor5/dist/js/plugin.iife.js b/plugins/_bundled/sirsoft-ckeditor5/dist/js/plugin.iife.js index 0445b4c1..eeb296c8 100644 --- a/plugins/_bundled/sirsoft-ckeditor5/dist/js/plugin.iife.js +++ b/plugins/_bundled/sirsoft-ckeditor5/dist/js/plugin.iife.js @@ -1,4 +1,4 @@ -var SirsoftCkeditor5=(function(M){"use strict";const E=new Map,Y="https://cdn.ckeditor.com/ckeditor5/43.3.1/ckeditor5.css",Z="https://cdn.ckeditor.com/ckeditor5/43.3.1/translations",N="ckeditor5-cdn-css",H="ckeditor5-dark-override",D="ckeditor5-tab-style",O={minimal:["bold","italic","underline","|","link","uploadImage","|","undo","redo"],standard:["heading","|","bold","italic","underline","strikethrough","|","alignment","|","link","blockQuote","|","bulletedList","numberedList","indent","outdent","|","insertTable","uploadImage","|","undo","redo"],full:["heading","|","fontSize","fontColor","fontBackgroundColor","|","bold","italic","underline","strikethrough","|","alignment","|","link","blockQuote","insertTable","uploadImage","mediaEmbed","horizontalLine","|","bulletedList","numberedList","indent","outdent","|","codeBlock","sourceEditing","|","undo","redo"]};function R(t){if(t==="en")return Promise.resolve();const o=`ckeditor5-translations-${t}`;return document.getElementById(o)?Promise.resolve():new Promise(e=>{const r=document.createElement("script");r.id=o,r.src=`${Z}/${t}.umd.js`,r.onload=()=>e(),r.onerror=()=>e(),document.head.appendChild(r)})}function K(){if(document.getElementById(N))return;const t=document.createElement("link");t.id=N,t.rel="stylesheet",t.href=Y,document.head.appendChild(t)}function tt(){if(document.getElementById(D))return;const t=document.createElement("style");t.id=D,t.textContent=` +var SirsoftCkeditor5=function(G){"use strict";const E=new Map,Y="https://cdn.ckeditor.com/ckeditor5/43.3.1/ckeditor5.css",Z="https://cdn.ckeditor.com/ckeditor5/43.3.1/translations",N="ckeditor5-cdn-css",H="ckeditor5-dark-override",D="ckeditor5-tab-style",O={minimal:["bold","italic","underline","|","link","uploadImage","|","undo","redo"],standard:["heading","|","bold","italic","underline","strikethrough","|","alignment","|","link","blockQuote","|","bulletedList","numberedList","indent","outdent","|","insertTable","uploadImage","|","undo","redo"],full:["heading","|","fontSize","fontColor","fontBackgroundColor","|","bold","italic","underline","strikethrough","|","alignment","|","link","blockQuote","insertTable","uploadImage","mediaEmbed","horizontalLine","|","bulletedList","numberedList","indent","outdent","|","codeBlock","sourceEditing","|","undo","redo"]};function R(t){if(t==="en")return Promise.resolve();const o=`ckeditor5-translations-${t}`;return document.getElementById(o)?Promise.resolve():new Promise(e=>{const r=document.createElement("script");r.id=o,r.src=`${Z}/${t}.umd.js`,r.onload=()=>e(),r.onerror=()=>e(),document.head.appendChild(r)})}function K(){if(document.getElementById(N))return;const t=document.createElement("link");t.id=N,t.rel="stylesheet",t.href=Y,document.head.appendChild(t)}function tt(){if(document.getElementById(D))return;const t=document.createElement("style");t.id=D,t.textContent=` /* 다국어 탭 컨테이너 */ .ckeditor5-locale-tabs { display: flex; @@ -332,7 +332,7 @@ var SirsoftCkeditor5=(function(M){"use strict";const E=new Map,Y="https://cdn.ck .ck.ck-editor__editable li::marker { color: #d1d5db; } - `,document.head.appendChild(o)}let x=null;function ot(){x||(x=new MutationObserver(()=>{q()}),x.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}))}function nt(){x&&(x.disconnect(),x=null)}const rt={ko:"한국어",en:"English",ja:"日本語",zh:"中文",fr:"Français",de:"Deutsch",es:"Español"};function ct(t){return rt[t]??t.toUpperCase()}function lt(){const t=window.G7Core;return t?.locale?.supported?t.locale.supported():[localStorage.getItem("g7_locale")||"ko"]}function I(){return window.G7Core?.locale?.current?.()??localStorage.getItem("g7_locale")??"ko"}function at(t,o,e){const r=[t.Essentials,t.Bold,t.Italic,t.Underline,t.Strikethrough,t.Link,t.Paragraph,t.Heading,t.BlockQuote,t.List,t.Alignment,t.Table,t.TableToolbar,t.TableProperties,t.TableCellProperties,t.Indent,t.IndentBlock,t.PasteFromOffice,t.GeneralHtmlSupport,t.Image,t.ImageResize,t.ImageStyle,t.ImageCaption,t.ImageToolbar];return o==="full"&&r.push(t.MediaEmbed,t.HorizontalLine,t.CodeBlock,t.SourceEditing,t.FontSize,t.FontColor,t.FontBackgroundColor),e&&r.push(t.ImageUpload,t.SimpleUploadAdapter),r}function it(t){const o="/api/plugins/sirsoft-ckeditor5/upload";return t?`${o}?permission=${encodeURIComponent(t)}`:o}function dt(){const t=localStorage.getItem("auth_token");return t?{Authorization:`Bearer ${t}`}:{}}async function F(t,o){const e=window.CKEDITOR;if(!e)throw new Error("[sirsoft-ckeditor5] CKEDITOR 전역 객체를 찾을 수 없습니다. CDN 스크립트가 로드되었는지 확인하세요.");const r=O[o.toolbar]||O.standard,c=o.imageUpload?r:r.filter(n=>n!=="uploadImage"),l={initialData:o.initialContent,plugins:at(e,o.toolbar,o.imageUpload),toolbar:{items:c},table:{contentToolbar:["tableColumn","tableRow","mergeTableCells","|","tableProperties","tableCellProperties"],tableProperties:{defaultProperties:{borderStyle:"solid",borderColor:"#d1d5db",borderWidth:"1px",alignment:"left"}},tableCellProperties:{defaultProperties:{borderStyle:"solid",borderColor:"#d1d5db",borderWidth:"1px",padding:"8px"}}},image:{toolbar:["imageStyle:inline","imageStyle:alignLeft","imageStyle:alignCenter","imageStyle:alignRight","|","toggleImageCaption","|","resizeImage"],resizeOptions:[{name:"resizeImage:original",label:"Original",value:null},{name:"resizeImage:25",label:"25%",value:"25"},{name:"resizeImage:50",label:"50%",value:"50"},{name:"resizeImage:75",label:"75%",value:"75"}],resizeUnit:"%"},indentBlock:{offset:40,unit:"px"},link:{defaultProtocol:"https://",decorators:{openInNewTab:{mode:"automatic",callback:n=>n.startsWith("http://")||n.startsWith("https://"),attributes:{target:"_blank",rel:"noopener noreferrer"}}}},htmlSupport:{allow:[{name:/.*/,attributes:!0,classes:!0,styles:!0}]},placeholder:o.placeholder,language:I()};o.imageUpload&&(l.simpleUpload={uploadUrl:it(o.uploadPermission),headers:dt()});const i=await e.ClassicEditor.create(t,l),s=`ckeditor5-height-style-${o.containerId}`,b=document.getElementById(s);if(b)b.textContent=`#${o.containerId} .ck-editor__editable { min-height: ${o.height}px !important; }`;else{const n=document.createElement("style");n.id=s,n.textContent=`#${o.containerId} .ck-editor__editable { min-height: ${o.height}px !important; }`,document.head.appendChild(n)}return o.readOnly&&i.enableReadOnlyMode("read-only"),i}function st(t,o,e,r,c){const l=document.createElement("div");l.className="ckeditor5-locale-tabs";const i=new Map;o.forEach(n=>{const a=document.createElement("div");a.dataset.locale=n,n!==e&&(a.style.cssText="display:none;");const C=document.createElement("div");a.appendChild(C),i.set(n,C)});const s=()=>{c&&l.querySelectorAll("button").forEach(n=>{const a=n.dataset.locale;if(!a||n.classList.contains("is-active")){const h=n.querySelector(".ck5-check");h&&h.remove();return}const g=!!c(a)?.trim(),p=n.querySelector(".ck5-check");if(g&&!p){const h=document.createElement("i");h.className="fas fa-check ck5-check",n.appendChild(h)}else!g&&p&&p.remove()})},b=o[0];return o.forEach(n=>{const a=n===b,C=n===e,g=document.createElement("button");g.type="button",g.dataset.locale=n,g.className=[C?"is-active":"",a?"is-default":""].filter(Boolean).join(" "),g.innerHTML=`${ct(n)}${a?'*':""}`,g.addEventListener("click",async()=>{l.querySelectorAll("button").forEach(p=>{const L=p.dataset.locale===n;p.classList.toggle("is-active",L)}),i.forEach((p,h)=>{const L=p.parentElement;L&&(L.style.display=h===n?"block":"none")}),r&&await r(n),s()}),l.appendChild(g)}),t.appendChild(l),i.forEach(n=>{n.parentElement&&t.appendChild(n.parentElement)}),{tabsEl:l,contentEls:i,updateCheckIcons:s}}function T(t,o,e,r){const c=window.G7Core;if(!c?.state?.setLocal)return;const l={[`form.${t}_mode`]:"html",hasChanges:!0};r?l[`form.${t}.${o}`]=e:l[`form.${t}`]=e,c.state.setLocal(l,{debounce:300,debounceKey:`ckeditor-sync-${t}`,render:!1})}async function ut(t,o){const e=t.params??{},c=`ckeditor5-${e.name??"content"}`,l=E.get(c);if(l&&l.size>0){const y=[];l.forEach(u=>{u&&typeof u.destroy=="function"&&y.push(u.destroy().catch(()=>{}))}),await Promise.allSettled(y),E.delete(c)}const i=document.getElementById(c);if(!i){console.warn(`[sirsoft-ckeditor5] 컨테이너 엘리먼트를 찾을 수 없습니다: #${c}`);return}K(),tt(),q(),ot(),await R(I());const s=window.G7Core,b=s?.state?.get()||{},n=b._global?.plugins?.["sirsoft-ckeditor5"]??b.plugins?.["sirsoft-ckeditor5"]??{},a=e.name??"content",C=e.multilingual===!0||e.multilingual==="true",g=e.readOnly===!0||e.readOnly==="true",p=e.imageUpload!==void 0?e.imageUpload===!0||e.imageUpload==="true":n.imageUpload===!0||n.imageUpload==="true",h=e.uploadPermission??"",L=e.placeholder??"",bt=e.height!==void 0?Number(e.height)||400:Number(n.editorHeight)||400,gt=(e.toolbar!==void 0?e.toolbar:n.toolbar)??"standard";let _={};if(C){try{typeof e.content=="string"&&e.content.startsWith("{")&&!e.content.startsWith("{{")?_=JSON.parse(e.content):typeof e.content=="object"&&e.content!==null&&(_=e.content)}catch{_={}}if(Object.keys(_).length===0&&a){const u=(s?.state?.getLocal?.()??{})?.form?.[a];if(u&&typeof u=="object"&&!Array.isArray(u)?_=u:typeof u=="string"&&u&&(_={[I()]:u}),Object.keys(_).length===0){const k=s?.state?.get?.()??{},d=(k?._global?.selectedItem??k?.selectedItem)?.[a];d&&typeof d=="object"&&!Array.isArray(d)&&(_=d)}}}const P=new Map;E.set(c,P);const J={placeholder:L,readOnly:g,imageUpload:p,uploadPermission:h,height:bt,toolbar:gt,containerId:c};if(C){const y=lt(),u=I(),k={current:new Map},$={current:()=>{}},d=async f=>{if(P.has(f))return;const U=k.current.get(f);if(!U)return;const pt=_[f]??"";try{const A=await F(U,{...J,initialContent:pt});P.set(f,A);let X=!0;if(A.model.document.on("change:data",()=>{if(X)return;const G=A.getData();T(a,f,G,!0),$.current()}),X=!1,a){const G=window.G7Core;(G?.state?.getLocal?.()??{}).form?.[`${a}_mode`]!=="html"&&G.state.setLocal({[`form.${a}_mode`]:"html"})}}catch(A){console.error(`[sirsoft-ckeditor5] 에디터 초기화 오류 (locale: ${f}):`,A)}},S=f=>{const U=P.get(f);return U?U.getData?.()??null:null},{contentEls:B,updateCheckIcons:w}=st(i,y,u,d,S);k.current=B,$.current=w,await d(u),setTimeout(()=>{y.filter(f=>f!==u).forEach(f=>{d(f)})},2e3)}else{const y=typeof e.content=="string"?e.content:"";let k=y.startsWith("{{")&&y.endsWith("}}")?"":y;if(!k&&a){const S=(s?.state?.getLocal?.()??{})?.form?.[a];typeof S=="string"&&S&&(k=S)}const $=document.createElement("div");i.appendChild($);try{const d=await F($,{...J,initialContent:k}),S=I();P.set(S,d);let B=!0;if(d.model.document.on("change:data",()=>{if(B)return;const w=d.getData();T(a,S,w,!1)}),B=!1,k){const w=d.getData();(!w||w.trim()==="")&&d.setData(k)}if(a){const w=window.G7Core;(w?.state?.getLocal?.()??{}).form?.[`${a}_mode`]!=="html"&&w.state.setLocal({[`form.${a}_mode`]:"html"})}}catch(d){console.error("[sirsoft-ckeditor5] 에디터 초기화 오류:",d),E.delete(c)}}}async function ft(t,o){const r=`ckeditor5-${t.params?.name??"content"}`,c=E.get(r);if(!c||c.size===0)return;const l=[];c.forEach(s=>{s&&typeof s.destroy=="function"&&l.push(s.destroy().catch(b=>{console.warn("[sirsoft-ckeditor5] destroyEditor error:",b)}))}),await Promise.allSettled(l),E.delete(r);const i=document.getElementById(`ckeditor5-height-style-${r}`);i&&i.remove(),E.size===0&&nt()}const m="sirsoft-ckeditor5",W="ckeditor5-content-styles",V="ckeditor5-content-styles-override",kt="https://cdn.ckeditor.com/ckeditor5/43.3.1/ckeditor5.css";function mt(){if(!document.getElementById(W)){const t=document.createElement("link");t.id=W,t.rel="stylesheet",t.href=kt,document.head.appendChild(t)}if(!document.getElementById(V)){const t=document.createElement("style");t.id=V,t.textContent=` + `,document.head.appendChild(o)}let x=null;function ot(){x||(x=new MutationObserver(()=>{q()}),x.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}))}function nt(){x&&(x.disconnect(),x=null)}const rt={ko:"한국어",en:"English",ja:"日本語",zh:"中文",fr:"Français",de:"Deutsch",es:"Español"};function ct(t){return rt[t]??t.toUpperCase()}function lt(){const t=window.G7Core;return t?.locale?.supported?t.locale.supported():[localStorage.getItem("g7_locale")||"ko"]}function I(){return window.G7Core?.locale?.current?.()??localStorage.getItem("g7_locale")??"ko"}function at(t,o,e){const r=[t.Essentials,t.Bold,t.Italic,t.Underline,t.Strikethrough,t.Link,t.Paragraph,t.Heading,t.BlockQuote,t.List,t.Alignment,t.Table,t.TableToolbar,t.TableProperties,t.TableCellProperties,t.Indent,t.IndentBlock,t.PasteFromOffice,t.GeneralHtmlSupport,t.Image,t.ImageResize,t.ImageStyle,t.ImageCaption,t.ImageToolbar];return o==="full"&&r.push(t.MediaEmbed,t.HorizontalLine,t.CodeBlock,t.SourceEditing,t.FontSize,t.FontColor,t.FontBackgroundColor),e&&r.push(t.ImageUpload,t.SimpleUploadAdapter),r}function it(t){const o="/api/plugins/sirsoft-ckeditor5/upload";return t?`${o}?permission=${encodeURIComponent(t)}`:o}function dt(){const t=localStorage.getItem("auth_token");return t?{Authorization:`Bearer ${t}`}:{}}async function F(t,o){const e=window.CKEDITOR;if(!e)throw new Error("[sirsoft-ckeditor5] CKEDITOR 전역 객체를 찾을 수 없습니다. CDN 스크립트가 로드되었는지 확인하세요.");const r=O[o.toolbar]||O.standard,c=o.imageUpload?r:r.filter(n=>n!=="uploadImage"),l={initialData:o.initialContent,plugins:at(e,o.toolbar,o.imageUpload),toolbar:{items:c},table:{contentToolbar:["tableColumn","tableRow","mergeTableCells","|","tableProperties","tableCellProperties"],tableProperties:{defaultProperties:{borderStyle:"solid",borderColor:"#d1d5db",borderWidth:"1px",alignment:"left"}},tableCellProperties:{defaultProperties:{borderStyle:"solid",borderColor:"#d1d5db",borderWidth:"1px",padding:"8px"}}},image:{toolbar:["imageStyle:inline","imageStyle:alignLeft","imageStyle:alignCenter","imageStyle:alignRight","|","toggleImageCaption","|","resizeImage"],resizeOptions:[{name:"resizeImage:original",label:"Original",value:null},{name:"resizeImage:25",label:"25%",value:"25"},{name:"resizeImage:50",label:"50%",value:"50"},{name:"resizeImage:75",label:"75%",value:"75"}],resizeUnit:"%"},indentBlock:{offset:40,unit:"px"},link:{defaultProtocol:"https://",decorators:{openInNewTab:{mode:"automatic",callback:n=>n.startsWith("http://")||n.startsWith("https://"),attributes:{target:"_blank",rel:"noopener noreferrer"}}}},htmlSupport:{allow:[{name:/.*/,attributes:!0,classes:!0,styles:!0}]},placeholder:o.placeholder,language:I()};o.imageUpload&&(l.simpleUpload={uploadUrl:it(o.uploadPermission),headers:dt()});const i=await e.ClassicEditor.create(t,l),s=`ckeditor5-height-style-${o.containerId}`,b=document.getElementById(s);if(b)b.textContent=`#${o.containerId} .ck-editor__editable { min-height: ${o.height}px !important; }`;else{const n=document.createElement("style");n.id=s,n.textContent=`#${o.containerId} .ck-editor__editable { min-height: ${o.height}px !important; }`,document.head.appendChild(n)}return o.readOnly&&i.enableReadOnlyMode("read-only"),i}function st(t,o,e,r,c){const l=document.createElement("div");l.className="ckeditor5-locale-tabs";const i=new Map;o.forEach(n=>{const a=document.createElement("div");a.dataset.locale=n,n!==e&&(a.style.cssText="display:none;");const C=document.createElement("div");a.appendChild(C),i.set(n,C)});const s=()=>{c&&l.querySelectorAll("button").forEach(n=>{const a=n.dataset.locale;if(!a||n.classList.contains("is-active")){const h=n.querySelector(".ck5-check");h&&h.remove();return}const g=!!c(a)?.trim(),p=n.querySelector(".ck5-check");if(g&&!p){const h=document.createElement("i");h.className="fas fa-check ck5-check",n.appendChild(h)}else!g&&p&&p.remove()})},b=o[0];return o.forEach(n=>{const a=n===b,C=n===e,g=document.createElement("button");g.type="button",g.dataset.locale=n,g.className=[C?"is-active":"",a?"is-default":""].filter(Boolean).join(" "),g.innerHTML=`${ct(n)}${a?'*':""}`,g.addEventListener("click",async()=>{l.querySelectorAll("button").forEach(p=>{const L=p.dataset.locale===n;p.classList.toggle("is-active",L)}),i.forEach((p,h)=>{const L=p.parentElement;L&&(L.style.display=h===n?"block":"none")}),r&&await r(n),s()}),l.appendChild(g)}),t.appendChild(l),i.forEach(n=>{n.parentElement&&t.appendChild(n.parentElement)}),{tabsEl:l,contentEls:i,updateCheckIcons:s}}function T(t,o,e,r){const c=window.G7Core;if(!c?.state?.setLocal)return;const l={[`form.${t}_mode`]:"html",hasChanges:!0};r?l[`form.${t}.${o}`]=e:l[`form.${t}`]=e,c.state.setLocal(l,{debounce:300,debounceKey:`ckeditor-sync-${t}`,render:!1,selfManaged:!0})}async function ut(t,o){const e=t.params??{},c=`ckeditor5-${e.name??"content"}`,l=E.get(c);if(l&&l.size>0){const y=[];l.forEach(u=>{u&&typeof u.destroy=="function"&&y.push(u.destroy().catch(()=>{}))}),await Promise.allSettled(y),E.delete(c)}const i=document.getElementById(c);if(!i){console.warn(`[sirsoft-ckeditor5] 컨테이너 엘리먼트를 찾을 수 없습니다: #${c}`);return}K(),tt(),q(),ot(),await R(I());const s=window.G7Core,b=s?.state?.get()||{},n=b._global?.plugins?.["sirsoft-ckeditor5"]??b.plugins?.["sirsoft-ckeditor5"]??{},a=e.name??"content",C=e.multilingual===!0||e.multilingual==="true",g=e.readOnly===!0||e.readOnly==="true",p=e.imageUpload!==void 0?e.imageUpload===!0||e.imageUpload==="true":n.imageUpload===!0||n.imageUpload==="true",h=e.uploadPermission??"",L=e.placeholder??"",bt=e.height!==void 0?Number(e.height)||400:Number(n.editorHeight)||400,gt=(e.toolbar!==void 0?e.toolbar:n.toolbar)??"standard";let _={};if(C){try{typeof e.content=="string"&&e.content.startsWith("{")&&!e.content.startsWith("{{")?_=JSON.parse(e.content):typeof e.content=="object"&&e.content!==null&&(_=e.content)}catch{_={}}if(Object.keys(_).length===0&&a){const u=(s?.state?.getLocal?.()??{})?.form?.[a];if(u&&typeof u=="object"&&!Array.isArray(u)?_=u:typeof u=="string"&&u&&(_={[I()]:u}),Object.keys(_).length===0){const k=s?.state?.get?.()??{},d=(k?._global?.selectedItem??k?.selectedItem)?.[a];d&&typeof d=="object"&&!Array.isArray(d)&&(_=d)}}}const P=new Map;E.set(c,P);const J={placeholder:L,readOnly:g,imageUpload:p,uploadPermission:h,height:bt,toolbar:gt,containerId:c};if(C){const y=lt(),u=I(),k={current:new Map},$={current:()=>{}},d=async f=>{if(P.has(f))return;const U=k.current.get(f);if(!U)return;const pt=_[f]??"";try{const A=await F(U,{...J,initialContent:pt});P.set(f,A);let X=!0;if(A.model.document.on("change:data",()=>{if(X)return;const M=A.getData();T(a,f,M,!0),$.current()}),X=!1,a){const M=window.G7Core;(M?.state?.getLocal?.()??{}).form?.[`${a}_mode`]!=="html"&&M.state.setLocal({[`form.${a}_mode`]:"html"})}}catch(A){console.error(`[sirsoft-ckeditor5] 에디터 초기화 오류 (locale: ${f}):`,A)}},S=f=>{const U=P.get(f);return U?U.getData?.()??null:null},{contentEls:B,updateCheckIcons:w}=st(i,y,u,d,S);k.current=B,$.current=w,await d(u),setTimeout(()=>{y.filter(f=>f!==u).forEach(f=>{d(f)})},2e3)}else{const y=typeof e.content=="string"?e.content:"";let k=y.startsWith("{{")&&y.endsWith("}}")?"":y;if(!k&&a){const S=(s?.state?.getLocal?.()??{})?.form?.[a];typeof S=="string"&&S&&(k=S)}const $=document.createElement("div");i.appendChild($);try{const d=await F($,{...J,initialContent:k}),S=I();P.set(S,d);let B=!0;if(d.model.document.on("change:data",()=>{if(B)return;const w=d.getData();T(a,S,w,!1)}),B=!1,k){const w=d.getData();(!w||w.trim()==="")&&d.setData(k)}if(a){const w=window.G7Core;(w?.state?.getLocal?.()??{}).form?.[`${a}_mode`]!=="html"&&w.state.setLocal({[`form.${a}_mode`]:"html"})}}catch(d){console.error("[sirsoft-ckeditor5] 에디터 초기화 오류:",d),E.delete(c)}}}async function ft(t,o){const r=`ckeditor5-${t.params?.name??"content"}`,c=E.get(r);if(!c||c.size===0)return;const l=[];c.forEach(s=>{s&&typeof s.destroy=="function"&&l.push(s.destroy().catch(b=>{console.warn("[sirsoft-ckeditor5] destroyEditor error:",b)}))}),await Promise.allSettled(l),E.delete(r);const i=document.getElementById(`ckeditor5-height-style-${r}`);i&&i.remove(),E.size===0&&nt()}const m="sirsoft-ckeditor5",W="ckeditor5-content-styles",V="ckeditor5-content-styles-override",kt="https://cdn.ckeditor.com/ckeditor5/43.3.1/ckeditor5.css";function mt(){if(!document.getElementById(W)){const t=document.createElement("link");t.id=W,t.rel="stylesheet",t.href=kt,document.head.appendChild(t)}if(!document.getElementById(V)){const t=document.createElement("style");t.id=V,t.textContent=` /* 이미지 캡션 - 다크모드 */ html.dark .ck-content .image > figcaption { color: hsl(0, 0%, 80%); background-color: hsl(0, 0%, 15%); } @@ -369,5 +369,5 @@ var SirsoftCkeditor5=(function(M){"use strict";const E=new Map,Y="https://cdn.ck .ck-content ul ul ul { list-style-type: square; padding-left: 2em; } .ck-content ol ol { list-style-type: lower-alpha; padding-left: 2em; } .ck-content ol ol ol { list-style-type: lower-roman; padding-left: 2em; } - `,document.head.appendChild(t)}}const v={initEditor:ut,destroyEditor:ft,injectContentCss:mt},z=window.G7Core?.createLogger?.(`Plugin:${m}`)??{log:(...t)=>console.log(`[Plugin:${m}]`,...t),warn:(...t)=>console.warn(`[Plugin:${m}]`,...t),error:(...t)=>console.error(`[Plugin:${m}]`,...t)};function Q(t=!1){const o=window.G7Core?.getActionDispatcher?.();if(o)Object.entries(v).forEach(([e,r])=>{const c=`${m}.${e}`;o.registerHandler(c,r,{category:"plugin",source:m})}),z.log(`${Object.keys(v).length} handler(s) registered:`,Object.keys(v).map(e=>`${m}.${e}`));else if(t){let e=0;const r=50,c=()=>{const l=window.G7Core?.getActionDispatcher?.();l?(Object.entries(v).forEach(([i,s])=>{const b=`${m}.${i}`;l.registerHandler(b,s,{category:"plugin",source:m})}),z.log(`${Object.keys(v).length} handler(s) registered:`,Object.keys(v).map(i=>`${m}.${i}`))):(e++,e<=r?(z.warn(`ActionDispatcher not found, retrying... (${e}/${r})`),setTimeout(c,100)):z.error("Failed to register handlers: ActionDispatcher not available after maximum retries"))};c()}else z.warn("ActionDispatcher not found, handlers not registered")}function j(){if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",()=>Q(!0));else{const t=!!window.G7Core?.getActionDispatcher?.();Q(!t)}}return j(),typeof window<"u"&&(window.__SirsoftCkeditor5={identifier:m,handlers:Object.keys(v),initPlugin:j}),M.initPlugin=j,Object.defineProperty(M,Symbol.toStringTag,{value:"Module"}),M})({}); + `,document.head.appendChild(t)}}const v={initEditor:ut,destroyEditor:ft,injectContentCss:mt},z=window.G7Core?.createLogger?.(`Plugin:${m}`)??{log:(...t)=>console.log(`[Plugin:${m}]`,...t),warn:(...t)=>console.warn(`[Plugin:${m}]`,...t),error:(...t)=>console.error(`[Plugin:${m}]`,...t)};function Q(t=!1){const o=window.G7Core?.getActionDispatcher?.();if(o)Object.entries(v).forEach(([e,r])=>{const c=`${m}.${e}`;o.registerHandler(c,r,{category:"plugin",source:m})}),z.log(`${Object.keys(v).length} handler(s) registered:`,Object.keys(v).map(e=>`${m}.${e}`));else if(t){let e=0;const r=50,c=()=>{const l=window.G7Core?.getActionDispatcher?.();l?(Object.entries(v).forEach(([i,s])=>{const b=`${m}.${i}`;l.registerHandler(b,s,{category:"plugin",source:m})}),z.log(`${Object.keys(v).length} handler(s) registered:`,Object.keys(v).map(i=>`${m}.${i}`))):(e++,e<=r?(z.warn(`ActionDispatcher not found, retrying... (${e}/${r})`),setTimeout(c,100)):z.error("Failed to register handlers: ActionDispatcher not available after maximum retries"))};c()}else z.warn("ActionDispatcher not found, handlers not registered")}function j(){if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",()=>Q(!0));else{const t=!!window.G7Core?.getActionDispatcher?.();Q(!t)}}return j(),typeof window<"u"&&(window.__SirsoftCkeditor5={identifier:m,handlers:Object.keys(v),initPlugin:j}),G.initPlugin=j,Object.defineProperty(G,Symbol.toStringTag,{value:"Module"}),G}({}); //# sourceMappingURL=plugin.iife.js.map diff --git a/plugins/_bundled/sirsoft-ckeditor5/dist/js/plugin.iife.js.map b/plugins/_bundled/sirsoft-ckeditor5/dist/js/plugin.iife.js.map index 0b27eda1..2ae7695f 100644 --- a/plugins/_bundled/sirsoft-ckeditor5/dist/js/plugin.iife.js.map +++ b/plugins/_bundled/sirsoft-ckeditor5/dist/js/plugin.iife.js.map @@ -1 +1 @@ -{"version":3,"file":"plugin.iife.js","sources":["../../resources/js/handlers/editorInstances.ts","../../resources/js/handlers/initEditor.ts","../../resources/js/handlers/destroyEditor.ts","../../resources/js/index.ts"],"sourcesContent":["/**\n * CKEditor5 인스턴스 공유 저장소\n *\n * containerId → locale별 에디터 인스턴스 맵을 관리합니다.\n * initEditor / destroyEditor 핸들러가 공유합니다.\n */\n\n// containerId → Map\nexport const editorInstances = new Map>();\n\n// setData() 중 change:data → syncToForm 재진입 방지 플래그\nlet _syncSuppressed = false;\nexport function isSyncSuppressed(): boolean {\n return _syncSuppressed;\n}\nexport function setSyncSuppressed(value: boolean): void {\n _syncSuppressed = value;\n}\n","/**\n * CKEditor5 초기화 핸들러\n *\n * 컴포넌트 마운트 시 CKEditor5 인스턴스를 생성합니다.\n * 다국어(multilingual) 모드: locale별 탭 + 인스턴스 생성\n * 단일 모드: 단일 인스턴스 생성\n */\n\nimport { editorInstances, isSyncSuppressed } from './editorInstances';\n\n/** CKEditor5 CDN CSS URL */\nconst CKEDITOR5_CSS_URL = 'https://cdn.ckeditor.com/ckeditor5/43.3.1/ckeditor5.css';\n/** CKEditor5 CDN 번역 파일 base URL */\nconst CKEDITOR5_TRANSLATIONS_BASE = 'https://cdn.ckeditor.com/ckeditor5/43.3.1/translations';\n/** CKEditor5 CSS 로드 상태 추적용 엘리먼트 ID */\nconst CKEDITOR5_CSS_ID = 'ckeditor5-cdn-css';\n/** CKEditor5 다크 모드 CSS 엘리먼트 ID */\nconst CKEDITOR5_DARK_CSS_ID = 'ckeditor5-dark-override';\n/** CKEditor5 다국어 탭 기본 CSS 엘리먼트 ID */\nconst CKEDITOR5_TAB_CSS_ID = 'ckeditor5-tab-style';\n\n/** CKEditor 전역 객체 타입 (CDN UMD 빌드 — window.CKEDITOR) */\ninterface CKEditorGlobal {\n ClassicEditor: any;\n Essentials: any;\n Bold: any;\n Italic: any;\n Underline: any;\n Strikethrough: any;\n Link: any;\n Paragraph: any;\n Heading: any;\n BlockQuote: any;\n List: any;\n Alignment: any;\n Table: any;\n TableToolbar: any;\n TableProperties: any;\n TableCellProperties: any;\n Image: any;\n ImageUpload: any;\n ImageResize: any;\n ImageStyle: any;\n ImageCaption: any;\n ImageToolbar: any;\n SimpleUploadAdapter: any;\n MediaEmbed: any;\n HorizontalLine: any;\n Indent: any;\n IndentBlock: any;\n CodeBlock: any;\n SourceEditing: any;\n FontSize: any;\n FontColor: any;\n FontBackgroundColor: any;\n PasteFromOffice: any;\n GeneralHtmlSupport: any;\n}\n\n/** initEditor 파라미터 타입 */\ninterface InitEditorParams {\n name?: string;\n content?: string;\n multilingual?: boolean | string;\n placeholder?: string;\n readOnly?: boolean | string;\n imageUpload?: boolean | string;\n uploadPermission?: string;\n height?: number | string;\n toolbar?: string;\n}\n\n/** 툴바 프리셋 */\nconst TOOLBAR_PRESETS: Record = {\n minimal: [\n 'bold', 'italic', 'underline', '|',\n 'link', 'uploadImage', '|',\n 'undo', 'redo',\n ],\n standard: [\n 'heading', '|',\n 'bold', 'italic', 'underline', 'strikethrough', '|',\n 'alignment', '|',\n 'link', 'blockQuote', '|',\n 'bulletedList', 'numberedList', 'indent', 'outdent', '|',\n 'insertTable', 'uploadImage', '|',\n 'undo', 'redo',\n ],\n full: [\n 'heading', '|',\n 'fontSize', 'fontColor', 'fontBackgroundColor', '|',\n 'bold', 'italic', 'underline', 'strikethrough', '|',\n 'alignment', '|',\n 'link', 'blockQuote', 'insertTable', 'uploadImage', 'mediaEmbed', 'horizontalLine', '|',\n 'bulletedList', 'numberedList', 'indent', 'outdent', '|',\n 'codeBlock', 'sourceEditing', '|',\n 'undo', 'redo',\n ],\n};\n\n/**\n * CKEditor5 번역 스크립트를 동적으로 로드합니다.\n * 영어(en)는 기본 내장이므로 로드하지 않습니다.\n */\nfunction loadCkeditorTranslations(locale: string): Promise {\n if (locale === 'en') return Promise.resolve();\n const id = `ckeditor5-translations-${locale}`;\n if (document.getElementById(id)) return Promise.resolve();\n return new Promise((resolve) => {\n const script = document.createElement('script');\n script.id = id;\n script.src = `${CKEDITOR5_TRANSLATIONS_BASE}/${locale}.umd.js`;\n script.onload = () => resolve();\n script.onerror = () => resolve(); // 번역 실패해도 에디터는 영어로 동작\n document.head.appendChild(script);\n });\n}\n\n/**\n * CKEditor5 CSS를 동적으로 로드합니다.\n * 이미 로드된 경우 중복 삽입하지 않습니다.\n */\nfunction loadCkeditorCss(): void {\n if (document.getElementById(CKEDITOR5_CSS_ID)) {\n return;\n }\n const link = document.createElement('link');\n link.id = CKEDITOR5_CSS_ID;\n link.rel = 'stylesheet';\n link.href = CKEDITOR5_CSS_URL;\n document.head.appendChild(link);\n}\n\n/**\n * 다국어 탭 버튼 기본 스타일(라이트/다크 공통 베이스)을 주입합니다.\n * 이미 주입된 경우 중복 삽입하지 않습니다.\n */\nfunction loadTabCss(): void {\n if (document.getElementById(CKEDITOR5_TAB_CSS_ID)) {\n return;\n }\n const style = document.createElement('style');\n style.id = CKEDITOR5_TAB_CSS_ID;\n style.textContent = `\n /* 다국어 탭 컨테이너 */\n .ckeditor5-locale-tabs {\n display: flex;\n gap: 8px;\n margin-bottom: 12px;\n align-items: center;\n }\n /* 다국어 탭 버튼 - HtmlEditor 언어탭 스타일 */\n .ckeditor5-locale-tabs button {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n padding: 6px 12px;\n border: none;\n border-radius: 9999px;\n cursor: pointer;\n font-size: 0.75rem;\n font-weight: 600;\n line-height: 1;\n transition: background 0.15s, color 0.15s, transform 0.15s, box-shadow 0.15s;\n }\n /* 비활성 - 기본언어 (blue) */\n .ckeditor5-locale-tabs button.is-default {\n background: #eff6ff;\n color: #2563eb;\n }\n .ckeditor5-locale-tabs button.is-default:hover {\n background: #dbeafe;\n }\n /* 비활성 - 비기본언어 (gray) */\n .ckeditor5-locale-tabs button:not(.is-default) {\n background: #f3f4f6;\n color: #4b5563;\n }\n .ckeditor5-locale-tabs button:not(.is-default):hover {\n background: #e5e7eb;\n }\n /* 활성 - 기본언어 */\n .ckeditor5-locale-tabs button.is-active.is-default {\n background: #3b82f6;\n color: #ffffff;\n box-shadow: 0 2px 6px rgba(0,0,0,0.15);\n transform: scale(1.05);\n }\n /* 활성 - 비기본언어 */\n .ckeditor5-locale-tabs button.is-active:not(.is-default) {\n background: #6b7280;\n color: #ffffff;\n box-shadow: 0 2px 6px rgba(0,0,0,0.15);\n transform: scale(1.05);\n }\n .ckeditor5-locale-tabs button .ck5-lang-icon {\n font-size: 0.75rem;\n line-height: 1;\n }\n .ckeditor5-locale-tabs button .ck5-required {\n color: #ef4444;\n }\n .ckeditor5-locale-tabs button.is-active .ck5-required {\n color: #fca5a5;\n }\n .ckeditor5-locale-tabs button .ck5-check {\n color: #22c55e;\n }\n /* 다크 모드 - 비활성 기본언어 */\n html.dark .ckeditor5-locale-tabs button.is-default {\n background: rgba(59, 130, 246, 0.15);\n color: #93c5fd;\n }\n html.dark .ckeditor5-locale-tabs button.is-default:hover {\n background: rgba(59, 130, 246, 0.25);\n }\n /* 다크 모드 - 비활성 비기본언어 */\n html.dark .ckeditor5-locale-tabs button:not(.is-default) {\n background: #374151;\n color: #d1d5db;\n }\n html.dark .ckeditor5-locale-tabs button:not(.is-default):hover {\n background: #4b5563;\n }\n /* 다크 모드 - 활성 기본언어 */\n html.dark .ckeditor5-locale-tabs button.is-active.is-default {\n background: #2563eb;\n color: #ffffff;\n }\n /* 다크 모드 - 활성 비기본언어 */\n html.dark .ckeditor5-locale-tabs button.is-active:not(.is-default) {\n background: #4b5563;\n color: #ffffff;\n }\n html.dark .ckeditor5-locale-tabs button .ck5-check {\n color: #4ade80;\n }\n /* 표 너비 인라인 스타일 무력화 - 컨테이너에 맞게 100% */\n .ck-content figure.table { width: 100%; }\n .ck-content figure.table table { width: 100%; }\n /* 표 tr 배경색 초기화 */\n .ck-content table tr { background-color: unset; }\n /* 표 col 절대 px 너비 무력화 - 컨테이너에 맞게 비율로 */\n .ck-content table col { width: auto !important; }\n /* 표 정렬 보정: CKEditor5 기본 CSS의 margin-left:auto를 float으로 덮어씀 */\n .ck-content figure.table[style*=\"float:left\"],\n .ck-content figure.table[style*=\"float: left\"] {\n margin-left: 0 !important;\n margin-right: 1em !important;\n }\n .ck-content figure.table[style*=\"float:right\"],\n .ck-content figure.table[style*=\"float: right\"] {\n margin-left: 1em !important;\n margin-right: 0 !important;\n }\n /* 이미지 캡션 - 라이트 모드 */\n .ck-content .image > figcaption {\n background-color: #f3f4f6;\n color: #374151;\n font-size: 0.875em;\n padding: 4px 8px;\n text-align: center;\n }\n /* 에디터 편집 영역 - 목록 마커 복원 (Tailwind preflight reset 대응) */\n .ck.ck-editor__editable ul,\n .ck-content ul {\n list-style-type: disc;\n padding-left: 2em;\n }\n .ck.ck-editor__editable ol,\n .ck-content ol {\n list-style-type: decimal;\n padding-left: 2em;\n }\n .ck.ck-editor__editable ul ul,\n .ck-content ul ul {\n list-style-type: circle;\n padding-left: 2em;\n }\n .ck.ck-editor__editable ul ul ul,\n .ck-content ul ul ul {\n list-style-type: square;\n padding-left: 2em;\n }\n .ck.ck-editor__editable ol ol,\n .ck-content ol ol {\n list-style-type: lower-alpha;\n padding-left: 2em;\n }\n .ck.ck-editor__editable ol ol ol,\n .ck-content ol ol ol {\n list-style-type: lower-roman;\n padding-left: 2em;\n }\n `;\n document.head.appendChild(style);\n}\n\n/**\n * 현재 다크 모드 여부를 반환합니다.\n */\nfunction isDarkMode(): boolean {\n return document.documentElement.classList.contains('dark');\n}\n\n/**\n * CKEditor5 다크 모드 CSS 변수를 동적으로 주입하거나 제거합니다.\n * document.documentElement의 'dark' 클래스를 기준으로 판단합니다.\n */\nfunction applyDarkModeOverride(): void {\n const existing = document.getElementById(CKEDITOR5_DARK_CSS_ID);\n\n if (!isDarkMode()) {\n // 라이트 모드: 다크 오버라이드 제거\n if (existing) {\n existing.remove();\n }\n return;\n }\n\n if (existing) {\n return;\n }\n\n const style = document.createElement('style');\n style.id = CKEDITOR5_DARK_CSS_ID;\n style.textContent = `\n /* CKEditor5 다크 모드 오버라이드 - CSS 변수 전역 적용 */\n :root {\n --ck-color-base-foreground: #1f2937;\n --ck-color-base-background: #1f2937;\n --ck-color-base-border: #374151;\n --ck-color-text: #f3f4f6;\n --ck-color-toolbar-background: #111827;\n --ck-color-toolbar-border: #374151;\n --ck-color-button-default-background: transparent;\n --ck-color-button-default-hover-background: #374151;\n --ck-color-button-default-active-background: #4b5563;\n --ck-color-button-on-background: #374151;\n --ck-color-button-on-hover-background: #4b5563;\n --ck-color-focus-border: #3b82f6;\n --ck-color-input-background: #1f2937;\n --ck-color-input-text: #f3f4f6;\n --ck-color-input-border: #374151;\n --ck-color-panel-background: #1f2937;\n --ck-color-panel-border: #374151;\n --ck-color-list-button-hover-background: #374151;\n --ck-color-list-button-on-background: #3b82f6;\n --ck-color-list-button-on-color: #f3f4f6;\n --ck-color-list-button-on-hover-background: #4b5563;\n --ck-color-labeled-field-label-background: #1f2937;\n --ck-color-link-default: #60a5fa;\n --ck-color-link-selected-background: rgba(96, 165, 250, 0.1);\n --ck-color-table-focused-cell-background: rgba(59, 130, 246, 0.1);\n }\n /* 에디터 본문 */\n .ck.ck-editor__editable_inline {\n background-color: #1f2937 !important;\n color: #f3f4f6 !important;\n border-color: #374151 !important;\n }\n /* 메인 툴바 */\n .ck.ck-toolbar {\n background-color: #111827 !important;\n border-color: #374151 !important;\n }\n /* 모든 버튼 텍스트 */\n .ck.ck-button,\n .ck.ck-button .ck-button__label {\n color: #f3f4f6 !important;\n }\n /* 모든 SVG 아이콘 (툴바, 드롭다운 화살표 포함) */\n .ck.ck-icon,\n .ck .ck-icon,\n .ck.ck-button .ck-icon,\n .ck.ck-dropdown__arrow {\n color: #f3f4f6 !important;\n }\n .ck.ck-button:hover,\n .ck.ck-button.ck-on {\n background-color: #374151 !important;\n }\n /* 툴팁 (호버 시 버튼 설명) */\n .ck.ck-tooltip .ck-tooltip__text {\n background-color: #1f2937 !important;\n color: #f3f4f6 !important;\n }\n /* 드롭다운 패널 / 리스트 / balloon 팝업 공통 */\n .ck.ck-dropdown__panel,\n .ck.ck-list,\n .ck.ck-balloon-panel {\n background-color: #1f2937 !important;\n border-color: #374151 !important;\n }\n /* 리스트 아이템 */\n .ck.ck-list__item .ck-button,\n .ck.ck-list__item .ck-button .ck-button__label {\n color: #f3f4f6 !important;\n }\n .ck.ck-list__item .ck-button:hover {\n background-color: #374151 !important;\n }\n .ck.ck-list__item .ck-button.ck-disabled .ck-button__label {\n color: #6b7280 !important;\n }\n /* 링크 팝업 / form */\n .ck.ck-link-form,\n .ck.ck-link-actions {\n background-color: #1f2937 !important;\n border-color: #374151 !important;\n }\n .ck.ck-input-text {\n background-color: #111827 !important;\n color: #f3f4f6 !important;\n border-color: #374151 !important;\n }\n .ck.ck-labeled-field-view__label {\n background-color: #1f2937 !important;\n color: #9ca3af !important;\n }\n /* 테이블 속성/셀 속성 폼 */\n .ck.ck-table-form,\n .ck.ck-table-cell-properties-form,\n .ck.ck-table-properties-form {\n background-color: #1f2937 !important;\n border-color: #374151 !important;\n }\n .ck.ck-table-form .ck-label,\n .ck.ck-table-cell-properties-form .ck-label,\n .ck.ck-table-properties-form .ck-label {\n color: #d1d5db !important;\n }\n /* 색상 선택 패널 */\n .ck.ck-color-table,\n .ck.ck-color-grid {\n background-color: #1f2937 !important;\n }\n .ck.ck-color-table .ck-color-table__remove-color,\n .ck.ck-color-table .ck-color-table__remove-color .ck-button__label {\n color: #f3f4f6 !important;\n }\n /* 헤딩/폰트 드롭다운 라벨 */\n .ck.ck-heading_paragraph,\n .ck.ck-heading_heading1,\n .ck.ck-heading_heading2,\n .ck.ck-heading_heading3 {\n color: #f3f4f6 !important;\n }\n /* 이미지 캡션 */\n .ck-content .image > figcaption {\n background-color: #374151 !important;\n color: #d1d5db !important;\n }\n /* 이미지 리사이즈 핸들 */\n .ck-content .image.ck-widget_selected .ck-widget__resizer__handle {\n background-color: #3b82f6 !important;\n border-color: #1d4ed8 !important;\n }\n /* 이미지 정렬 툴바 아이콘 */\n .ck.ck-toolbar .ck-button .ck-icon {\n color: #f3f4f6 !important;\n }\n /* 이미지 선택 시 balloon toolbar (floating) */\n .ck.ck-toolbar_floating {\n background-color: #111827 !important;\n border-color: #374151 !important;\n }\n /* 이미지 리사이즈 드롭다운 버튼 라벨 (25%, 50% 등) */\n .ck.ck-dropdown .ck-button__label {\n color: #f3f4f6 !important;\n }\n /* 이미지 리사이즈 드롭다운 내 선택 리스트 */\n .ck.ck-resize-image-form,\n .ck.ck-image-resize-form {\n background-color: #1f2937 !important;\n border-color: #374151 !important;\n color: #f3f4f6 !important;\n }\n .ck.ck-resize-image-form .ck-label,\n .ck.ck-image-resize-form .ck-label {\n color: #d1d5db !important;\n }\n .ck.ck-resize-image-form .ck-input-text,\n .ck.ck-image-resize-form .ck-input-text {\n background-color: #111827 !important;\n color: #f3f4f6 !important;\n border-color: #374151 !important;\n }\n /* 표 안 에디터 내용 (다크 배경) */\n .ck-content table tr {\n background-color: unset;\n }\n .ck-content table td,\n .ck-content table th {\n border-color: #4b5563;\n color: #f3f4f6 !important;\n }\n /* 표 col 절대 px 너비 무력화 */\n .ck-content table col {\n width: auto !important;\n }\n /* 목록 마커 색상 - 다크모드 */\n .ck.ck-editor__editable ul,\n .ck.ck-editor__editable ol {\n color: #f3f4f6;\n }\n .ck.ck-editor__editable li::marker {\n color: #d1d5db;\n }\n `;\n document.head.appendChild(style);\n}\n\n/** 다크 모드 MutationObserver 인스턴스 (cleanup용) */\nlet darkModeObserver: MutationObserver | null = null;\n\n/**\n * 클래스 변경을 감지하여 다크 모드 전환 시 즉시 반영합니다.\n * 최초 1회만 등록합니다.\n */\nfunction watchDarkMode(): void {\n if (darkModeObserver) {\n return;\n }\n\n darkModeObserver = new MutationObserver(() => {\n applyDarkModeOverride();\n });\n\n darkModeObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ['class'],\n });\n}\n\n/**\n * 다크 모드 MutationObserver를 해제합니다.\n */\nexport function disconnectDarkModeObserver(): void {\n if (darkModeObserver) {\n darkModeObserver.disconnect();\n darkModeObserver = null;\n }\n}\n\n/** locale 코드 → 표시 이름 매핑 */\nconst LOCALE_LABELS: Record = {\n ko: '한국어',\n en: 'English',\n ja: '日本語',\n zh: '中文',\n fr: 'Français',\n de: 'Deutsch',\n es: 'Español',\n};\n\n/**\n * locale 코드를 표시 이름으로 변환합니다.\n * 매핑에 없는 경우 대문자 코드를 반환합니다.\n */\nfunction getLocaleLabel(locale: string): string {\n return LOCALE_LABELS[locale] ?? locale.toUpperCase();\n}\n\n/**\n * 지원 locale 목록을 반환합니다.\n * localStorage의 g7_locale 값과 서버 설정을 활용합니다.\n */\nfunction getSupportedLocales(): string[] {\n const G7Core = (window as any).G7Core;\n if (G7Core?.locale?.supported) {\n return G7Core.locale.supported();\n }\n // 폴백: 현재 locale만 사용\n const currentLocale = localStorage.getItem('g7_locale') || 'ko';\n return [currentLocale];\n}\n\n/**\n * 현재 locale을 반환합니다.\n * G7Core.locale.current() 우선, 폴백으로 localStorage 사용.\n */\nfunction getCurrentLocale(): string {\n const G7Core = (window as any).G7Core;\n return G7Core?.locale?.current?.() ?? localStorage.getItem('g7_locale') ?? 'ko';\n}\n\n/**\n * CKEditor 플러그인 목록을 toolbar 타입에 따라 반환합니다.\n */\nfunction getPlugins(CKEDITOR: CKEditorGlobal, toolbarType: string, withImageUpload: boolean): any[] {\n const base = [\n CKEDITOR.Essentials,\n CKEDITOR.Bold,\n CKEDITOR.Italic,\n CKEDITOR.Underline,\n CKEDITOR.Strikethrough,\n CKEDITOR.Link,\n CKEDITOR.Paragraph,\n CKEDITOR.Heading,\n CKEDITOR.BlockQuote,\n CKEDITOR.List,\n CKEDITOR.Alignment,\n CKEDITOR.Table,\n CKEDITOR.TableToolbar,\n CKEDITOR.TableProperties,\n CKEDITOR.TableCellProperties,\n CKEDITOR.Indent,\n CKEDITOR.IndentBlock,\n CKEDITOR.PasteFromOffice,\n CKEDITOR.GeneralHtmlSupport,\n // 이미지 플러그인은 업로드 여부와 무관하게 항상 포함 (기존 이미지 크기 조정/정렬 지원)\n CKEDITOR.Image,\n CKEDITOR.ImageResize,\n CKEDITOR.ImageStyle,\n CKEDITOR.ImageCaption,\n CKEDITOR.ImageToolbar,\n ];\n\n if (toolbarType === 'full') {\n base.push(\n CKEDITOR.MediaEmbed,\n CKEDITOR.HorizontalLine,\n CKEDITOR.CodeBlock,\n CKEDITOR.SourceEditing,\n CKEDITOR.FontSize,\n CKEDITOR.FontColor,\n CKEDITOR.FontBackgroundColor,\n );\n }\n\n if (withImageUpload) {\n base.push(\n CKEDITOR.ImageUpload,\n CKEDITOR.SimpleUploadAdapter,\n );\n }\n\n return base;\n}\n\n/**\n * 이미지 업로드 URL을 생성합니다.\n * uploadPermission이 있으면 쿼리스트링으로 추가합니다.\n */\nfunction buildUploadUrl(uploadPermission: string): string {\n const base = '/api/plugins/sirsoft-ckeditor5/upload';\n if (uploadPermission) {\n return `${base}?permission=${encodeURIComponent(uploadPermission)}`;\n }\n return base;\n}\n\n/**\n * 이미지 업로드 헤더를 반환합니다.\n * Bearer 토큰을 Authorization 헤더에 포함합니다.\n */\nfunction getUploadHeaders(): Record {\n const token = localStorage.getItem('auth_token');\n if (token) {\n return { Authorization: `Bearer ${token}` };\n }\n return {};\n}\n\n/**\n * 단일 CKEditor 인스턴스를 생성합니다.\n */\nasync function createEditorInstance(\n element: HTMLElement,\n options: {\n initialContent: string;\n placeholder: string;\n readOnly: boolean;\n imageUpload: boolean;\n uploadPermission: string;\n height: number;\n toolbar: string;\n containerId: string;\n }\n): Promise {\n const CKEDITOR = (window as any).CKEDITOR as CKEditorGlobal;\n if (!CKEDITOR) {\n throw new Error('[sirsoft-ckeditor5] CKEDITOR 전역 객체를 찾을 수 없습니다. CDN 스크립트가 로드되었는지 확인하세요.');\n }\n\n const toolbarItems = TOOLBAR_PRESETS[options.toolbar] || TOOLBAR_PRESETS.standard;\n\n // 이미지 업로드 비활성화 시 uploadImage 버튼 제거\n const finalToolbar = options.imageUpload\n ? toolbarItems\n : toolbarItems.filter(item => item !== 'uploadImage');\n\n const editorConfig: Record = {\n initialData: options.initialContent,\n plugins: getPlugins(CKEDITOR, options.toolbar, options.imageUpload),\n toolbar: { items: finalToolbar },\n table: {\n contentToolbar: [\n 'tableColumn', 'tableRow', 'mergeTableCells',\n '|', 'tableProperties', 'tableCellProperties',\n ],\n tableProperties: {\n defaultProperties: {\n borderStyle: 'solid',\n borderColor: '#d1d5db',\n borderWidth: '1px',\n alignment: 'left',\n },\n },\n tableCellProperties: {\n defaultProperties: {\n borderStyle: 'solid',\n borderColor: '#d1d5db',\n borderWidth: '1px',\n padding: '8px',\n },\n },\n },\n image: {\n toolbar: [\n 'imageStyle:inline',\n 'imageStyle:alignLeft',\n 'imageStyle:alignCenter',\n 'imageStyle:alignRight',\n '|',\n 'toggleImageCaption',\n '|',\n 'resizeImage',\n ],\n resizeOptions: [\n { name: 'resizeImage:original', label: 'Original', value: null },\n { name: 'resizeImage:25', label: '25%', value: '25' },\n { name: 'resizeImage:50', label: '50%', value: '50' },\n { name: 'resizeImage:75', label: '75%', value: '75' },\n ],\n resizeUnit: '%' as const,\n },\n indentBlock: {\n offset: 40,\n unit: 'px',\n },\n link: {\n defaultProtocol: 'https://',\n decorators: {\n openInNewTab: {\n mode: 'automatic' as const,\n callback: (url: string) => url.startsWith('http://') || url.startsWith('https://'),\n attributes: {\n target: '_blank',\n rel: 'noopener noreferrer',\n },\n },\n },\n },\n htmlSupport: {\n allow: [\n { name: /.*/, attributes: true, classes: true, styles: true },\n ],\n },\n placeholder: options.placeholder,\n language: getCurrentLocale(),\n };\n\n if (options.imageUpload) {\n editorConfig.simpleUpload = {\n uploadUrl: buildUploadUrl(options.uploadPermission),\n headers: getUploadHeaders(),\n };\n }\n\n const editor = await CKEDITOR.ClassicEditor.create(element, editorConfig);\n\n // 높이 설정: 인라인 스타일은 포커스 시 CKEditor 내부에서 초기화될 수 있으므로\n // containerId 기반 CSS 규칙으로 강제 적용 (remount 시 동일 ID로 덮어씀)\n const heightStyleId = `ckeditor5-height-style-${options.containerId}`;\n const existingHeightStyle = document.getElementById(heightStyleId);\n if (existingHeightStyle) {\n existingHeightStyle.textContent = `#${options.containerId} .ck-editor__editable { min-height: ${options.height}px !important; }`;\n } else {\n const heightStyle = document.createElement('style');\n heightStyle.id = heightStyleId;\n heightStyle.textContent = `#${options.containerId} .ck-editor__editable { min-height: ${options.height}px !important; }`;\n document.head.appendChild(heightStyle);\n }\n\n if (options.readOnly) {\n editor.enableReadOnlyMode('read-only');\n }\n\n return editor;\n}\n\n/**\n * 다국어 탭 UI를 생성합니다.\n */\nfunction createMultilingualTabs(\n container: HTMLElement,\n locales: string[],\n activeLocale: string,\n onTabActivate?: (locale: string) => Promise,\n getEditorData?: (locale: string) => string | null\n): { tabsEl: HTMLElement; contentEls: Map; updateCheckIcons: () => void } {\n const tabsEl = document.createElement('div');\n tabsEl.className = 'ckeditor5-locale-tabs';\n\n const contentEls = new Map();\n\n // 에디터 컨텐츠 영역 먼저 생성\n // CKEditor ClassicEditor.create(element)는 element를 숨기고 nextSibling 위치에\n // .ck-editor를 삽입하므로, wrapper div로 감싸서 display:none을 wrapper에 적용해야\n // 비활성 locale의 에디터가 보이지 않음\n locales.forEach(locale => {\n const wrapperEl = document.createElement('div');\n wrapperEl.dataset.locale = locale;\n if (locale !== activeLocale) {\n wrapperEl.style.cssText = 'display:none;';\n }\n const contentEl = document.createElement('div');\n wrapperEl.appendChild(contentEl);\n contentEls.set(locale, contentEl);\n });\n\n /**\n * 비활성 탭의 체크 아이콘을 갱신합니다.\n * 에디터에 값이 있으면 체크 아이콘을 표시하고, 없으면 제거합니다.\n */\n const updateCheckIcons = () => {\n if (!getEditorData) return;\n tabsEl.querySelectorAll('button').forEach(btn => {\n const btnLocale = (btn as HTMLButtonElement).dataset.locale;\n if (!btnLocale || btn.classList.contains('is-active')) {\n // 활성 탭은 체크 아이콘 제거\n const existing = btn.querySelector('.ck5-check');\n if (existing) existing.remove();\n return;\n }\n const data = getEditorData(btnLocale);\n const hasValue = Boolean(data?.trim());\n const existing = btn.querySelector('.ck5-check');\n if (hasValue && !existing) {\n const icon = document.createElement('i');\n icon.className = 'fas fa-check ck5-check';\n btn.appendChild(icon);\n } else if (!hasValue && existing) {\n existing.remove();\n }\n });\n };\n\n // 탭 버튼 생성\n const defaultLocale = locales[0];\n locales.forEach(locale => {\n const isDefault = locale === defaultLocale;\n const isActive = locale === activeLocale;\n const tab = document.createElement('button');\n tab.type = 'button';\n tab.dataset.locale = locale;\n tab.className = [isActive ? 'is-active' : '', isDefault ? 'is-default' : ''].filter(Boolean).join(' ');\n tab.innerHTML = `${getLocaleLabel(locale)}${isDefault ? '*' : ''}`;\n tab.addEventListener('click', async () => {\n // 탭 활성화 전환 (에디터 생성 전에 먼저 실행)\n tabsEl.querySelectorAll('button').forEach(btn => {\n const btnLocale = (btn as HTMLButtonElement).dataset.locale;\n const btnIsActive = btnLocale === locale;\n btn.classList.toggle('is-active', btnIsActive);\n });\n // 에디터 컨텐츠 영역 전환 (새 locale만 표시, 나머지 숨김)\n // wrapperEl(contentEl.parentElement)에 display를 적용해야\n // CKEditor가 삽입한 .ck-editor sibling도 함께 숨겨짐\n contentEls.forEach((el, elLocale) => {\n const wrapperEl = el.parentElement;\n if (wrapperEl) {\n wrapperEl.style.display = elLocale === locale ? 'block' : 'none';\n }\n });\n // lazy 에디터 생성 (아직 없는 경우, display 전환 후 실행)\n if (onTabActivate) {\n await onTabActivate(locale);\n }\n // 탭 전환 완료 후 체크 아이콘 갱신\n updateCheckIcons();\n });\n tabsEl.appendChild(tab);\n });\n\n container.appendChild(tabsEl);\n contentEls.forEach(el => {\n if (el.parentElement) {\n container.appendChild(el.parentElement);\n }\n });\n\n return { tabsEl, contentEls, updateCheckIcons };\n}\n\n/**\n * 폼 데이터 업데이트를 위해 G7Core setState를 호출합니다.\n */\nfunction syncToForm(\n name: string,\n locale: string,\n value: string,\n isMultilingual: boolean\n): void {\n // setData() 호출 중 change:data 재진입 방지\n if (isSyncSuppressed()) return;\n\n const G7Core = (window as any).G7Core;\n if (!G7Core?.state?.setLocal) {\n return;\n }\n\n const updates: Record = {\n [`form.${name}_mode`]: 'html',\n hasChanges: true,\n };\n\n if (isMultilingual) {\n updates[`form.${name}.${locale}`] = value;\n } else {\n updates[`form.${name}`] = value;\n }\n\n // G7 표준 debounce + render: false 사용 (engine-v1.42.0)\n // - debounce: ActionDispatcher 타이머 인프라 활용, 컴포넌트 언마운트 시 자동 정리\n // - render: false: CKEditor가 자체 DOM을 관리하므로 React 리렌더 불필요\n // 타이핑 중 전체 폼 트리 리렌더 방지 (37,000+ 바인딩 평가 제거)\n // - 저장 시: flushPendingDebounceTimers → globalStateUpdater({}) 강제 렌더 1회\n G7Core.state.setLocal(updates, {\n debounce: 300,\n debounceKey: `ckeditor-sync-${name}`,\n render: false,\n });\n}\n\n\n/**\n * initEditor 핸들러\n *\n * onMount 시 CKEditor5 인스턴스를 초기화합니다.\n * multilingual=true 시 locale별 탭 UI와 별도 인스턴스를 생성합니다.\n *\n * @param params 핸들러 파라미터\n * @param context 액션 컨텍스트\n */\nexport async function initEditorHandler(\n action: { params?: InitEditorParams; [key: string]: any },\n _context: unknown\n): Promise {\n // ActionHandler 시그니처: (action: ActionDefinition, context: ActionContext)\n // action.params에 실제 파라미터가 있음 (ActionDispatcher에서 resolveParams 후 전달)\n const params: InitEditorParams = (action.params as InitEditorParams) ?? {};\n // 컨테이너 ID: html-editor.json의 props.id와 동일한 패턴으로 계산\n // 동일 페이지에 에디터가 여러 개 있을 때 충돌 방지\n const editorName = (params.name as string) ?? 'content';\n const containerId = `ckeditor5-${editorName}`;\n\n // 기존 인스턴스가 있으면 먼저 정리\n const existing = editorInstances.get(containerId);\n if (existing && existing.size > 0) {\n const destroyPromises: Promise[] = [];\n existing.forEach((editor: any) => {\n if (editor && typeof editor.destroy === 'function') {\n destroyPromises.push(editor.destroy().catch(() => {}));\n }\n });\n await Promise.allSettled(destroyPromises);\n editorInstances.delete(containerId);\n }\n\n // 컨테이너 DOM 찾기\n const container = document.getElementById(containerId);\n if (!container) {\n console.warn(`[sirsoft-ckeditor5] 컨테이너 엘리먼트를 찾을 수 없습니다: #${containerId}`);\n return;\n }\n\n // CKEditor CSS 동적 로드 및 다크 모드 오버라이드 적용\n loadCkeditorCss();\n loadTabCss();\n applyDarkModeOverride();\n watchDarkMode();\n\n // 번역 파일 로드 (에디터 생성 전 완료되어야 함)\n await loadCkeditorTranslations(getCurrentLocale());\n\n // 플러그인 설정을 G7Core 전역 상태에서 직접 읽기 (params 바인딩 실패 대비 폴백)\n const G7Core = (window as any).G7Core;\n const globalState = G7Core?.state?.get() || {};\n // getGlobalState()는 { sidebarOpen, plugins, ... } 구조를 반환\n // _global 래퍼가 있는 경우와 없는 경우 모두 처리\n const pluginSettings = globalState._global?.plugins?.['sirsoft-ckeditor5']\n ?? globalState.plugins?.['sirsoft-ckeditor5']\n ?? {};\n\n // 파라미터 파싱 (params 바인딩 성공 시 우선 사용, 실패(undefined) 시 플러그인 설정 폴백)\n const name = params.name ?? 'content';\n const isMultilingual = params.multilingual === true || params.multilingual === 'true';\n const isReadOnly = params.readOnly === true || params.readOnly === 'true';\n const withImageUpload = params.imageUpload !== undefined\n ? (params.imageUpload === true || params.imageUpload === 'true')\n : (pluginSettings.imageUpload === true || pluginSettings.imageUpload === 'true');\n const uploadPermission = params.uploadPermission ?? '';\n const placeholder = params.placeholder ?? '';\n const height = params.height !== undefined ? (Number(params.height) || 400) : (Number(pluginSettings.editorHeight) || 400);\n const toolbarType = (params.toolbar !== undefined ? (params.toolbar as string) : (pluginSettings.toolbar as string)) ?? 'standard';\n\n // content 파싱: 다국어 시 객체, 단일 시 문자열\n // extensionPointProps를 통해 전달되는 경우 표현식이 평가되지 않고 raw 문자열로 전달될 수 있음\n // 이 경우 G7Core.state.getLocal().form[name] 폴백 사용\n let contentMap: Record = {};\n if (isMultilingual) {\n try {\n if (typeof params.content === 'string' && params.content.startsWith('{') && !params.content.startsWith('{{')) {\n contentMap = JSON.parse(params.content);\n } else if (typeof params.content === 'object' && params.content !== null) {\n contentMap = params.content as unknown as Record;\n }\n } catch {\n contentMap = {};\n }\n // contentMap이 비어있으면 G7Core.state.getLocal().form[name]에서 폴백\n if (Object.keys(contentMap).length === 0 && name) {\n const localState = G7Core?.state?.getLocal?.() ?? {};\n const formValue = localState?.form?.[name];\n // 배열은 content 미설정 상태(API 기본값 [])이므로 무시\n if (formValue && typeof formValue === 'object' && !Array.isArray(formValue)) {\n contentMap = formValue as Record;\n } else if (typeof formValue === 'string' && formValue) {\n // 단일 문자열인 경우 현재 로케일에 매핑\n const currentLocale = getCurrentLocale();\n contentMap = { [currentLocale]: formValue };\n }\n // form[name]도 비어있으면 _global.selectedItem[name]에서 추가 폴백\n if (Object.keys(contentMap).length === 0) {\n const globalState = G7Core?.state?.get?.() ?? {};\n const selectedItem = globalState?._global?.selectedItem ?? globalState?.selectedItem;\n const selectedValue = selectedItem?.[name];\n if (selectedValue && typeof selectedValue === 'object' && !Array.isArray(selectedValue)) {\n contentMap = selectedValue as Record;\n }\n }\n }\n }\n\n const instanceMap = new Map();\n editorInstances.set(containerId, instanceMap);\n\n const editorOptions = {\n placeholder,\n readOnly: isReadOnly,\n imageUpload: withImageUpload,\n uploadPermission,\n height,\n toolbar: toolbarType,\n containerId,\n };\n\n if (isMultilingual) {\n const locales = getSupportedLocales();\n const activeLocale = getCurrentLocale();\n\n // createLocaleEditor ↔ createMultilingualTabs 순환 참조를 끊기 위한 ref\n const contentElsRef = { current: new Map() };\n const updateCheckIconsRef = { current: () => {} };\n\n // 에디터 인스턴스 생성 헬퍼\n const createLocaleEditor = async (locale: string) => {\n if (instanceMap.has(locale)) return; // 이미 생성된 경우 skip\n const contentEl = contentElsRef.current.get(locale);\n if (!contentEl) return;\n\n const initialContent = contentMap[locale] ?? '';\n\n try {\n const editor = await createEditorInstance(contentEl, {\n ...editorOptions,\n initialContent,\n });\n\n instanceMap.set(locale, editor);\n\n // 초기화 중 change:data 이벤트 억제 (CKEditor 내부 initialData 처리 시 발생 가능)\n let isInitializing = true;\n\n (editor as any).model.document.on('change:data', () => {\n if (isInitializing) return;\n const html = (editor as any).getData();\n syncToForm(name, locale, html, true);\n updateCheckIconsRef.current();\n });\n\n isInitializing = false;\n\n // 초기 콘텐츠 재동기화 제거 — initLocal이 이미 form state에 반영\n // mode만 설정 (create 모드에서 _mode 미설정 방지)\n // hasChanges는 설정하지 않음 (사용자 변경 아님)\n if (name) {\n const G7Core = (window as any).G7Core;\n const local = G7Core?.state?.getLocal?.() ?? {};\n if (local.form?.[`${name}_mode`] !== 'html') {\n G7Core.state.setLocal({ [`form.${name}_mode`]: 'html' });\n }\n }\n } catch (err) {\n console.error(`[sirsoft-ckeditor5] 에디터 초기화 오류 (locale: ${locale}):`, err);\n }\n };\n\n // instanceMap에서 에디터 데이터를 반환하는 콜백\n const getEditorData = (locale: string): string | null => {\n const editor = instanceMap.get(locale);\n if (!editor) return null;\n return (editor as any).getData?.() ?? null;\n };\n\n // 탭 클릭 시 lazy 생성 콜백을 전달하여 탭 UI 생성\n const { contentEls, updateCheckIcons } = createMultilingualTabs(container, locales, activeLocale, createLocaleEditor, getEditorData);\n contentElsRef.current = contentEls;\n updateCheckIconsRef.current = updateCheckIcons;\n\n // 활성 locale 에디터 먼저 생성\n await createLocaleEditor(activeLocale);\n\n // 나머지 locale 에디터 백그라운드에서 미리 생성 (탭 전환 시 딜레이 제거)\n // setTimeout으로 지연하여 활성 에디터 초기 입력 반응성 확보\n setTimeout(() => {\n locales.filter(l => l !== activeLocale).forEach(locale => {\n createLocaleEditor(locale);\n });\n }, 2000);\n\n } else {\n // 단일 에디터 모드\n // params.content가 빈 문자열이거나 미평가 표현식({{...}})인 경우\n // onMount 타이밍 문제로 _local.form이 아직 미적용된 것일 수 있음\n // G7Core.state.getLocal()로 현재 상태를 직접 읽어 폴백\n const rawContent = typeof params.content === 'string' ? params.content : '';\n const isUnresolvedExpression = rawContent.startsWith('{{') && rawContent.endsWith('}}');\n let initialContent = isUnresolvedExpression ? '' : rawContent;\n if (!initialContent && name) {\n const localState = G7Core?.state?.getLocal?.() ?? {};\n const formValue = localState?.form?.[name];\n if (typeof formValue === 'string' && formValue) {\n initialContent = formValue;\n }\n }\n const editorEl = document.createElement('div');\n container.appendChild(editorEl);\n\n try {\n const editor = await createEditorInstance(editorEl, {\n ...editorOptions,\n initialContent,\n });\n\n const singleLocale = getCurrentLocale();\n instanceMap.set(singleLocale, editor);\n\n // 초기화 중 change:data 이벤트 억제 (CKEditor 내부 initialData 처리 시 발생 가능)\n let isInitializing = true;\n\n // change:data 이벤트 → 폼 상태 동기화 (디바운스는 setLocal 내부에서 처리)\n (editor as any).model.document.on('change:data', () => {\n if (isInitializing) return;\n const html = (editor as any).getData();\n syncToForm(name, singleLocale, html, false);\n });\n\n isInitializing = false;\n\n // 초기값 강제 설정 (initialData가 무시되는 경우 대비)\n if (initialContent) {\n const currentData = (editor as any).getData();\n if (!currentData || currentData.trim() === '') {\n (editor as any).setData(initialContent);\n }\n // 초기 콘텐츠 재동기화 제거 — initLocal이 이미 form state에 반영\n }\n\n // mode만 설정 (create 모드에서 _mode 미설정 방지)\n if (name) {\n const G7Core = (window as any).G7Core;\n const local = G7Core?.state?.getLocal?.() ?? {};\n if (local.form?.[`${name}_mode`] !== 'html') {\n G7Core.state.setLocal({ [`form.${name}_mode`]: 'html' });\n }\n }\n\n // 단일 에디터는 페이지 이동 없이 form이 교체되는 패턴이 없으므로\n // 외부 상태 변경 polling 불필요\n } catch (err) {\n console.error('[sirsoft-ckeditor5] 에디터 초기화 오류:', err);\n editorInstances.delete(containerId);\n }\n }\n}\n","/**\n * CKEditor5 인스턴스 정리 핸들러\n *\n * 컴포넌트 언마운트 시 CKEditor 인스턴스를 파괴합니다.\n */\n\n// 컨테이너 ID → 인스턴스 맵 (initEditor.ts와 공유)\nimport { editorInstances } from './editorInstances';\nimport { disconnectDarkModeObserver } from './initEditor';\n\n/**\n * destroyEditor 핸들러\n *\n * onUnmount 시 해당 컨테이너의 모든 CKEditor 인스턴스를 파괴합니다.\n *\n * @param params 핸들러 파라미터 (사용 안 함)\n * @param context 액션 컨텍스트\n */\nexport async function destroyEditorHandler(\n action: Record,\n _context: unknown\n): Promise {\n // ActionHandler 시그니처: (action: ActionDefinition, context: ActionContext)\n // action.params.name 기반으로 containerId 계산 (initEditor와 동일한 패턴)\n const editorName = (action.params?.name as string) ?? 'content';\n const containerId = `ckeditor5-${editorName}`;\n const instances = editorInstances.get(containerId);\n\n if (!instances || instances.size === 0) {\n return;\n }\n\n const destroyPromises: Promise[] = [];\n\n instances.forEach((editor) => {\n if (editor && typeof editor.destroy === 'function') {\n destroyPromises.push(\n editor.destroy().catch((err: unknown) => {\n console.warn('[sirsoft-ckeditor5] destroyEditor error:', err);\n })\n );\n }\n });\n\n await Promise.allSettled(destroyPromises);\n\n editorInstances.delete(containerId);\n\n // height style 요소 정리\n const heightStyle = document.getElementById(`ckeditor5-height-style-${containerId}`);\n if (heightStyle) {\n heightStyle.remove();\n }\n\n // 모든 에디터 인스턴스가 제거되면 다크모드 옵저버도 해제\n if (editorInstances.size === 0) {\n disconnectDarkModeObserver();\n }\n}\n","/**\n * sirsoft-ckeditor5 플러그인 엔트리포인트\n *\n * 플러그인 활성화 시 자동으로 로드되어 핸들러를 등록합니다.\n */\n\nimport { initEditorHandler } from './handlers/initEditor';\nimport { destroyEditorHandler } from './handlers/destroyEditor';\n\nconst PLUGIN_IDENTIFIER = 'sirsoft-ckeditor5';\n\nconst CKEDITOR5_CSS_ID = 'ckeditor5-content-styles';\nconst CKEDITOR5_CSS_OVERRIDE_ID = 'ckeditor5-content-styles-override';\nconst CKEDITOR5_CSS_URL = 'https://cdn.ckeditor.com/ckeditor5/43.3.1/ckeditor5.css';\n\n/**\n * CKEditor5 content styles CSS를 동적으로 주입하는 핸들러\n * html-content.json extension_point의 onMount에서 호출됩니다.\n *\n * HtmlContent 컴포넌트에 ck-content 클래스가 적용되어 CDN CSS가 직접 동작합니다.\n * 다크모드(CDN 미지원)와 col 너비 처리만 override로 추가합니다.\n */\nfunction injectContentCssHandler(): void {\n if (!document.getElementById(CKEDITOR5_CSS_ID)) {\n const link = document.createElement('link');\n link.id = CKEDITOR5_CSS_ID;\n link.rel = 'stylesheet';\n link.href = CKEDITOR5_CSS_URL;\n document.head.appendChild(link);\n }\n\n if (!document.getElementById(CKEDITOR5_CSS_OVERRIDE_ID)) {\n const style = document.createElement('style');\n style.id = CKEDITOR5_CSS_OVERRIDE_ID;\n // 다크모드(CDN 미지원)와 col 너비 처리만 override로 유지\n style.textContent = `\n /* 이미지 캡션 - 다크모드 */\n html.dark .ck-content .image > figcaption { color: hsl(0, 0%, 80%); background-color: hsl(0, 0%, 15%); }\n\n /* CKEditor5 표 스타일 - 다크모드 */\n html.dark .ck-content figure.table table { border-color: hsl(0, 0%, 35%); }\n html.dark .ck-content figure.table table tr { background-color: unset; }\n html.dark .ck-content figure.table table td, html.dark .ck-content figure.table table th { border-color: hsl(0, 0%, 30%); color: hsl(0, 0%, 90%); background-color: unset; }\n html.dark .ck-content figure.table table th { background-color: hsl(215, 20%, 25%); }\n\n /* figure.table 전체 너비 - prose와의 충돌 방지 */\n .ck-content figure.table { display: table; width: 100%; margin: 1em 0; }\n .ck-content figure.table table { width: 100%; }\n .ck-content table tr { background-color: unset; }\n .ck-content table col { width: auto !important; }\n\n /* 표 정렬 보정 */\n .ck-content figure.table[style*=\"float:left\"],\n .ck-content figure.table[style*=\"float: left\"] { margin-left: 0 !important; margin-right: 1em !important; }\n .ck-content figure.table[style*=\"float:right\"],\n .ck-content figure.table[style*=\"float: right\"] { margin-left: 1em !important; margin-right: 0 !important; }\n\n /* 이미지 인라인/정렬 - Tailwind preflight img:block 대응 */\n .ck-content img { display: inline; margin: 0; max-width: 100%; }\n .ck-content p:has(img) { line-height: 0; }\n .ck-content p:has(img[style*=\"float\"]) { overflow: hidden; }\n\n /* 이미지 캡션 - 라이트 모드 */\n .ck-content .image > figcaption { background-color: #f3f4f6; color: #374151; font-size: 0.875em; padding: 4px 8px; text-align: center; }\n\n /* 목록 마커 및 들여쓰기 - Tailwind preflight reset 대응 */\n .ck-content ul { list-style-type: disc; padding-left: 2em; }\n .ck-content ol { list-style-type: decimal; padding-left: 2em; }\n .ck-content ul ul { list-style-type: circle; padding-left: 2em; }\n .ck-content ul ul ul { list-style-type: square; padding-left: 2em; }\n .ck-content ol ol { list-style-type: lower-alpha; padding-left: 2em; }\n .ck-content ol ol ol { list-style-type: lower-roman; padding-left: 2em; }\n `;\n document.head.appendChild(style);\n }\n\n}\n\nconst handlerMap: Record = {\n initEditor: initEditorHandler,\n destroyEditor: destroyEditorHandler,\n injectContentCss: injectContentCssHandler,\n};\n\nconst logger = ((window as any).G7Core?.createLogger?.(`Plugin:${PLUGIN_IDENTIFIER}`)) ?? {\n log: (...args: unknown[]) => console.log(`[Plugin:${PLUGIN_IDENTIFIER}]`, ...args),\n warn: (...args: unknown[]) => console.warn(`[Plugin:${PLUGIN_IDENTIFIER}]`, ...args),\n error: (...args: unknown[]) => console.error(`[Plugin:${PLUGIN_IDENTIFIER}]`, ...args),\n};\n\nfunction registerHandlers(retry: boolean = false): void {\n const actionDispatcher = (window as any).G7Core?.getActionDispatcher?.();\n\n if (actionDispatcher) {\n Object.entries(handlerMap).forEach(([name, handler]) => {\n const fullName = `${PLUGIN_IDENTIFIER}.${name}`;\n actionDispatcher.registerHandler(fullName, handler, {\n category: 'plugin',\n source: PLUGIN_IDENTIFIER,\n });\n });\n\n logger.log(\n `${Object.keys(handlerMap).length} handler(s) registered:`,\n Object.keys(handlerMap).map(name => `${PLUGIN_IDENTIFIER}.${name}`)\n );\n } else if (retry) {\n let retryCount = 0;\n const maxRetries = 50;\n\n const retryRegister = () => {\n const dispatcher = (window as any).G7Core?.getActionDispatcher?.();\n\n if (dispatcher) {\n Object.entries(handlerMap).forEach(([name, handler]) => {\n const fullName = `${PLUGIN_IDENTIFIER}.${name}`;\n dispatcher.registerHandler(fullName, handler, {\n category: 'plugin',\n source: PLUGIN_IDENTIFIER,\n });\n });\n\n logger.log(\n `${Object.keys(handlerMap).length} handler(s) registered:`,\n Object.keys(handlerMap).map(name => `${PLUGIN_IDENTIFIER}.${name}`)\n );\n } else {\n retryCount++;\n if (retryCount <= maxRetries) {\n logger.warn(`ActionDispatcher not found, retrying... (${retryCount}/${maxRetries})`);\n setTimeout(retryRegister, 100);\n } else {\n logger.error(`Failed to register handlers: ActionDispatcher not available after maximum retries`);\n }\n }\n };\n\n retryRegister();\n } else {\n logger.warn(`ActionDispatcher not found, handlers not registered`);\n }\n}\n\nexport function initPlugin(): void {\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => registerHandlers(true));\n } else {\n const hasDispatcher = !!(window as any).G7Core?.getActionDispatcher?.();\n registerHandlers(hasDispatcher ? false : true);\n }\n}\n\ninitPlugin();\n\nif (typeof window !== 'undefined') {\n (window as any).__SirsoftCkeditor5 = {\n identifier: PLUGIN_IDENTIFIER,\n handlers: Object.keys(handlerMap),\n initPlugin,\n };\n}"],"names":["editorInstances","CKEDITOR5_CSS_URL","CKEDITOR5_TRANSLATIONS_BASE","CKEDITOR5_CSS_ID","CKEDITOR5_DARK_CSS_ID","CKEDITOR5_TAB_CSS_ID","TOOLBAR_PRESETS","loadCkeditorTranslations","locale","id","resolve","script","loadCkeditorCss","link","loadTabCss","style","isDarkMode","applyDarkModeOverride","existing","darkModeObserver","watchDarkMode","disconnectDarkModeObserver","LOCALE_LABELS","getLocaleLabel","getSupportedLocales","G7Core","getCurrentLocale","getPlugins","CKEDITOR","toolbarType","withImageUpload","base","buildUploadUrl","uploadPermission","getUploadHeaders","token","createEditorInstance","element","options","toolbarItems","finalToolbar","item","editorConfig","url","editor","heightStyleId","existingHeightStyle","heightStyle","createMultilingualTabs","container","locales","activeLocale","onTabActivate","getEditorData","tabsEl","contentEls","wrapperEl","contentEl","updateCheckIcons","btn","btnLocale","hasValue","icon","defaultLocale","isDefault","isActive","tab","btnIsActive","el","elLocale","syncToForm","name","value","isMultilingual","updates","initEditorHandler","action","_context","params","containerId","destroyPromises","globalState","pluginSettings","isReadOnly","placeholder","height","contentMap","formValue","selectedValue","instanceMap","editorOptions","contentElsRef","updateCheckIconsRef","createLocaleEditor","initialContent","isInitializing","html","err","l","rawContent","editorEl","singleLocale","currentData","destroyEditorHandler","instances","PLUGIN_IDENTIFIER","CKEDITOR5_CSS_OVERRIDE_ID","injectContentCssHandler","handlerMap","logger","args","registerHandlers","retry","actionDispatcher","handler","fullName","retryCount","maxRetries","retryRegister","dispatcher","initPlugin","hasDispatcher"],"mappings":"+CAQO,MAAMA,MAAsB,ICG7BC,EAAoB,0DAEpBC,EAA8B,yDAE9BC,EAAmB,oBAEnBC,EAAwB,0BAExBC,EAAuB,sBAsDvBC,EAA4C,CAC9C,QAAS,CACL,OAAQ,SAAU,YAAa,IAC/B,OAAQ,cAAe,IACvB,OAAQ,MAAA,EAEZ,SAAU,CACN,UAAW,IACX,OAAQ,SAAU,YAAa,gBAAiB,IAChD,YAAa,IACb,OAAQ,aAAc,IACtB,eAAgB,eAAgB,SAAU,UAAW,IACrD,cAAe,cAAe,IAC9B,OAAQ,MAAA,EAEZ,KAAM,CACF,UAAW,IACX,WAAY,YAAa,sBAAuB,IAChD,OAAQ,SAAU,YAAa,gBAAiB,IAChD,YAAa,IACb,OAAQ,aAAc,cAAe,cAAe,aAAc,iBAAkB,IACpF,eAAgB,eAAgB,SAAU,UAAW,IACrD,YAAa,gBAAiB,IAC9B,OAAQ,MAAA,CAEhB,EAMA,SAASC,EAAyBC,EAA+B,CAC7D,GAAIA,IAAW,KAAM,OAAO,QAAQ,QAAA,EACpC,MAAMC,EAAK,0BAA0BD,CAAM,GAC3C,OAAI,SAAS,eAAeC,CAAE,EAAU,QAAQ,QAAA,EACzC,IAAI,QAASC,GAAY,CAC5B,MAAMC,EAAS,SAAS,cAAc,QAAQ,EAC9CA,EAAO,GAAKF,EACZE,EAAO,IAAM,GAAGT,CAA2B,IAAIM,CAAM,UACrDG,EAAO,OAAS,IAAMD,EAAA,EACtBC,EAAO,QAAU,IAAMD,EAAA,EACvB,SAAS,KAAK,YAAYC,CAAM,CACpC,CAAC,CACL,CAMA,SAASC,GAAwB,CAC7B,GAAI,SAAS,eAAeT,CAAgB,EACxC,OAEJ,MAAMU,EAAO,SAAS,cAAc,MAAM,EAC1CA,EAAK,GAAKV,EACVU,EAAK,IAAM,aACXA,EAAK,KAAOZ,EACZ,SAAS,KAAK,YAAYY,CAAI,CAClC,CAMA,SAASC,IAAmB,CACxB,GAAI,SAAS,eAAeT,CAAoB,EAC5C,OAEJ,MAAMU,EAAQ,SAAS,cAAc,OAAO,EAC5CA,EAAM,GAAKV,EACXU,EAAM,YAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAwJpB,SAAS,KAAK,YAAYA,CAAK,CACnC,CAKA,SAASC,IAAsB,CAC3B,OAAO,SAAS,gBAAgB,UAAU,SAAS,MAAM,CAC7D,CAMA,SAASC,GAA8B,CACnC,MAAMC,EAAW,SAAS,eAAed,CAAqB,EAE9D,GAAI,CAACY,KAAc,CAEXE,GACAA,EAAS,OAAA,EAEb,MACJ,CAEA,GAAIA,EACA,OAGJ,MAAMH,EAAQ,SAAS,cAAc,OAAO,EAC5CA,EAAM,GAAKX,EACXW,EAAM,YAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAwLpB,SAAS,KAAK,YAAYA,CAAK,CACnC,CAGA,IAAII,EAA4C,KAMhD,SAASC,IAAsB,CACvBD,IAIJA,EAAmB,IAAI,iBAAiB,IAAM,CAC1CF,EAAA,CACJ,CAAC,EAEDE,EAAiB,QAAQ,SAAS,gBAAiB,CAC/C,WAAY,GACZ,gBAAiB,CAAC,OAAO,CAAA,CAC5B,EACL,CAKO,SAASE,IAAmC,CAC3CF,IACAA,EAAiB,WAAA,EACjBA,EAAmB,KAE3B,CAGA,MAAMG,GAAwC,CAC1C,GAAI,MACJ,GAAI,UACJ,GAAI,MACJ,GAAI,KACJ,GAAI,WACJ,GAAI,UACJ,GAAI,SACR,EAMA,SAASC,GAAef,EAAwB,CAC5C,OAAOc,GAAcd,CAAM,GAAKA,EAAO,YAAA,CAC3C,CAMA,SAASgB,IAAgC,CACrC,MAAMC,EAAU,OAAe,OAC/B,OAAIA,GAAQ,QAAQ,UACTA,EAAO,OAAO,UAAA,EAIlB,CADe,aAAa,QAAQ,WAAW,GAAK,IACtC,CACzB,CAMA,SAASC,GAA2B,CAEhC,OADgB,OAAe,QAChB,QAAQ,UAAA,GAAe,aAAa,QAAQ,WAAW,GAAK,IAC/E,CAKA,SAASC,GAAWC,EAA0BC,EAAqBC,EAAiC,CAChG,MAAMC,EAAO,CACTH,EAAS,WACTA,EAAS,KACTA,EAAS,OACTA,EAAS,UACTA,EAAS,cACTA,EAAS,KACTA,EAAS,UACTA,EAAS,QACTA,EAAS,WACTA,EAAS,KACTA,EAAS,UACTA,EAAS,MACTA,EAAS,aACTA,EAAS,gBACTA,EAAS,oBACTA,EAAS,OACTA,EAAS,YACTA,EAAS,gBACTA,EAAS,mBAETA,EAAS,MACTA,EAAS,YACTA,EAAS,WACTA,EAAS,aACTA,EAAS,YAAA,EAGb,OAAIC,IAAgB,QAChBE,EAAK,KACDH,EAAS,WACTA,EAAS,eACTA,EAAS,UACTA,EAAS,cACTA,EAAS,SACTA,EAAS,UACTA,EAAS,mBAAA,EAIbE,GACAC,EAAK,KACDH,EAAS,YACTA,EAAS,mBAAA,EAIVG,CACX,CAMA,SAASC,GAAeC,EAAkC,CACtD,MAAMF,EAAO,wCACb,OAAIE,EACO,GAAGF,CAAI,eAAe,mBAAmBE,CAAgB,CAAC,GAE9DF,CACX,CAMA,SAASG,IAA2C,CAChD,MAAMC,EAAQ,aAAa,QAAQ,YAAY,EAC/C,OAAIA,EACO,CAAE,cAAe,UAAUA,CAAK,EAAA,EAEpC,CAAA,CACX,CAKA,eAAeC,EACXC,EACAC,EAUgB,CAChB,MAAMV,EAAY,OAAe,SACjC,GAAI,CAACA,EACD,MAAM,IAAI,MAAM,wEAAwE,EAG5F,MAAMW,EAAejC,EAAgBgC,EAAQ,OAAO,GAAKhC,EAAgB,SAGnEkC,EAAeF,EAAQ,YACvBC,EACAA,EAAa,OAAOE,GAAQA,IAAS,aAAa,EAElDC,EAAoC,CACtC,YAAaJ,EAAQ,eACrB,QAASX,GAAWC,EAAUU,EAAQ,QAASA,EAAQ,WAAW,EAClE,QAAS,CAAE,MAAOE,CAAA,EAClB,MAAO,CACH,eAAgB,CACZ,cAAe,WAAY,kBAC3B,IAAK,kBAAmB,qBAAA,EAE5B,gBAAiB,CACb,kBAAmB,CACf,YAAa,QACb,YAAa,UACb,YAAa,MACb,UAAW,MAAA,CACf,EAEJ,oBAAqB,CACjB,kBAAmB,CACf,YAAa,QACb,YAAa,UACb,YAAa,MACb,QAAS,KAAA,CACb,CACJ,EAEJ,MAAO,CACH,QAAS,CACL,oBACA,uBACA,yBACA,wBACA,IACA,qBACA,IACA,aAAA,EAEJ,cAAe,CACX,CAAE,KAAM,uBAAwB,MAAO,WAAY,MAAO,IAAA,EAC1D,CAAE,KAAM,iBAAkB,MAAO,MAAO,MAAO,IAAA,EAC/C,CAAE,KAAM,iBAAkB,MAAO,MAAO,MAAO,IAAA,EAC/C,CAAE,KAAM,iBAAkB,MAAO,MAAO,MAAO,IAAA,CAAK,EAExD,WAAY,GAAA,EAEhB,YAAa,CACT,OAAQ,GACR,KAAM,IAAA,EAEV,KAAM,CACF,gBAAiB,WACjB,WAAY,CACR,aAAc,CACV,KAAM,YACN,SAAWG,GAAgBA,EAAI,WAAW,SAAS,GAAKA,EAAI,WAAW,UAAU,EACjF,WAAY,CACR,OAAQ,SACR,IAAK,qBAAA,CACT,CACJ,CACJ,EAEJ,YAAa,CACT,MAAO,CACH,CAAE,KAAM,KAAM,WAAY,GAAM,QAAS,GAAM,OAAQ,EAAA,CAAK,CAChE,EAEJ,YAAaL,EAAQ,YACrB,SAAUZ,EAAA,CAAiB,EAG3BY,EAAQ,cACRI,EAAa,aAAe,CACxB,UAAWV,GAAeM,EAAQ,gBAAgB,EAClD,QAASJ,GAAA,CAAiB,GAIlC,MAAMU,EAAS,MAAMhB,EAAS,cAAc,OAAOS,EAASK,CAAY,EAIlEG,EAAgB,0BAA0BP,EAAQ,WAAW,GAC7DQ,EAAsB,SAAS,eAAeD,CAAa,EACjE,GAAIC,EACAA,EAAoB,YAAc,IAAIR,EAAQ,WAAW,uCAAuCA,EAAQ,MAAM,uBAC3G,CACH,MAAMS,EAAc,SAAS,cAAc,OAAO,EAClDA,EAAY,GAAKF,EACjBE,EAAY,YAAc,IAAIT,EAAQ,WAAW,uCAAuCA,EAAQ,MAAM,mBACtG,SAAS,KAAK,YAAYS,CAAW,CACzC,CAEA,OAAIT,EAAQ,UACRM,EAAO,mBAAmB,WAAW,EAGlCA,CACX,CAKA,SAASI,GACLC,EACAC,EACAC,EACAC,EACAC,EAC2F,CAC3F,MAAMC,EAAS,SAAS,cAAc,KAAK,EAC3CA,EAAO,UAAY,wBAEnB,MAAMC,MAAiB,IAMvBL,EAAQ,QAAQ1C,GAAU,CACtB,MAAMgD,EAAY,SAAS,cAAc,KAAK,EAC9CA,EAAU,QAAQ,OAAShD,EACvBA,IAAW2C,IACXK,EAAU,MAAM,QAAU,iBAE9B,MAAMC,EAAY,SAAS,cAAc,KAAK,EAC9CD,EAAU,YAAYC,CAAS,EAC/BF,EAAW,IAAI/C,EAAQiD,CAAS,CACpC,CAAC,EAMD,MAAMC,EAAmB,IAAM,CACtBL,GACLC,EAAO,iBAAiB,QAAQ,EAAE,QAAQK,GAAO,CAC7C,MAAMC,EAAaD,EAA0B,QAAQ,OACrD,GAAI,CAACC,GAAaD,EAAI,UAAU,SAAS,WAAW,EAAG,CAEnD,MAAMzC,EAAWyC,EAAI,cAAc,YAAY,EAC3CzC,GAAUA,EAAS,OAAA,EACvB,MACJ,CAEA,MAAM2C,EAAW,EADJR,EAAcO,CAAS,GACL,KAAA,EACzB1C,EAAWyC,EAAI,cAAc,YAAY,EAC/C,GAAIE,GAAY,CAAC3C,EAAU,CACvB,MAAM4C,EAAO,SAAS,cAAc,GAAG,EACvCA,EAAK,UAAY,yBACjBH,EAAI,YAAYG,CAAI,CACxB,KAAW,CAACD,GAAY3C,GACpBA,EAAS,OAAA,CAEjB,CAAC,CACL,EAGM6C,EAAgBb,EAAQ,CAAC,EAC/B,OAAAA,EAAQ,QAAQ1C,GAAU,CACtB,MAAMwD,EAAYxD,IAAWuD,EACvBE,EAAWzD,IAAW2C,EACtBe,EAAM,SAAS,cAAc,QAAQ,EAC3CA,EAAI,KAAO,SACXA,EAAI,QAAQ,OAAS1D,EACrB0D,EAAI,UAAY,CAACD,EAAW,YAAc,GAAID,EAAY,aAAe,EAAE,EAAE,OAAO,OAAO,EAAE,KAAK,GAAG,EACrGE,EAAI,UAAY,mDAAmD3C,GAAef,CAAM,CAAC,UAAUwD,EAAY,sCAAwC,EAAE,GACzJE,EAAI,iBAAiB,QAAS,SAAY,CAEtCZ,EAAO,iBAAiB,QAAQ,EAAE,QAAQK,GAAO,CAE7C,MAAMQ,EADaR,EAA0B,QAAQ,SACnBnD,EAClCmD,EAAI,UAAU,OAAO,YAAaQ,CAAW,CACjD,CAAC,EAIDZ,EAAW,QAAQ,CAACa,EAAIC,IAAa,CACjC,MAAMb,EAAYY,EAAG,cACjBZ,IACAA,EAAU,MAAM,QAAUa,IAAa7D,EAAS,QAAU,OAElE,CAAC,EAEG4C,GACA,MAAMA,EAAc5C,CAAM,EAG9BkD,EAAA,CACJ,CAAC,EACDJ,EAAO,YAAYY,CAAG,CAC1B,CAAC,EAEDjB,EAAU,YAAYK,CAAM,EAC5BC,EAAW,QAAQa,GAAM,CACjBA,EAAG,eACHnB,EAAU,YAAYmB,EAAG,aAAa,CAE9C,CAAC,EAEM,CAAE,OAAAd,EAAQ,WAAAC,EAAY,iBAAAG,CAAA,CACjC,CAKA,SAASY,EACLC,EACA/D,EACAgE,EACAC,EACI,CAIJ,MAAMhD,EAAU,OAAe,OAC/B,GAAI,CAACA,GAAQ,OAAO,SAChB,OAGJ,MAAMiD,EAA+B,CACjC,CAAC,QAAQH,CAAI,OAAO,EAAG,OACvB,WAAY,EAAA,EAGZE,EACAC,EAAQ,QAAQH,CAAI,IAAI/D,CAAM,EAAE,EAAIgE,EAEpCE,EAAQ,QAAQH,CAAI,EAAE,EAAIC,EAQ9B/C,EAAO,MAAM,SAASiD,EAAS,CAC3B,SAAU,IACV,YAAa,iBAAiBH,CAAI,GAClC,OAAQ,EAAA,CACX,CACL,CAYA,eAAsBI,GAClBC,EACAC,EACa,CAGb,MAAMC,EAA4BF,EAAO,QAA+B,CAAA,EAIlEG,EAAc,aADAD,EAAO,MAAmB,SACH,GAGrC5D,EAAWlB,EAAgB,IAAI+E,CAAW,EAChD,GAAI7D,GAAYA,EAAS,KAAO,EAAG,CAC/B,MAAM8D,EAAmC,CAAA,EACzC9D,EAAS,QAAS0B,GAAgB,CAC1BA,GAAU,OAAOA,EAAO,SAAY,YACpCoC,EAAgB,KAAKpC,EAAO,QAAA,EAAU,MAAM,IAAM,CAAC,CAAC,CAAC,CAE7D,CAAC,EACD,MAAM,QAAQ,WAAWoC,CAAe,EACxChF,EAAgB,OAAO+E,CAAW,CACtC,CAGA,MAAM9B,EAAY,SAAS,eAAe8B,CAAW,EACrD,GAAI,CAAC9B,EAAW,CACZ,QAAQ,KAAK,8CAA8C8B,CAAW,EAAE,EACxE,MACJ,CAGAnE,EAAA,EACAE,GAAA,EACAG,EAAA,EACAG,GAAA,EAGA,MAAMb,EAAyBmB,GAAkB,EAGjD,MAAMD,EAAU,OAAe,OACzBwD,EAAcxD,GAAQ,OAAO,IAAA,GAAS,CAAA,EAGtCyD,EAAiBD,EAAY,SAAS,UAAU,mBAAmB,GAClEA,EAAY,UAAU,mBAAmB,GACzC,CAAA,EAGDV,EAAOO,EAAO,MAAQ,UACtBL,EAAiBK,EAAO,eAAiB,IAAQA,EAAO,eAAiB,OACzEK,EAAaL,EAAO,WAAa,IAAQA,EAAO,WAAa,OAC7DhD,EAAkBgD,EAAO,cAAgB,OACxCA,EAAO,cAAgB,IAAQA,EAAO,cAAgB,OACtDI,EAAe,cAAgB,IAAQA,EAAe,cAAgB,OACvEjD,EAAmB6C,EAAO,kBAAoB,GAC9CM,EAAcN,EAAO,aAAe,GACpCO,GAASP,EAAO,SAAW,OAAa,OAAOA,EAAO,MAAM,GAAK,IAAQ,OAAOI,EAAe,YAAY,GAAK,IAChHrD,IAAeiD,EAAO,UAAY,OAAaA,EAAO,QAAsBI,EAAe,UAAuB,WAKxH,IAAII,EAAqC,CAAA,EACzC,GAAIb,EAAgB,CAChB,GAAI,CACI,OAAOK,EAAO,SAAY,UAAYA,EAAO,QAAQ,WAAW,GAAG,GAAK,CAACA,EAAO,QAAQ,WAAW,IAAI,EACvGQ,EAAa,KAAK,MAAMR,EAAO,OAAO,EAC/B,OAAOA,EAAO,SAAY,UAAYA,EAAO,UAAY,OAChEQ,EAAaR,EAAO,QAE5B,MAAQ,CACJQ,EAAa,CAAA,CACjB,CAEA,GAAI,OAAO,KAAKA,CAAU,EAAE,SAAW,GAAKf,EAAM,CAE9C,MAAMgB,GADa9D,GAAQ,OAAO,WAAA,GAAgB,CAAA,IACpB,OAAO8C,CAAI,EAUzC,GARIgB,GAAa,OAAOA,GAAc,UAAY,CAAC,MAAM,QAAQA,CAAS,EACtED,EAAaC,EACN,OAAOA,GAAc,UAAYA,IAGxCD,EAAa,CAAE,CADO5D,EAAA,CACO,EAAG6D,CAAA,GAGhC,OAAO,KAAKD,CAAU,EAAE,SAAW,EAAG,CACtC,MAAML,EAAcxD,GAAQ,OAAO,MAAA,GAAW,CAAA,EAExC+D,GADeP,GAAa,SAAS,cAAgBA,GAAa,gBACnCV,CAAI,EACrCiB,GAAiB,OAAOA,GAAkB,UAAY,CAAC,MAAM,QAAQA,CAAa,IAClFF,EAAaE,EAErB,CACJ,CACJ,CAEA,MAAMC,MAAkB,IACxBzF,EAAgB,IAAI+E,EAAaU,CAAW,EAE5C,MAAMC,EAAgB,CAClB,YAAAN,EACA,SAAUD,EACV,YAAarD,EACb,iBAAAG,EACA,OAAAoD,GACA,QAASxD,GACT,YAAAkD,CAAA,EAGJ,GAAIN,EAAgB,CAChB,MAAMvB,EAAU1B,GAAA,EACV2B,EAAezB,EAAA,EAGfiE,EAAgB,CAAE,QAAS,IAAI,GAAyB,EACxDC,EAAsB,CAAE,QAAS,IAAM,CAAC,CAAA,EAGxCC,EAAqB,MAAOrF,GAAmB,CACjD,GAAIiF,EAAY,IAAIjF,CAAM,EAAG,OAC7B,MAAMiD,EAAYkC,EAAc,QAAQ,IAAInF,CAAM,EAClD,GAAI,CAACiD,EAAW,OAEhB,MAAMqC,GAAiBR,EAAW9E,CAAM,GAAK,GAE7C,GAAI,CACA,MAAMoC,EAAS,MAAMR,EAAqBqB,EAAW,CACjD,GAAGiC,EACH,eAAAI,EAAA,CACH,EAEDL,EAAY,IAAIjF,EAAQoC,CAAM,EAG9B,IAAImD,EAAiB,GAcrB,GAZCnD,EAAe,MAAM,SAAS,GAAG,cAAe,IAAM,CACnD,GAAImD,EAAgB,OACpB,MAAMC,EAAQpD,EAAe,QAAA,EAC7B0B,EAAWC,EAAM/D,EAAQwF,EAAM,EAAI,EACnCJ,EAAoB,QAAA,CACxB,CAAC,EAEDG,EAAiB,GAKbxB,EAAM,CACN,MAAM9C,EAAU,OAAe,QACjBA,GAAQ,OAAO,WAAA,GAAgB,CAAA,GACnC,OAAO,GAAG8C,CAAI,OAAO,IAAM,QACjC9C,EAAO,MAAM,SAAS,CAAE,CAAC,QAAQ8C,CAAI,OAAO,EAAG,OAAQ,CAE/D,CACJ,OAAS0B,EAAK,CACV,QAAQ,MAAM,2CAA2CzF,CAAM,KAAMyF,CAAG,CAC5E,CACJ,EAGM5C,EAAiB7C,GAAkC,CACrD,MAAMoC,EAAS6C,EAAY,IAAIjF,CAAM,EACrC,OAAKoC,EACGA,EAAe,aAAe,KADlB,IAExB,EAGM,CAAE,WAAAW,EAAY,iBAAAG,CAAA,EAAqBV,GAAuBC,EAAWC,EAASC,EAAc0C,EAAoBxC,CAAa,EACnIsC,EAAc,QAAUpC,EACxBqC,EAAoB,QAAUlC,EAG9B,MAAMmC,EAAmB1C,CAAY,EAIrC,WAAW,IAAM,CACbD,EAAQ,OAAOgD,GAAKA,IAAM/C,CAAY,EAAE,QAAQ3C,GAAU,CACtDqF,EAAmBrF,CAAM,CAC7B,CAAC,CACL,EAAG,GAAI,CAEX,KAAO,CAKH,MAAM2F,EAAa,OAAOrB,EAAO,SAAY,SAAWA,EAAO,QAAU,GAEzE,IAAIgB,EAD2BK,EAAW,WAAW,IAAI,GAAKA,EAAW,SAAS,IAAI,EACxC,GAAKA,EACnD,GAAI,CAACL,GAAkBvB,EAAM,CAEzB,MAAMgB,GADa9D,GAAQ,OAAO,WAAA,GAAgB,CAAA,IACpB,OAAO8C,CAAI,EACrC,OAAOgB,GAAc,UAAYA,IACjCO,EAAiBP,EAEzB,CACA,MAAMa,EAAW,SAAS,cAAc,KAAK,EAC7CnD,EAAU,YAAYmD,CAAQ,EAE9B,GAAI,CACA,MAAMxD,EAAS,MAAMR,EAAqBgE,EAAU,CAChD,GAAGV,EACH,eAAAI,CAAA,CACH,EAEKO,EAAe3E,EAAA,EACrB+D,EAAY,IAAIY,EAAczD,CAAM,EAGpC,IAAImD,EAAiB,GAYrB,GATCnD,EAAe,MAAM,SAAS,GAAG,cAAe,IAAM,CACnD,GAAImD,EAAgB,OACpB,MAAMC,EAAQpD,EAAe,QAAA,EAC7B0B,EAAWC,EAAM8B,EAAcL,EAAM,EAAK,CAC9C,CAAC,EAEDD,EAAiB,GAGbD,EAAgB,CAChB,MAAMQ,EAAe1D,EAAe,QAAA,GAChC,CAAC0D,GAAeA,EAAY,KAAA,IAAW,KACtC1D,EAAe,QAAQkD,CAAc,CAG9C,CAGA,GAAIvB,EAAM,CACN,MAAM9C,EAAU,OAAe,QACjBA,GAAQ,OAAO,WAAA,GAAgB,CAAA,GACnC,OAAO,GAAG8C,CAAI,OAAO,IAAM,QACjC9C,EAAO,MAAM,SAAS,CAAE,CAAC,QAAQ8C,CAAI,OAAO,EAAG,OAAQ,CAE/D,CAIJ,OAAS0B,EAAK,CACV,QAAQ,MAAM,kCAAmCA,CAAG,EACpDjG,EAAgB,OAAO+E,CAAW,CACtC,CACJ,CACJ,CC3pCA,eAAsBwB,GAClB3B,EACAC,EACa,CAIb,MAAME,EAAc,aADAH,EAAO,QAAQ,MAAmB,SACX,GACrC4B,EAAYxG,EAAgB,IAAI+E,CAAW,EAEjD,GAAI,CAACyB,GAAaA,EAAU,OAAS,EACjC,OAGJ,MAAMxB,EAAmC,CAAA,EAEzCwB,EAAU,QAAS5D,GAAW,CACtBA,GAAU,OAAOA,EAAO,SAAY,YACpCoC,EAAgB,KACZpC,EAAO,QAAA,EAAU,MAAOqD,GAAiB,CACrC,QAAQ,KAAK,2CAA4CA,CAAG,CAChE,CAAC,CAAA,CAGb,CAAC,EAED,MAAM,QAAQ,WAAWjB,CAAe,EAExChF,EAAgB,OAAO+E,CAAW,EAGlC,MAAMhC,EAAc,SAAS,eAAe,0BAA0BgC,CAAW,EAAE,EAC/EhC,GACAA,EAAY,OAAA,EAIZ/C,EAAgB,OAAS,GACzBqB,GAAA,CAER,CCjDA,MAAMoF,EAAoB,oBAEpBtG,EAAmB,2BACnBuG,EAA4B,oCAC5BzG,GAAoB,0DAS1B,SAAS0G,IAAgC,CACrC,GAAI,CAAC,SAAS,eAAexG,CAAgB,EAAG,CAC5C,MAAMU,EAAO,SAAS,cAAc,MAAM,EAC1CA,EAAK,GAAKV,EACVU,EAAK,IAAM,aACXA,EAAK,KAAOZ,GACZ,SAAS,KAAK,YAAYY,CAAI,CAClC,CAEA,GAAI,CAAC,SAAS,eAAe6F,CAAyB,EAAG,CACrD,MAAM3F,EAAQ,SAAS,cAAc,OAAO,EAC5CA,EAAM,GAAK2F,EAEX3F,EAAM,YAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAsCpB,SAAS,KAAK,YAAYA,CAAK,CACnC,CAEJ,CAEA,MAAM6F,EAAuC,CACzC,WAAYjC,GACZ,cAAe4B,GACf,iBAAkBI,EACtB,EAEME,EAAW,OAAe,QAAQ,eAAe,UAAUJ,CAAiB,EAAE,GAAM,CACtF,IAAK,IAAIK,IAAoB,QAAQ,IAAI,WAAWL,CAAiB,IAAK,GAAGK,CAAI,EACjF,KAAM,IAAIA,IAAoB,QAAQ,KAAK,WAAWL,CAAiB,IAAK,GAAGK,CAAI,EACnF,MAAO,IAAIA,IAAoB,QAAQ,MAAM,WAAWL,CAAiB,IAAK,GAAGK,CAAI,CACzF,EAEA,SAASC,EAAiBC,EAAiB,GAAa,CACpD,MAAMC,EAAoB,OAAe,QAAQ,sBAAA,EAEjD,GAAIA,EACA,OAAO,QAAQL,CAAU,EAAE,QAAQ,CAAC,CAACrC,EAAM2C,CAAO,IAAM,CACpD,MAAMC,EAAW,GAAGV,CAAiB,IAAIlC,CAAI,GAC7C0C,EAAiB,gBAAgBE,EAAUD,EAAS,CAChD,SAAU,SACV,OAAQT,CAAA,CACX,CACL,CAAC,EAEDI,EAAO,IACH,GAAG,OAAO,KAAKD,CAAU,EAAE,MAAM,0BACjC,OAAO,KAAKA,CAAU,EAAE,OAAY,GAAGH,CAAiB,IAAIlC,CAAI,EAAE,CAAA,UAE/DyC,EAAO,CACd,IAAII,EAAa,EACjB,MAAMC,EAAa,GAEbC,EAAgB,IAAM,CACxB,MAAMC,EAAc,OAAe,QAAQ,sBAAA,EAEvCA,GACA,OAAO,QAAQX,CAAU,EAAE,QAAQ,CAAC,CAACrC,EAAM2C,CAAO,IAAM,CACpD,MAAMC,EAAW,GAAGV,CAAiB,IAAIlC,CAAI,GAC7CgD,EAAW,gBAAgBJ,EAAUD,EAAS,CAC1C,SAAU,SACV,OAAQT,CAAA,CACX,CACL,CAAC,EAEDI,EAAO,IACH,GAAG,OAAO,KAAKD,CAAU,EAAE,MAAM,0BACjC,OAAO,KAAKA,CAAU,EAAE,OAAY,GAAGH,CAAiB,IAAIlC,CAAI,EAAE,CAAA,IAGtE6C,IACIA,GAAcC,GACdR,EAAO,KAAK,4CAA4CO,CAAU,IAAIC,CAAU,GAAG,EACnF,WAAWC,EAAe,GAAG,GAE7BT,EAAO,MAAM,mFAAmF,EAG5G,EAEAS,EAAA,CACJ,MACIT,EAAO,KAAK,qDAAqD,CAEzE,CAEO,SAASW,GAAmB,CAC/B,GAAI,SAAS,aAAe,UACxB,SAAS,iBAAiB,mBAAoB,IAAMT,EAAiB,EAAI,CAAC,MACvE,CACH,MAAMU,EAAgB,CAAC,CAAE,OAAe,QAAQ,sBAAA,EAChDV,EAAiB,CAAAU,CAA4B,CACjD,CACJ,CAEA,OAAAD,EAAA,EAEI,OAAO,OAAW,MACjB,OAAe,mBAAqB,CACjC,WAAYf,EACZ,SAAU,OAAO,KAAKG,CAAU,EAChC,WAAAY,CAAA"} \ No newline at end of file +{"version":3,"file":"plugin.iife.js","sources":["../../resources/js/handlers/editorInstances.ts","../../resources/js/handlers/initEditor.ts","../../resources/js/handlers/destroyEditor.ts","../../resources/js/index.ts"],"sourcesContent":["/**\n * CKEditor5 인스턴스 공유 저장소\n *\n * containerId → locale별 에디터 인스턴스 맵을 관리합니다.\n * initEditor / destroyEditor 핸들러가 공유합니다.\n */\n\n// containerId → Map\nexport const editorInstances = new Map>();\n\n// setData() 중 change:data → syncToForm 재진입 방지 플래그\nlet _syncSuppressed = false;\nexport function isSyncSuppressed(): boolean {\n return _syncSuppressed;\n}\nexport function setSyncSuppressed(value: boolean): void {\n _syncSuppressed = value;\n}\n","/**\n * CKEditor5 초기화 핸들러\n *\n * 컴포넌트 마운트 시 CKEditor5 인스턴스를 생성합니다.\n * 다국어(multilingual) 모드: locale별 탭 + 인스턴스 생성\n * 단일 모드: 단일 인스턴스 생성\n */\n\nimport { editorInstances, isSyncSuppressed } from './editorInstances';\n\n/** CKEditor5 CDN CSS URL */\nconst CKEDITOR5_CSS_URL = 'https://cdn.ckeditor.com/ckeditor5/43.3.1/ckeditor5.css';\n/** CKEditor5 CDN 번역 파일 base URL */\nconst CKEDITOR5_TRANSLATIONS_BASE = 'https://cdn.ckeditor.com/ckeditor5/43.3.1/translations';\n/** CKEditor5 CSS 로드 상태 추적용 엘리먼트 ID */\nconst CKEDITOR5_CSS_ID = 'ckeditor5-cdn-css';\n/** CKEditor5 다크 모드 CSS 엘리먼트 ID */\nconst CKEDITOR5_DARK_CSS_ID = 'ckeditor5-dark-override';\n/** CKEditor5 다국어 탭 기본 CSS 엘리먼트 ID */\nconst CKEDITOR5_TAB_CSS_ID = 'ckeditor5-tab-style';\n\n/** CKEditor 전역 객체 타입 (CDN UMD 빌드 — window.CKEDITOR) */\ninterface CKEditorGlobal {\n ClassicEditor: any;\n Essentials: any;\n Bold: any;\n Italic: any;\n Underline: any;\n Strikethrough: any;\n Link: any;\n Paragraph: any;\n Heading: any;\n BlockQuote: any;\n List: any;\n Alignment: any;\n Table: any;\n TableToolbar: any;\n TableProperties: any;\n TableCellProperties: any;\n Image: any;\n ImageUpload: any;\n ImageResize: any;\n ImageStyle: any;\n ImageCaption: any;\n ImageToolbar: any;\n SimpleUploadAdapter: any;\n MediaEmbed: any;\n HorizontalLine: any;\n Indent: any;\n IndentBlock: any;\n CodeBlock: any;\n SourceEditing: any;\n FontSize: any;\n FontColor: any;\n FontBackgroundColor: any;\n PasteFromOffice: any;\n GeneralHtmlSupport: any;\n}\n\n/** initEditor 파라미터 타입 */\ninterface InitEditorParams {\n name?: string;\n content?: string;\n multilingual?: boolean | string;\n placeholder?: string;\n readOnly?: boolean | string;\n imageUpload?: boolean | string;\n uploadPermission?: string;\n height?: number | string;\n toolbar?: string;\n}\n\n/** 툴바 프리셋 */\nconst TOOLBAR_PRESETS: Record = {\n minimal: [\n 'bold', 'italic', 'underline', '|',\n 'link', 'uploadImage', '|',\n 'undo', 'redo',\n ],\n standard: [\n 'heading', '|',\n 'bold', 'italic', 'underline', 'strikethrough', '|',\n 'alignment', '|',\n 'link', 'blockQuote', '|',\n 'bulletedList', 'numberedList', 'indent', 'outdent', '|',\n 'insertTable', 'uploadImage', '|',\n 'undo', 'redo',\n ],\n full: [\n 'heading', '|',\n 'fontSize', 'fontColor', 'fontBackgroundColor', '|',\n 'bold', 'italic', 'underline', 'strikethrough', '|',\n 'alignment', '|',\n 'link', 'blockQuote', 'insertTable', 'uploadImage', 'mediaEmbed', 'horizontalLine', '|',\n 'bulletedList', 'numberedList', 'indent', 'outdent', '|',\n 'codeBlock', 'sourceEditing', '|',\n 'undo', 'redo',\n ],\n};\n\n/**\n * CKEditor5 번역 스크립트를 동적으로 로드합니다.\n * 영어(en)는 기본 내장이므로 로드하지 않습니다.\n */\nfunction loadCkeditorTranslations(locale: string): Promise {\n if (locale === 'en') return Promise.resolve();\n const id = `ckeditor5-translations-${locale}`;\n if (document.getElementById(id)) return Promise.resolve();\n return new Promise((resolve) => {\n const script = document.createElement('script');\n script.id = id;\n script.src = `${CKEDITOR5_TRANSLATIONS_BASE}/${locale}.umd.js`;\n script.onload = () => resolve();\n script.onerror = () => resolve(); // 번역 실패해도 에디터는 영어로 동작\n document.head.appendChild(script);\n });\n}\n\n/**\n * CKEditor5 CSS를 동적으로 로드합니다.\n * 이미 로드된 경우 중복 삽입하지 않습니다.\n */\nfunction loadCkeditorCss(): void {\n if (document.getElementById(CKEDITOR5_CSS_ID)) {\n return;\n }\n const link = document.createElement('link');\n link.id = CKEDITOR5_CSS_ID;\n link.rel = 'stylesheet';\n link.href = CKEDITOR5_CSS_URL;\n document.head.appendChild(link);\n}\n\n/**\n * 다국어 탭 버튼 기본 스타일(라이트/다크 공통 베이스)을 주입합니다.\n * 이미 주입된 경우 중복 삽입하지 않습니다.\n */\nfunction loadTabCss(): void {\n if (document.getElementById(CKEDITOR5_TAB_CSS_ID)) {\n return;\n }\n const style = document.createElement('style');\n style.id = CKEDITOR5_TAB_CSS_ID;\n style.textContent = `\n /* 다국어 탭 컨테이너 */\n .ckeditor5-locale-tabs {\n display: flex;\n gap: 8px;\n margin-bottom: 12px;\n align-items: center;\n }\n /* 다국어 탭 버튼 - HtmlEditor 언어탭 스타일 */\n .ckeditor5-locale-tabs button {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n padding: 6px 12px;\n border: none;\n border-radius: 9999px;\n cursor: pointer;\n font-size: 0.75rem;\n font-weight: 600;\n line-height: 1;\n transition: background 0.15s, color 0.15s, transform 0.15s, box-shadow 0.15s;\n }\n /* 비활성 - 기본언어 (blue) */\n .ckeditor5-locale-tabs button.is-default {\n background: #eff6ff;\n color: #2563eb;\n }\n .ckeditor5-locale-tabs button.is-default:hover {\n background: #dbeafe;\n }\n /* 비활성 - 비기본언어 (gray) */\n .ckeditor5-locale-tabs button:not(.is-default) {\n background: #f3f4f6;\n color: #4b5563;\n }\n .ckeditor5-locale-tabs button:not(.is-default):hover {\n background: #e5e7eb;\n }\n /* 활성 - 기본언어 */\n .ckeditor5-locale-tabs button.is-active.is-default {\n background: #3b82f6;\n color: #ffffff;\n box-shadow: 0 2px 6px rgba(0,0,0,0.15);\n transform: scale(1.05);\n }\n /* 활성 - 비기본언어 */\n .ckeditor5-locale-tabs button.is-active:not(.is-default) {\n background: #6b7280;\n color: #ffffff;\n box-shadow: 0 2px 6px rgba(0,0,0,0.15);\n transform: scale(1.05);\n }\n .ckeditor5-locale-tabs button .ck5-lang-icon {\n font-size: 0.75rem;\n line-height: 1;\n }\n .ckeditor5-locale-tabs button .ck5-required {\n color: #ef4444;\n }\n .ckeditor5-locale-tabs button.is-active .ck5-required {\n color: #fca5a5;\n }\n .ckeditor5-locale-tabs button .ck5-check {\n color: #22c55e;\n }\n /* 다크 모드 - 비활성 기본언어 */\n html.dark .ckeditor5-locale-tabs button.is-default {\n background: rgba(59, 130, 246, 0.15);\n color: #93c5fd;\n }\n html.dark .ckeditor5-locale-tabs button.is-default:hover {\n background: rgba(59, 130, 246, 0.25);\n }\n /* 다크 모드 - 비활성 비기본언어 */\n html.dark .ckeditor5-locale-tabs button:not(.is-default) {\n background: #374151;\n color: #d1d5db;\n }\n html.dark .ckeditor5-locale-tabs button:not(.is-default):hover {\n background: #4b5563;\n }\n /* 다크 모드 - 활성 기본언어 */\n html.dark .ckeditor5-locale-tabs button.is-active.is-default {\n background: #2563eb;\n color: #ffffff;\n }\n /* 다크 모드 - 활성 비기본언어 */\n html.dark .ckeditor5-locale-tabs button.is-active:not(.is-default) {\n background: #4b5563;\n color: #ffffff;\n }\n html.dark .ckeditor5-locale-tabs button .ck5-check {\n color: #4ade80;\n }\n /* 표 너비 인라인 스타일 무력화 - 컨테이너에 맞게 100% */\n .ck-content figure.table { width: 100%; }\n .ck-content figure.table table { width: 100%; }\n /* 표 tr 배경색 초기화 */\n .ck-content table tr { background-color: unset; }\n /* 표 col 절대 px 너비 무력화 - 컨테이너에 맞게 비율로 */\n .ck-content table col { width: auto !important; }\n /* 표 정렬 보정: CKEditor5 기본 CSS의 margin-left:auto를 float으로 덮어씀 */\n .ck-content figure.table[style*=\"float:left\"],\n .ck-content figure.table[style*=\"float: left\"] {\n margin-left: 0 !important;\n margin-right: 1em !important;\n }\n .ck-content figure.table[style*=\"float:right\"],\n .ck-content figure.table[style*=\"float: right\"] {\n margin-left: 1em !important;\n margin-right: 0 !important;\n }\n /* 이미지 캡션 - 라이트 모드 */\n .ck-content .image > figcaption {\n background-color: #f3f4f6;\n color: #374151;\n font-size: 0.875em;\n padding: 4px 8px;\n text-align: center;\n }\n /* 에디터 편집 영역 - 목록 마커 복원 (Tailwind preflight reset 대응) */\n .ck.ck-editor__editable ul,\n .ck-content ul {\n list-style-type: disc;\n padding-left: 2em;\n }\n .ck.ck-editor__editable ol,\n .ck-content ol {\n list-style-type: decimal;\n padding-left: 2em;\n }\n .ck.ck-editor__editable ul ul,\n .ck-content ul ul {\n list-style-type: circle;\n padding-left: 2em;\n }\n .ck.ck-editor__editable ul ul ul,\n .ck-content ul ul ul {\n list-style-type: square;\n padding-left: 2em;\n }\n .ck.ck-editor__editable ol ol,\n .ck-content ol ol {\n list-style-type: lower-alpha;\n padding-left: 2em;\n }\n .ck.ck-editor__editable ol ol ol,\n .ck-content ol ol ol {\n list-style-type: lower-roman;\n padding-left: 2em;\n }\n `;\n document.head.appendChild(style);\n}\n\n/**\n * 현재 다크 모드 여부를 반환합니다.\n */\nfunction isDarkMode(): boolean {\n return document.documentElement.classList.contains('dark');\n}\n\n/**\n * CKEditor5 다크 모드 CSS 변수를 동적으로 주입하거나 제거합니다.\n * document.documentElement의 'dark' 클래스를 기준으로 판단합니다.\n */\nfunction applyDarkModeOverride(): void {\n const existing = document.getElementById(CKEDITOR5_DARK_CSS_ID);\n\n if (!isDarkMode()) {\n // 라이트 모드: 다크 오버라이드 제거\n if (existing) {\n existing.remove();\n }\n return;\n }\n\n if (existing) {\n return;\n }\n\n const style = document.createElement('style');\n style.id = CKEDITOR5_DARK_CSS_ID;\n style.textContent = `\n /* CKEditor5 다크 모드 오버라이드 - CSS 변수 전역 적용 */\n :root {\n --ck-color-base-foreground: #1f2937;\n --ck-color-base-background: #1f2937;\n --ck-color-base-border: #374151;\n --ck-color-text: #f3f4f6;\n --ck-color-toolbar-background: #111827;\n --ck-color-toolbar-border: #374151;\n --ck-color-button-default-background: transparent;\n --ck-color-button-default-hover-background: #374151;\n --ck-color-button-default-active-background: #4b5563;\n --ck-color-button-on-background: #374151;\n --ck-color-button-on-hover-background: #4b5563;\n --ck-color-focus-border: #3b82f6;\n --ck-color-input-background: #1f2937;\n --ck-color-input-text: #f3f4f6;\n --ck-color-input-border: #374151;\n --ck-color-panel-background: #1f2937;\n --ck-color-panel-border: #374151;\n --ck-color-list-button-hover-background: #374151;\n --ck-color-list-button-on-background: #3b82f6;\n --ck-color-list-button-on-color: #f3f4f6;\n --ck-color-list-button-on-hover-background: #4b5563;\n --ck-color-labeled-field-label-background: #1f2937;\n --ck-color-link-default: #60a5fa;\n --ck-color-link-selected-background: rgba(96, 165, 250, 0.1);\n --ck-color-table-focused-cell-background: rgba(59, 130, 246, 0.1);\n }\n /* 에디터 본문 */\n .ck.ck-editor__editable_inline {\n background-color: #1f2937 !important;\n color: #f3f4f6 !important;\n border-color: #374151 !important;\n }\n /* 메인 툴바 */\n .ck.ck-toolbar {\n background-color: #111827 !important;\n border-color: #374151 !important;\n }\n /* 모든 버튼 텍스트 */\n .ck.ck-button,\n .ck.ck-button .ck-button__label {\n color: #f3f4f6 !important;\n }\n /* 모든 SVG 아이콘 (툴바, 드롭다운 화살표 포함) */\n .ck.ck-icon,\n .ck .ck-icon,\n .ck.ck-button .ck-icon,\n .ck.ck-dropdown__arrow {\n color: #f3f4f6 !important;\n }\n .ck.ck-button:hover,\n .ck.ck-button.ck-on {\n background-color: #374151 !important;\n }\n /* 툴팁 (호버 시 버튼 설명) */\n .ck.ck-tooltip .ck-tooltip__text {\n background-color: #1f2937 !important;\n color: #f3f4f6 !important;\n }\n /* 드롭다운 패널 / 리스트 / balloon 팝업 공통 */\n .ck.ck-dropdown__panel,\n .ck.ck-list,\n .ck.ck-balloon-panel {\n background-color: #1f2937 !important;\n border-color: #374151 !important;\n }\n /* 리스트 아이템 */\n .ck.ck-list__item .ck-button,\n .ck.ck-list__item .ck-button .ck-button__label {\n color: #f3f4f6 !important;\n }\n .ck.ck-list__item .ck-button:hover {\n background-color: #374151 !important;\n }\n .ck.ck-list__item .ck-button.ck-disabled .ck-button__label {\n color: #6b7280 !important;\n }\n /* 링크 팝업 / form */\n .ck.ck-link-form,\n .ck.ck-link-actions {\n background-color: #1f2937 !important;\n border-color: #374151 !important;\n }\n .ck.ck-input-text {\n background-color: #111827 !important;\n color: #f3f4f6 !important;\n border-color: #374151 !important;\n }\n .ck.ck-labeled-field-view__label {\n background-color: #1f2937 !important;\n color: #9ca3af !important;\n }\n /* 테이블 속성/셀 속성 폼 */\n .ck.ck-table-form,\n .ck.ck-table-cell-properties-form,\n .ck.ck-table-properties-form {\n background-color: #1f2937 !important;\n border-color: #374151 !important;\n }\n .ck.ck-table-form .ck-label,\n .ck.ck-table-cell-properties-form .ck-label,\n .ck.ck-table-properties-form .ck-label {\n color: #d1d5db !important;\n }\n /* 색상 선택 패널 */\n .ck.ck-color-table,\n .ck.ck-color-grid {\n background-color: #1f2937 !important;\n }\n .ck.ck-color-table .ck-color-table__remove-color,\n .ck.ck-color-table .ck-color-table__remove-color .ck-button__label {\n color: #f3f4f6 !important;\n }\n /* 헤딩/폰트 드롭다운 라벨 */\n .ck.ck-heading_paragraph,\n .ck.ck-heading_heading1,\n .ck.ck-heading_heading2,\n .ck.ck-heading_heading3 {\n color: #f3f4f6 !important;\n }\n /* 이미지 캡션 */\n .ck-content .image > figcaption {\n background-color: #374151 !important;\n color: #d1d5db !important;\n }\n /* 이미지 리사이즈 핸들 */\n .ck-content .image.ck-widget_selected .ck-widget__resizer__handle {\n background-color: #3b82f6 !important;\n border-color: #1d4ed8 !important;\n }\n /* 이미지 정렬 툴바 아이콘 */\n .ck.ck-toolbar .ck-button .ck-icon {\n color: #f3f4f6 !important;\n }\n /* 이미지 선택 시 balloon toolbar (floating) */\n .ck.ck-toolbar_floating {\n background-color: #111827 !important;\n border-color: #374151 !important;\n }\n /* 이미지 리사이즈 드롭다운 버튼 라벨 (25%, 50% 등) */\n .ck.ck-dropdown .ck-button__label {\n color: #f3f4f6 !important;\n }\n /* 이미지 리사이즈 드롭다운 내 선택 리스트 */\n .ck.ck-resize-image-form,\n .ck.ck-image-resize-form {\n background-color: #1f2937 !important;\n border-color: #374151 !important;\n color: #f3f4f6 !important;\n }\n .ck.ck-resize-image-form .ck-label,\n .ck.ck-image-resize-form .ck-label {\n color: #d1d5db !important;\n }\n .ck.ck-resize-image-form .ck-input-text,\n .ck.ck-image-resize-form .ck-input-text {\n background-color: #111827 !important;\n color: #f3f4f6 !important;\n border-color: #374151 !important;\n }\n /* 표 안 에디터 내용 (다크 배경) */\n .ck-content table tr {\n background-color: unset;\n }\n .ck-content table td,\n .ck-content table th {\n border-color: #4b5563;\n color: #f3f4f6 !important;\n }\n /* 표 col 절대 px 너비 무력화 */\n .ck-content table col {\n width: auto !important;\n }\n /* 목록 마커 색상 - 다크모드 */\n .ck.ck-editor__editable ul,\n .ck.ck-editor__editable ol {\n color: #f3f4f6;\n }\n .ck.ck-editor__editable li::marker {\n color: #d1d5db;\n }\n `;\n document.head.appendChild(style);\n}\n\n/** 다크 모드 MutationObserver 인스턴스 (cleanup용) */\nlet darkModeObserver: MutationObserver | null = null;\n\n/**\n * 클래스 변경을 감지하여 다크 모드 전환 시 즉시 반영합니다.\n * 최초 1회만 등록합니다.\n */\nfunction watchDarkMode(): void {\n if (darkModeObserver) {\n return;\n }\n\n darkModeObserver = new MutationObserver(() => {\n applyDarkModeOverride();\n });\n\n darkModeObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ['class'],\n });\n}\n\n/**\n * 다크 모드 MutationObserver를 해제합니다.\n */\nexport function disconnectDarkModeObserver(): void {\n if (darkModeObserver) {\n darkModeObserver.disconnect();\n darkModeObserver = null;\n }\n}\n\n/** locale 코드 → 표시 이름 매핑 */\nconst LOCALE_LABELS: Record = {\n ko: '한국어',\n en: 'English',\n ja: '日本語',\n zh: '中文',\n fr: 'Français',\n de: 'Deutsch',\n es: 'Español',\n};\n\n/**\n * locale 코드를 표시 이름으로 변환합니다.\n * 매핑에 없는 경우 대문자 코드를 반환합니다.\n */\nfunction getLocaleLabel(locale: string): string {\n return LOCALE_LABELS[locale] ?? locale.toUpperCase();\n}\n\n/**\n * 지원 locale 목록을 반환합니다.\n * localStorage의 g7_locale 값과 서버 설정을 활용합니다.\n */\nfunction getSupportedLocales(): string[] {\n const G7Core = (window as any).G7Core;\n if (G7Core?.locale?.supported) {\n return G7Core.locale.supported();\n }\n // 폴백: 현재 locale만 사용\n const currentLocale = localStorage.getItem('g7_locale') || 'ko';\n return [currentLocale];\n}\n\n/**\n * 현재 locale을 반환합니다.\n * G7Core.locale.current() 우선, 폴백으로 localStorage 사용.\n */\nfunction getCurrentLocale(): string {\n const G7Core = (window as any).G7Core;\n return G7Core?.locale?.current?.() ?? localStorage.getItem('g7_locale') ?? 'ko';\n}\n\n/**\n * CKEditor 플러그인 목록을 toolbar 타입에 따라 반환합니다.\n */\nfunction getPlugins(CKEDITOR: CKEditorGlobal, toolbarType: string, withImageUpload: boolean): any[] {\n const base = [\n CKEDITOR.Essentials,\n CKEDITOR.Bold,\n CKEDITOR.Italic,\n CKEDITOR.Underline,\n CKEDITOR.Strikethrough,\n CKEDITOR.Link,\n CKEDITOR.Paragraph,\n CKEDITOR.Heading,\n CKEDITOR.BlockQuote,\n CKEDITOR.List,\n CKEDITOR.Alignment,\n CKEDITOR.Table,\n CKEDITOR.TableToolbar,\n CKEDITOR.TableProperties,\n CKEDITOR.TableCellProperties,\n CKEDITOR.Indent,\n CKEDITOR.IndentBlock,\n CKEDITOR.PasteFromOffice,\n CKEDITOR.GeneralHtmlSupport,\n // 이미지 플러그인은 업로드 여부와 무관하게 항상 포함 (기존 이미지 크기 조정/정렬 지원)\n CKEDITOR.Image,\n CKEDITOR.ImageResize,\n CKEDITOR.ImageStyle,\n CKEDITOR.ImageCaption,\n CKEDITOR.ImageToolbar,\n ];\n\n if (toolbarType === 'full') {\n base.push(\n CKEDITOR.MediaEmbed,\n CKEDITOR.HorizontalLine,\n CKEDITOR.CodeBlock,\n CKEDITOR.SourceEditing,\n CKEDITOR.FontSize,\n CKEDITOR.FontColor,\n CKEDITOR.FontBackgroundColor,\n );\n }\n\n if (withImageUpload) {\n base.push(\n CKEDITOR.ImageUpload,\n CKEDITOR.SimpleUploadAdapter,\n );\n }\n\n return base;\n}\n\n/**\n * 이미지 업로드 URL을 생성합니다.\n * uploadPermission이 있으면 쿼리스트링으로 추가합니다.\n */\nfunction buildUploadUrl(uploadPermission: string): string {\n const base = '/api/plugins/sirsoft-ckeditor5/upload';\n if (uploadPermission) {\n return `${base}?permission=${encodeURIComponent(uploadPermission)}`;\n }\n return base;\n}\n\n/**\n * 이미지 업로드 헤더를 반환합니다.\n * Bearer 토큰을 Authorization 헤더에 포함합니다.\n */\nfunction getUploadHeaders(): Record {\n const token = localStorage.getItem('auth_token');\n if (token) {\n return { Authorization: `Bearer ${token}` };\n }\n return {};\n}\n\n/**\n * 단일 CKEditor 인스턴스를 생성합니다.\n */\nasync function createEditorInstance(\n element: HTMLElement,\n options: {\n initialContent: string;\n placeholder: string;\n readOnly: boolean;\n imageUpload: boolean;\n uploadPermission: string;\n height: number;\n toolbar: string;\n containerId: string;\n }\n): Promise {\n const CKEDITOR = (window as any).CKEDITOR as CKEditorGlobal;\n if (!CKEDITOR) {\n throw new Error('[sirsoft-ckeditor5] CKEDITOR 전역 객체를 찾을 수 없습니다. CDN 스크립트가 로드되었는지 확인하세요.');\n }\n\n const toolbarItems = TOOLBAR_PRESETS[options.toolbar] || TOOLBAR_PRESETS.standard;\n\n // 이미지 업로드 비활성화 시 uploadImage 버튼 제거\n const finalToolbar = options.imageUpload\n ? toolbarItems\n : toolbarItems.filter(item => item !== 'uploadImage');\n\n const editorConfig: Record = {\n initialData: options.initialContent,\n plugins: getPlugins(CKEDITOR, options.toolbar, options.imageUpload),\n toolbar: { items: finalToolbar },\n table: {\n contentToolbar: [\n 'tableColumn', 'tableRow', 'mergeTableCells',\n '|', 'tableProperties', 'tableCellProperties',\n ],\n tableProperties: {\n defaultProperties: {\n borderStyle: 'solid',\n borderColor: '#d1d5db',\n borderWidth: '1px',\n alignment: 'left',\n },\n },\n tableCellProperties: {\n defaultProperties: {\n borderStyle: 'solid',\n borderColor: '#d1d5db',\n borderWidth: '1px',\n padding: '8px',\n },\n },\n },\n image: {\n toolbar: [\n 'imageStyle:inline',\n 'imageStyle:alignLeft',\n 'imageStyle:alignCenter',\n 'imageStyle:alignRight',\n '|',\n 'toggleImageCaption',\n '|',\n 'resizeImage',\n ],\n resizeOptions: [\n { name: 'resizeImage:original', label: 'Original', value: null },\n { name: 'resizeImage:25', label: '25%', value: '25' },\n { name: 'resizeImage:50', label: '50%', value: '50' },\n { name: 'resizeImage:75', label: '75%', value: '75' },\n ],\n resizeUnit: '%' as const,\n },\n indentBlock: {\n offset: 40,\n unit: 'px',\n },\n link: {\n defaultProtocol: 'https://',\n decorators: {\n openInNewTab: {\n mode: 'automatic' as const,\n callback: (url: string) => url.startsWith('http://') || url.startsWith('https://'),\n attributes: {\n target: '_blank',\n rel: 'noopener noreferrer',\n },\n },\n },\n },\n htmlSupport: {\n allow: [\n { name: /.*/, attributes: true, classes: true, styles: true },\n ],\n },\n placeholder: options.placeholder,\n language: getCurrentLocale(),\n };\n\n if (options.imageUpload) {\n editorConfig.simpleUpload = {\n uploadUrl: buildUploadUrl(options.uploadPermission),\n headers: getUploadHeaders(),\n };\n }\n\n const editor = await CKEDITOR.ClassicEditor.create(element, editorConfig);\n\n // 높이 설정: 인라인 스타일은 포커스 시 CKEditor 내부에서 초기화될 수 있으므로\n // containerId 기반 CSS 규칙으로 강제 적용 (remount 시 동일 ID로 덮어씀)\n const heightStyleId = `ckeditor5-height-style-${options.containerId}`;\n const existingHeightStyle = document.getElementById(heightStyleId);\n if (existingHeightStyle) {\n existingHeightStyle.textContent = `#${options.containerId} .ck-editor__editable { min-height: ${options.height}px !important; }`;\n } else {\n const heightStyle = document.createElement('style');\n heightStyle.id = heightStyleId;\n heightStyle.textContent = `#${options.containerId} .ck-editor__editable { min-height: ${options.height}px !important; }`;\n document.head.appendChild(heightStyle);\n }\n\n if (options.readOnly) {\n editor.enableReadOnlyMode('read-only');\n }\n\n return editor;\n}\n\n/**\n * 다국어 탭 UI를 생성합니다.\n */\nfunction createMultilingualTabs(\n container: HTMLElement,\n locales: string[],\n activeLocale: string,\n onTabActivate?: (locale: string) => Promise,\n getEditorData?: (locale: string) => string | null\n): { tabsEl: HTMLElement; contentEls: Map; updateCheckIcons: () => void } {\n const tabsEl = document.createElement('div');\n tabsEl.className = 'ckeditor5-locale-tabs';\n\n const contentEls = new Map();\n\n // 에디터 컨텐츠 영역 먼저 생성\n // CKEditor ClassicEditor.create(element)는 element를 숨기고 nextSibling 위치에\n // .ck-editor를 삽입하므로, wrapper div로 감싸서 display:none을 wrapper에 적용해야\n // 비활성 locale의 에디터가 보이지 않음\n locales.forEach(locale => {\n const wrapperEl = document.createElement('div');\n wrapperEl.dataset.locale = locale;\n if (locale !== activeLocale) {\n wrapperEl.style.cssText = 'display:none;';\n }\n const contentEl = document.createElement('div');\n wrapperEl.appendChild(contentEl);\n contentEls.set(locale, contentEl);\n });\n\n /**\n * 비활성 탭의 체크 아이콘을 갱신합니다.\n * 에디터에 값이 있으면 체크 아이콘을 표시하고, 없으면 제거합니다.\n */\n const updateCheckIcons = () => {\n if (!getEditorData) return;\n tabsEl.querySelectorAll('button').forEach(btn => {\n const btnLocale = (btn as HTMLButtonElement).dataset.locale;\n if (!btnLocale || btn.classList.contains('is-active')) {\n // 활성 탭은 체크 아이콘 제거\n const existing = btn.querySelector('.ck5-check');\n if (existing) existing.remove();\n return;\n }\n const data = getEditorData(btnLocale);\n const hasValue = Boolean(data?.trim());\n const existing = btn.querySelector('.ck5-check');\n if (hasValue && !existing) {\n const icon = document.createElement('i');\n icon.className = 'fas fa-check ck5-check';\n btn.appendChild(icon);\n } else if (!hasValue && existing) {\n existing.remove();\n }\n });\n };\n\n // 탭 버튼 생성\n const defaultLocale = locales[0];\n locales.forEach(locale => {\n const isDefault = locale === defaultLocale;\n const isActive = locale === activeLocale;\n const tab = document.createElement('button');\n tab.type = 'button';\n tab.dataset.locale = locale;\n tab.className = [isActive ? 'is-active' : '', isDefault ? 'is-default' : ''].filter(Boolean).join(' ');\n tab.innerHTML = `${getLocaleLabel(locale)}${isDefault ? '*' : ''}`;\n tab.addEventListener('click', async () => {\n // 탭 활성화 전환 (에디터 생성 전에 먼저 실행)\n tabsEl.querySelectorAll('button').forEach(btn => {\n const btnLocale = (btn as HTMLButtonElement).dataset.locale;\n const btnIsActive = btnLocale === locale;\n btn.classList.toggle('is-active', btnIsActive);\n });\n // 에디터 컨텐츠 영역 전환 (새 locale만 표시, 나머지 숨김)\n // wrapperEl(contentEl.parentElement)에 display를 적용해야\n // CKEditor가 삽입한 .ck-editor sibling도 함께 숨겨짐\n contentEls.forEach((el, elLocale) => {\n const wrapperEl = el.parentElement;\n if (wrapperEl) {\n wrapperEl.style.display = elLocale === locale ? 'block' : 'none';\n }\n });\n // lazy 에디터 생성 (아직 없는 경우, display 전환 후 실행)\n if (onTabActivate) {\n await onTabActivate(locale);\n }\n // 탭 전환 완료 후 체크 아이콘 갱신\n updateCheckIcons();\n });\n tabsEl.appendChild(tab);\n });\n\n container.appendChild(tabsEl);\n contentEls.forEach(el => {\n if (el.parentElement) {\n container.appendChild(el.parentElement);\n }\n });\n\n return { tabsEl, contentEls, updateCheckIcons };\n}\n\n/**\n * 폼 데이터 업데이트를 위해 G7Core setState를 호출합니다.\n */\nfunction syncToForm(\n name: string,\n locale: string,\n value: string,\n isMultilingual: boolean\n): void {\n // setData() 호출 중 change:data 재진입 방지\n if (isSyncSuppressed()) return;\n\n const G7Core = (window as any).G7Core;\n if (!G7Core?.state?.setLocal) {\n return;\n }\n\n const updates: Record = {\n [`form.${name}_mode`]: 'html',\n hasChanges: true,\n };\n\n if (isMultilingual) {\n updates[`form.${name}.${locale}`] = value;\n } else {\n updates[`form.${name}`] = value;\n }\n\n // G7 표준 debounce + render: false + selfManaged: true (engine-v1.43.0+)\n // - debounce: ActionDispatcher 타이머 인프라 활용, 컴포넌트 언마운트 시 자동 정리\n // - render: false: CKEditor가 자체 DOM을 관리하므로 React 리렌더 불필요\n // 타이핑 중 전체 폼 트리 리렌더 방지 (37,000+ 바인딩 평가 제거)\n // - selfManaged: true: engine-v1.43.0 자동 승격 예외 명시. HtmlEditor 내부 Textarea가\n // form.content에 자동바인딩되어 레지스트리에 등록되지만, CKEditor는 자체 DOM 관리이므로\n // render:false를 유지해야 성능 이점(37,000+ 바인딩 재평가 방지) 보존.\n // - 저장 시: flushPendingDebounceTimers → globalStateUpdater({}) 강제 렌더 1회\n G7Core.state.setLocal(updates, {\n debounce: 300,\n debounceKey: `ckeditor-sync-${name}`,\n render: false,\n selfManaged: true,\n });\n}\n\n\n/**\n * initEditor 핸들러\n *\n * onMount 시 CKEditor5 인스턴스를 초기화합니다.\n * multilingual=true 시 locale별 탭 UI와 별도 인스턴스를 생성합니다.\n *\n * @param params 핸들러 파라미터\n * @param context 액션 컨텍스트\n */\nexport async function initEditorHandler(\n action: { params?: InitEditorParams; [key: string]: any },\n _context: unknown\n): Promise {\n // ActionHandler 시그니처: (action: ActionDefinition, context: ActionContext)\n // action.params에 실제 파라미터가 있음 (ActionDispatcher에서 resolveParams 후 전달)\n const params: InitEditorParams = (action.params as InitEditorParams) ?? {};\n // 컨테이너 ID: html-editor.json의 props.id와 동일한 패턴으로 계산\n // 동일 페이지에 에디터가 여러 개 있을 때 충돌 방지\n const editorName = (params.name as string) ?? 'content';\n const containerId = `ckeditor5-${editorName}`;\n\n // 기존 인스턴스가 있으면 먼저 정리\n const existing = editorInstances.get(containerId);\n if (existing && existing.size > 0) {\n const destroyPromises: Promise[] = [];\n existing.forEach((editor: any) => {\n if (editor && typeof editor.destroy === 'function') {\n destroyPromises.push(editor.destroy().catch(() => {}));\n }\n });\n await Promise.allSettled(destroyPromises);\n editorInstances.delete(containerId);\n }\n\n // 컨테이너 DOM 찾기\n const container = document.getElementById(containerId);\n if (!container) {\n console.warn(`[sirsoft-ckeditor5] 컨테이너 엘리먼트를 찾을 수 없습니다: #${containerId}`);\n return;\n }\n\n // CKEditor CSS 동적 로드 및 다크 모드 오버라이드 적용\n loadCkeditorCss();\n loadTabCss();\n applyDarkModeOverride();\n watchDarkMode();\n\n // 번역 파일 로드 (에디터 생성 전 완료되어야 함)\n await loadCkeditorTranslations(getCurrentLocale());\n\n // 플러그인 설정을 G7Core 전역 상태에서 직접 읽기 (params 바인딩 실패 대비 폴백)\n const G7Core = (window as any).G7Core;\n const globalState = G7Core?.state?.get() || {};\n // getGlobalState()는 { sidebarOpen, plugins, ... } 구조를 반환\n // _global 래퍼가 있는 경우와 없는 경우 모두 처리\n const pluginSettings = globalState._global?.plugins?.['sirsoft-ckeditor5']\n ?? globalState.plugins?.['sirsoft-ckeditor5']\n ?? {};\n\n // 파라미터 파싱 (params 바인딩 성공 시 우선 사용, 실패(undefined) 시 플러그인 설정 폴백)\n const name = params.name ?? 'content';\n const isMultilingual = params.multilingual === true || params.multilingual === 'true';\n const isReadOnly = params.readOnly === true || params.readOnly === 'true';\n const withImageUpload = params.imageUpload !== undefined\n ? (params.imageUpload === true || params.imageUpload === 'true')\n : (pluginSettings.imageUpload === true || pluginSettings.imageUpload === 'true');\n const uploadPermission = params.uploadPermission ?? '';\n const placeholder = params.placeholder ?? '';\n const height = params.height !== undefined ? (Number(params.height) || 400) : (Number(pluginSettings.editorHeight) || 400);\n const toolbarType = (params.toolbar !== undefined ? (params.toolbar as string) : (pluginSettings.toolbar as string)) ?? 'standard';\n\n // content 파싱: 다국어 시 객체, 단일 시 문자열\n // extensionPointProps를 통해 전달되는 경우 표현식이 평가되지 않고 raw 문자열로 전달될 수 있음\n // 이 경우 G7Core.state.getLocal().form[name] 폴백 사용\n let contentMap: Record = {};\n if (isMultilingual) {\n try {\n if (typeof params.content === 'string' && params.content.startsWith('{') && !params.content.startsWith('{{')) {\n contentMap = JSON.parse(params.content);\n } else if (typeof params.content === 'object' && params.content !== null) {\n contentMap = params.content as unknown as Record;\n }\n } catch {\n contentMap = {};\n }\n // contentMap이 비어있으면 G7Core.state.getLocal().form[name]에서 폴백\n if (Object.keys(contentMap).length === 0 && name) {\n const localState = G7Core?.state?.getLocal?.() ?? {};\n const formValue = localState?.form?.[name];\n // 배열은 content 미설정 상태(API 기본값 [])이므로 무시\n if (formValue && typeof formValue === 'object' && !Array.isArray(formValue)) {\n contentMap = formValue as Record;\n } else if (typeof formValue === 'string' && formValue) {\n // 단일 문자열인 경우 현재 로케일에 매핑\n const currentLocale = getCurrentLocale();\n contentMap = { [currentLocale]: formValue };\n }\n // form[name]도 비어있으면 _global.selectedItem[name]에서 추가 폴백\n if (Object.keys(contentMap).length === 0) {\n const globalState = G7Core?.state?.get?.() ?? {};\n const selectedItem = globalState?._global?.selectedItem ?? globalState?.selectedItem;\n const selectedValue = selectedItem?.[name];\n if (selectedValue && typeof selectedValue === 'object' && !Array.isArray(selectedValue)) {\n contentMap = selectedValue as Record;\n }\n }\n }\n }\n\n const instanceMap = new Map();\n editorInstances.set(containerId, instanceMap);\n\n const editorOptions = {\n placeholder,\n readOnly: isReadOnly,\n imageUpload: withImageUpload,\n uploadPermission,\n height,\n toolbar: toolbarType,\n containerId,\n };\n\n if (isMultilingual) {\n const locales = getSupportedLocales();\n const activeLocale = getCurrentLocale();\n\n // createLocaleEditor ↔ createMultilingualTabs 순환 참조를 끊기 위한 ref\n const contentElsRef = { current: new Map() };\n const updateCheckIconsRef = { current: () => {} };\n\n // 에디터 인스턴스 생성 헬퍼\n const createLocaleEditor = async (locale: string) => {\n if (instanceMap.has(locale)) return; // 이미 생성된 경우 skip\n const contentEl = contentElsRef.current.get(locale);\n if (!contentEl) return;\n\n const initialContent = contentMap[locale] ?? '';\n\n try {\n const editor = await createEditorInstance(contentEl, {\n ...editorOptions,\n initialContent,\n });\n\n instanceMap.set(locale, editor);\n\n // 초기화 중 change:data 이벤트 억제 (CKEditor 내부 initialData 처리 시 발생 가능)\n let isInitializing = true;\n\n (editor as any).model.document.on('change:data', () => {\n if (isInitializing) return;\n const html = (editor as any).getData();\n syncToForm(name, locale, html, true);\n updateCheckIconsRef.current();\n });\n\n isInitializing = false;\n\n // 초기 콘텐츠 재동기화 제거 — initLocal이 이미 form state에 반영\n // mode만 설정 (create 모드에서 _mode 미설정 방지)\n // hasChanges는 설정하지 않음 (사용자 변경 아님)\n if (name) {\n const G7Core = (window as any).G7Core;\n const local = G7Core?.state?.getLocal?.() ?? {};\n if (local.form?.[`${name}_mode`] !== 'html') {\n G7Core.state.setLocal({ [`form.${name}_mode`]: 'html' });\n }\n }\n } catch (err) {\n console.error(`[sirsoft-ckeditor5] 에디터 초기화 오류 (locale: ${locale}):`, err);\n }\n };\n\n // instanceMap에서 에디터 데이터를 반환하는 콜백\n const getEditorData = (locale: string): string | null => {\n const editor = instanceMap.get(locale);\n if (!editor) return null;\n return (editor as any).getData?.() ?? null;\n };\n\n // 탭 클릭 시 lazy 생성 콜백을 전달하여 탭 UI 생성\n const { contentEls, updateCheckIcons } = createMultilingualTabs(container, locales, activeLocale, createLocaleEditor, getEditorData);\n contentElsRef.current = contentEls;\n updateCheckIconsRef.current = updateCheckIcons;\n\n // 활성 locale 에디터 먼저 생성\n await createLocaleEditor(activeLocale);\n\n // 나머지 locale 에디터 백그라운드에서 미리 생성 (탭 전환 시 딜레이 제거)\n // setTimeout으로 지연하여 활성 에디터 초기 입력 반응성 확보\n setTimeout(() => {\n locales.filter(l => l !== activeLocale).forEach(locale => {\n createLocaleEditor(locale);\n });\n }, 2000);\n\n } else {\n // 단일 에디터 모드\n // params.content가 빈 문자열이거나 미평가 표현식({{...}})인 경우\n // onMount 타이밍 문제로 _local.form이 아직 미적용된 것일 수 있음\n // G7Core.state.getLocal()로 현재 상태를 직접 읽어 폴백\n const rawContent = typeof params.content === 'string' ? params.content : '';\n const isUnresolvedExpression = rawContent.startsWith('{{') && rawContent.endsWith('}}');\n let initialContent = isUnresolvedExpression ? '' : rawContent;\n if (!initialContent && name) {\n const localState = G7Core?.state?.getLocal?.() ?? {};\n const formValue = localState?.form?.[name];\n if (typeof formValue === 'string' && formValue) {\n initialContent = formValue;\n }\n }\n const editorEl = document.createElement('div');\n container.appendChild(editorEl);\n\n try {\n const editor = await createEditorInstance(editorEl, {\n ...editorOptions,\n initialContent,\n });\n\n const singleLocale = getCurrentLocale();\n instanceMap.set(singleLocale, editor);\n\n // 초기화 중 change:data 이벤트 억제 (CKEditor 내부 initialData 처리 시 발생 가능)\n let isInitializing = true;\n\n // change:data 이벤트 → 폼 상태 동기화 (디바운스는 setLocal 내부에서 처리)\n (editor as any).model.document.on('change:data', () => {\n if (isInitializing) return;\n const html = (editor as any).getData();\n syncToForm(name, singleLocale, html, false);\n });\n\n isInitializing = false;\n\n // 초기값 강제 설정 (initialData가 무시되는 경우 대비)\n if (initialContent) {\n const currentData = (editor as any).getData();\n if (!currentData || currentData.trim() === '') {\n (editor as any).setData(initialContent);\n }\n // 초기 콘텐츠 재동기화 제거 — initLocal이 이미 form state에 반영\n }\n\n // mode만 설정 (create 모드에서 _mode 미설정 방지)\n if (name) {\n const G7Core = (window as any).G7Core;\n const local = G7Core?.state?.getLocal?.() ?? {};\n if (local.form?.[`${name}_mode`] !== 'html') {\n G7Core.state.setLocal({ [`form.${name}_mode`]: 'html' });\n }\n }\n\n // 단일 에디터는 페이지 이동 없이 form이 교체되는 패턴이 없으므로\n // 외부 상태 변경 polling 불필요\n } catch (err) {\n console.error('[sirsoft-ckeditor5] 에디터 초기화 오류:', err);\n editorInstances.delete(containerId);\n }\n }\n}\n","/**\n * CKEditor5 인스턴스 정리 핸들러\n *\n * 컴포넌트 언마운트 시 CKEditor 인스턴스를 파괴합니다.\n */\n\n// 컨테이너 ID → 인스턴스 맵 (initEditor.ts와 공유)\nimport { editorInstances } from './editorInstances';\nimport { disconnectDarkModeObserver } from './initEditor';\n\n/**\n * destroyEditor 핸들러\n *\n * onUnmount 시 해당 컨테이너의 모든 CKEditor 인스턴스를 파괴합니다.\n *\n * @param params 핸들러 파라미터 (사용 안 함)\n * @param context 액션 컨텍스트\n */\nexport async function destroyEditorHandler(\n action: Record,\n _context: unknown\n): Promise {\n // ActionHandler 시그니처: (action: ActionDefinition, context: ActionContext)\n // action.params.name 기반으로 containerId 계산 (initEditor와 동일한 패턴)\n const editorName = (action.params?.name as string) ?? 'content';\n const containerId = `ckeditor5-${editorName}`;\n const instances = editorInstances.get(containerId);\n\n if (!instances || instances.size === 0) {\n return;\n }\n\n const destroyPromises: Promise[] = [];\n\n instances.forEach((editor) => {\n if (editor && typeof editor.destroy === 'function') {\n destroyPromises.push(\n editor.destroy().catch((err: unknown) => {\n console.warn('[sirsoft-ckeditor5] destroyEditor error:', err);\n })\n );\n }\n });\n\n await Promise.allSettled(destroyPromises);\n\n editorInstances.delete(containerId);\n\n // height style 요소 정리\n const heightStyle = document.getElementById(`ckeditor5-height-style-${containerId}`);\n if (heightStyle) {\n heightStyle.remove();\n }\n\n // 모든 에디터 인스턴스가 제거되면 다크모드 옵저버도 해제\n if (editorInstances.size === 0) {\n disconnectDarkModeObserver();\n }\n}\n","/**\n * sirsoft-ckeditor5 플러그인 엔트리포인트\n *\n * 플러그인 활성화 시 자동으로 로드되어 핸들러를 등록합니다.\n */\n\nimport { initEditorHandler } from './handlers/initEditor';\nimport { destroyEditorHandler } from './handlers/destroyEditor';\n\nconst PLUGIN_IDENTIFIER = 'sirsoft-ckeditor5';\n\nconst CKEDITOR5_CSS_ID = 'ckeditor5-content-styles';\nconst CKEDITOR5_CSS_OVERRIDE_ID = 'ckeditor5-content-styles-override';\nconst CKEDITOR5_CSS_URL = 'https://cdn.ckeditor.com/ckeditor5/43.3.1/ckeditor5.css';\n\n/**\n * CKEditor5 content styles CSS를 동적으로 주입하는 핸들러\n * html-content.json extension_point의 onMount에서 호출됩니다.\n *\n * HtmlContent 컴포넌트에 ck-content 클래스가 적용되어 CDN CSS가 직접 동작합니다.\n * 다크모드(CDN 미지원)와 col 너비 처리만 override로 추가합니다.\n */\nfunction injectContentCssHandler(): void {\n if (!document.getElementById(CKEDITOR5_CSS_ID)) {\n const link = document.createElement('link');\n link.id = CKEDITOR5_CSS_ID;\n link.rel = 'stylesheet';\n link.href = CKEDITOR5_CSS_URL;\n document.head.appendChild(link);\n }\n\n if (!document.getElementById(CKEDITOR5_CSS_OVERRIDE_ID)) {\n const style = document.createElement('style');\n style.id = CKEDITOR5_CSS_OVERRIDE_ID;\n // 다크모드(CDN 미지원)와 col 너비 처리만 override로 유지\n style.textContent = `\n /* 이미지 캡션 - 다크모드 */\n html.dark .ck-content .image > figcaption { color: hsl(0, 0%, 80%); background-color: hsl(0, 0%, 15%); }\n\n /* CKEditor5 표 스타일 - 다크모드 */\n html.dark .ck-content figure.table table { border-color: hsl(0, 0%, 35%); }\n html.dark .ck-content figure.table table tr { background-color: unset; }\n html.dark .ck-content figure.table table td, html.dark .ck-content figure.table table th { border-color: hsl(0, 0%, 30%); color: hsl(0, 0%, 90%); background-color: unset; }\n html.dark .ck-content figure.table table th { background-color: hsl(215, 20%, 25%); }\n\n /* figure.table 전체 너비 - prose와의 충돌 방지 */\n .ck-content figure.table { display: table; width: 100%; margin: 1em 0; }\n .ck-content figure.table table { width: 100%; }\n .ck-content table tr { background-color: unset; }\n .ck-content table col { width: auto !important; }\n\n /* 표 정렬 보정 */\n .ck-content figure.table[style*=\"float:left\"],\n .ck-content figure.table[style*=\"float: left\"] { margin-left: 0 !important; margin-right: 1em !important; }\n .ck-content figure.table[style*=\"float:right\"],\n .ck-content figure.table[style*=\"float: right\"] { margin-left: 1em !important; margin-right: 0 !important; }\n\n /* 이미지 인라인/정렬 - Tailwind preflight img:block 대응 */\n .ck-content img { display: inline; margin: 0; max-width: 100%; }\n .ck-content p:has(img) { line-height: 0; }\n .ck-content p:has(img[style*=\"float\"]) { overflow: hidden; }\n\n /* 이미지 캡션 - 라이트 모드 */\n .ck-content .image > figcaption { background-color: #f3f4f6; color: #374151; font-size: 0.875em; padding: 4px 8px; text-align: center; }\n\n /* 목록 마커 및 들여쓰기 - Tailwind preflight reset 대응 */\n .ck-content ul { list-style-type: disc; padding-left: 2em; }\n .ck-content ol { list-style-type: decimal; padding-left: 2em; }\n .ck-content ul ul { list-style-type: circle; padding-left: 2em; }\n .ck-content ul ul ul { list-style-type: square; padding-left: 2em; }\n .ck-content ol ol { list-style-type: lower-alpha; padding-left: 2em; }\n .ck-content ol ol ol { list-style-type: lower-roman; padding-left: 2em; }\n `;\n document.head.appendChild(style);\n }\n\n}\n\nconst handlerMap: Record = {\n initEditor: initEditorHandler,\n destroyEditor: destroyEditorHandler,\n injectContentCss: injectContentCssHandler,\n};\n\nconst logger = ((window as any).G7Core?.createLogger?.(`Plugin:${PLUGIN_IDENTIFIER}`)) ?? {\n log: (...args: unknown[]) => console.log(`[Plugin:${PLUGIN_IDENTIFIER}]`, ...args),\n warn: (...args: unknown[]) => console.warn(`[Plugin:${PLUGIN_IDENTIFIER}]`, ...args),\n error: (...args: unknown[]) => console.error(`[Plugin:${PLUGIN_IDENTIFIER}]`, ...args),\n};\n\nfunction registerHandlers(retry: boolean = false): void {\n const actionDispatcher = (window as any).G7Core?.getActionDispatcher?.();\n\n if (actionDispatcher) {\n Object.entries(handlerMap).forEach(([name, handler]) => {\n const fullName = `${PLUGIN_IDENTIFIER}.${name}`;\n actionDispatcher.registerHandler(fullName, handler, {\n category: 'plugin',\n source: PLUGIN_IDENTIFIER,\n });\n });\n\n logger.log(\n `${Object.keys(handlerMap).length} handler(s) registered:`,\n Object.keys(handlerMap).map(name => `${PLUGIN_IDENTIFIER}.${name}`)\n );\n } else if (retry) {\n let retryCount = 0;\n const maxRetries = 50;\n\n const retryRegister = () => {\n const dispatcher = (window as any).G7Core?.getActionDispatcher?.();\n\n if (dispatcher) {\n Object.entries(handlerMap).forEach(([name, handler]) => {\n const fullName = `${PLUGIN_IDENTIFIER}.${name}`;\n dispatcher.registerHandler(fullName, handler, {\n category: 'plugin',\n source: PLUGIN_IDENTIFIER,\n });\n });\n\n logger.log(\n `${Object.keys(handlerMap).length} handler(s) registered:`,\n Object.keys(handlerMap).map(name => `${PLUGIN_IDENTIFIER}.${name}`)\n );\n } else {\n retryCount++;\n if (retryCount <= maxRetries) {\n logger.warn(`ActionDispatcher not found, retrying... (${retryCount}/${maxRetries})`);\n setTimeout(retryRegister, 100);\n } else {\n logger.error(`Failed to register handlers: ActionDispatcher not available after maximum retries`);\n }\n }\n };\n\n retryRegister();\n } else {\n logger.warn(`ActionDispatcher not found, handlers not registered`);\n }\n}\n\nexport function initPlugin(): void {\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => registerHandlers(true));\n } else {\n const hasDispatcher = !!(window as any).G7Core?.getActionDispatcher?.();\n registerHandlers(hasDispatcher ? false : true);\n }\n}\n\ninitPlugin();\n\nif (typeof window !== 'undefined') {\n (window as any).__SirsoftCkeditor5 = {\n identifier: PLUGIN_IDENTIFIER,\n handlers: Object.keys(handlerMap),\n initPlugin,\n };\n}"],"names":["editorInstances","CKEDITOR5_CSS_URL","CKEDITOR5_TRANSLATIONS_BASE","CKEDITOR5_CSS_ID","CKEDITOR5_DARK_CSS_ID","CKEDITOR5_TAB_CSS_ID","TOOLBAR_PRESETS","loadCkeditorTranslations","locale","id","resolve","script","loadCkeditorCss","link","loadTabCss","style","isDarkMode","applyDarkModeOverride","existing","darkModeObserver","watchDarkMode","disconnectDarkModeObserver","LOCALE_LABELS","getLocaleLabel","getSupportedLocales","G7Core","getCurrentLocale","getPlugins","CKEDITOR","toolbarType","withImageUpload","base","buildUploadUrl","uploadPermission","getUploadHeaders","token","createEditorInstance","element","options","toolbarItems","finalToolbar","item","editorConfig","url","editor","heightStyleId","existingHeightStyle","heightStyle","createMultilingualTabs","container","locales","activeLocale","onTabActivate","getEditorData","tabsEl","contentEls","wrapperEl","contentEl","updateCheckIcons","btn","btnLocale","hasValue","icon","defaultLocale","isDefault","isActive","tab","btnIsActive","el","elLocale","syncToForm","name","value","isMultilingual","updates","initEditorHandler","action","_context","params","containerId","destroyPromises","globalState","pluginSettings","isReadOnly","placeholder","height","contentMap","formValue","selectedValue","instanceMap","editorOptions","contentElsRef","updateCheckIconsRef","createLocaleEditor","initialContent","isInitializing","html","err","l","rawContent","editorEl","singleLocale","currentData","destroyEditorHandler","instances","PLUGIN_IDENTIFIER","CKEDITOR5_CSS_OVERRIDE_ID","injectContentCssHandler","handlerMap","logger","args","registerHandlers","retry","actionDispatcher","handler","fullName","retryCount","maxRetries","retryRegister","dispatcher","initPlugin","hasDispatcher"],"mappings":"8CAQO,MAAMA,MAAsB,ICG7BC,EAAoB,0DAEpBC,EAA8B,yDAE9BC,EAAmB,oBAEnBC,EAAwB,0BAExBC,EAAuB,sBAsDvBC,EAA4C,CAC9C,QAAS,CACL,OAAQ,SAAU,YAAa,IAC/B,OAAQ,cAAe,IACvB,OAAQ,MAAA,EAEZ,SAAU,CACN,UAAW,IACX,OAAQ,SAAU,YAAa,gBAAiB,IAChD,YAAa,IACb,OAAQ,aAAc,IACtB,eAAgB,eAAgB,SAAU,UAAW,IACrD,cAAe,cAAe,IAC9B,OAAQ,MAAA,EAEZ,KAAM,CACF,UAAW,IACX,WAAY,YAAa,sBAAuB,IAChD,OAAQ,SAAU,YAAa,gBAAiB,IAChD,YAAa,IACb,OAAQ,aAAc,cAAe,cAAe,aAAc,iBAAkB,IACpF,eAAgB,eAAgB,SAAU,UAAW,IACrD,YAAa,gBAAiB,IAC9B,OAAQ,MAAA,CAEhB,EAMA,SAASC,EAAyBC,EAA+B,CAC7D,GAAIA,IAAW,KAAM,OAAO,QAAQ,QAAA,EACpC,MAAMC,EAAK,0BAA0BD,CAAM,GAC3C,OAAI,SAAS,eAAeC,CAAE,EAAU,QAAQ,QAAA,EACzC,IAAI,QAASC,GAAY,CAC5B,MAAMC,EAAS,SAAS,cAAc,QAAQ,EAC9CA,EAAO,GAAKF,EACZE,EAAO,IAAM,GAAGT,CAA2B,IAAIM,CAAM,UACrDG,EAAO,OAAS,IAAMD,EAAA,EACtBC,EAAO,QAAU,IAAMD,EAAA,EACvB,SAAS,KAAK,YAAYC,CAAM,CACpC,CAAC,CACL,CAMA,SAASC,GAAwB,CAC7B,GAAI,SAAS,eAAeT,CAAgB,EACxC,OAEJ,MAAMU,EAAO,SAAS,cAAc,MAAM,EAC1CA,EAAK,GAAKV,EACVU,EAAK,IAAM,aACXA,EAAK,KAAOZ,EACZ,SAAS,KAAK,YAAYY,CAAI,CAClC,CAMA,SAASC,IAAmB,CACxB,GAAI,SAAS,eAAeT,CAAoB,EAC5C,OAEJ,MAAMU,EAAQ,SAAS,cAAc,OAAO,EAC5CA,EAAM,GAAKV,EACXU,EAAM,YAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAwJpB,SAAS,KAAK,YAAYA,CAAK,CACnC,CAKA,SAASC,IAAsB,CAC3B,OAAO,SAAS,gBAAgB,UAAU,SAAS,MAAM,CAC7D,CAMA,SAASC,GAA8B,CACnC,MAAMC,EAAW,SAAS,eAAed,CAAqB,EAE9D,GAAI,CAACY,KAAc,CAEXE,GACAA,EAAS,OAAA,EAEb,MACJ,CAEA,GAAIA,EACA,OAGJ,MAAMH,EAAQ,SAAS,cAAc,OAAO,EAC5CA,EAAM,GAAKX,EACXW,EAAM,YAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAwLpB,SAAS,KAAK,YAAYA,CAAK,CACnC,CAGA,IAAII,EAA4C,KAMhD,SAASC,IAAsB,CACvBD,IAIJA,EAAmB,IAAI,iBAAiB,IAAM,CAC1CF,EAAA,CACJ,CAAC,EAEDE,EAAiB,QAAQ,SAAS,gBAAiB,CAC/C,WAAY,GACZ,gBAAiB,CAAC,OAAO,CAAA,CAC5B,EACL,CAKO,SAASE,IAAmC,CAC3CF,IACAA,EAAiB,WAAA,EACjBA,EAAmB,KAE3B,CAGA,MAAMG,GAAwC,CAC1C,GAAI,MACJ,GAAI,UACJ,GAAI,MACJ,GAAI,KACJ,GAAI,WACJ,GAAI,UACJ,GAAI,SACR,EAMA,SAASC,GAAef,EAAwB,CAC5C,OAAOc,GAAcd,CAAM,GAAKA,EAAO,YAAA,CAC3C,CAMA,SAASgB,IAAgC,CACrC,MAAMC,EAAU,OAAe,OAC/B,OAAIA,GAAQ,QAAQ,UACTA,EAAO,OAAO,UAAA,EAIlB,CADe,aAAa,QAAQ,WAAW,GAAK,IACtC,CACzB,CAMA,SAASC,GAA2B,CAEhC,OADgB,OAAe,QAChB,QAAQ,UAAA,GAAe,aAAa,QAAQ,WAAW,GAAK,IAC/E,CAKA,SAASC,GAAWC,EAA0BC,EAAqBC,EAAiC,CAChG,MAAMC,EAAO,CACTH,EAAS,WACTA,EAAS,KACTA,EAAS,OACTA,EAAS,UACTA,EAAS,cACTA,EAAS,KACTA,EAAS,UACTA,EAAS,QACTA,EAAS,WACTA,EAAS,KACTA,EAAS,UACTA,EAAS,MACTA,EAAS,aACTA,EAAS,gBACTA,EAAS,oBACTA,EAAS,OACTA,EAAS,YACTA,EAAS,gBACTA,EAAS,mBAETA,EAAS,MACTA,EAAS,YACTA,EAAS,WACTA,EAAS,aACTA,EAAS,YAAA,EAGb,OAAIC,IAAgB,QAChBE,EAAK,KACDH,EAAS,WACTA,EAAS,eACTA,EAAS,UACTA,EAAS,cACTA,EAAS,SACTA,EAAS,UACTA,EAAS,mBAAA,EAIbE,GACAC,EAAK,KACDH,EAAS,YACTA,EAAS,mBAAA,EAIVG,CACX,CAMA,SAASC,GAAeC,EAAkC,CACtD,MAAMF,EAAO,wCACb,OAAIE,EACO,GAAGF,CAAI,eAAe,mBAAmBE,CAAgB,CAAC,GAE9DF,CACX,CAMA,SAASG,IAA2C,CAChD,MAAMC,EAAQ,aAAa,QAAQ,YAAY,EAC/C,OAAIA,EACO,CAAE,cAAe,UAAUA,CAAK,EAAA,EAEpC,CAAA,CACX,CAKA,eAAeC,EACXC,EACAC,EAUgB,CAChB,MAAMV,EAAY,OAAe,SACjC,GAAI,CAACA,EACD,MAAM,IAAI,MAAM,wEAAwE,EAG5F,MAAMW,EAAejC,EAAgBgC,EAAQ,OAAO,GAAKhC,EAAgB,SAGnEkC,EAAeF,EAAQ,YACvBC,EACAA,EAAa,OAAOE,GAAQA,IAAS,aAAa,EAElDC,EAAoC,CACtC,YAAaJ,EAAQ,eACrB,QAASX,GAAWC,EAAUU,EAAQ,QAASA,EAAQ,WAAW,EAClE,QAAS,CAAE,MAAOE,CAAA,EAClB,MAAO,CACH,eAAgB,CACZ,cAAe,WAAY,kBAC3B,IAAK,kBAAmB,qBAAA,EAE5B,gBAAiB,CACb,kBAAmB,CACf,YAAa,QACb,YAAa,UACb,YAAa,MACb,UAAW,MAAA,CACf,EAEJ,oBAAqB,CACjB,kBAAmB,CACf,YAAa,QACb,YAAa,UACb,YAAa,MACb,QAAS,KAAA,CACb,CACJ,EAEJ,MAAO,CACH,QAAS,CACL,oBACA,uBACA,yBACA,wBACA,IACA,qBACA,IACA,aAAA,EAEJ,cAAe,CACX,CAAE,KAAM,uBAAwB,MAAO,WAAY,MAAO,IAAA,EAC1D,CAAE,KAAM,iBAAkB,MAAO,MAAO,MAAO,IAAA,EAC/C,CAAE,KAAM,iBAAkB,MAAO,MAAO,MAAO,IAAA,EAC/C,CAAE,KAAM,iBAAkB,MAAO,MAAO,MAAO,IAAA,CAAK,EAExD,WAAY,GAAA,EAEhB,YAAa,CACT,OAAQ,GACR,KAAM,IAAA,EAEV,KAAM,CACF,gBAAiB,WACjB,WAAY,CACR,aAAc,CACV,KAAM,YACN,SAAWG,GAAgBA,EAAI,WAAW,SAAS,GAAKA,EAAI,WAAW,UAAU,EACjF,WAAY,CACR,OAAQ,SACR,IAAK,qBAAA,CACT,CACJ,CACJ,EAEJ,YAAa,CACT,MAAO,CACH,CAAE,KAAM,KAAM,WAAY,GAAM,QAAS,GAAM,OAAQ,EAAA,CAAK,CAChE,EAEJ,YAAaL,EAAQ,YACrB,SAAUZ,EAAA,CAAiB,EAG3BY,EAAQ,cACRI,EAAa,aAAe,CACxB,UAAWV,GAAeM,EAAQ,gBAAgB,EAClD,QAASJ,GAAA,CAAiB,GAIlC,MAAMU,EAAS,MAAMhB,EAAS,cAAc,OAAOS,EAASK,CAAY,EAIlEG,EAAgB,0BAA0BP,EAAQ,WAAW,GAC7DQ,EAAsB,SAAS,eAAeD,CAAa,EACjE,GAAIC,EACAA,EAAoB,YAAc,IAAIR,EAAQ,WAAW,uCAAuCA,EAAQ,MAAM,uBAC3G,CACH,MAAMS,EAAc,SAAS,cAAc,OAAO,EAClDA,EAAY,GAAKF,EACjBE,EAAY,YAAc,IAAIT,EAAQ,WAAW,uCAAuCA,EAAQ,MAAM,mBACtG,SAAS,KAAK,YAAYS,CAAW,CACzC,CAEA,OAAIT,EAAQ,UACRM,EAAO,mBAAmB,WAAW,EAGlCA,CACX,CAKA,SAASI,GACLC,EACAC,EACAC,EACAC,EACAC,EAC2F,CAC3F,MAAMC,EAAS,SAAS,cAAc,KAAK,EAC3CA,EAAO,UAAY,wBAEnB,MAAMC,MAAiB,IAMvBL,EAAQ,QAAQ1C,GAAU,CACtB,MAAMgD,EAAY,SAAS,cAAc,KAAK,EAC9CA,EAAU,QAAQ,OAAShD,EACvBA,IAAW2C,IACXK,EAAU,MAAM,QAAU,iBAE9B,MAAMC,EAAY,SAAS,cAAc,KAAK,EAC9CD,EAAU,YAAYC,CAAS,EAC/BF,EAAW,IAAI/C,EAAQiD,CAAS,CACpC,CAAC,EAMD,MAAMC,EAAmB,IAAM,CACtBL,GACLC,EAAO,iBAAiB,QAAQ,EAAE,QAAQK,GAAO,CAC7C,MAAMC,EAAaD,EAA0B,QAAQ,OACrD,GAAI,CAACC,GAAaD,EAAI,UAAU,SAAS,WAAW,EAAG,CAEnD,MAAMzC,EAAWyC,EAAI,cAAc,YAAY,EAC3CzC,GAAUA,EAAS,OAAA,EACvB,MACJ,CAEA,MAAM2C,EAAW,EADJR,EAAcO,CAAS,GACL,KAAA,EACzB1C,EAAWyC,EAAI,cAAc,YAAY,EAC/C,GAAIE,GAAY,CAAC3C,EAAU,CACvB,MAAM4C,EAAO,SAAS,cAAc,GAAG,EACvCA,EAAK,UAAY,yBACjBH,EAAI,YAAYG,CAAI,CACxB,KAAW,CAACD,GAAY3C,GACpBA,EAAS,OAAA,CAEjB,CAAC,CACL,EAGM6C,EAAgBb,EAAQ,CAAC,EAC/B,OAAAA,EAAQ,QAAQ1C,GAAU,CACtB,MAAMwD,EAAYxD,IAAWuD,EACvBE,EAAWzD,IAAW2C,EACtBe,EAAM,SAAS,cAAc,QAAQ,EAC3CA,EAAI,KAAO,SACXA,EAAI,QAAQ,OAAS1D,EACrB0D,EAAI,UAAY,CAACD,EAAW,YAAc,GAAID,EAAY,aAAe,EAAE,EAAE,OAAO,OAAO,EAAE,KAAK,GAAG,EACrGE,EAAI,UAAY,mDAAmD3C,GAAef,CAAM,CAAC,UAAUwD,EAAY,sCAAwC,EAAE,GACzJE,EAAI,iBAAiB,QAAS,SAAY,CAEtCZ,EAAO,iBAAiB,QAAQ,EAAE,QAAQK,GAAO,CAE7C,MAAMQ,EADaR,EAA0B,QAAQ,SACnBnD,EAClCmD,EAAI,UAAU,OAAO,YAAaQ,CAAW,CACjD,CAAC,EAIDZ,EAAW,QAAQ,CAACa,EAAIC,IAAa,CACjC,MAAMb,EAAYY,EAAG,cACjBZ,IACAA,EAAU,MAAM,QAAUa,IAAa7D,EAAS,QAAU,OAElE,CAAC,EAEG4C,GACA,MAAMA,EAAc5C,CAAM,EAG9BkD,EAAA,CACJ,CAAC,EACDJ,EAAO,YAAYY,CAAG,CAC1B,CAAC,EAEDjB,EAAU,YAAYK,CAAM,EAC5BC,EAAW,QAAQa,GAAM,CACjBA,EAAG,eACHnB,EAAU,YAAYmB,EAAG,aAAa,CAE9C,CAAC,EAEM,CAAE,OAAAd,EAAQ,WAAAC,EAAY,iBAAAG,CAAA,CACjC,CAKA,SAASY,EACLC,EACA/D,EACAgE,EACAC,EACI,CAIJ,MAAMhD,EAAU,OAAe,OAC/B,GAAI,CAACA,GAAQ,OAAO,SAChB,OAGJ,MAAMiD,EAA+B,CACjC,CAAC,QAAQH,CAAI,OAAO,EAAG,OACvB,WAAY,EAAA,EAGZE,EACAC,EAAQ,QAAQH,CAAI,IAAI/D,CAAM,EAAE,EAAIgE,EAEpCE,EAAQ,QAAQH,CAAI,EAAE,EAAIC,EAW9B/C,EAAO,MAAM,SAASiD,EAAS,CAC3B,SAAU,IACV,YAAa,iBAAiBH,CAAI,GAClC,OAAQ,GACR,YAAa,EAAA,CAChB,CACL,CAYA,eAAsBI,GAClBC,EACAC,EACa,CAGb,MAAMC,EAA4BF,EAAO,QAA+B,CAAA,EAIlEG,EAAc,aADAD,EAAO,MAAmB,SACH,GAGrC5D,EAAWlB,EAAgB,IAAI+E,CAAW,EAChD,GAAI7D,GAAYA,EAAS,KAAO,EAAG,CAC/B,MAAM8D,EAAmC,CAAA,EACzC9D,EAAS,QAAS0B,GAAgB,CAC1BA,GAAU,OAAOA,EAAO,SAAY,YACpCoC,EAAgB,KAAKpC,EAAO,QAAA,EAAU,MAAM,IAAM,CAAC,CAAC,CAAC,CAE7D,CAAC,EACD,MAAM,QAAQ,WAAWoC,CAAe,EACxChF,EAAgB,OAAO+E,CAAW,CACtC,CAGA,MAAM9B,EAAY,SAAS,eAAe8B,CAAW,EACrD,GAAI,CAAC9B,EAAW,CACZ,QAAQ,KAAK,8CAA8C8B,CAAW,EAAE,EACxE,MACJ,CAGAnE,EAAA,EACAE,GAAA,EACAG,EAAA,EACAG,GAAA,EAGA,MAAMb,EAAyBmB,GAAkB,EAGjD,MAAMD,EAAU,OAAe,OACzBwD,EAAcxD,GAAQ,OAAO,IAAA,GAAS,CAAA,EAGtCyD,EAAiBD,EAAY,SAAS,UAAU,mBAAmB,GAClEA,EAAY,UAAU,mBAAmB,GACzC,CAAA,EAGDV,EAAOO,EAAO,MAAQ,UACtBL,EAAiBK,EAAO,eAAiB,IAAQA,EAAO,eAAiB,OACzEK,EAAaL,EAAO,WAAa,IAAQA,EAAO,WAAa,OAC7DhD,EAAkBgD,EAAO,cAAgB,OACxCA,EAAO,cAAgB,IAAQA,EAAO,cAAgB,OACtDI,EAAe,cAAgB,IAAQA,EAAe,cAAgB,OACvEjD,EAAmB6C,EAAO,kBAAoB,GAC9CM,EAAcN,EAAO,aAAe,GACpCO,GAASP,EAAO,SAAW,OAAa,OAAOA,EAAO,MAAM,GAAK,IAAQ,OAAOI,EAAe,YAAY,GAAK,IAChHrD,IAAeiD,EAAO,UAAY,OAAaA,EAAO,QAAsBI,EAAe,UAAuB,WAKxH,IAAII,EAAqC,CAAA,EACzC,GAAIb,EAAgB,CAChB,GAAI,CACI,OAAOK,EAAO,SAAY,UAAYA,EAAO,QAAQ,WAAW,GAAG,GAAK,CAACA,EAAO,QAAQ,WAAW,IAAI,EACvGQ,EAAa,KAAK,MAAMR,EAAO,OAAO,EAC/B,OAAOA,EAAO,SAAY,UAAYA,EAAO,UAAY,OAChEQ,EAAaR,EAAO,QAE5B,MAAQ,CACJQ,EAAa,CAAA,CACjB,CAEA,GAAI,OAAO,KAAKA,CAAU,EAAE,SAAW,GAAKf,EAAM,CAE9C,MAAMgB,GADa9D,GAAQ,OAAO,WAAA,GAAgB,CAAA,IACpB,OAAO8C,CAAI,EAUzC,GARIgB,GAAa,OAAOA,GAAc,UAAY,CAAC,MAAM,QAAQA,CAAS,EACtED,EAAaC,EACN,OAAOA,GAAc,UAAYA,IAGxCD,EAAa,CAAE,CADO5D,EAAA,CACO,EAAG6D,CAAA,GAGhC,OAAO,KAAKD,CAAU,EAAE,SAAW,EAAG,CACtC,MAAML,EAAcxD,GAAQ,OAAO,MAAA,GAAW,CAAA,EAExC+D,GADeP,GAAa,SAAS,cAAgBA,GAAa,gBACnCV,CAAI,EACrCiB,GAAiB,OAAOA,GAAkB,UAAY,CAAC,MAAM,QAAQA,CAAa,IAClFF,EAAaE,EAErB,CACJ,CACJ,CAEA,MAAMC,MAAkB,IACxBzF,EAAgB,IAAI+E,EAAaU,CAAW,EAE5C,MAAMC,EAAgB,CAClB,YAAAN,EACA,SAAUD,EACV,YAAarD,EACb,iBAAAG,EACA,OAAAoD,GACA,QAASxD,GACT,YAAAkD,CAAA,EAGJ,GAAIN,EAAgB,CAChB,MAAMvB,EAAU1B,GAAA,EACV2B,EAAezB,EAAA,EAGfiE,EAAgB,CAAE,QAAS,IAAI,GAAyB,EACxDC,EAAsB,CAAE,QAAS,IAAM,CAAC,CAAA,EAGxCC,EAAqB,MAAOrF,GAAmB,CACjD,GAAIiF,EAAY,IAAIjF,CAAM,EAAG,OAC7B,MAAMiD,EAAYkC,EAAc,QAAQ,IAAInF,CAAM,EAClD,GAAI,CAACiD,EAAW,OAEhB,MAAMqC,GAAiBR,EAAW9E,CAAM,GAAK,GAE7C,GAAI,CACA,MAAMoC,EAAS,MAAMR,EAAqBqB,EAAW,CACjD,GAAGiC,EACH,eAAAI,EAAA,CACH,EAEDL,EAAY,IAAIjF,EAAQoC,CAAM,EAG9B,IAAImD,EAAiB,GAcrB,GAZCnD,EAAe,MAAM,SAAS,GAAG,cAAe,IAAM,CACnD,GAAImD,EAAgB,OACpB,MAAMC,EAAQpD,EAAe,QAAA,EAC7B0B,EAAWC,EAAM/D,EAAQwF,EAAM,EAAI,EACnCJ,EAAoB,QAAA,CACxB,CAAC,EAEDG,EAAiB,GAKbxB,EAAM,CACN,MAAM9C,EAAU,OAAe,QACjBA,GAAQ,OAAO,WAAA,GAAgB,CAAA,GACnC,OAAO,GAAG8C,CAAI,OAAO,IAAM,QACjC9C,EAAO,MAAM,SAAS,CAAE,CAAC,QAAQ8C,CAAI,OAAO,EAAG,OAAQ,CAE/D,CACJ,OAAS0B,EAAK,CACV,QAAQ,MAAM,2CAA2CzF,CAAM,KAAMyF,CAAG,CAC5E,CACJ,EAGM5C,EAAiB7C,GAAkC,CACrD,MAAMoC,EAAS6C,EAAY,IAAIjF,CAAM,EACrC,OAAKoC,EACGA,EAAe,aAAe,KADlB,IAExB,EAGM,CAAE,WAAAW,EAAY,iBAAAG,CAAA,EAAqBV,GAAuBC,EAAWC,EAASC,EAAc0C,EAAoBxC,CAAa,EACnIsC,EAAc,QAAUpC,EACxBqC,EAAoB,QAAUlC,EAG9B,MAAMmC,EAAmB1C,CAAY,EAIrC,WAAW,IAAM,CACbD,EAAQ,OAAOgD,GAAKA,IAAM/C,CAAY,EAAE,QAAQ3C,GAAU,CACtDqF,EAAmBrF,CAAM,CAC7B,CAAC,CACL,EAAG,GAAI,CAEX,KAAO,CAKH,MAAM2F,EAAa,OAAOrB,EAAO,SAAY,SAAWA,EAAO,QAAU,GAEzE,IAAIgB,EAD2BK,EAAW,WAAW,IAAI,GAAKA,EAAW,SAAS,IAAI,EACxC,GAAKA,EACnD,GAAI,CAACL,GAAkBvB,EAAM,CAEzB,MAAMgB,GADa9D,GAAQ,OAAO,WAAA,GAAgB,CAAA,IACpB,OAAO8C,CAAI,EACrC,OAAOgB,GAAc,UAAYA,IACjCO,EAAiBP,EAEzB,CACA,MAAMa,EAAW,SAAS,cAAc,KAAK,EAC7CnD,EAAU,YAAYmD,CAAQ,EAE9B,GAAI,CACA,MAAMxD,EAAS,MAAMR,EAAqBgE,EAAU,CAChD,GAAGV,EACH,eAAAI,CAAA,CACH,EAEKO,EAAe3E,EAAA,EACrB+D,EAAY,IAAIY,EAAczD,CAAM,EAGpC,IAAImD,EAAiB,GAYrB,GATCnD,EAAe,MAAM,SAAS,GAAG,cAAe,IAAM,CACnD,GAAImD,EAAgB,OACpB,MAAMC,EAAQpD,EAAe,QAAA,EAC7B0B,EAAWC,EAAM8B,EAAcL,EAAM,EAAK,CAC9C,CAAC,EAEDD,EAAiB,GAGbD,EAAgB,CAChB,MAAMQ,EAAe1D,EAAe,QAAA,GAChC,CAAC0D,GAAeA,EAAY,KAAA,IAAW,KACtC1D,EAAe,QAAQkD,CAAc,CAG9C,CAGA,GAAIvB,EAAM,CACN,MAAM9C,EAAU,OAAe,QACjBA,GAAQ,OAAO,WAAA,GAAgB,CAAA,GACnC,OAAO,GAAG8C,CAAI,OAAO,IAAM,QACjC9C,EAAO,MAAM,SAAS,CAAE,CAAC,QAAQ8C,CAAI,OAAO,EAAG,OAAQ,CAE/D,CAIJ,OAAS0B,EAAK,CACV,QAAQ,MAAM,kCAAmCA,CAAG,EACpDjG,EAAgB,OAAO+E,CAAW,CACtC,CACJ,CACJ,CC/pCA,eAAsBwB,GAClB3B,EACAC,EACa,CAIb,MAAME,EAAc,aADAH,EAAO,QAAQ,MAAmB,SACX,GACrC4B,EAAYxG,EAAgB,IAAI+E,CAAW,EAEjD,GAAI,CAACyB,GAAaA,EAAU,OAAS,EACjC,OAGJ,MAAMxB,EAAmC,CAAA,EAEzCwB,EAAU,QAAS5D,GAAW,CACtBA,GAAU,OAAOA,EAAO,SAAY,YACpCoC,EAAgB,KACZpC,EAAO,QAAA,EAAU,MAAOqD,GAAiB,CACrC,QAAQ,KAAK,2CAA4CA,CAAG,CAChE,CAAC,CAAA,CAGb,CAAC,EAED,MAAM,QAAQ,WAAWjB,CAAe,EAExChF,EAAgB,OAAO+E,CAAW,EAGlC,MAAMhC,EAAc,SAAS,eAAe,0BAA0BgC,CAAW,EAAE,EAC/EhC,GACAA,EAAY,OAAA,EAIZ/C,EAAgB,OAAS,GACzBqB,GAAA,CAER,CCjDA,MAAMoF,EAAoB,oBAEpBtG,EAAmB,2BACnBuG,EAA4B,oCAC5BzG,GAAoB,0DAS1B,SAAS0G,IAAgC,CACrC,GAAI,CAAC,SAAS,eAAexG,CAAgB,EAAG,CAC5C,MAAMU,EAAO,SAAS,cAAc,MAAM,EAC1CA,EAAK,GAAKV,EACVU,EAAK,IAAM,aACXA,EAAK,KAAOZ,GACZ,SAAS,KAAK,YAAYY,CAAI,CAClC,CAEA,GAAI,CAAC,SAAS,eAAe6F,CAAyB,EAAG,CACrD,MAAM3F,EAAQ,SAAS,cAAc,OAAO,EAC5CA,EAAM,GAAK2F,EAEX3F,EAAM,YAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAsCpB,SAAS,KAAK,YAAYA,CAAK,CACnC,CAEJ,CAEA,MAAM6F,EAAuC,CACzC,WAAYjC,GACZ,cAAe4B,GACf,iBAAkBI,EACtB,EAEME,EAAW,OAAe,QAAQ,eAAe,UAAUJ,CAAiB,EAAE,GAAM,CACtF,IAAK,IAAIK,IAAoB,QAAQ,IAAI,WAAWL,CAAiB,IAAK,GAAGK,CAAI,EACjF,KAAM,IAAIA,IAAoB,QAAQ,KAAK,WAAWL,CAAiB,IAAK,GAAGK,CAAI,EACnF,MAAO,IAAIA,IAAoB,QAAQ,MAAM,WAAWL,CAAiB,IAAK,GAAGK,CAAI,CACzF,EAEA,SAASC,EAAiBC,EAAiB,GAAa,CACpD,MAAMC,EAAoB,OAAe,QAAQ,sBAAA,EAEjD,GAAIA,EACA,OAAO,QAAQL,CAAU,EAAE,QAAQ,CAAC,CAACrC,EAAM2C,CAAO,IAAM,CACpD,MAAMC,EAAW,GAAGV,CAAiB,IAAIlC,CAAI,GAC7C0C,EAAiB,gBAAgBE,EAAUD,EAAS,CAChD,SAAU,SACV,OAAQT,CAAA,CACX,CACL,CAAC,EAEDI,EAAO,IACH,GAAG,OAAO,KAAKD,CAAU,EAAE,MAAM,0BACjC,OAAO,KAAKA,CAAU,EAAE,OAAY,GAAGH,CAAiB,IAAIlC,CAAI,EAAE,CAAA,UAE/DyC,EAAO,CACd,IAAII,EAAa,EACjB,MAAMC,EAAa,GAEbC,EAAgB,IAAM,CACxB,MAAMC,EAAc,OAAe,QAAQ,sBAAA,EAEvCA,GACA,OAAO,QAAQX,CAAU,EAAE,QAAQ,CAAC,CAACrC,EAAM2C,CAAO,IAAM,CACpD,MAAMC,EAAW,GAAGV,CAAiB,IAAIlC,CAAI,GAC7CgD,EAAW,gBAAgBJ,EAAUD,EAAS,CAC1C,SAAU,SACV,OAAQT,CAAA,CACX,CACL,CAAC,EAEDI,EAAO,IACH,GAAG,OAAO,KAAKD,CAAU,EAAE,MAAM,0BACjC,OAAO,KAAKA,CAAU,EAAE,OAAY,GAAGH,CAAiB,IAAIlC,CAAI,EAAE,CAAA,IAGtE6C,IACIA,GAAcC,GACdR,EAAO,KAAK,4CAA4CO,CAAU,IAAIC,CAAU,GAAG,EACnF,WAAWC,EAAe,GAAG,GAE7BT,EAAO,MAAM,mFAAmF,EAG5G,EAEAS,EAAA,CACJ,MACIT,EAAO,KAAK,qDAAqD,CAEzE,CAEO,SAASW,GAAmB,CAC/B,GAAI,SAAS,aAAe,UACxB,SAAS,iBAAiB,mBAAoB,IAAMT,EAAiB,EAAI,CAAC,MACvE,CACH,MAAMU,EAAgB,CAAC,CAAE,OAAe,QAAQ,sBAAA,EAChDV,EAAiB,CAAAU,CAA4B,CACjD,CACJ,CAEA,OAAAD,EAAA,EAEI,OAAO,OAAW,MACjB,OAAe,mBAAqB,CACjC,WAAYf,EACZ,SAAU,OAAO,KAAKG,CAAU,EAChC,WAAAY,CAAA"} \ No newline at end of file diff --git a/plugins/_bundled/sirsoft-ckeditor5/package.json b/plugins/_bundled/sirsoft-ckeditor5/package.json index accc520d..f0c69a11 100644 --- a/plugins/_bundled/sirsoft-ckeditor5/package.json +++ b/plugins/_bundled/sirsoft-ckeditor5/package.json @@ -1,6 +1,6 @@ { "name": "@g7/sirsoft-ckeditor5", - "version": "1.0.0-beta.1", + "version": "1.0.0-beta.2", "description": "그누보드7 CKEditor 5 WYSIWYG 에디터 플러그인 프론트엔드 에셋", "private": true, "type": "module", diff --git a/plugins/_bundled/sirsoft-ckeditor5/plugin.json b/plugins/_bundled/sirsoft-ckeditor5/plugin.json index 5dec862b..0458baf3 100644 --- a/plugins/_bundled/sirsoft-ckeditor5/plugin.json +++ b/plugins/_bundled/sirsoft-ckeditor5/plugin.json @@ -5,13 +5,13 @@ "ko": "CKEditor 5 WYSIWYG 에디터", "en": "CKEditor 5 WYSIWYG Editor" }, - "version": "1.0.0-beta.1", + "version": "1.0.0-beta.2", "license": "MIT", "description": { "ko": "CKEditor 5를 이용한 WYSIWYG 에디터 플러그인입니다. 플러그인 설치만으로 기존 HtmlEditor가 교체됩니다.", "en": "WYSIWYG editor plugin using CKEditor 5. Installing this plugin replaces the default HtmlEditor." }, - "g7_version": ">=7.0.0-beta.1", + "g7_version": ">=7.0.0-beta.3", "dependencies": { "modules": {}, "plugins": {} diff --git a/plugins/_bundled/sirsoft-ckeditor5/resources/js/handlers/initEditor.ts b/plugins/_bundled/sirsoft-ckeditor5/resources/js/handlers/initEditor.ts index 2bee6e8f..2cdeb1da 100644 --- a/plugins/_bundled/sirsoft-ckeditor5/resources/js/handlers/initEditor.ts +++ b/plugins/_bundled/sirsoft-ckeditor5/resources/js/handlers/initEditor.ts @@ -922,15 +922,19 @@ function syncToForm( updates[`form.${name}`] = value; } - // G7 표준 debounce + render: false 사용 (engine-v1.42.0) + // G7 표준 debounce + render: false + selfManaged: true (engine-v1.43.0+) // - debounce: ActionDispatcher 타이머 인프라 활용, 컴포넌트 언마운트 시 자동 정리 // - render: false: CKEditor가 자체 DOM을 관리하므로 React 리렌더 불필요 // 타이핑 중 전체 폼 트리 리렌더 방지 (37,000+ 바인딩 평가 제거) + // - selfManaged: true: engine-v1.43.0 자동 승격 예외 명시. HtmlEditor 내부 Textarea가 + // form.content에 자동바인딩되어 레지스트리에 등록되지만, CKEditor는 자체 DOM 관리이므로 + // render:false를 유지해야 성능 이점(37,000+ 바인딩 재평가 방지) 보존. // - 저장 시: flushPendingDebounceTimers → globalStateUpdater({}) 강제 렌더 1회 G7Core.state.setLocal(updates, { debounce: 300, debounceKey: `ckeditor-sync-${name}`, render: false, + selfManaged: true, }); } diff --git a/public/build/core/template-engine.min.js b/public/build/core/template-engine.min.js index f1ac142b..912ad07c 100644 --- a/public/build/core/template-engine.min.js +++ b/public/build/core/template-engine.min.js @@ -1,4 +1,4 @@ -var _1=Object.defineProperty;var A1=(ln,Za,es)=>Za in ln?_1(ln,Za,{enumerable:!0,configurable:!0,writable:!0,value:es}):ln[Za]=es;var H=(ln,Za,es)=>A1(ln,typeof Za!="symbol"?Za+"":Za,es);(function(ln){"use strict";function Za(r,e){for(var t=0;ta[i]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}function es(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Ru={exports:{}},Ze={};/** +var A1=Object.defineProperty;var T1=(ln,Za,es)=>Za in ln?A1(ln,Za,{enumerable:!0,configurable:!0,writable:!0,value:es}):ln[Za]=es;var H=(ln,Za,es)=>T1(ln,typeof Za!="symbol"?Za+"":Za,es);(function(ln){"use strict";function Za(r,e){for(var t=0;ta[i]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}function es(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Ru={exports:{}},Ze={};/** * @license React * react.production.js * @@ -6,7 +6,7 @@ var _1=Object.defineProperty;var A1=(ln,Za,es)=>Za in ln?_1(ln,Za,{enumerable:!0 * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var Ap;function yw(){if(Ap)return Ze;Ap=1;var r=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),t=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),d=Symbol.for("react.context"),g=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),f=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),y=Symbol.for("react.activity"),x=Symbol.iterator;function S(R){return R===null||typeof R!="object"?null:(R=x&&R[x]||R["@@iterator"],typeof R=="function"?R:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},w=Object.assign,k={};function A(R,U,re){this.props=R,this.context=U,this.refs=k,this.updater=re||v}A.prototype.isReactComponent={},A.prototype.setState=function(R,U){if(typeof R!="object"&&typeof R!="function"&&R!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,R,U,"setState")},A.prototype.forceUpdate=function(R){this.updater.enqueueForceUpdate(this,R,"forceUpdate")};function O(){}O.prototype=A.prototype;function N(R,U,re){this.props=R,this.context=U,this.refs=k,this.updater=re||v}var D=N.prototype=new O;D.constructor=N,w(D,A.prototype),D.isPureReactComponent=!0;var $=Array.isArray;function M(){}var z={H:null,A:null,T:null,S:null},K=Object.prototype.hasOwnProperty;function pe(R,U,re){var ye=re.ref;return{$$typeof:r,type:R,key:U,ref:ye!==void 0?ye:null,props:re}}function we(R,U){return pe(R.type,U,R.props)}function J(R){return typeof R=="object"&&R!==null&&R.$$typeof===r}function be(R){var U={"=":"=0",":":"=2"};return"$"+R.replace(/[=:]/g,function(re){return U[re]})}var le=/\/+/g;function de(R,U){return typeof R=="object"&&R!==null&&R.key!=null?be(""+R.key):U.toString(36)}function je(R){switch(R.status){case"fulfilled":return R.value;case"rejected":throw R.reason;default:switch(typeof R.status=="string"?R.then(M,M):(R.status="pending",R.then(function(U){R.status==="pending"&&(R.status="fulfilled",R.value=U)},function(U){R.status==="pending"&&(R.status="rejected",R.reason=U)})),R.status){case"fulfilled":return R.value;case"rejected":throw R.reason}}throw R}function W(R,U,re,ye,oe){var ke=typeof R;(ke==="undefined"||ke==="boolean")&&(R=null);var Oe=!1;if(R===null)Oe=!0;else switch(ke){case"bigint":case"string":case"number":Oe=!0;break;case"object":switch(R.$$typeof){case r:case e:Oe=!0;break;case p:return Oe=R._init,W(Oe(R._payload),U,re,ye,oe)}}if(Oe)return oe=oe(R),Oe=ye===""?"."+de(R,0):ye,$(oe)?(re="",Oe!=null&&(re=Oe.replace(le,"$&/")+"/"),W(oe,U,re,"",function(Ie){return Ie})):oe!=null&&(J(oe)&&(oe=we(oe,re+(oe.key==null||R&&R.key===oe.key?"":(""+oe.key).replace(le,"$&/")+"/")+Oe)),U.push(oe)),1;Oe=0;var Te=ye===""?".":ye+":";if($(R))for(var qe=0;qeZa in ln?_1(ln,Za,{enumerable:!0 * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var Dp;function xw(){return Dp||(Dp=1,(function(r){function e(W,ge){var ne=W.length;W.push(ge);e:for(;0>>1,ae=W[X];if(0>>1;Xi(re,ne))yei(oe,re)?(W[X]=oe,W[ye]=ne,X=ye):(W[X]=re,W[U]=ne,X=U);else if(yei(oe,ne))W[X]=oe,W[ye]=ne,X=ye;else break e}}return ge}function i(W,ge){var ne=W.sortIndex-ge.sortIndex;return ne!==0?ne:W.id-ge.id}if(r.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;r.unstable_now=function(){return o.now()}}else{var d=Date,g=d.now();r.unstable_now=function(){return d.now()-g}}var h=[],f=[],p=1,y=null,x=3,S=!1,v=!1,w=!1,k=!1,A=typeof setTimeout=="function"?setTimeout:null,O=typeof clearTimeout=="function"?clearTimeout:null,N=typeof setImmediate<"u"?setImmediate:null;function D(W){for(var ge=t(f);ge!==null;){if(ge.callback===null)a(f);else if(ge.startTime<=W)a(f),ge.sortIndex=ge.expirationTime,e(h,ge);else break;ge=t(f)}}function $(W){if(w=!1,D(W),!v)if(t(h)!==null)v=!0,M||(M=!0,be());else{var ge=t(f);ge!==null&&je($,ge.startTime-W)}}var M=!1,z=-1,K=5,pe=-1;function we(){return k?!0:!(r.unstable_now()-peW&&we());){var X=y.callback;if(typeof X=="function"){y.callback=null,x=y.priorityLevel;var ae=X(y.expirationTime<=W);if(W=r.unstable_now(),typeof ae=="function"){y.callback=ae,D(W),ge=!0;break t}y===t(h)&&a(h),D(W)}else a(h);y=t(h)}if(y!==null)ge=!0;else{var R=t(f);R!==null&&je($,R.startTime-W),ge=!1}}break e}finally{y=null,x=ne,S=!1}ge=void 0}}finally{ge?be():M=!1}}}var be;if(typeof N=="function")be=function(){N(J)};else if(typeof MessageChannel<"u"){var le=new MessageChannel,de=le.port2;le.port1.onmessage=J,be=function(){de.postMessage(null)}}else be=function(){A(J,0)};function je(W,ge){z=A(function(){W(r.unstable_now())},ge)}r.unstable_IdlePriority=5,r.unstable_ImmediatePriority=1,r.unstable_LowPriority=4,r.unstable_NormalPriority=3,r.unstable_Profiling=null,r.unstable_UserBlockingPriority=2,r.unstable_cancelCallback=function(W){W.callback=null},r.unstable_forceFrameRate=function(W){0>W||125X?(W.sortIndex=ne,e(f,W),t(h)===null&&W===t(f)&&(w?(O(z),z=-1):w=!0,je($,ne-X))):(W.sortIndex=ae,e(h,W),v||S||(v=!0,M||(M=!0,be()))),W},r.unstable_shouldYield=we,r.unstable_wrapCallback=function(W){var ge=x;return function(){var ne=x;x=ge;try{return W.apply(this,arguments)}finally{x=ne}}}})($u)),$u}var Rp;function bw(){return Rp||(Rp=1,Mu.exports=xw()),Mu.exports}var Iu={exports:{}},kn={};/** + */var Dp;function bw(){return Dp||(Dp=1,(function(r){function e(W,he){var ee=W.length;W.push(he);e:for(;0>>1,ae=W[X];if(0>>1;Xi(re,ee))xei(oe,re)?(W[X]=oe,W[xe]=ee,X=xe):(W[X]=re,W[U]=ee,X=U);else if(xei(oe,ee))W[X]=oe,W[xe]=ee,X=xe;else break e}}return he}function i(W,he){var ee=W.sortIndex-he.sortIndex;return ee!==0?ee:W.id-he.id}if(r.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;r.unstable_now=function(){return o.now()}}else{var d=Date,g=d.now();r.unstable_now=function(){return d.now()-g}}var h=[],f=[],p=1,y=null,x=3,S=!1,v=!1,w=!1,k=!1,A=typeof setTimeout=="function"?setTimeout:null,O=typeof clearTimeout=="function"?clearTimeout:null,N=typeof setImmediate<"u"?setImmediate:null;function D(W){for(var he=t(f);he!==null;){if(he.callback===null)a(f);else if(he.startTime<=W)a(f),he.sortIndex=he.expirationTime,e(h,he);else break;he=t(f)}}function $(W){if(w=!1,D(W),!v)if(t(h)!==null)v=!0,M||(M=!0,ve());else{var he=t(f);he!==null&&je($,he.startTime-W)}}var M=!1,z=-1,K=5,ye=-1;function we(){return k?!0:!(r.unstable_now()-yeW&&we());){var X=y.callback;if(typeof X=="function"){y.callback=null,x=y.priorityLevel;var ae=X(y.expirationTime<=W);if(W=r.unstable_now(),typeof ae=="function"){y.callback=ae,D(W),he=!0;break t}y===t(h)&&a(h),D(W)}else a(h);y=t(h)}if(y!==null)he=!0;else{var R=t(f);R!==null&&je($,R.startTime-W),he=!1}}break e}finally{y=null,x=ee,S=!1}he=void 0}}finally{he?ve():M=!1}}}var ve;if(typeof N=="function")ve=function(){N(J)};else if(typeof MessageChannel<"u"){var le=new MessageChannel,de=le.port2;le.port1.onmessage=J,ve=function(){de.postMessage(null)}}else ve=function(){A(J,0)};function je(W,he){z=A(function(){W(r.unstable_now())},he)}r.unstable_IdlePriority=5,r.unstable_ImmediatePriority=1,r.unstable_LowPriority=4,r.unstable_NormalPriority=3,r.unstable_Profiling=null,r.unstable_UserBlockingPriority=2,r.unstable_cancelCallback=function(W){W.callback=null},r.unstable_forceFrameRate=function(W){0>W||125X?(W.sortIndex=ee,e(f,W),t(h)===null&&W===t(f)&&(w?(O(z),z=-1):w=!0,je($,ee-X))):(W.sortIndex=ae,e(h,W),v||S||(v=!0,M||(M=!0,ve()))),W},r.unstable_shouldYield=we,r.unstable_wrapCallback=function(W){var he=x;return function(){var ee=x;x=he;try{return W.apply(this,arguments)}finally{x=ee}}}})($u)),$u}var Rp;function vw(){return Rp||(Rp=1,Mu.exports=bw()),Mu.exports}var Iu={exports:{}},kn={};/** * @license React * react-dom.production.js * @@ -22,7 +22,7 @@ var _1=Object.defineProperty;var A1=(ln,Za,es)=>Za in ln?_1(ln,Za,{enumerable:!0 * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var Op;function vw(){if(Op)return kn;Op=1;var r=Ou();function e(h){var f="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(r)}catch(e){console.error(e)}}return r(),Iu.exports=vw(),Iu.exports}/** + */var Op;function ww(){if(Op)return kn;Op=1;var r=Ou();function e(h){var f="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(r)}catch(e){console.error(e)}}return r(),Iu.exports=ww(),Iu.exports}/** * @license React * react-dom-client.production.js * @@ -30,20 +30,20 @@ var _1=Object.defineProperty;var A1=(ln,Za,es)=>Za in ln?_1(ln,Za,{enumerable:!0 * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var $p;function ww(){if($p)return ro;$p=1;var r=bw(),e=Ou(),t=Mp();function a(n){var s="https://react.dev/errors/"+n;if(1ae||(n.current=X[ae],X[ae]=null,ae--)}function re(n,s){ae++,X[ae]=n.current,n.current=s}var ye=R(null),oe=R(null),ke=R(null),Oe=R(null);function Te(n,s){switch(re(ke,s),re(oe,n),re(ye,null),s.nodeType){case 9:case 11:n=(n=s.documentElement)&&(n=n.namespaceURI)?zv(n):0;break;default:if(n=s.tagName,s=s.namespaceURI)s=zv(s),n=Hv(s,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}U(ye),re(ye,n)}function qe(){U(ye),U(oe),U(ke)}function Ie(n){n.memoizedState!==null&&re(Oe,n);var s=ye.current,c=Hv(s,n.type);s!==c&&(re(oe,n),re(ye,c))}function Nt(n){oe.current===n&&(U(ye),U(oe)),Oe.current===n&&(U(Oe),Yl._currentValue=ne)}var Tt,Xt;function Ot(n){if(Tt===void 0)try{throw Error()}catch(c){var s=c.stack.trim().match(/\n( *(at )?)/);Tt=s&&s[1]||"",Xt=-1ae||(n.current=X[ae],X[ae]=null,ae--)}function re(n,s){ae++,X[ae]=n.current,n.current=s}var xe=R(null),oe=R(null),ke=R(null),Oe=R(null);function Te(n,s){switch(re(ke,s),re(oe,n),re(xe,null),s.nodeType){case 9:case 11:n=(n=s.documentElement)&&(n=n.namespaceURI)?Hv(n):0;break;default:if(n=s.tagName,s=s.namespaceURI)s=Hv(s),n=Pv(s,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}U(xe),re(xe,n)}function qe(){U(xe),U(oe),U(ke)}function Ie(n){n.memoizedState!==null&&re(Oe,n);var s=xe.current,c=Pv(s,n.type);s!==c&&(re(oe,n),re(xe,c))}function Nt(n){oe.current===n&&(U(xe),U(oe)),Oe.current===n&&(U(Oe),Jl._currentValue=ee)}var Rt,Xt;function Mt(n){if(Rt===void 0)try{throw Error()}catch(c){var s=c.stack.trim().match(/\n( *(at )?)/);Rt=s&&s[1]||"",Xt=-1)":-1m||B[u]!==Z[m]){var ce=` -`+B[u].replace(" at new "," at ");return n.displayName&&ce.includes("")&&(ce=ce.replace("",n.displayName)),ce}while(1<=u&&0<=m);break}}}finally{Qt=!1,Error.prepareStackTrace=c}return(c=n?n.displayName||n.name:"")?Ot(c):""}function Tn(n,s){switch(n.tag){case 26:case 27:case 5:return Ot(n.type);case 16:return Ot("Lazy");case 13:return n.child!==s&&s!==null?Ot("Suspense Fallback"):Ot("Suspense");case 19:return Ot("SuspenseList");case 0:case 15:return It(n.type,!1);case 11:return It(n.type.render,!1);case 1:return It(n.type,!0);case 31:return Ot("Activity");default:return""}}function Ce(n){try{var s="",c=null;do s+=Tn(n,c),c=n,n=n.return;while(n);return s}catch(u){return` +`+B[u].replace(" at new "," at ");return n.displayName&&ce.includes("")&&(ce=ce.replace("",n.displayName)),ce}while(1<=u&&0<=m);break}}}finally{Qt=!1,Error.prepareStackTrace=c}return(c=n?n.displayName||n.name:"")?Mt(c):""}function Tn(n,s){switch(n.tag){case 26:case 27:case 5:return Mt(n.type);case 16:return Mt("Lazy");case 13:return n.child!==s&&s!==null?Mt("Suspense Fallback"):Mt("Suspense");case 19:return Mt("SuspenseList");case 0:case 15:return Et(n.type,!1);case 11:return Et(n.type.render,!1);case 1:return Et(n.type,!0);case 31:return Mt("Activity");default:return""}}function Ce(n){try{var s="",c=null;do s+=Tn(n,c),c=n,n=n.return;while(n);return s}catch(u){return` Error generating stack: `+u.message+` -`+u.stack}}var Ge=Object.prototype.hasOwnProperty,at=r.unstable_scheduleCallback,ft=r.unstable_cancelCallback,bt=r.unstable_shouldYield,Et=r.unstable_requestPaint,pt=r.unstable_now,tt=r.unstable_getCurrentPriorityLevel,bn=r.unstable_ImmediatePriority,wt=r.unstable_UserBlockingPriority,At=r.unstable_NormalPriority,qt=r.unstable_LowPriority,Yn=r.unstable_IdlePriority,dn=r.log,Ta=r.unstable_setDisableYieldValue,ca=null,V=null;function ve(n){if(typeof dn=="function"&&Ta(n),V&&typeof V.setStrictMode=="function")try{V.setStrictMode(ca,n)}catch{}}var me=Math.clz32?Math.clz32:Ae,te=Math.log,_e=Math.LN2;function Ae(n){return n>>>=0,n===0?32:31-(te(n)/_e|0)|0}var Re=256,Pe=262144,Ue=4194304;function Le(n){var s=n&42;if(s!==0)return s;switch(n&-n){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return n&261888;case 262144:case 524288:case 1048576:case 2097152:return n&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return n&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return n}}function Fe(n,s,c){var u=n.pendingLanes;if(u===0)return 0;var m=0,b=n.suspendedLanes,E=n.pingedLanes;n=n.warmLanes;var L=u&134217727;return L!==0?(u=L&~b,u!==0?m=Le(u):(E&=L,E!==0?m=Le(E):c||(c=L&~n,c!==0&&(m=Le(c))))):(L=u&~b,L!==0?m=Le(L):E!==0?m=Le(E):c||(c=u&~n,c!==0&&(m=Le(c)))),m===0?0:s!==0&&s!==m&&(s&b)===0&&(b=m&-m,c=s&-s,b>=c||b===32&&(c&4194048)!==0)?s:m}function We(n,s){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&s)===0}function Je(n,s){switch(n){case 1:case 2:case 4:case 8:case 64:return s+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return s+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function st(){var n=Ue;return Ue<<=1,(Ue&62914560)===0&&(Ue=4194304),n}function Be(n){for(var s=[],c=0;31>c;c++)s.push(n);return s}function De(n,s){n.pendingLanes|=s,s!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function $e(n,s,c,u,m,b){var E=n.pendingLanes;n.pendingLanes=c,n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0,n.expiredLanes&=c,n.entangledLanes&=c,n.errorRecoveryDisabledLanes&=c,n.shellSuspendCounter=0;var L=n.entanglements,B=n.expirationTimes,Z=n.hiddenUpdates;for(c=E&~c;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var Tr=/[\n"\\]/g;function Pn(n){return n.replace(Tr,function(s){return"\\"+s.charCodeAt(0).toString(16)+" "})}function hs(n,s,c,u,m,b,E,L){n.name="",E!=null&&typeof E!="function"&&typeof E!="symbol"&&typeof E!="boolean"?n.type=E:n.removeAttribute("type"),s!=null?E==="number"?(s===0&&n.value===""||n.value!=s)&&(n.value=""+Hn(s)):n.value!==""+Hn(s)&&(n.value=""+Hn(s)):E!=="submit"&&E!=="reset"||n.removeAttribute("value"),s!=null?el(n,E,Hn(s)):c!=null?el(n,E,Hn(c)):u!=null&&n.removeAttribute("value"),m==null&&b!=null&&(n.defaultChecked=!!b),m!=null&&(n.checked=m&&typeof m!="function"&&typeof m!="symbol"),L!=null&&typeof L!="function"&&typeof L!="symbol"&&typeof L!="boolean"?n.name=""+Hn(L):n.removeAttribute("name")}function md(n,s,c,u,m,b,E,L){if(b!=null&&typeof b!="function"&&typeof b!="symbol"&&typeof b!="boolean"&&(n.type=b),s!=null||c!=null){if(!(b!=="submit"&&b!=="reset"||s!=null)){Qo(n);return}c=c!=null?""+Hn(c):"",s=s!=null?""+Hn(s):c,L||s===n.value||(n.value=s),n.defaultValue=s}u=u??m,u=typeof u!="function"&&typeof u!="symbol"&&!!u,n.checked=L?n.checked:!!u,n.defaultChecked=!!u,E!=null&&typeof E!="function"&&typeof E!="symbol"&&typeof E!="boolean"&&(n.name=E),Qo(n)}function el(n,s,c){s==="number"&&gs(n.ownerDocument)===n||n.defaultValue===""+c||(n.defaultValue=""+c)}function qs(n,s,c,u){if(n=n.options,s){s={};for(var m=0;m"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),sl=!1;if(Oa)try{var Rr={};Object.defineProperty(Rr,"passive",{get:function(){sl=!0}}),window.addEventListener("test",Rr,Rr),window.removeEventListener("test",Rr,Rr)}catch{sl=!1}var La=null,rl=null,Ei=null;function Xe(){if(Ei)return Ei;var n,s=rl,c=s.length,u,m="value"in La?La.value:La.textContent,b=m.length;for(n=0;n=yt),kd=" ",ul=!1;function Nd(n,s){switch(n){case"keyup":return Qe.indexOf(s.keyCode)!==-1;case"keydown":return s.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function gl(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var Ws=!1;function Ed(n,s){switch(n){case"compositionend":return gl(s);case"keypress":return s.which!==32?null:(ul=!0,kd);case"textInput":return n=s.data,n===kd&&ul?null:n;default:return null}}function Mh(n,s){if(Ws)return n==="compositionend"||!dt&&Nd(n,s)?(n=Xe(),Ei=rl=La=null,Ws=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(s.ctrlKey||s.altKey||s.metaKey)||s.ctrlKey&&s.altKey){if(s.char&&1=s)return{node:c,offset:s-n};n=u}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=nb(c)}}function sb(n,s){return n&&s?n===s?!0:n&&n.nodeType===3?!1:s&&s.nodeType===3?sb(n,s.parentNode):"contains"in n?n.contains(s):n.compareDocumentPosition?!!(n.compareDocumentPosition(s)&16):!1:!1}function rb(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var s=gs(n.document);s instanceof n.HTMLIFrameElement;){try{var c=typeof s.contentWindow.location.href=="string"}catch{c=!1}if(c)n=s.contentWindow;else break;s=gs(n.document)}return s}function Ih(n){var s=n&&n.nodeName&&n.nodeName.toLowerCase();return s&&(s==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||s==="textarea"||n.contentEditable==="true")}var o_=Oa&&"documentMode"in document&&11>=document.documentMode,Di=null,zh=null,vl=null,Hh=!1;function ib(n,s,c){var u=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Hh||Di==null||Di!==gs(u)||(u=Di,"selectionStart"in u&&Ih(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),vl&&bl(vl,u)||(vl=u,u=yu(zh,"onSelect"),0>=E,m-=E,Ya=1<<32-me(s)+m|c<ot?(gt=He,He=null):gt=He.sibling;var jt=ee(Y,He,Q[ot],fe);if(jt===null){He===null&&(He=gt);break}n&&He&&jt.alternate===null&&s(Y,He),F=b(jt,F,ot),Ct===null?Ve=jt:Ct.sibling=jt,Ct=jt,He=gt}if(ot===Q.length)return c(Y,He),xt&&ys(Y,ot),Ve;if(He===null){for(;otot?(gt=He,He=null):gt=He.sibling;var yr=ee(Y,He,jt.value,fe);if(yr===null){He===null&&(He=gt);break}n&&He&&yr.alternate===null&&s(Y,He),F=b(yr,F,ot),Ct===null?Ve=yr:Ct.sibling=yr,Ct=yr,He=gt}if(jt.done)return c(Y,He),xt&&ys(Y,ot),Ve;if(He===null){for(;!jt.done;ot++,jt=Q.next())jt=xe(Y,jt.value,fe),jt!==null&&(F=b(jt,F,ot),Ct===null?Ve=jt:Ct.sibling=jt,Ct=jt);return xt&&ys(Y,ot),Ve}for(He=u(He);!jt.done;ot++,jt=Q.next())jt=ie(He,Y,ot,jt.value,fe),jt!==null&&(n&&jt.alternate!==null&&He.delete(jt.key===null?ot:jt.key),F=b(jt,F,ot),Ct===null?Ve=jt:Ct.sibling=jt,Ct=jt);return n&&He.forEach(function(E1){return s(Y,E1)}),xt&&ys(Y,ot),Ve}function $t(Y,F,Q,fe){if(typeof Q=="object"&&Q!==null&&Q.type===w&&Q.key===null&&(Q=Q.props.children),typeof Q=="object"&&Q!==null){switch(Q.$$typeof){case S:e:{for(var Ve=Q.key;F!==null;){if(F.key===Ve){if(Ve=Q.type,Ve===w){if(F.tag===7){c(Y,F.sibling),fe=m(F,Q.props.children),fe.return=Y,Y=fe;break e}}else if(F.elementType===Ve||typeof Ve=="object"&&Ve!==null&&Ve.$$typeof===K&&Gr(Ve)===F.type){c(Y,F.sibling),fe=m(F,Q.props),Nl(fe,Q),fe.return=Y,Y=fe;break e}c(Y,F);break}else s(Y,F);F=F.sibling}Q.type===w?(fe=Hr(Q.props.children,Y.mode,fe,Q.key),fe.return=Y,Y=fe):(fe=Ld(Q.type,Q.key,Q.props,null,Y.mode,fe),Nl(fe,Q),fe.return=Y,Y=fe)}return E(Y);case v:e:{for(Ve=Q.key;F!==null;){if(F.key===Ve)if(F.tag===4&&F.stateNode.containerInfo===Q.containerInfo&&F.stateNode.implementation===Q.implementation){c(Y,F.sibling),fe=m(F,Q.children||[]),fe.return=Y,Y=fe;break e}else{c(Y,F);break}else s(Y,F);F=F.sibling}fe=Vh(Q,Y.mode,fe),fe.return=Y,Y=fe}return E(Y);case K:return Q=Gr(Q),$t(Y,F,Q,fe)}if(je(Q))return Me(Y,F,Q,fe);if(be(Q)){if(Ve=be(Q),typeof Ve!="function")throw Error(a(150));return Q=Ve.call(Q),Ye(Y,F,Q,fe)}if(typeof Q.then=="function")return $t(Y,F,Bd(Q),fe);if(Q.$$typeof===N)return $t(Y,F,Id(Y,Q),fe);Ud(Y,Q)}return typeof Q=="string"&&Q!==""||typeof Q=="number"||typeof Q=="bigint"?(Q=""+Q,F!==null&&F.tag===6?(c(Y,F.sibling),fe=m(F,Q),fe.return=Y,Y=fe):(c(Y,F),fe=Fh(Q,Y.mode,fe),fe.return=Y,Y=fe),E(Y)):c(Y,F)}return function(Y,F,Q,fe){try{kl=0;var Ve=$t(Y,F,Q,fe);return Ui=null,Ve}catch(He){if(He===Bi||He===Hd)throw He;var Ct=Zn(29,He,null,Y.mode);return Ct.lanes=fe,Ct.return=Y,Ct}finally{}}}var Vr=Ab(!0),Tb=Ab(!1),er=!1;function sf(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function rf(n,s){n=n.updateQueue,s.updateQueue===n&&(s.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function tr(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function nr(n,s,c){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(_t&2)!==0){var m=u.pending;return m===null?s.next=s:(s.next=m.next,m.next=s),u.pending=s,s=Od(n),hb(n,null,c),s}return Rd(n,u,s,c),Od(n)}function El(n,s,c){if(s=s.updateQueue,s!==null&&(s=s.shared,(c&4194048)!==0)){var u=s.lanes;u&=n.pendingLanes,c|=u,s.lanes=c,zt(n,c)}}function of(n,s){var c=n.updateQueue,u=n.alternate;if(u!==null&&(u=u.updateQueue,c===u)){var m=null,b=null;if(c=c.firstBaseUpdate,c!==null){do{var E={lane:c.lane,tag:c.tag,payload:c.payload,callback:null,next:null};b===null?m=b=E:b=b.next=E,c=c.next}while(c!==null);b===null?m=b=s:b=b.next=s}else m=b=s;c={baseState:u.baseState,firstBaseUpdate:m,lastBaseUpdate:b,shared:u.shared,callbacks:u.callbacks},n.updateQueue=c;return}n=c.lastBaseUpdate,n===null?c.firstBaseUpdate=s:n.next=s,c.lastBaseUpdate=s}var lf=!1;function _l(){if(lf){var n=Pi;if(n!==null)throw n}}function Al(n,s,c,u){lf=!1;var m=n.updateQueue;er=!1;var b=m.firstBaseUpdate,E=m.lastBaseUpdate,L=m.shared.pending;if(L!==null){m.shared.pending=null;var B=L,Z=B.next;B.next=null,E===null?b=Z:E.next=Z,E=B;var ce=n.alternate;ce!==null&&(ce=ce.updateQueue,L=ce.lastBaseUpdate,L!==E&&(L===null?ce.firstBaseUpdate=Z:L.next=Z,ce.lastBaseUpdate=B))}if(b!==null){var xe=m.baseState;E=0,ce=Z=B=null,L=b;do{var ee=L.lane&-536870913,ie=ee!==L.lane;if(ie?(ut&ee)===ee:(u&ee)===ee){ee!==0&&ee===Hi&&(lf=!0),ce!==null&&(ce=ce.next={lane:0,tag:L.tag,payload:L.payload,callback:null,next:null});e:{var Me=n,Ye=L;ee=s;var $t=c;switch(Ye.tag){case 1:if(Me=Ye.payload,typeof Me=="function"){xe=Me.call($t,xe,ee);break e}xe=Me;break e;case 3:Me.flags=Me.flags&-65537|128;case 0:if(Me=Ye.payload,ee=typeof Me=="function"?Me.call($t,xe,ee):Me,ee==null)break e;xe=y({},xe,ee);break e;case 2:er=!0}}ee=L.callback,ee!==null&&(n.flags|=64,ie&&(n.flags|=8192),ie=m.callbacks,ie===null?m.callbacks=[ee]:ie.push(ee))}else ie={lane:ee,tag:L.tag,payload:L.payload,callback:L.callback,next:null},ce===null?(Z=ce=ie,B=xe):ce=ce.next=ie,E|=ee;if(L=L.next,L===null){if(L=m.shared.pending,L===null)break;ie=L,L=ie.next,ie.next=null,m.lastBaseUpdate=ie,m.shared.pending=null}}while(!0);ce===null&&(B=xe),m.baseState=B,m.firstBaseUpdate=Z,m.lastBaseUpdate=ce,b===null&&(m.shared.lanes=0),or|=E,n.lanes=E,n.memoizedState=xe}}function Db(n,s){if(typeof n!="function")throw Error(a(191,n));n.call(s)}function Rb(n,s){var c=n.callbacks;if(c!==null)for(n.callbacks=null,n=0;nb?b:8;var E=W.T,L={};W.T=L,Ef(n,!1,s,c);try{var B=m(),Z=W.S;if(Z!==null&&Z(L,B),B!==null&&typeof B=="object"&&typeof B.then=="function"){var ce=m_(B,u);Rl(n,s,ce,sa(n))}else Rl(n,s,u,sa(n))}catch(xe){Rl(n,s,{then:function(){},status:"rejected",reason:xe},sa())}finally{ge.p=b,E!==null&&L.types!==null&&(E.types=L.types),W.T=E}}function S_(){}function kf(n,s,c,u){if(n.tag!==5)throw Error(a(476));var m=d0(n).queue;c0(n,m,s,ne,c===null?S_:function(){return u0(n),c(u)})}function d0(n){var s=n.memoizedState;if(s!==null)return s;s={memoizedState:ne,baseState:ne,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ws,lastRenderedState:ne},next:null};var c={};return s.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ws,lastRenderedState:c},next:null},n.memoizedState=s,n=n.alternate,n!==null&&(n.memoizedState=s),s}function u0(n){var s=d0(n);s.next===null&&(s=n.alternate.memoizedState),Rl(n,s.next.queue,{},sa())}function Nf(){return Sn(Yl)}function g0(){return en().memoizedState}function h0(){return en().memoizedState}function C_(n){for(var s=n.return;s!==null;){switch(s.tag){case 24:case 3:var c=sa();n=tr(c);var u=nr(s,n,c);u!==null&&(Fn(u,s,c),El(u,s,c)),s={cache:ef()},n.payload=s;return}s=s.return}}function j_(n,s,c){var u=sa();c={lane:u,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Qd(n)?p0(s,c):(c=qh(n,s,c,u),c!==null&&(Fn(c,n,u),m0(c,s,u)))}function f0(n,s,c){var u=sa();Rl(n,s,c,u)}function Rl(n,s,c,u){var m={lane:u,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null};if(Qd(n))p0(s,m);else{var b=n.alternate;if(n.lanes===0&&(b===null||b.lanes===0)&&(b=s.lastRenderedReducer,b!==null))try{var E=s.lastRenderedState,L=b(E,c);if(m.hasEagerState=!0,m.eagerState=L,Qn(L,E))return Rd(n,s,m,0),Ht===null&&Dd(),!1}catch{}finally{}if(c=qh(n,s,m,u),c!==null)return Fn(c,n,u),m0(c,s,u),!0}return!1}function Ef(n,s,c,u){if(u={lane:2,revertLane:rp(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Qd(n)){if(s)throw Error(a(479))}else s=qh(n,c,u,2),s!==null&&Fn(s,n,2)}function Qd(n){var s=n.alternate;return n===rt||s!==null&&s===rt}function p0(n,s){Gi=Fd=!0;var c=n.pending;c===null?s.next=s:(s.next=c.next,c.next=s),n.pending=s}function m0(n,s,c){if((c&4194048)!==0){var u=s.lanes;u&=n.pendingLanes,c|=u,s.lanes=c,zt(n,c)}}var Ol={readContext:Sn,use:Wd,useCallback:Wt,useContext:Wt,useEffect:Wt,useImperativeHandle:Wt,useLayoutEffect:Wt,useInsertionEffect:Wt,useMemo:Wt,useReducer:Wt,useRef:Wt,useState:Wt,useDebugValue:Wt,useDeferredValue:Wt,useTransition:Wt,useSyncExternalStore:Wt,useId:Wt,useHostTransitionStatus:Wt,useFormState:Wt,useActionState:Wt,useOptimistic:Wt,useMemoCache:Wt,useCacheRefresh:Wt};Ol.useEffectEvent=Wt;var y0={readContext:Sn,use:Wd,useCallback:function(n,s){return Dn().memoizedState=[n,s===void 0?null:s],n},useContext:Sn,useEffect:e0,useImperativeHandle:function(n,s,c){c=c!=null?c.concat([n]):null,Jd(4194308,4,s0.bind(null,s,n),c)},useLayoutEffect:function(n,s){return Jd(4194308,4,n,s)},useInsertionEffect:function(n,s){Jd(4,2,n,s)},useMemo:function(n,s){var c=Dn();s=s===void 0?null:s;var u=n();if(Kr){ve(!0);try{n()}finally{ve(!1)}}return c.memoizedState=[u,s],u},useReducer:function(n,s,c){var u=Dn();if(c!==void 0){var m=c(s);if(Kr){ve(!0);try{c(s)}finally{ve(!1)}}}else m=s;return u.memoizedState=u.baseState=m,n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:m},u.queue=n,n=n.dispatch=j_.bind(null,rt,n),[u.memoizedState,n]},useRef:function(n){var s=Dn();return n={current:n},s.memoizedState=n},useState:function(n){n=vf(n);var s=n.queue,c=f0.bind(null,rt,s);return s.dispatch=c,[n.memoizedState,c]},useDebugValue:Cf,useDeferredValue:function(n,s){var c=Dn();return jf(c,n,s)},useTransition:function(){var n=vf(!1);return n=c0.bind(null,rt,n.queue,!0,!1),Dn().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,s,c){var u=rt,m=Dn();if(xt){if(c===void 0)throw Error(a(407));c=c()}else{if(c=s(),Ht===null)throw Error(a(349));(ut&127)!==0||zb(u,s,c)}m.memoizedState=c;var b={value:c,getSnapshot:s};return m.queue=b,e0(Pb.bind(null,u,b,n),[n]),u.flags|=2048,Vi(9,{destroy:void 0},Hb.bind(null,u,b,c,s),null),c},useId:function(){var n=Dn(),s=Ht.identifierPrefix;if(xt){var c=Ja,u=Ya;c=(u&~(1<<32-me(u)-1)).toString(32)+c,s="_"+s+"R_"+c,c=Vd++,0<\/script>",b=b.removeChild(b.firstChild);break;case"select":b=typeof u.is=="string"?E.createElement("select",{is:u.is}):E.createElement("select"),u.multiple?b.multiple=!0:u.size&&(b.size=u.size);break;default:b=typeof u.is=="string"?E.createElement(m,{is:u.is}):E.createElement(m)}}b[un]=s,b[vn]=u;e:for(E=s.child;E!==null;){if(E.tag===5||E.tag===6)b.appendChild(E.stateNode);else if(E.tag!==4&&E.tag!==27&&E.child!==null){E.child.return=E,E=E.child;continue}if(E===s)break e;for(;E.sibling===null;){if(E.return===null||E.return===s)break e;E=E.return}E.sibling.return=E.return,E=E.sibling}s.stateNode=b;e:switch(jn(b,m,u),m){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&Cs(s)}}return Bt(s),Bf(s,s.type,n===null?null:n.memoizedProps,s.pendingProps,c),null;case 6:if(n&&s.stateNode!=null)n.memoizedProps!==u&&Cs(s);else{if(typeof u!="string"&&s.stateNode===null)throw Error(a(166));if(n=ke.current,Ii(s)){if(n=s.stateNode,c=s.memoizedProps,u=null,m=wn,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[un]=s,n=!!(n.nodeValue===c||u!==null&&u.suppressHydrationWarning===!0||$v(n.nodeValue,c)),n||Qs(s,!0)}else n=xu(n).createTextNode(u),n[un]=s,s.stateNode=n}return Bt(s),null;case 31:if(c=s.memoizedState,n===null||n.memoizedState!==null){if(u=Ii(s),c!==null){if(n===null){if(!u)throw Error(a(318));if(n=s.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(a(557));n[un]=s}else Pr(),(s.flags&128)===0&&(s.memoizedState=null),s.flags|=4;Bt(s),n=!1}else c=Jh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=c),n=!0;if(!n)return s.flags&256?(ta(s),s):(ta(s),null);if((s.flags&128)!==0)throw Error(a(558))}return Bt(s),null;case 13:if(u=s.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=Ii(s),u!==null&&u.dehydrated!==null){if(n===null){if(!m)throw Error(a(318));if(m=s.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(a(317));m[un]=s}else Pr(),(s.flags&128)===0&&(s.memoizedState=null),s.flags|=4;Bt(s),m=!1}else m=Jh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return s.flags&256?(ta(s),s):(ta(s),null)}return ta(s),(s.flags&128)!==0?(s.lanes=c,s):(c=u!==null,n=n!==null&&n.memoizedState!==null,c&&(u=s.child,m=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(m=u.alternate.memoizedState.cachePool.pool),b=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(b=u.memoizedState.cachePool.pool),b!==m&&(u.flags|=2048)),c!==n&&c&&(s.child.flags|=8192),au(s,s.updateQueue),Bt(s),null);case 4:return qe(),n===null&&cp(s.stateNode.containerInfo),Bt(s),null;case 10:return bs(s.type),Bt(s),null;case 19:if(U(Zt),u=s.memoizedState,u===null)return Bt(s),null;if(m=(s.flags&128)!==0,b=u.rendering,b===null)if(m)Ml(u,!1);else{if(Yt!==0||n!==null&&(n.flags&128)!==0)for(n=s.child;n!==null;){if(b=Gd(n),b!==null){for(s.flags|=128,Ml(u,!1),n=b.updateQueue,s.updateQueue=n,au(s,n),s.subtreeFlags=0,n=c,c=s.child;c!==null;)fb(c,n),c=c.sibling;return re(Zt,Zt.current&1|2),xt&&ys(s,u.treeForkCount),s.child}n=n.sibling}u.tail!==null&&pt()>lu&&(s.flags|=128,m=!0,Ml(u,!1),s.lanes=4194304)}else{if(!m)if(n=Gd(b),n!==null){if(s.flags|=128,m=!0,n=n.updateQueue,s.updateQueue=n,au(s,n),Ml(u,!0),u.tail===null&&u.tailMode==="hidden"&&!b.alternate&&!xt)return Bt(s),null}else 2*pt()-u.renderingStartTime>lu&&c!==536870912&&(s.flags|=128,m=!0,Ml(u,!1),s.lanes=4194304);u.isBackwards?(b.sibling=s.child,s.child=b):(n=u.last,n!==null?n.sibling=b:s.child=b,u.last=b)}return u.tail!==null?(n=u.tail,u.rendering=n,u.tail=n.sibling,u.renderingStartTime=pt(),n.sibling=null,c=Zt.current,re(Zt,m?c&1|2:c&1),xt&&ys(s,u.treeForkCount),n):(Bt(s),null);case 22:case 23:return ta(s),df(),u=s.memoizedState!==null,n!==null?n.memoizedState!==null!==u&&(s.flags|=8192):u&&(s.flags|=8192),u?(c&536870912)!==0&&(s.flags&128)===0&&(Bt(s),s.subtreeFlags&6&&(s.flags|=8192)):Bt(s),c=s.updateQueue,c!==null&&au(s,c.retryQueue),c=null,n!==null&&n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(c=n.memoizedState.cachePool.pool),u=null,s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(u=s.memoizedState.cachePool.pool),u!==c&&(s.flags|=2048),n!==null&&U(qr),null;case 24:return c=null,n!==null&&(c=n.memoizedState.cache),s.memoizedState.cache!==c&&(s.flags|=2048),bs(an),Bt(s),null;case 25:return null;case 30:return null}throw Error(a(156,s.tag))}function A_(n,s){switch(Wh(s),s.tag){case 1:return n=s.flags,n&65536?(s.flags=n&-65537|128,s):null;case 3:return bs(an),qe(),n=s.flags,(n&65536)!==0&&(n&128)===0?(s.flags=n&-65537|128,s):null;case 26:case 27:case 5:return Nt(s),null;case 31:if(s.memoizedState!==null){if(ta(s),s.alternate===null)throw Error(a(340));Pr()}return n=s.flags,n&65536?(s.flags=n&-65537|128,s):null;case 13:if(ta(s),n=s.memoizedState,n!==null&&n.dehydrated!==null){if(s.alternate===null)throw Error(a(340));Pr()}return n=s.flags,n&65536?(s.flags=n&-65537|128,s):null;case 19:return U(Zt),null;case 4:return qe(),null;case 10:return bs(s.type),null;case 22:case 23:return ta(s),df(),n!==null&&U(qr),n=s.flags,n&65536?(s.flags=n&-65537|128,s):null;case 24:return bs(an),null;case 25:return null;default:return null}}function B0(n,s){switch(Wh(s),s.tag){case 3:bs(an),qe();break;case 26:case 27:case 5:Nt(s);break;case 4:qe();break;case 31:s.memoizedState!==null&&ta(s);break;case 13:ta(s);break;case 19:U(Zt);break;case 10:bs(s.type);break;case 22:case 23:ta(s),df(),n!==null&&U(qr);break;case 24:bs(an)}}function $l(n,s){try{var c=s.updateQueue,u=c!==null?c.lastEffect:null;if(u!==null){var m=u.next;c=m;do{if((c.tag&n)===n){u=void 0;var b=c.create,E=c.inst;u=b(),E.destroy=u}c=c.next}while(c!==m)}}catch(L){Rt(s,s.return,L)}}function rr(n,s,c){try{var u=s.updateQueue,m=u!==null?u.lastEffect:null;if(m!==null){var b=m.next;u=b;do{if((u.tag&n)===n){var E=u.inst,L=E.destroy;if(L!==void 0){E.destroy=void 0,m=s;var B=c,Z=L;try{Z()}catch(ce){Rt(m,B,ce)}}}u=u.next}while(u!==b)}}catch(ce){Rt(s,s.return,ce)}}function U0(n){var s=n.updateQueue;if(s!==null){var c=n.stateNode;try{Rb(s,c)}catch(u){Rt(n,n.return,u)}}}function q0(n,s,c){c.props=Wr(n.type,n.memoizedProps),c.state=n.memoizedState;try{c.componentWillUnmount()}catch(u){Rt(n,s,u)}}function Il(n,s){try{var c=n.ref;if(c!==null){switch(n.tag){case 26:case 27:case 5:var u=n.stateNode;break;case 30:u=n.stateNode;break;default:u=n.stateNode}typeof c=="function"?n.refCleanup=c(u):c.current=u}}catch(m){Rt(n,s,m)}}function Xa(n,s){var c=n.ref,u=n.refCleanup;if(c!==null)if(typeof u=="function")try{u()}catch(m){Rt(n,s,m)}finally{n.refCleanup=null,n=n.alternate,n!=null&&(n.refCleanup=null)}else if(typeof c=="function")try{c(null)}catch(m){Rt(n,s,m)}else c.current=null}function G0(n){var s=n.type,c=n.memoizedProps,u=n.stateNode;try{e:switch(s){case"button":case"input":case"select":case"textarea":c.autoFocus&&u.focus();break e;case"img":c.src?u.src=c.src:c.srcSet&&(u.srcset=c.srcSet)}}catch(m){Rt(n,n.return,m)}}function Uf(n,s,c){try{var u=n.stateNode;X_(u,n.type,c,s),u[vn]=s}catch(m){Rt(n,n.return,m)}}function F0(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&gr(n.type)||n.tag===4}function qf(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||F0(n.return))return null;n=n.return}for(n.sibling.return=n.return,n=n.sibling;n.tag!==5&&n.tag!==6&&n.tag!==18;){if(n.tag===27&&gr(n.type)||n.flags&2||n.child===null||n.tag===4)continue e;n.child.return=n,n=n.child}if(!(n.flags&2))return n.stateNode}}function Gf(n,s,c){var u=n.tag;if(u===5||u===6)n=n.stateNode,s?(c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c).insertBefore(n,s):(s=c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c,s.appendChild(n),c=c._reactRootContainer,c!=null||s.onclick!==null||(s.onclick=da));else if(u!==4&&(u===27&&gr(n.type)&&(c=n.stateNode,s=null),n=n.child,n!==null))for(Gf(n,s,c),n=n.sibling;n!==null;)Gf(n,s,c),n=n.sibling}function su(n,s,c){var u=n.tag;if(u===5||u===6)n=n.stateNode,s?c.insertBefore(n,s):c.appendChild(n);else if(u!==4&&(u===27&&gr(n.type)&&(c=n.stateNode),n=n.child,n!==null))for(su(n,s,c),n=n.sibling;n!==null;)su(n,s,c),n=n.sibling}function V0(n){var s=n.stateNode,c=n.memoizedProps;try{for(var u=n.type,m=s.attributes;m.length;)s.removeAttributeNode(m[0]);jn(s,u,c),s[un]=n,s[vn]=c}catch(b){Rt(n,n.return,b)}}var js=!1,on=!1,Ff=!1,K0=typeof WeakSet=="function"?WeakSet:Set,xn=null;function T_(n,s){if(n=n.containerInfo,gp=ku,n=rb(n),Ih(n)){if("selectionStart"in n)var c={start:n.selectionStart,end:n.selectionEnd};else e:{c=(c=n.ownerDocument)&&c.defaultView||window;var u=c.getSelection&&c.getSelection();if(u&&u.rangeCount!==0){c=u.anchorNode;var m=u.anchorOffset,b=u.focusNode;u=u.focusOffset;try{c.nodeType,b.nodeType}catch{c=null;break e}var E=0,L=-1,B=-1,Z=0,ce=0,xe=n,ee=null;t:for(;;){for(var ie;xe!==c||m!==0&&xe.nodeType!==3||(L=E+m),xe!==b||u!==0&&xe.nodeType!==3||(B=E+u),xe.nodeType===3&&(E+=xe.nodeValue.length),(ie=xe.firstChild)!==null;)ee=xe,xe=ie;for(;;){if(xe===n)break t;if(ee===c&&++Z===m&&(L=E),ee===b&&++ce===u&&(B=E),(ie=xe.nextSibling)!==null)break;xe=ee,ee=xe.parentNode}xe=ie}c=L===-1||B===-1?null:{start:L,end:B}}else c=null}c=c||{start:0,end:0}}else c=null;for(hp={focusedElem:n,selectionRange:c},ku=!1,xn=s;xn!==null;)if(s=xn,n=s.child,(s.subtreeFlags&1028)!==0&&n!==null)n.return=s,xn=n;else for(;xn!==null;){switch(s=xn,b=s.alternate,n=s.flags,s.tag){case 0:if((n&4)!==0&&(n=s.updateQueue,n=n!==null?n.events:null,n!==null))for(c=0;c title"))),jn(b,u,c),b[un]=n,nn(b),u=b;break e;case"link":var E=Zv("link","href",m).get(u+(c.href||""));if(E){for(var L=0;L$t&&(E=$t,$t=Ye,Ye=E);var Y=ab(L,Ye),F=ab(L,$t);if(Y&&F&&(ie.rangeCount!==1||ie.anchorNode!==Y.node||ie.anchorOffset!==Y.offset||ie.focusNode!==F.node||ie.focusOffset!==F.offset)){var Q=xe.createRange();Q.setStart(Y.node,Y.offset),ie.removeAllRanges(),Ye>$t?(ie.addRange(Q),ie.extend(F.node,F.offset)):(Q.setEnd(F.node,F.offset),ie.addRange(Q))}}}}for(xe=[],ie=L;ie=ie.parentNode;)ie.nodeType===1&&xe.push({element:ie,left:ie.scrollLeft,top:ie.scrollTop});for(typeof L.focus=="function"&&L.focus(),L=0;Lc?32:c,W.T=null,c=Qf,Qf=null;var b=cr,E=As;if(hn=0,Xi=cr=null,As=0,(_t&6)!==0)throw Error(a(331));var L=_t;if(_t|=4,sv(b.current),tv(b,b.current,E,c),_t=L,ql(0,!1),V&&typeof V.onPostCommitFiberRoot=="function")try{V.onPostCommitFiberRoot(ca,b)}catch{}return!0}finally{ge.p=m,W.T=u,Sv(n,s)}}function jv(n,s,c){s=ga(c,s),s=Df(n.stateNode,s,2),n=nr(n,s,2),n!==null&&(De(n,2),Qa(n))}function Rt(n,s,c){if(n.tag===3)jv(n,n,c);else for(;s!==null;){if(s.tag===3){jv(s,n,c);break}else if(s.tag===1){var u=s.stateNode;if(typeof s.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(lr===null||!lr.has(u))){n=ga(c,n),c=k0(2),u=nr(s,c,2),u!==null&&(N0(c,u,s,n),De(u,2),Qa(u));break}}s=s.return}}function np(n,s,c){var u=n.pingCache;if(u===null){u=n.pingCache=new O_;var m=new Set;u.set(s,m)}else m=u.get(s),m===void 0&&(m=new Set,u.set(s,m));m.has(c)||(Wf=!0,m.add(c),n=z_.bind(null,n,s,c),s.then(n,n))}function z_(n,s,c){var u=n.pingCache;u!==null&&u.delete(s),n.pingedLanes|=n.suspendedLanes&c,n.warmLanes&=~c,Ht===n&&(ut&c)===c&&(Yt===4||Yt===3&&(ut&62914560)===ut&&300>pt()-ou?(_t&2)===0&&Qi(n,0):Yf|=c,Ji===ut&&(Ji=0)),Qa(n)}function kv(n,s){s===0&&(s=st()),n=zr(n,s),n!==null&&(De(n,s),Qa(n))}function H_(n){var s=n.memoizedState,c=0;s!==null&&(c=s.retryLane),kv(n,c)}function P_(n,s){var c=0;switch(n.tag){case 31:case 13:var u=n.stateNode,m=n.memoizedState;m!==null&&(c=m.retryLane);break;case 19:u=n.stateNode;break;case 22:u=n.stateNode._retryCache;break;default:throw Error(a(314))}u!==null&&u.delete(s),kv(n,c)}function B_(n,s){return at(n,s)}var fu=null,eo=null,ap=!1,pu=!1,sp=!1,ur=0;function Qa(n){n!==eo&&n.next===null&&(eo===null?fu=eo=n:eo=eo.next=n),pu=!0,ap||(ap=!0,q_())}function ql(n,s){if(!sp&&pu){sp=!0;do for(var c=!1,u=fu;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var b=0;else{var E=u.suspendedLanes,L=u.pingedLanes;b=(1<<31-me(42|n)+1)-1,b&=m&~(E&~L),b=b&201326741?b&201326741|1:b?b|2:0}b!==0&&(c=!0,Av(u,b))}else b=ut,b=Fe(u,u===Ht?b:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(b&3)===0||We(u,b)||(c=!0,Av(u,b));u=u.next}while(c);sp=!1}}function U_(){Nv()}function Nv(){pu=ap=!1;var n=0;ur!==0&&Z_()&&(n=ur);for(var s=pt(),c=null,u=fu;u!==null;){var m=u.next,b=Ev(u,s);b===0?(u.next=null,c===null?fu=m:c.next=m,m===null&&(eo=c)):(c=u,(n!==0||(b&3)!==0)&&(pu=!0)),u=m}hn!==0&&hn!==5||ql(n),ur!==0&&(ur=0)}function Ev(n,s){for(var c=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,b=n.pendingLanes&-62914561;0L)break;var ce=B.transferSize,xe=B.initiatorType;ce&&Iv(xe)&&(B=B.responseEnd,E+=ce*(B"u"?null:document;function Yv(n,s,c){var u=to;if(u&&typeof s=="string"&&s){var m=Pn(s);m='link[rel="'+n+'"][href="'+m+'"]',typeof c=="string"&&(m+='[crossorigin="'+c+'"]'),Wv.has(m)||(Wv.add(m),n={rel:n,crossOrigin:c,href:s},u.querySelector(m)===null&&(s=u.createElement("link"),jn(s,"link",n),nn(s),u.head.appendChild(s)))}}function l1(n){Ts.D(n),Yv("dns-prefetch",n,null)}function c1(n,s){Ts.C(n,s),Yv("preconnect",n,s)}function d1(n,s,c){Ts.L(n,s,c);var u=to;if(u&&n&&s){var m='link[rel="preload"][as="'+Pn(s)+'"]';s==="image"&&c&&c.imageSrcSet?(m+='[imagesrcset="'+Pn(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(m+='[imagesizes="'+Pn(c.imageSizes)+'"]')):m+='[href="'+Pn(n)+'"]';var b=m;switch(s){case"style":b=no(n);break;case"script":b=ao(n)}xa.has(b)||(n=y({rel:"preload",href:s==="image"&&c&&c.imageSrcSet?void 0:n,as:s},c),xa.set(b,n),u.querySelector(m)!==null||s==="style"&&u.querySelector(Kl(b))||s==="script"&&u.querySelector(Wl(b))||(s=u.createElement("link"),jn(s,"link",n),nn(s),u.head.appendChild(s)))}}function u1(n,s){Ts.m(n,s);var c=to;if(c&&n){var u=s&&typeof s.as=="string"?s.as:"script",m='link[rel="modulepreload"][as="'+Pn(u)+'"][href="'+Pn(n)+'"]',b=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":b=ao(n)}if(!xa.has(b)&&(n=y({rel:"modulepreload",href:n},s),xa.set(b,n),c.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(Wl(b)))return}u=c.createElement("link"),jn(u,"link",n),nn(u),c.head.appendChild(u)}}}function g1(n,s,c){Ts.S(n,s,c);var u=to;if(u&&n){var m=Fa(u).hoistableStyles,b=no(n);s=s||"default";var E=m.get(b);if(!E){var L={loading:0,preload:null};if(E=u.querySelector(Kl(b)))L.loading=5;else{n=y({rel:"stylesheet",href:n,"data-precedence":s},c),(c=xa.get(b))&&vp(n,c);var B=E=u.createElement("link");nn(B),jn(B,"link",n),B._p=new Promise(function(Z,ce){B.onload=Z,B.onerror=ce}),B.addEventListener("load",function(){L.loading|=1}),B.addEventListener("error",function(){L.loading|=2}),L.loading|=4,vu(E,s,u)}E={type:"stylesheet",instance:E,count:1,state:L},m.set(b,E)}}}function h1(n,s){Ts.X(n,s);var c=to;if(c&&n){var u=Fa(c).hoistableScripts,m=ao(n),b=u.get(m);b||(b=c.querySelector(Wl(m)),b||(n=y({src:n,async:!0},s),(s=xa.get(m))&&wp(n,s),b=c.createElement("script"),nn(b),jn(b,"link",n),c.head.appendChild(b)),b={type:"script",instance:b,count:1,state:null},u.set(m,b))}}function f1(n,s){Ts.M(n,s);var c=to;if(c&&n){var u=Fa(c).hoistableScripts,m=ao(n),b=u.get(m);b||(b=c.querySelector(Wl(m)),b||(n=y({src:n,async:!0,type:"module"},s),(s=xa.get(m))&&wp(n,s),b=c.createElement("script"),nn(b),jn(b,"link",n),c.head.appendChild(b)),b={type:"script",instance:b,count:1,state:null},u.set(m,b))}}function Jv(n,s,c,u){var m=(m=ke.current)?bu(m):null;if(!m)throw Error(a(446));switch(n){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(s=no(c.href),c=Fa(m).hoistableStyles,u=c.get(s),u||(u={type:"style",instance:null,count:0,state:null},c.set(s,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){n=no(c.href);var b=Fa(m).hoistableStyles,E=b.get(n);if(E||(m=m.ownerDocument||m,E={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},b.set(n,E),(b=m.querySelector(Kl(n)))&&!b._p&&(E.instance=b,E.state.loading=5),xa.has(n)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},xa.set(n,c),b||p1(m,n,c,E.state))),s&&u===null)throw Error(a(528,""));return E}if(s&&u!==null)throw Error(a(529,""));return null;case"script":return s=c.async,c=c.src,typeof c=="string"&&s&&typeof s!="function"&&typeof s!="symbol"?(s=ao(c),c=Fa(m).hoistableScripts,u=c.get(s),u||(u={type:"script",instance:null,count:0,state:null},c.set(s,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(a(444,n))}}function no(n){return'href="'+Pn(n)+'"'}function Kl(n){return'link[rel="stylesheet"]['+n+"]"}function Xv(n){return y({},n,{"data-precedence":n.precedence,precedence:null})}function p1(n,s,c,u){n.querySelector('link[rel="preload"][as="style"]['+s+"]")?u.loading=1:(s=n.createElement("link"),u.preload=s,s.addEventListener("load",function(){return u.loading|=1}),s.addEventListener("error",function(){return u.loading|=2}),jn(s,"link",c),nn(s),n.head.appendChild(s))}function ao(n){return'[src="'+Pn(n)+'"]'}function Wl(n){return"script[async]"+n}function Qv(n,s,c){if(s.count++,s.instance===null)switch(s.type){case"style":var u=n.querySelector('style[data-href~="'+Pn(c.href)+'"]');if(u)return s.instance=u,nn(u),u;var m=y({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return u=(n.ownerDocument||n).createElement("style"),nn(u),jn(u,"style",m),vu(u,c.precedence,n),s.instance=u;case"stylesheet":m=no(c.href);var b=n.querySelector(Kl(m));if(b)return s.state.loading|=4,s.instance=b,nn(b),b;u=Xv(c),(m=xa.get(m))&&vp(u,m),b=(n.ownerDocument||n).createElement("link"),nn(b);var E=b;return E._p=new Promise(function(L,B){E.onload=L,E.onerror=B}),jn(b,"link",u),s.state.loading|=4,vu(b,c.precedence,n),s.instance=b;case"script":return b=ao(c.src),(m=n.querySelector(Wl(b)))?(s.instance=m,nn(m),m):(u=c,(m=xa.get(b))&&(u=y({},c),wp(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),nn(m),jn(m,"link",u),n.head.appendChild(m),s.instance=m);case"void":return null;default:throw Error(a(443,s.type))}else s.type==="stylesheet"&&(s.state.loading&4)===0&&(u=s.instance,s.state.loading|=4,vu(u,c.precedence,n));return s.instance}function vu(n,s,c){for(var u=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),m=u.length?u[u.length-1]:null,b=m,E=0;E title"):null)}function m1(n,s,c){if(c===1||s.itemProp!=null)return!1;switch(n){case"meta":case"title":return!0;case"style":if(typeof s.precedence!="string"||typeof s.href!="string"||s.href==="")break;return!0;case"link":if(typeof s.rel!="string"||typeof s.href!="string"||s.href===""||s.onLoad||s.onError)break;switch(s.rel){case"stylesheet":return n=s.disabled,typeof s.precedence=="string"&&n==null;default:return!0}case"script":if(s.async&&typeof s.async!="function"&&typeof s.async!="symbol"&&!s.onLoad&&!s.onError&&s.src&&typeof s.src=="string")return!0}return!1}function tw(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function y1(n,s,c,u){if(c.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var m=no(u.href),b=s.querySelector(Kl(m));if(b){s=b._p,s!==null&&typeof s=="object"&&typeof s.then=="function"&&(n.count++,n=Su.bind(n),s.then(n,n)),c.state.loading|=4,c.instance=b,nn(b);return}b=s.ownerDocument||s,u=Xv(u),(m=xa.get(m))&&vp(u,m),b=b.createElement("link"),nn(b);var E=b;E._p=new Promise(function(L,B){E.onload=L,E.onerror=B}),jn(b,"link",u),c.instance=b}n.stylesheets===null&&(n.stylesheets=new Map),n.stylesheets.set(c,s),(s=c.state.preload)&&(c.state.loading&3)===0&&(n.count++,c=Su.bind(n),s.addEventListener("load",c),s.addEventListener("error",c))}}var Sp=0;function x1(n,s){return n.stylesheets&&n.count===0&&ju(n,n.stylesheets),0Sp?50:800)+s);return n.unsuspend=c,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function Su(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)ju(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Cu=null;function ju(n,s){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Cu=new Map,s.forEach(b1,n),Cu=null,Su.call(n))}function b1(n,s){if(!(s.state.loading&4)){var c=Cu.get(n);if(c)var u=c.get(null);else{c=new Map,Cu.set(n,c);for(var m=n.querySelectorAll("link[data-precedence],style[data-precedence]"),b=0;b"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(r)}catch(e){console.error(e)}}return r(),Lu.exports=ww(),Lu.exports}var zu=Sw();const Hu=es(zu),io=[],Cw=50;let Pu=!1;function zp(){try{return window.G7Core?.devTools}catch{return}}function Xr(r,e,t){const a=zp();if(Pu&&a?.isEnabled?.()){a.trackLog?.(r,e,t);return}Pu||(r==="error"||r==="warn")&&io.length{t.isDebugEnabled()&&console.log(e,...a),Xr("log",r,a)},warn:(...a)=>{t.isDebugEnabled()&&console.warn(e,...a),Xr("warn",r,a)},error:(...a)=>{t.isDebugEnabled()&&console.error(e,...a),Xr("error",r,a)}}}oo.getInstance();const za=it("ComponentRegistry");class fn extends Error{constructor(e,t,a){super(e),this.code=t,this.details=a,this.name="ComponentRegistryError"}}const la=class la{constructor(){H(this,"registry",{});H(this,"manifest",null);H(this,"loadingState","idle");H(this,"error",null);H(this,"templateId",null);H(this,"templateType",null)}static getInstance(){return la.instance||(la.instance=new la),la.instance}static resetInstance(){la.instance=null}async loadComponents(e,t){if(this.loadingState==="loading")throw new fn("Components are already being loaded","LOADING_IN_PROGRESS");if(this.loadingState==="loaded"&&this.templateId===e&&this.templateType===t){za.log("Components already loaded for template:",e,t);return}this.loadingState="loading",this.templateId=e,this.templateType=t,this.error=null;try{await this.loadManifest(),await this.loadComponentBundle(),this.loadingState="loaded",za.log("Successfully loaded components:",Object.keys(this.registry).length)}catch(a){throw this.loadingState="error",this.error=a instanceof Error?a:new Error(String(a)),new fn(`Failed to load components: ${this.error.message}`,"LOAD_FAILED",{originalError:this.error})}}async loadManifest(){try{if(!this.templateId)throw new fn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=`${this.templateId}:${this.templateType}`;if(la.manifestCache.has(e)){this.manifest=la.manifestCache.get(e),za.log("Manifest loaded from cache:",this.manifest.templateId);return}const t=`/api/templates/${this.templateId}/components.json`,a=await fetch(t);if(!a.ok)throw new fn(`Failed to fetch manifest: ${a.status} ${a.statusText}`,"MANIFEST_FETCH_FAILED",{status:a.status,statusText:a.statusText});const i=await a.json();this.validateManifest(i),this.manifest=i,la.manifestCache.set(e,i),za.log("Manifest loaded and cached:",i.templateId)}catch(e){throw e instanceof fn?e:new fn("Failed to load component manifest","MANIFEST_LOAD_FAILED",{originalError:e})}}validateManifest(e){if(!e.version)throw new fn("Manifest missing required field: version","MANIFEST_INVALID",{field:"version"});if(!e.templateId)throw new fn("Manifest missing required field: templateId","MANIFEST_INVALID",{field:"templateId"});if(!e.components||typeof e.components!="object")throw new fn("Manifest missing required field: components","MANIFEST_INVALID",{field:"components"});const t=["basic","composite","layout"];for(const a of t){if(!Array.isArray(e.components[a]))throw new fn(`Manifest field 'components.${a}' must be an array`,"MANIFEST_INVALID",{field:`components.${a}`,value:e.components[a]});e.components[a].forEach((i,o)=>{if(!i.name||typeof i.name!="string")throw new fn(`Invalid component metadata at ${a}[${o}]: missing or invalid 'name'`,"MANIFEST_INVALID",{type:a,index:o,metadata:i});if(!i.type||typeof i.type!="string")throw new fn(`Invalid component metadata at ${a}[${o}]: missing or invalid 'type'`,"MANIFEST_INVALID",{type:a,index:o,metadata:i})})}za.log("Manifest validation passed")}async loadComponentBundle(){try{if(!this.templateId)throw new fn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=this.getGlobalVariableName(),t=window[e];if(!t||typeof t!="object")throw new fn(`Component bundle not loaded. Expected global variable: ${e}. Ensure admin.blade.php includes the IIFE bundle script.`,"BUNDLE_NOT_LOADED",{expectedVariable:e});await this.registerComponentsFromManifest(t),za.log("Component bundle loaded from global variable:",e)}catch(e){throw e instanceof fn?e:new fn("Failed to load component bundle","BUNDLE_LOAD_FAILED",{originalError:e})}}getGlobalVariableName(){if(!this.templateId)throw new fn("Template ID not set","TEMPLATE_ID_NOT_SET");return this.templateId.split(/[-_]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}async registerComponentsFromManifest(e){if(!this.manifest)throw new fn("Manifest not loaded","MANIFEST_NOT_LOADED");const t=["basic","composite","layout"];for(const a of t){const i=this.manifest.components[a]||[];for(const o of i){const d=o.name,g=e[d];if(!g){za.warn(`Component '${d}' not found in bundle`);continue}this.registerComponent(d,g,o)}}}registerComponent(e,t,a){this.registry[e]&&za.warn(`Component '${e}' already registered, overwriting`);const i=Ke.memo(t);this.registry[e]={component:i,metadata:a},za.log(`[ComponentRegistry] Registered component: ${e} (${a.type})`)}getComponent(e){const t=this.registry[e];return t?t.component:null}getMetadata(e){const t=this.registry[e];return t?t.metadata:null}hasComponent(e){return e in this.registry}getComponentsByType(e){return Object.entries(this.registry).filter(([t,a])=>a.metadata.type===e).map(([t,a])=>t)}getAllComponents(){return Object.keys(this.registry)}getComponentMap(){const e={};for(const[t,a]of Object.entries(this.registry))e[t]=a.component;return e}getLoadingState(){return this.loadingState}getError(){return this.error}getTemplateId(){return this.templateId}getManifest(){return this.manifest}clear(){this.registry={},this.manifest=null,this.loadingState="idle",this.error=null,this.templateId=null,this.templateType=null,za.log("Registry cleared")}};H(la,"instance",null),H(la,"manifestCache",new Map);let ba=la;const Pp=it("TranslationEngine");class Bu extends Error{constructor(e,t,a){super(e),this.key=t,this.locale=a,this.name="TranslationError"}}const $n=class $n{constructor(e={}){H(this,"cache",new Map);H(this,"translations",new Map);H(this,"options");H(this,"cacheVersion",0);this.options={defaultLocale:e.defaultLocale||"ko",fallbackLocale:e.fallbackLocale||"en",cacheTTL:e.cacheTTL||3e5}}static getInstance(e={}){return $n.instance||($n.instance=new $n(e)),$n.instance}static resetInstance(){$n.instance=null}setCacheVersion(e){this.cacheVersion!==e&&(Pp.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.cache.clear())}getCacheVersion(){return this.cacheVersion}async loadTranslations(e,t,a="/api",i=!1){const o=`${e}:${t}`;if(!i){const d=this.getFromCache(o);if(d)return this.translations.set(o,d),d}try{let d=`${a}/templates/${e}/lang/${t}.json`;const g=[];this.cacheVersion>0&&g.push(`v=${this.cacheVersion}`),i&&g.push(`_=${Date.now()}`),g.length>0&&(d+=`?${g.join("&")}`);const h=await fetch(d);if(!h.ok)throw new Bu(`Failed to load translations: ${h.statusText}`,void 0,t);const p=await h.json();return this.saveToCache(o,p),this.translations.set(o,p),p}catch(d){throw new Bu(`Failed to fetch translations for ${t}: ${d instanceof Error?d.message:String(d)}`,void 0,t)}}resolveTranslations(e,t,a){let i=e;const o=5;let d=0;for(;d"="+this.translate(p,t,void 0,a)),i===g)break;d++}return i.replace($n.TRANSLATION_PATTERN,(g,h,f)=>{const{cleanedParams:p,trailing:y}=this.separateTrailingText(f);return this.translate(h,t,p,a)+y})}translate(e,t,a,i){const o=this.getTranslation(e,t),d=a&&this.cleanParamsStr(a);if(d){const g=this.parseParams(d,i);return this.replaceParams(o,g)}return o}getTranslation(e,t){const{templateId:a,locale:i}=t,o=`${a}:${i}`,d=this.translations.get(o);if(d){const g=this.getNestedValue(d,e);if(g!==null)return g}if(i!==this.options.fallbackLocale){const g=`${a}:${this.options.fallbackLocale}`,h=this.translations.get(g);if(h){const f=this.getNestedValue(h,e);if(f!==null)return f}}return e}getNestedValue(e,t){const a=t.split(".");let i=e;for(const o of a){if(i==null||typeof i!="object")return null;i=i[o]}return typeof i=="string"?i:null}parseParams(e,t){const a={},i=e.startsWith("|")?e.slice(1):e,o=[],g=i.replace(/\{\{(?:[^}]|\}(?!\}))*\}\}/g,h=>(o.push(h),`__PLACEHOLDER_${o.length-1}__`)).matchAll($n.PARAM_PATTERN);for(const h of g){const[,f,p]=h,y=p.replace(/__PLACEHOLDER_(\d+)__/g,(x,S)=>o[parseInt(S,10)]);a[f.trim()]=this.resolveParamValue(y.trim(),t)}return a}resolveParamValue(e,t){if(e.startsWith("{{")&&e.endsWith("}}")){const a=e.slice(2,-2).trim();if(/[|&()[\]!?:+\-*/%<>=\s]/.test(a)&&t)try{const d=new Function(...Object.keys(t),`return ${a}`)(...Object.values(t));return String(d??"")}catch(o){return Pp.error("Expression evaluation failed:",a,o),""}else{const o=this.getNestedDataValue(t,a);return String(o??"")}}return e}separateTrailingText(e){if(!e)return{cleanedParams:void 0,trailing:""};if(e.trimEnd().endsWith("}}"))return{cleanedParams:e,trailing:""};if(!(e.startsWith("|")?e.slice(1):e).includes("="))return{cleanedParams:void 0,trailing:e};const a=e.match(/(\s+[^\p{L}\w=|&\s][^\p{L}\w=]*\s*)$/u);return a?{cleanedParams:e.slice(0,-a[1].length),trailing:a[1]}:{cleanedParams:e,trailing:""}}cleanParamsStr(e){return this.separateTrailingText(e).cleanedParams||""}getNestedDataValue(e,t){if(!e)return;const a=t.split(".");let i=e;for(const o of a){if(i==null)return;i=i[o]}return i}replaceParams(e,t){let a=e;for(const[i,o]of Object.entries(t)){const d=new RegExp(`\\{\\{${i}\\}\\}`,"g");a=a.replace(d,String(o));const g=new RegExp(`\\{${i}\\}`,"g");a=a.replace(g,String(o))}return a}getFromCache(e){const t=this.cache.get(e);return t?Date.now()-t.timestamp>this.options.cacheTTL?(this.cache.delete(e),null):t.data:null}saveToCache(e,t){this.cache.set(e,{data:t,timestamp:Date.now()})}clearCache(){this.cache.clear(),this.translations.clear()}pruneCache(){const e=Date.now(),t=[];for(const[a,i]of this.cache.entries())e-i.timestamp>this.options.cacheTTL&&t.push(a);for(const a of t)this.cache.delete(a)}getCacheStats(){const e=Date.now();let t=0;for(const a of this.cache.values())e-a.timestamp>this.options.cacheTTL&&t++;return{size:this.cache.size,expired:t}}};H($n,"instance",null),H($n,"TRANSLATION_PATTERN",/\$t:([a-zA-Z0-9._-]+)(\|(?:(?!\$t:).)+)?/g),H($n,"NESTED_TRANSLATION_PARAM_PATTERN",/=(\$t:([a-zA-Z0-9._-]+))(?=[|&\s]|$)/g),H($n,"PARAM_PATTERN",/([^=|&]+)=([^|&]+)/g);let xr=$n;const Bp=Object.freeze(Object.defineProperty({__proto__:null,TranslationEngine:xr,TranslationError:Bu},Symbol.toStringTag,{value:"Module"})),Qr=it("PipeRegistry");function Up(r,e){const t=r.getFullYear(),a=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0"),o=String(r.getHours()).padStart(2,"0"),d=String(r.getMinutes()).padStart(2,"0"),g=String(r.getSeconds()).padStart(2,"0");return e.replace("YYYY",String(t)).replace("YY",String(t).slice(-2)).replace("MM",a).replace("M",String(r.getMonth()+1)).replace("DD",i).replace("D",String(r.getDate())).replace("HH",o).replace("H",String(r.getHours())).replace("mm",d).replace("m",String(r.getMinutes())).replace("ss",g).replace("s",String(r.getSeconds()))}function jw(r,e="ko"){const a=new Date().getTime()-r.getTime(),i=Math.floor(a/1e3),o=Math.floor(i/60),d=Math.floor(o/60),g=Math.floor(d/24),h=Math.floor(g/7),f=Math.floor(g/30),p=Math.floor(g/365);return e==="ko"?i<60?"방금 전":o<60?`${o}분 전`:d<24?`${d}시간 전`:g<7?`${g}일 전`:h<4?`${h}주 전`:f<12?`${f}개월 전`:`${p}년 전`:i<60?"just now":o<60?`${o} minute${o===1?"":"s"} ago`:d<24?`${d} hour${d===1?"":"s"} ago`:g<7?`${g} day${g===1?"":"s"} ago`:h<4?`${h} week${h===1?"":"s"} ago`:f<12?`${f} month${f===1?"":"s"} ago`:`${p} year${p===1?"":"s"} ago`}function Uu(r){if(r==null)return null;if(r instanceof Date)return r;if(typeof r=="number")return new Date(r);if(typeof r=="string"){const e=new Date(r);return isNaN(e.getTime())?null:e}return null}const lo={date:{fn:(r,e="YYYY-MM-DD")=>{const t=Uu(r);return t?Up(t,e):""},description:"날짜 포맷 (기본: YYYY-MM-DD)"},datetime:{fn:(r,e="YYYY-MM-DD HH:mm")=>{const t=Uu(r);return t?Up(t,e):""},description:"날짜+시간 포맷 (기본: YYYY-MM-DD HH:mm)"},relativeTime:{fn:(r,e="ko")=>{const t=Uu(r);return t?jw(t,e):""},description:'상대 시간 표시 (예: "3분 전")'},number:{fn:(r,e)=>{const t=Number(r);if(isNaN(t))return String(r??"");const a={};return e!==void 0&&(a.minimumFractionDigits=e,a.maximumFractionDigits=e),t.toLocaleString(void 0,a)},description:"숫자 포맷 (천단위 구분, 선택적 소수점)"},truncate:{fn:(r,e=100,t="...")=>typeof r!="string"?String(r??""):r.length<=e?r:r.slice(0,e)+t,description:'문자열 자르기 (기본: 100자, 접미사: "...")'},uppercase:{fn:r=>typeof r!="string"?String(r??""):r.toUpperCase(),description:"대문자 변환"},lowercase:{fn:r=>typeof r!="string"?String(r??""):r.toLowerCase(),description:"소문자 변환"},stripHtml:{fn:r=>typeof r!="string"?String(r??""):r.replace(/<[^>]*>/g,""),description:"HTML 태그 제거"},default:{fn:(r,e="")=>r==null||r===""?e:r,description:"기본값 설정 (null, undefined, 빈문자열 시)"},fallback:{fn:(r,e)=>r??e,description:"폴백 값 설정 (null, undefined 시만)"},first:{fn:r=>{if(Array.isArray(r))return r[0]},description:"배열의 첫 번째 요소"},last:{fn:r=>{if(Array.isArray(r))return r[r.length-1]},description:"배열의 마지막 요소"},join:{fn:(r,e=", ")=>Array.isArray(r)?r.join(e):"",description:'배열을 문자열로 결합 (기본 구분자: ", ")'},length:{fn:r=>Array.isArray(r)||typeof r=="string"?r.length:0,description:"배열/문자열 길이"},filterBy:{fn:(r,e,t)=>Array.isArray(r)?Array.isArray(e)?r.filter(a=>{const i=t?a?.[t]:a;return e.includes(i)}):r:[],description:"배열 필터링 (allowList에 포함된 항목만 반환)"},keys:{fn:r=>r==null||typeof r!="object"?[]:Object.keys(r),description:"객체의 키 배열"},values:{fn:r=>r==null||typeof r!="object"?[]:Object.values(r),description:"객체의 값 배열"},json:{fn:(r,e)=>{try{return JSON.stringify(r,null,e)}catch{return""}},description:"JSON 문자열로 변환"},localized:{fn:(r,e)=>r==null?"":typeof r=="string"?r:typeof r!="object"?String(r):r[e||"ko"]||r.ko||r.en||Object.values(r)[0]||"",description:"다국어 객체에서 로케일에 맞는 값 추출"}},Zr=new Map,Nr=class Nr{static getInstance(){return Nr.instance||(Nr.instance=new Nr),Nr.instance}register(e,t,a){if(lo[e]){Qr.warn(`[PipeRegistry] 내장 파이프를 덮어쓸 수 없습니다: ${e}`);return}Zr.set(e,{fn:t,description:a}),Qr.log(`[PipeRegistry] 커스텀 파이프 등록됨: ${e}`)}unregister(e){if(lo[e])return Qr.warn(`[PipeRegistry] 내장 파이프는 해제할 수 없습니다: ${e}`),!1;const t=Zr.delete(e);return t&&Qr.log(`[PipeRegistry] 커스텀 파이프 해제됨: ${e}`),t}get(e){const t=lo[e];return t?t.fn:Zr.get(e)?.fn}has(e){return!!lo[e]||Zr.has(e)}execute(e,t,a=[]){const i=this.get(e);if(!i)return Qr.warn(`[PipeRegistry] 알 수 없는 파이프: ${e}`),t;try{return i(t,...a)}catch(o){return Qr.error(`[PipeRegistry] 파이프 실행 오류 (${e}):`,o),t}}list(){const e=[];for(const[t,a]of Object.entries(lo))e.push({name:t,description:a.description,type:"built-in"});for(const[t,a]of Zr.entries())e.push({name:t,description:a.description,type:"custom"});return e.sort((t,a)=>t.name.localeCompare(a.name))}clearCustomPipes(){Zr.clear()}};H(Nr,"instance",null);let Zl=Nr;Zl.getInstance();function kw(r){const e=r.trim(),t=e.indexOf("(");if(t===-1)return{name:e,args:[]};const a=e.slice(0,t).trim(),i=e.slice(t+1,-1);if(!i.trim())return{name:a,args:[]};const o=[];let d="",g=null,h=0;for(let f=0;f0?i[f-1]:"")==="\\"){d+=p;continue}if((p==='"'||p==="'")&&!g){g=p;continue}if(p===g){g=null;continue}if(g){d+=p;continue}if(p==="("||p==="["||p==="{"){h++,d+=p;continue}if(p===")"||p==="]"||p==="}"){h--,d+=p;continue}if(p===","&&h===0){o.push(qp(d.trim())),d="";continue}d+=p}return d.trim()&&o.push(qp(d.trim())),{name:a,args:o}}function qp(r){if(r==="null")return null;if(r==="undefined")return;if(r==="true")return!0;if(r==="false")return!1;const e=Number(r);return!isNaN(e)&&r!==""?e:r}function Nw(r){const e=[];let t="",a=null,i=0;for(let o=0;o0?r[o-1]:"",h=o0?r[a-1]:"",d=a=2&&r.charCodeAt(0)===64976&&r.charCodeAt(r.length-1)===64977}function Vp(r){return r.includes(ec)}function Kp(r){return r.slice(1,-1)}function go(r){if(typeof r=="string")return uo(r);if(Array.isArray(r))return r.map(go);if(r&&typeof r=="object"){const e={};for(const[t,a]of Object.entries(r))e[t]=go(a);return e}return r}const ho=it("DataBindingEngine");function tc(){try{return window.G7Core?.devTools}catch{return}}class qu extends Error{constructor(e,t,a){super(e),this.path=t,this.context=a,this.name="DataBindingError"}}const Ea=class Ea{constructor(e){H(this,"cache",new Map);H(this,"expressionFnCache",new Map);H(this,"renderCycleCache",new Map);H(this,"currentRenderCycleId",0);H(this,"defaultOptions",{defaultValue:void 0,nullSafe:!0,detectCircular:!0,maxDepth:10});e&&(this.defaultOptions={...this.defaultOptions,...e})}startRenderCycle(){this.currentRenderCycleId++,this.renderCycleCache.clear()}isRenderCycleCacheActive(){return this.currentRenderCycleId>0}getFromRenderCycleCache(e){if(this.isRenderCycleCacheActive())return this.renderCycleCache.get(e)}saveToRenderCycleCache(e,t){this.isRenderCycleCacheActive()&&this.renderCycleCache.set(e,t)}resolveBindings(e,t,a,i){const o={...this.defaultOptions,...a},d=tc(),g=t._computed&&!t.$computed?{...t,$computed:t._computed}:t;return e.replace(Ea.BINDING_PATTERN,(h,f)=>{const p=f.trim();let y=!1,x=p;if(p.startsWith(Ds)&&(y=!0,x=p.slice(Ds.length)),Gp(x)){const N=d?.isEnabled()?performance.now():0;try{const[D,$]=Nw(x);let M,z=!1;const K=/[?:|&!+\-*/<>=()]/.test(D)||/\[['"]/.test(D),pe=D.startsWith("_global")||D.startsWith("_local")||D.startsWith("_isolated")||D.startsWith("$parent");if(o.skipCache)K?M=this.evaluateExpression(D,g):M=this.resolvePath(D,g,o);else if(K){const be=this.getFromRenderCycleCache(`expr:${D}`);be!==void 0?(M=be,z=!0):(M=this.evaluateExpression(D,g),this.saveToRenderCycleCache(`expr:${D}`,M))}else if(pe){const be=this.getFromRenderCycleCache(D);be!==void 0?(M=be,z=!0):(M=this.resolvePath(D,g,o),this.saveToRenderCycleCache(D,M))}else{const be=this.getFromCache(D);be!==void 0?(M=be,z=!0):(M=this.resolvePath(D,g,o),this.saveToCache(D,M))}const we=Ew(M,$);if(d?.isEnabled()){const be=performance.now()-N;d.trackExpressionEval({expression:`{{${p}}}`,result:this.sanitizeResultForTracking(we),resultType:this.getResultType(we),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:z,duration:be,method:"resolveBindings",skipCache:o.skipCache})}const J=this.formatValue(we);return y?uo(J):J}catch(D){return ho.error("Pipe expression evaluation failed:",x,D),h}}if(/[?:&!+\-*/<>=()]/.test(x)||/\|\|/.test(x)||/\[['"]/.test(x)){const N=d?.isEnabled()?performance.now():0;try{let D,$=!1;if(o.skipCache)D=this.evaluateExpression(x,g);else{const z=`expr:${x}`,K=this.getFromRenderCycleCache(z);K!==void 0?(D=K,$=!0):(D=this.evaluateExpression(x,g),this.saveToRenderCycleCache(z,D))}if(d?.isEnabled()){const z=performance.now()-N;d.trackExpressionEval({expression:`{{${p}}}`,result:this.sanitizeResultForTracking(D),resultType:this.getResultType(D),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:$,duration:z,method:"resolveBindings",skipCache:o.skipCache})}const M=this.formatValue(D);return y?uo(M):M}catch(D){return ho.error("Expression evaluation failed:",x,D),h}}if(o.skipCache){const N=d?.isEnabled()?performance.now():0,D=this.resolvePath(x,g,o);if(d?.isEnabled()){const M=performance.now()-N;d.trackExpressionEval({expression:`{{${p}}}`,result:this.sanitizeResultForTracking(D),resultType:this.getResultType(D),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:M,method:"resolveBindings",skipCache:!0})}const $=this.formatValue(D);return y?uo($):$}const v=x.startsWith("_global")||x.startsWith("_local")||x.startsWith("_isolated")||x.startsWith("$parent"),w=d?.isEnabled()?performance.now():0;let k,A=!1;if(v){const N=this.getFromRenderCycleCache(x);N!==void 0?(k=N,A=!0):(k=this.resolvePath(x,g,o),this.saveToRenderCycleCache(x,k))}else{const N=this.getFromCache(x);N!==void 0?(k=N,A=!0):(k=this.resolvePath(x,g,o),this.saveToCache(x,k))}if(d?.isEnabled()){const N=performance.now()-w;d.trackExpressionEval({expression:`{{${p}}}`,result:this.sanitizeResultForTracking(k),resultType:this.getResultType(k),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:A,duration:N,method:"resolveBindings",skipCache:o.skipCache})}const O=this.formatValue(k);return y?uo(O):O})}resolve(e,t,a,i){const o={...this.defaultOptions,...a},d=tc(),g=d?.isEnabled()?performance.now():0;if(o.skipCache){const y=this.resolvePath(e,t,o);return d?.isEnabled()&&d.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(y),resultType:this.getResultType(y),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:performance.now()-g,method:"resolve",skipCache:!0}),y}const h=e.startsWith("_global")||e.startsWith("_local")||e.startsWith("_isolated")||e.startsWith("$parent");let f=!1;if(h){const y=this.getFromRenderCycleCache(e);if(y!==void 0)return f=!0,d?.isEnabled()&&d.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(y),resultType:this.getResultType(y),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!0,duration:performance.now()-g,method:"resolve",skipCache:o.skipCache}),y}else{const y=this.getFromCache(e);if(y!==void 0)return f=!0,d?.isEnabled()&&d.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(y),resultType:this.getResultType(y),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!0,duration:performance.now()-g,method:"resolve",skipCache:o.skipCache}),y}const p=this.resolvePath(e,t,o);return h?this.saveToRenderCycleCache(e,p):this.saveToCache(e,p),d?.isEnabled()&&d.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(p),resultType:this.getResultType(p),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:f,duration:performance.now()-g,method:"resolve",skipCache:o.skipCache}),p}resolvePath(e,t,a,i=0,o=new WeakSet){if(a.maxDepth&&i>a.maxDepth){if(a.detectCircular)throw new qu(`Maximum depth exceeded (${a.maxDepth}). Possible circular reference.`,e,t);return a.defaultValue}const d=this.parsePath(e);let g=t;for(let h=0;hEa.CACHE_EXPIRY){this.cache.delete(e),a?.isEnabled()&&a.recordCacheMiss();return}return a?.isEnabled()&&a.recordCacheHit(),t.value}saveToCache(e,t){this.cache.set(e,{value:t,timestamp:Date.now()})}isActionDefinition(e){return typeof e.handler!="string"?!1:e.params!==void 0||Array.isArray(e.actions)||typeof e.target=="string"||e.onSuccess!==void 0||e.onError!==void 0}resolveObject(e,t,a){if(this.isSwitchExpression(e)){const g=e;return this.resolveSwitch(g,t,a)}if(this.isActionDefinition(e))return{...e};if("iteration"in e)return{...e};const i={},d=[...["cellChildren","expandChildren","expandContext","render"],...a?.skipBindingKeys||[]];for(const[g,h]of Object.entries(e)){if(d.includes(g)){i[g]=h;continue}if(typeof h=="string"){const f=h.match(/^\{\{([^}]+)\}\}$/);if(f){const p=f[1].trim();let y=!1,x=p;p.startsWith(Ds)&&(y=!0,x=p.slice(Ds.length));const v=/[?:|&!+\-*/<>=()]/.test(x)||/\[['"]/.test(x)?this.evaluateExpression(x,t,a):this.resolve(x,t,a);i[g]=y&&v!=null?go(v):v}else i[g]=this.resolveBindings(h,t,a)}else Array.isArray(h)?i[g]=h.map(f=>typeof f=="string"?this.resolveBindings(f,t,a):typeof f=="object"&&f!==null?this.resolveObject(f,t,a):f):h&&typeof h=="object"?i[g]=this.resolveObject(h,t,a):i[g]=h}return i}clearCache(){this.cache.clear(),this.expressionFnCache.clear()}invalidateCacheByKeys(e){for(const t of this.cache.keys())for(const a of e)if(t===a||t.startsWith(`${a}.`)||t.startsWith(`${a}[`)){this.cache.delete(t);break}}pruneCache(){const e=Date.now();for(const[t,a]of this.cache.entries())e-a.timestamp>Ea.CACHE_EXPIRY&&this.cache.delete(t)}getCacheStats(){const e=Date.now();let t=0;for(const a of this.cache.values())e-a.timestamp>Ea.CACHE_EXPIRY&&t++;return{size:this.cache.size,expired:t}}evaluateExpression(e,t,a){const i=tc(),o=i?.isEnabled()?performance.now():0;i?.isEnabled()&&i.trackBindingEval();try{let d=this.preprocessOptionalChaining(e);d=this.preprocessTranslationTokens(d);const g=this.extractVariablesFromExpression(d),h={...t};for(const D of g)D in h||(h[D]=void 0);t._computed&&!h.$computed&&(h.$computed=t._computed);const f=t.$locale||"ko";h.$localized=D=>D==null?"":typeof D=="string"?D:typeof D=="object"?D[f]||D.ko||D.en||Object.values(D)[0]||"":String(D);const p=typeof window<"u"?window.G7Core:void 0;h.$uuid=()=>p?.uuid?p.uuid():typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,D=>{const $=Math.random()*16|0;return(D==="x"?$:$&3|8).toString(16)});let y=t.$templateId,x=f;if(!y&&typeof window<"u"){const $=window.__templateApp?.getConfig?.();$?.templateId&&(y=$.templateId,!t.$locale&&$.locale&&(x=$.locale))}const S={templateId:y||"",locale:x};h.$t=D=>{if(!D||typeof D!="string")return"";try{return xr.getInstance().translate(D,S)}catch($){return ho.warn("$t() translation failed for key:",D,$),D}},h.$get=(D,$,M=void 0)=>{if(D==null)return M;const z=Array.isArray($)?$:[$];if(z.length===0)return D;let K=D;for(const pe of z){if(K==null||pe==null)return M;K=K[pe]}return K??M};const v=Object.keys(h),w=Object.values(h),k=`${d}|${v.join(",")}`;let A=this.expressionFnCache.get(k);const O=!!A;A||(A=new Function(...v,`return (${d});`),this.expressionFnCache.set(k,A));const N=A(...w);if(i?.isEnabled()){const D=performance.now()-o;i.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(N),resultType:this.getResultType(N),componentId:a?.componentId,componentName:a?.componentName,propName:a?.propName,fromCache:O,duration:D,method:"evaluateExpression",skipCache:a?.skipCache})}return N}catch(d){throw new Error(`Failed to evaluate expression "${e}": ${d instanceof Error?d.message:String(d)}`)}}getResultType(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}sanitizeResultForTracking(e){if(e==null||typeof e!="object")return e;try{if(Array.isArray(e))return e.length>10?`[Array(${e.length})]`:e.slice(0,10);const t=Object.keys(e);return t.length>20?`{Object(${t.length} keys)}`:(JSON.stringify(e),e)}catch{return"[Complex Object]"}}preprocessTranslationTokens(e){return e=e.replace(/(['"])(\$t:([a-zA-Z_][a-zA-Z0-9_.\-]*))\1/g,(t,a,i,o)=>`$t('${o}')`),e.replace(/(?(t.push(o),`__STRING_LITERAL_${t.length-1}__`));const i=[];return a=a.replace(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*(?:\|[^'"\s,)]+)?/g,o=>(i.push(o),`__TRANSLATION_TOKEN_${i.length-1}__`)),a=a.replace(/([a-zA-Z_$][a-zA-Z0-9_$]*)\.(?!\?)/g,"$1?."),a=a.replace(/__TRANSLATION_TOKEN_(\d+)__/g,(o,d)=>i[parseInt(d,10)]),a=a.replace(/__STRING_LITERAL_(\d+)__/g,(o,d)=>t[parseInt(d,10)]),a}extractVariablesFromExpression(e){const t=new Set(["true","false","null","undefined","NaN","Infinity","if","else","for","while","do","switch","case","break","continue","return","function","class","const","let","var","new","delete","typeof","instanceof","this","super","import","export","default","try","catch","finally","throw","Math","Date","JSON","Array","Object","String","Number","Boolean","RegExp","parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent"]),a=/(?{t!==null&&clearTimeout(t),t=setTimeout(()=>{r(...a)},e)})}class Aw{constructor(){H(this,"subscribers",new Set);H(this,"currentWidth",1024);H(this,"debouncedHandler",null);H(this,"isInitialized",!1);this.initialize()}initialize(){typeof window>"u"||(this.currentWidth=window.innerWidth,this.isInitialized=!0,this.debouncedHandler=_w(()=>{this.currentWidth=window.innerWidth,this.notifySubscribers()},150),window.addEventListener("resize",this.debouncedHandler))}notifySubscribers(){this.subscribers.forEach(e=>{e(this.currentWidth)})}subscribe(e){return this.subscribers.add(e),e(this.currentWidth),()=>{this.subscribers.delete(e)}}getWidth(){return this.currentWidth}parseRange(e){if(nc.has(e))return nc.get(e)??null;let t=null;if(Gu[e])t={...Gu[e]};else{const a=e.match(/^(-?\d*)-(-?\d*)$/);if(a){const[,i,o]=a,d=i===""?0:parseInt(i,10),g=o===""?1/0:parseInt(o,10);!isNaN(d)&&!isNaN(g)&&d<=g&&(t={min:d,max:g})}}return nc.set(e,t),t}getMatchingKey(e,t){const a=[];for(const i of Object.keys(e)){const o=this.parseRange(i);o&&t>=o.min&&t<=o.max&&a.push({key:i,range:o,isPreset:!!Gu[i]})}return a.length===0?null:(a.sort((i,o)=>{if(i.isPreset!==o.isPreset)return i.isPreset?1:-1;const d=i.range.max-i.range.min,g=o.range.max-o.range.min;return d-g}),a[0].key)}matches(e){const t=this.parseRange(e);return t?this.currentWidth>=t.min&&this.currentWidth<=t.max:!1}clearSubscribers(){this.subscribers.clear()}destroy(){this.debouncedHandler&&typeof window<"u"&&window.removeEventListener("resize",this.debouncedHandler),this.clearSubscribers(),nc.clear()}_setWidthForTesting(e){this.currentWidth=e,this.notifySubscribers()}}const ei=new Aw,ac=it("ConditionEvaluator");function Tw(r){switch(r){case"true":return{value:!0};case"false":return{value:!1};case"null":return{value:null};case"undefined":return{value:void 0};default:return}}function Dw(r){return/[?:|&!+\-*/<>=()]/.test(r)}function Rw(r){if(!r.startsWith("{{")||!r.endsWith("}}"))return null;const e=r.slice(2,-2);let t=null,a=0;for(let i=0;i0?e[i-1]:"")!=="\\"&&((o==='"'||o==="'")&&!t?t=o:o===t&&(t=null),!t&&(o==="{"&&a++,o==="}"&&a--,a<0)))return null}return a===0?e.trim():null}function Ow(r,e,t){if(!r)return!0;try{const a=Rw(r);let i;if(a!==null){const o=Tw(a);o!==void 0?i=o.value:Dw(a)?i=t.evaluateExpression(a,e):i=t.resolve(a,e,{skipCache:!0})}else i=t.resolveBindings(r,e,{skipCache:!0});if(typeof i=="string"){const o=i.toLowerCase().trim();if(o==="false"||o==="0"||o===""||o==="null"||o==="undefined")return!1}return!!i}catch(a){return ac.warn(`evaluateStringCondition: 조건 평가 실패: ${r}`,a),!1}}function sc(r,e,t){if(typeof r=="string")return Ow(r,e,t);if("and"in r){if(!Array.isArray(r.and)||r.and.length===0)return ac.warn("evaluateConditionExpression: AND 그룹이 비어있습니다"),!0;for(const a of r.and)if(!sc(a,e,t))return!1;return!0}if("or"in r){if(!Array.isArray(r.or)||r.or.length===0)return ac.warn("evaluateConditionExpression: OR 그룹이 비어있습니다"),!1;for(const a of r.or)if(sc(a,e,t))return!0;return!1}return ac.warn("evaluateConditionExpression: 알 수 없는 조건 형식",r),!1}function Wp(r,e,t){if(!Array.isArray(r)||r.length===0)return{matched:!1,branchIndex:-1};for(let a=0;a=()]/.test(r)}function Xp(r){if(!r.startsWith("{{")||!r.endsWith("}}"))return null;const e=r.slice(2,-2);let t=null,a=0;for(let i=0;i0?e[i-1]:"")!=="\\"&&((o==='"'||o==="'")&&!t?t=o:o===t&&(t=null),!t&&(o==="{"&&a++,o==="}"&&a--,a<0)))return null}return a===0?e.trim():null}function Vu(r,e,t){let a=r;if(r.startsWith("{{")&&r.endsWith("}}")&&(a=r.slice(2,-2).trim()),Fu(a))try{return t.evaluateExpression(a,e)}catch(i){ts.warn(`resolveIterationSource: 표현식 평가 실패: ${r}`,i);return}return t.resolve(a,e,{skipCache:!0})}function Iw(r,e){const t={...r};if(e?.parentDataContext)for(const[a,i]of Object.entries(e.parentDataContext))a in t||(t[a]=i);if(e?.state){const a=t._local||{};t._local={...a,...e.state}}return e?.isolatedContext?.state&&(t._isolated=e.isolatedContext.state),t}function Ku(r,e,t,a){if(!e||!Array.isArray(e)||e.length===0)return r;const i=a?.actionDispatcher??Fm(),o={...r,actions:e},d=i.bindActionsToProps(o,t,a?.componentContext);return delete d.actions,d}function Qp(r,e,t,a){if(typeof r=="boolean")return r;if(!r)return!0;try{const i=Xp(r);let o;if(i!==null){const d=$w.get(i);d!==void 0?o=d:Fu(i)?o=t.evaluateExpression(i,e):o=t.resolve(i,e,{skipCache:!0})}else o=t.resolveBindings(r,e,{skipCache:!0});if(typeof o=="string"){const d=o.toLowerCase().trim();if(d==="false"||d==="0"||d===""||d==="null"||d==="undefined")return!1}return!!o}catch(i){return ts.warn(`evaluateIfCondition: 조건 평가 실패 (컴포넌트: ${a||"unknown"}):`,i),!1}}function ti(r,e,t,a){if(r.if!==void 0)return Qp(r.if,e,t,a);if(r.condition!==void 0)return Qp(r.condition,e,t,a);if(r.conditions===void 0)return!0;const i=r.conditions;try{return Lw(i)?sc(i,e,t):Mw(i)?Wp(i,e,t).matched:(ts.warn(`evaluateRenderCondition: 알 수 없는 conditions 형식 (컴포넌트: ${a||"unknown"})`),!0)}catch(o){return ts.warn(`evaluateRenderCondition: conditions 평가 실패 (컴포넌트: ${a||"unknown"}):`,o),!1}}function Zp(r){if(!r.responsive)return r;const e=ei.getWidth(),t=ei.getMatchingKey(r.responsive,e);if(!t)return r;const a=r.responsive[t];return{...r,props:{...r.props,...a.props},children:a.children??r.children,text:a.text??r.text,if:a.if??r.if,iteration:a.iteration??r.iteration}}function fo(r,e,t,a,i){if(!r||r.length===0)return[];const o=i?.bindingEngine??new _n,d=i?.translationEngine??xr.getInstance(),g=i?.translationContext??{templateId:"",locale:"ko"},h=Iw(e,i?.componentContext),f=(x,S)=>{if(typeof x=="string"){if(Fp(x))return Kp(x);if(Vp(x)){const w=[],k=x.replace(new RegExp(`${ec}([^${co}]*)${co}`,"g"),(O,N)=>(w.push(N),`${Rs}${w.length-1}${Rs}`));let A=k;return/\$t:[a-zA-Z0-9._-]+/.test(k)&&(A=d.resolveTranslations(k,g,S)),A.replace(new RegExp(`${Rs}(\\d+)${Rs}`,"g"),(O,N)=>w[parseInt(N)])}if(x.startsWith("$t:defer:")){const w="$t:"+x.slice(9);return d.resolveTranslations(w,g,S)}if(x.startsWith("$t:"))return d.resolveTranslations(x,g,S);const v=Xp(x);if(v!==null){let w=!1,k=v;v.startsWith(Ds)&&(w=!0,k=v.slice(Ds.length));let A;if(Fu(k))try{A=o.evaluateExpression(k,S)}catch(O){ts.warn("renderItemChildren: 표현식 평가 실패:",O);return}else A=o.resolve(k,S,{skipCache:!0});return!w&&typeof A=="string"&&/\$t:[a-zA-Z0-9._-]+/.test(A)&&(A=d.resolveTranslations(A,g,S)),w&&A!=null?go(A):A}if(x.includes("{{")){const w=o.resolveBindings(x,S,{skipCache:!0});return typeof w=="string"&&/\$t:[a-zA-Z0-9._-]+/.test(w)?d.resolveTranslations(w,g,S):w}return x}if(Array.isArray(x))return x.map(v=>f(v,S));if(x&&typeof x=="object"){const v={};for(const[w,k]of Object.entries(x))v[w]=f(k,S);return v}return x},p=(x,S)=>{if(!x)return{};const v={};for(const[w,k]of Object.entries(x))v[w]=f(k,S);return v},y=(x,S,v)=>{const w=Zp(x),k=w.iteration;if(!k)return[];const A=Vu(k.source,v,o);if(!Array.isArray(A))return ts.warn(`renderItemChildren: iteration.source가 배열이 아닙니다: ${k.source}`),[];const O=Yp();if(O?.isEnabled()){const D=`${S}-iteration`;O.trackIteration(D,k.source,k.item_var,k.index_var,A.length)}const N=t[w.name];return N?A.flatMap((D,$)=>{const M={...v,[k.item_var]:D,[`${k.item_var}_index`]:$,...k.index_var?{[k.index_var]:$}:{}},z=ti({if:w.if,condition:w.condition,conditions:w.conditions},M,o,w.id);if(w.if&&O?.isEnabled()){const de=`${S}-iter-${$}-if`;O.trackIfCondition(de,w.if,z,w.name)}if(!z)return[];const K=w.id?String(f(w.id,M)):void 0,pe=`${S}-iter-${$}`,we=i?.getRemountKey?i.getRemountKey(K,pe):pe,J=p(w.props,M),be=Ku(J,w.actions,M,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let le=null;return w.text!==void 0?le=f(w.text,M):w.children&&w.children.length>0&&(le=fo(w.children,M,t,we,i)),O?.isEnabled()&&O.trackRender(w.name),[Ke.createElement(N,{key:we,...be},le)]}):(ts.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${w.name}`),[])};return r.flatMap((x,S)=>{const v=Zp(x),w=v.id?String(f(v.id,h)):void 0,k=a?`${a}-${w||S}`:w||`child-${S}`,A=i?.getRemountKey?i.getRemountKey(w,k):k;if(v.iteration)return y(v,A,h);const O=ti({if:v.if,condition:v.condition,conditions:v.conditions},h,o,v.id),N=Yp();if(v.if&&N?.isEnabled()){const K=`${A}-if`;N.trackIfCondition(K,v.if,O,v.name)}if(!O)return[];const D=t[v.name];if(!D)return ts.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${v.name}`),[];const $=p(v.props,h),M=Ku($,v.actions,h,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let z=null;return v.text!==void 0?z=f(v.text,h):v.children&&v.children.length>0&&(z=fo(v.children,h,t,A,i)),N?.isEnabled()&&N.trackRender(v.name),[Ke.createElement(D,{key:A,...M},z)]})}function ni(r,e,t,a){let i,o;return t instanceof _n?(i=t,o=a):(i=Jp,o=t),i.resolveBindings(r,e,o)}function zw(r,e,t,a){const i=t??Jp,o={skipCache:!0,...a};let d;try{d=i.resolveBindings(r.key,e,{skipCache:o.skipCache})?.toString()?.trim()??""}catch(f){ts.warn("resolveClassMap: key 평가 실패:",r.key,f),d=""}let g="";d&&r.variants&&d in r.variants?g=r.variants[d]:r.default&&(g=r.default);const h=[];return r.base?.trim()&&h.push(r.base.trim()),g?.trim()&&h.push(g.trim()),h.join(" ")}function em(r,e){return function(){return r.apply(e,arguments)}}const{toString:Hw}=Object.prototype,{getPrototypeOf:Wu}=Object,{iterator:rc,toStringTag:tm}=Symbol,ic=(r=>e=>{const t=Hw.call(e);return r[t]||(r[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),va=r=>(r=r.toLowerCase(),e=>ic(e)===r),oc=r=>e=>typeof e===r,{isArray:ai}=Array,si=oc("undefined");function po(r){return r!==null&&!si(r)&&r.constructor!==null&&!si(r.constructor)&&Rn(r.constructor.isBuffer)&&r.constructor.isBuffer(r)}const nm=va("ArrayBuffer");function Pw(r){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(r):e=r&&r.buffer&&nm(r.buffer),e}const Bw=oc("string"),Rn=oc("function"),am=oc("number"),mo=r=>r!==null&&typeof r=="object",Uw=r=>r===!0||r===!1,lc=r=>{if(ic(r)!=="object")return!1;const e=Wu(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(tm in r)&&!(rc in r)},qw=r=>{if(!mo(r)||po(r))return!1;try{return Object.keys(r).length===0&&Object.getPrototypeOf(r)===Object.prototype}catch{return!1}},Gw=va("Date"),Fw=va("File"),Vw=va("Blob"),Kw=va("FileList"),Ww=r=>mo(r)&&Rn(r.pipe),Yw=r=>{let e;return r&&(typeof FormData=="function"&&r instanceof FormData||Rn(r.append)&&((e=ic(r))==="formdata"||e==="object"&&Rn(r.toString)&&r.toString()==="[object FormData]"))},Jw=va("URLSearchParams"),[Xw,Qw,Zw,eS]=["ReadableStream","Request","Response","Headers"].map(va),tS=r=>r.trim?r.trim():r.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function yo(r,e,{allOwnKeys:t=!1}={}){if(r===null||typeof r>"u")return;let a,i;if(typeof r!="object"&&(r=[r]),ai(r))for(a=0,i=r.length;a0;)if(i=t[a],e===i.toLowerCase())return i;return null}const br=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,rm=r=>!si(r)&&r!==br;function Yu(){const{caseless:r,skipUndefined:e}=rm(this)&&this||{},t={},a=(i,o)=>{const d=r&&sm(t,o)||o;lc(t[d])&&lc(i)?t[d]=Yu(t[d],i):lc(i)?t[d]=Yu({},i):ai(i)?t[d]=i.slice():(!e||!si(i))&&(t[d]=i)};for(let i=0,o=arguments.length;i(yo(e,(i,o)=>{t&&Rn(i)?r[o]=em(i,t):r[o]=i},{allOwnKeys:a}),r),aS=r=>(r.charCodeAt(0)===65279&&(r=r.slice(1)),r),sS=(r,e,t,a)=>{r.prototype=Object.create(e.prototype,a),r.prototype.constructor=r,Object.defineProperty(r,"super",{value:e.prototype}),t&&Object.assign(r.prototype,t)},rS=(r,e,t,a)=>{let i,o,d;const g={};if(e=e||{},r==null)return e;do{for(i=Object.getOwnPropertyNames(r),o=i.length;o-- >0;)d=i[o],(!a||a(d,r,e))&&!g[d]&&(e[d]=r[d],g[d]=!0);r=t!==!1&&Wu(r)}while(r&&(!t||t(r,e))&&r!==Object.prototype);return e},iS=(r,e,t)=>{r=String(r),(t===void 0||t>r.length)&&(t=r.length),t-=e.length;const a=r.indexOf(e,t);return a!==-1&&a===t},oS=r=>{if(!r)return null;if(ai(r))return r;let e=r.length;if(!am(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=r[e];return t},lS=(r=>e=>r&&e instanceof r)(typeof Uint8Array<"u"&&Wu(Uint8Array)),cS=(r,e)=>{const a=(r&&r[rc]).call(r);let i;for(;(i=a.next())&&!i.done;){const o=i.value;e.call(r,o[0],o[1])}},dS=(r,e)=>{let t;const a=[];for(;(t=r.exec(e))!==null;)a.push(t);return a},uS=va("HTMLFormElement"),gS=r=>r.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,a,i){return a.toUpperCase()+i}),im=(({hasOwnProperty:r})=>(e,t)=>r.call(e,t))(Object.prototype),hS=va("RegExp"),om=(r,e)=>{const t=Object.getOwnPropertyDescriptors(r),a={};yo(t,(i,o)=>{let d;(d=e(i,o,r))!==!1&&(a[o]=d||i)}),Object.defineProperties(r,a)},fS=r=>{om(r,(e,t)=>{if(Rn(r)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const a=r[t];if(Rn(a)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},pS=(r,e)=>{const t={},a=i=>{i.forEach(o=>{t[o]=!0})};return ai(r)?a(r):a(String(r).split(e)),t},mS=()=>{},yS=(r,e)=>r!=null&&Number.isFinite(r=+r)?r:e;function xS(r){return!!(r&&Rn(r.append)&&r[tm]==="FormData"&&r[rc])}const bS=r=>{const e=new Array(10),t=(a,i)=>{if(mo(a)){if(e.indexOf(a)>=0)return;if(po(a))return a;if(!("toJSON"in a)){e[i]=a;const o=ai(a)?[]:{};return yo(a,(d,g)=>{const h=t(d,i+1);!si(h)&&(o[g]=h)}),e[i]=void 0,o}}return a};return t(r,0)},vS=va("AsyncFunction"),wS=r=>r&&(mo(r)||Rn(r))&&Rn(r.then)&&Rn(r.catch),lm=((r,e)=>r?setImmediate:e?((t,a)=>(br.addEventListener("message",({source:i,data:o})=>{i===br&&o===t&&a.length&&a.shift()()},!1),i=>{a.push(i),br.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",Rn(br.postMessage)),SS=typeof queueMicrotask<"u"?queueMicrotask.bind(br):typeof process<"u"&&process.nextTick||lm,se={isArray:ai,isArrayBuffer:nm,isBuffer:po,isFormData:Yw,isArrayBufferView:Pw,isString:Bw,isNumber:am,isBoolean:Uw,isObject:mo,isPlainObject:lc,isEmptyObject:qw,isReadableStream:Xw,isRequest:Qw,isResponse:Zw,isHeaders:eS,isUndefined:si,isDate:Gw,isFile:Fw,isBlob:Vw,isRegExp:hS,isFunction:Rn,isStream:Ww,isURLSearchParams:Jw,isTypedArray:lS,isFileList:Kw,forEach:yo,merge:Yu,extend:nS,trim:tS,stripBOM:aS,inherits:sS,toFlatObject:rS,kindOf:ic,kindOfTest:va,endsWith:iS,toArray:oS,forEachEntry:cS,matchAll:dS,isHTMLForm:uS,hasOwnProperty:im,hasOwnProp:im,reduceDescriptors:om,freezeMethods:fS,toObjectSet:pS,toCamelCase:gS,noop:mS,toFiniteNumber:yS,findKey:sm,global:br,isContextDefined:rm,isSpecCompliantForm:xS,toJSONObject:bS,isAsyncFn:vS,isThenable:wS,setImmediate:lm,asap:SS,isIterable:r=>r!=null&&Rn(r[rc])};function nt(r,e,t,a,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=r,this.name="AxiosError",e&&(this.code=e),t&&(this.config=t),a&&(this.request=a),i&&(this.response=i,this.status=i.status?i.status:null)}se.inherits(nt,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:se.toJSONObject(this.config),code:this.code,status:this.status}}});const cm=nt.prototype,dm={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(r=>{dm[r]={value:r}}),Object.defineProperties(nt,dm),Object.defineProperty(cm,"isAxiosError",{value:!0}),nt.from=(r,e,t,a,i,o)=>{const d=Object.create(cm);se.toFlatObject(r,d,function(p){return p!==Error.prototype},f=>f!=="isAxiosError");const g=r&&r.message?r.message:"Error",h=e==null&&r?r.code:e;return nt.call(d,g,h,t,a,i),r&&d.cause==null&&Object.defineProperty(d,"cause",{value:r,configurable:!0}),d.name=r&&r.name||"Error",o&&Object.assign(d,o),d};const CS=null;function Ju(r){return se.isPlainObject(r)||se.isArray(r)}function um(r){return se.endsWith(r,"[]")?r.slice(0,-2):r}function gm(r,e,t){return r?r.concat(e).map(function(i,o){return i=um(i),!t&&o?"["+i+"]":i}).join(t?".":""):e}function jS(r){return se.isArray(r)&&!r.some(Ju)}const kS=se.toFlatObject(se,{},null,function(e){return/^is[A-Z]/.test(e)});function cc(r,e,t){if(!se.isObject(r))throw new TypeError("target must be an object");e=e||new FormData,t=se.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(w,k){return!se.isUndefined(k[w])});const a=t.metaTokens,i=t.visitor||p,o=t.dots,d=t.indexes,h=(t.Blob||typeof Blob<"u"&&Blob)&&se.isSpecCompliantForm(e);if(!se.isFunction(i))throw new TypeError("visitor must be a function");function f(v){if(v===null)return"";if(se.isDate(v))return v.toISOString();if(se.isBoolean(v))return v.toString();if(!h&&se.isBlob(v))throw new nt("Blob is not supported. Use a Buffer instead.");return se.isArrayBuffer(v)||se.isTypedArray(v)?h&&typeof Blob=="function"?new Blob([v]):Buffer.from(v):v}function p(v,w,k){let A=v;if(v&&!k&&typeof v=="object"){if(se.endsWith(w,"{}"))w=a?w:w.slice(0,-2),v=JSON.stringify(v);else if(se.isArray(v)&&jS(v)||(se.isFileList(v)||se.endsWith(w,"[]"))&&(A=se.toArray(v)))return w=um(w),A.forEach(function(N,D){!(se.isUndefined(N)||N===null)&&e.append(d===!0?gm([w],D,o):d===null?w:w+"[]",f(N))}),!1}return Ju(v)?!0:(e.append(gm(k,w,o),f(v)),!1)}const y=[],x=Object.assign(kS,{defaultVisitor:p,convertValue:f,isVisitable:Ju});function S(v,w){if(!se.isUndefined(v)){if(y.indexOf(v)!==-1)throw Error("Circular reference detected in "+w.join("."));y.push(v),se.forEach(v,function(A,O){(!(se.isUndefined(A)||A===null)&&i.call(e,A,se.isString(O)?O.trim():O,w,x))===!0&&S(A,w?w.concat(O):[O])}),y.pop()}}if(!se.isObject(r))throw new TypeError("data must be an object");return S(r),e}function hm(r){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(r).replace(/[!'()~]|%20|%00/g,function(a){return e[a]})}function Xu(r,e){this._pairs=[],r&&cc(r,this,e)}const fm=Xu.prototype;fm.append=function(e,t){this._pairs.push([e,t])},fm.toString=function(e){const t=e?function(a){return e.call(this,a,hm)}:hm;return this._pairs.map(function(i){return t(i[0])+"="+t(i[1])},"").join("&")};function NS(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function pm(r,e,t){if(!e)return r;const a=t&&t.encode||NS;se.isFunction(t)&&(t={serialize:t});const i=t&&t.serialize;let o;if(i?o=i(e,t):o=se.isURLSearchParams(e)?e.toString():new Xu(e,t).toString(a),o){const d=r.indexOf("#");d!==-1&&(r=r.slice(0,d)),r+=(r.indexOf("?")===-1?"?":"&")+o}return r}class mm{constructor(){this.handlers=[]}use(e,t,a){return this.handlers.push({fulfilled:e,rejected:t,synchronous:a?a.synchronous:!1,runWhen:a?a.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){se.forEach(this.handlers,function(a){a!==null&&e(a)})}}const ym={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},ES={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:Xu,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},Qu=typeof window<"u"&&typeof document<"u",Zu=typeof navigator=="object"&&navigator||void 0,_S=Qu&&(!Zu||["ReactNative","NativeScript","NS"].indexOf(Zu.product)<0),AS=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",TS=Qu&&window.location.href||"http://localhost",Nn={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Qu,hasStandardBrowserEnv:_S,hasStandardBrowserWebWorkerEnv:AS,navigator:Zu,origin:TS},Symbol.toStringTag,{value:"Module"})),...ES};function DS(r,e){return cc(r,new Nn.classes.URLSearchParams,{visitor:function(t,a,i,o){return Nn.isNode&&se.isBuffer(t)?(this.append(a,t.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...e})}function RS(r){return se.matchAll(/\w+|\[(\w*)]/g,r).map(e=>e[0]==="[]"?"":e[1]||e[0])}function OS(r){const e={},t=Object.keys(r);let a;const i=t.length;let o;for(a=0;a=t.length;return d=!d&&se.isArray(i)?i.length:d,h?(se.hasOwnProp(i,d)?i[d]=[i[d],a]:i[d]=a,!g):((!i[d]||!se.isObject(i[d]))&&(i[d]=[]),e(t,a,i[d],o)&&se.isArray(i[d])&&(i[d]=OS(i[d])),!g)}if(se.isFormData(r)&&se.isFunction(r.entries)){const t={};return se.forEachEntry(r,(a,i)=>{e(RS(a),i,t,0)}),t}return null}function LS(r,e,t){if(se.isString(r))try{return(e||JSON.parse)(r),se.trim(r)}catch(a){if(a.name!=="SyntaxError")throw a}return(t||JSON.stringify)(r)}const xo={transitional:ym,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const a=t.getContentType()||"",i=a.indexOf("application/json")>-1,o=se.isObject(e);if(o&&se.isHTMLForm(e)&&(e=new FormData(e)),se.isFormData(e))return i?JSON.stringify(xm(e)):e;if(se.isArrayBuffer(e)||se.isBuffer(e)||se.isStream(e)||se.isFile(e)||se.isBlob(e)||se.isReadableStream(e))return e;if(se.isArrayBufferView(e))return e.buffer;if(se.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let g;if(o){if(a.indexOf("application/x-www-form-urlencoded")>-1)return DS(e,this.formSerializer).toString();if((g=se.isFileList(e))||a.indexOf("multipart/form-data")>-1){const h=this.env&&this.env.FormData;return cc(g?{"files[]":e}:e,h&&new h,this.formSerializer)}}return o||i?(t.setContentType("application/json",!1),LS(e)):e}],transformResponse:[function(e){const t=this.transitional||xo.transitional,a=t&&t.forcedJSONParsing,i=this.responseType==="json";if(se.isResponse(e)||se.isReadableStream(e))return e;if(e&&se.isString(e)&&(a&&!this.responseType||i)){const d=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e,this.parseReviver)}catch(g){if(d)throw g.name==="SyntaxError"?nt.from(g,nt.ERR_BAD_RESPONSE,this,null,this.response):g}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Nn.classes.FormData,Blob:Nn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};se.forEach(["delete","get","head","post","put","patch"],r=>{xo.headers[r]={}});const MS=se.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),$S=r=>{const e={};let t,a,i;return r&&r.split(` -`).forEach(function(d){i=d.indexOf(":"),t=d.substring(0,i).trim().toLowerCase(),a=d.substring(i+1).trim(),!(!t||e[t]&&MS[t])&&(t==="set-cookie"?e[t]?e[t].push(a):e[t]=[a]:e[t]=e[t]?e[t]+", "+a:a)}),e},bm=Symbol("internals");function bo(r){return r&&String(r).trim().toLowerCase()}function dc(r){return r===!1||r==null?r:se.isArray(r)?r.map(dc):String(r)}function IS(r){const e=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let a;for(;a=t.exec(r);)e[a[1]]=a[2];return e}const zS=r=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(r.trim());function eg(r,e,t,a,i){if(se.isFunction(a))return a.call(this,e,t);if(i&&(e=t),!!se.isString(e)){if(se.isString(a))return e.indexOf(a)!==-1;if(se.isRegExp(a))return a.test(e)}}function HS(r){return r.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,a)=>t.toUpperCase()+a)}function PS(r,e){const t=se.toCamelCase(" "+e);["get","set","has"].forEach(a=>{Object.defineProperty(r,a+t,{value:function(i,o,d){return this[a].call(this,e,i,o,d)},configurable:!0})})}let On=class{constructor(e){e&&this.set(e)}set(e,t,a){const i=this;function o(g,h,f){const p=bo(h);if(!p)throw new Error("header name must be a non-empty string");const y=se.findKey(i,p);(!y||i[y]===void 0||f===!0||f===void 0&&i[y]!==!1)&&(i[y||h]=dc(g))}const d=(g,h)=>se.forEach(g,(f,p)=>o(f,p,h));if(se.isPlainObject(e)||e instanceof this.constructor)d(e,t);else if(se.isString(e)&&(e=e.trim())&&!zS(e))d($S(e),t);else if(se.isObject(e)&&se.isIterable(e)){let g={},h,f;for(const p of e){if(!se.isArray(p))throw TypeError("Object iterator must return a key-value pair");g[f=p[0]]=(h=g[f])?se.isArray(h)?[...h,p[1]]:[h,p[1]]:p[1]}d(g,t)}else e!=null&&o(t,e,a);return this}get(e,t){if(e=bo(e),e){const a=se.findKey(this,e);if(a){const i=this[a];if(!t)return i;if(t===!0)return IS(i);if(se.isFunction(t))return t.call(this,i,a);if(se.isRegExp(t))return t.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=bo(e),e){const a=se.findKey(this,e);return!!(a&&this[a]!==void 0&&(!t||eg(this,this[a],a,t)))}return!1}delete(e,t){const a=this;let i=!1;function o(d){if(d=bo(d),d){const g=se.findKey(a,d);g&&(!t||eg(a,a[g],g,t))&&(delete a[g],i=!0)}}return se.isArray(e)?e.forEach(o):o(e),i}clear(e){const t=Object.keys(this);let a=t.length,i=!1;for(;a--;){const o=t[a];(!e||eg(this,this[o],o,e,!0))&&(delete this[o],i=!0)}return i}normalize(e){const t=this,a={};return se.forEach(this,(i,o)=>{const d=se.findKey(a,o);if(d){t[d]=dc(i),delete t[o];return}const g=e?HS(o):String(o).trim();g!==o&&delete t[o],t[g]=dc(i),a[g]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return se.forEach(this,(a,i)=>{a!=null&&a!==!1&&(t[i]=e&&se.isArray(a)?a.join(", "):a)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join(` -`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const a=new this(e);return t.forEach(i=>a.set(i)),a}static accessor(e){const a=(this[bm]=this[bm]={accessors:{}}).accessors,i=this.prototype;function o(d){const g=bo(d);a[g]||(PS(i,d),a[g]=!0)}return se.isArray(e)?e.forEach(o):o(e),this}};On.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),se.reduceDescriptors(On.prototype,({value:r},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>r,set(a){this[t]=a}}}),se.freezeMethods(On);function tg(r,e){const t=this||xo,a=e||t,i=On.from(a.headers);let o=a.data;return se.forEach(r,function(g){o=g.call(t,o,i.normalize(),e?e.status:void 0)}),i.normalize(),o}function vm(r){return!!(r&&r.__CANCEL__)}function ri(r,e,t){nt.call(this,r??"canceled",nt.ERR_CANCELED,e,t),this.name="CanceledError"}se.inherits(ri,nt,{__CANCEL__:!0});function wm(r,e,t){const a=t.config.validateStatus;!t.status||!a||a(t.status)?r(t):e(new nt("Request failed with status code "+t.status,[nt.ERR_BAD_REQUEST,nt.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function BS(r){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(r);return e&&e[1]||""}function US(r,e){r=r||10;const t=new Array(r),a=new Array(r);let i=0,o=0,d;return e=e!==void 0?e:1e3,function(h){const f=Date.now(),p=a[o];d||(d=f),t[i]=h,a[i]=f;let y=o,x=0;for(;y!==i;)x+=t[y++],y=y%r;if(i=(i+1)%r,i===o&&(o=(o+1)%r),f-d{t=p,i=null,o&&(clearTimeout(o),o=null),r(...f)};return[(...f)=>{const p=Date.now(),y=p-t;y>=a?d(f,p):(i=f,o||(o=setTimeout(()=>{o=null,d(i)},a-y)))},()=>i&&d(i)]}const uc=(r,e,t=3)=>{let a=0;const i=US(50,250);return qS(o=>{const d=o.loaded,g=o.lengthComputable?o.total:void 0,h=d-a,f=i(h),p=d<=g;a=d;const y={loaded:d,total:g,progress:g?d/g:void 0,bytes:h,rate:f||void 0,estimated:f&&g&&p?(g-d)/f:void 0,event:o,lengthComputable:g!=null,[e?"download":"upload"]:!0};r(y)},t)},Sm=(r,e)=>{const t=r!=null;return[a=>e[0]({lengthComputable:t,total:r,loaded:a}),e[1]]},Cm=r=>(...e)=>se.asap(()=>r(...e)),GS=Nn.hasStandardBrowserEnv?((r,e)=>t=>(t=new URL(t,Nn.origin),r.protocol===t.protocol&&r.host===t.host&&(e||r.port===t.port)))(new URL(Nn.origin),Nn.navigator&&/(msie|trident)/i.test(Nn.navigator.userAgent)):()=>!0,FS=Nn.hasStandardBrowserEnv?{write(r,e,t,a,i,o){const d=[r+"="+encodeURIComponent(e)];se.isNumber(t)&&d.push("expires="+new Date(t).toGMTString()),se.isString(a)&&d.push("path="+a),se.isString(i)&&d.push("domain="+i),o===!0&&d.push("secure"),document.cookie=d.join("; ")},read(r){const e=document.cookie.match(new RegExp("(^|;\\s*)("+r+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(r){this.write(r,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function VS(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function KS(r,e){return e?r.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):r}function jm(r,e,t){let a=!VS(e);return r&&(a||t==!1)?KS(r,e):e}const km=r=>r instanceof On?{...r}:r;function vr(r,e){e=e||{};const t={};function a(f,p,y,x){return se.isPlainObject(f)&&se.isPlainObject(p)?se.merge.call({caseless:x},f,p):se.isPlainObject(p)?se.merge({},p):se.isArray(p)?p.slice():p}function i(f,p,y,x){if(se.isUndefined(p)){if(!se.isUndefined(f))return a(void 0,f,y,x)}else return a(f,p,y,x)}function o(f,p){if(!se.isUndefined(p))return a(void 0,p)}function d(f,p){if(se.isUndefined(p)){if(!se.isUndefined(f))return a(void 0,f)}else return a(void 0,p)}function g(f,p,y){if(y in e)return a(f,p);if(y in r)return a(void 0,f)}const h={url:o,method:o,data:o,baseURL:d,transformRequest:d,transformResponse:d,paramsSerializer:d,timeout:d,timeoutMessage:d,withCredentials:d,withXSRFToken:d,adapter:d,responseType:d,xsrfCookieName:d,xsrfHeaderName:d,onUploadProgress:d,onDownloadProgress:d,decompress:d,maxContentLength:d,maxBodyLength:d,beforeRedirect:d,transport:d,httpAgent:d,httpsAgent:d,cancelToken:d,socketPath:d,responseEncoding:d,validateStatus:g,headers:(f,p,y)=>i(km(f),km(p),y,!0)};return se.forEach(Object.keys({...r,...e}),function(p){const y=h[p]||i,x=y(r[p],e[p],p);se.isUndefined(x)&&y!==g||(t[p]=x)}),t}const Nm=r=>{const e=vr({},r);let{data:t,withXSRFToken:a,xsrfHeaderName:i,xsrfCookieName:o,headers:d,auth:g}=e;if(e.headers=d=On.from(d),e.url=pm(jm(e.baseURL,e.url,e.allowAbsoluteUrls),r.params,r.paramsSerializer),g&&d.set("Authorization","Basic "+btoa((g.username||"")+":"+(g.password?unescape(encodeURIComponent(g.password)):""))),se.isFormData(t)){if(Nn.hasStandardBrowserEnv||Nn.hasStandardBrowserWebWorkerEnv)d.setContentType(void 0);else if(se.isFunction(t.getHeaders)){const h=t.getHeaders(),f=["content-type","content-length"];Object.entries(h).forEach(([p,y])=>{f.includes(p.toLowerCase())&&d.set(p,y)})}}if(Nn.hasStandardBrowserEnv&&(a&&se.isFunction(a)&&(a=a(e)),a||a!==!1&&GS(e.url))){const h=i&&o&&FS.read(o);h&&d.set(i,h)}return e},WS=typeof XMLHttpRequest<"u"&&function(r){return new Promise(function(t,a){const i=Nm(r);let o=i.data;const d=On.from(i.headers).normalize();let{responseType:g,onUploadProgress:h,onDownloadProgress:f}=i,p,y,x,S,v;function w(){S&&S(),v&&v(),i.cancelToken&&i.cancelToken.unsubscribe(p),i.signal&&i.signal.removeEventListener("abort",p)}let k=new XMLHttpRequest;k.open(i.method.toUpperCase(),i.url,!0),k.timeout=i.timeout;function A(){if(!k)return;const N=On.from("getAllResponseHeaders"in k&&k.getAllResponseHeaders()),$={data:!g||g==="text"||g==="json"?k.responseText:k.response,status:k.status,statusText:k.statusText,headers:N,config:r,request:k};wm(function(z){t(z),w()},function(z){a(z),w()},$),k=null}"onloadend"in k?k.onloadend=A:k.onreadystatechange=function(){!k||k.readyState!==4||k.status===0&&!(k.responseURL&&k.responseURL.indexOf("file:")===0)||setTimeout(A)},k.onabort=function(){k&&(a(new nt("Request aborted",nt.ECONNABORTED,r,k)),k=null)},k.onerror=function(D){const $=D&&D.message?D.message:"Network Error",M=new nt($,nt.ERR_NETWORK,r,k);M.event=D||null,a(M),k=null},k.ontimeout=function(){let D=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const $=i.transitional||ym;i.timeoutErrorMessage&&(D=i.timeoutErrorMessage),a(new nt(D,$.clarifyTimeoutError?nt.ETIMEDOUT:nt.ECONNABORTED,r,k)),k=null},o===void 0&&d.setContentType(null),"setRequestHeader"in k&&se.forEach(d.toJSON(),function(D,$){k.setRequestHeader($,D)}),se.isUndefined(i.withCredentials)||(k.withCredentials=!!i.withCredentials),g&&g!=="json"&&(k.responseType=i.responseType),f&&([x,v]=uc(f,!0),k.addEventListener("progress",x)),h&&k.upload&&([y,S]=uc(h),k.upload.addEventListener("progress",y),k.upload.addEventListener("loadend",S)),(i.cancelToken||i.signal)&&(p=N=>{k&&(a(!N||N.type?new ri(null,r,k):N),k.abort(),k=null)},i.cancelToken&&i.cancelToken.subscribe(p),i.signal&&(i.signal.aborted?p():i.signal.addEventListener("abort",p)));const O=BS(i.url);if(O&&Nn.protocols.indexOf(O)===-1){a(new nt("Unsupported protocol "+O+":",nt.ERR_BAD_REQUEST,r));return}k.send(o||null)})},YS=(r,e)=>{const{length:t}=r=r?r.filter(Boolean):[];if(e||t){let a=new AbortController,i;const o=function(f){if(!i){i=!0,g();const p=f instanceof Error?f:this.reason;a.abort(p instanceof nt?p:new ri(p instanceof Error?p.message:p))}};let d=e&&setTimeout(()=>{d=null,o(new nt(`timeout ${e} of ms exceeded`,nt.ETIMEDOUT))},e);const g=()=>{r&&(d&&clearTimeout(d),d=null,r.forEach(f=>{f.unsubscribe?f.unsubscribe(o):f.removeEventListener("abort",o)}),r=null)};r.forEach(f=>f.addEventListener("abort",o));const{signal:h}=a;return h.unsubscribe=()=>se.asap(g),h}},JS=function*(r,e){let t=r.byteLength;if(t{const i=XS(r,e);let o=0,d,g=h=>{d||(d=!0,a&&a(h))};return new ReadableStream({async pull(h){try{const{done:f,value:p}=await i.next();if(f){g(),h.close();return}let y=p.byteLength;if(t){let x=o+=y;t(x)}h.enqueue(new Uint8Array(p))}catch(f){throw g(f),f}},cancel(h){return g(h),i.return()}},{highWaterMark:2})},_m=64*1024,{isFunction:gc}=se,ZS=(({Request:r,Response:e})=>({Request:r,Response:e}))(se.global),{ReadableStream:Am,TextEncoder:Tm}=se.global,Dm=(r,...e)=>{try{return!!r(...e)}catch{return!1}},e7=r=>{r=se.merge.call({skipUndefined:!0},ZS,r);const{fetch:e,Request:t,Response:a}=r,i=e?gc(e):typeof fetch=="function",o=gc(t),d=gc(a);if(!i)return!1;const g=i&&gc(Am),h=i&&(typeof Tm=="function"?(v=>w=>v.encode(w))(new Tm):async v=>new Uint8Array(await new t(v).arrayBuffer())),f=o&&g&&Dm(()=>{let v=!1;const w=new t(Nn.origin,{body:new Am,method:"POST",get duplex(){return v=!0,"half"}}).headers.has("Content-Type");return v&&!w}),p=d&&g&&Dm(()=>se.isReadableStream(new a("").body)),y={stream:p&&(v=>v.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(v=>{!y[v]&&(y[v]=(w,k)=>{let A=w&&w[v];if(A)return A.call(w);throw new nt(`Response type '${v}' is not supported`,nt.ERR_NOT_SUPPORT,k)})});const x=async v=>{if(v==null)return 0;if(se.isBlob(v))return v.size;if(se.isSpecCompliantForm(v))return(await new t(Nn.origin,{method:"POST",body:v}).arrayBuffer()).byteLength;if(se.isArrayBufferView(v)||se.isArrayBuffer(v))return v.byteLength;if(se.isURLSearchParams(v)&&(v=v+""),se.isString(v))return(await h(v)).byteLength},S=async(v,w)=>{const k=se.toFiniteNumber(v.getContentLength());return k??x(w)};return async v=>{let{url:w,method:k,data:A,signal:O,cancelToken:N,timeout:D,onDownloadProgress:$,onUploadProgress:M,responseType:z,headers:K,withCredentials:pe="same-origin",fetchOptions:we}=Nm(v),J=e||fetch;z=z?(z+"").toLowerCase():"text";let be=YS([O,N&&N.toAbortSignal()],D),le=null;const de=be&&be.unsubscribe&&(()=>{be.unsubscribe()});let je;try{if(M&&f&&k!=="get"&&k!=="head"&&(je=await S(K,A))!==0){let R=new t(w,{method:"POST",body:A,duplex:"half"}),U;if(se.isFormData(A)&&(U=R.headers.get("content-type"))&&K.setContentType(U),R.body){const[re,ye]=Sm(je,uc(Cm(M)));A=Em(R.body,_m,re,ye)}}se.isString(pe)||(pe=pe?"include":"omit");const W=o&&"credentials"in t.prototype,ge={...we,signal:be,method:k.toUpperCase(),headers:K.normalize().toJSON(),body:A,duplex:"half",credentials:W?pe:void 0};le=o&&new t(w,ge);let ne=await(o?J(le,we):J(w,ge));const X=p&&(z==="stream"||z==="response");if(p&&($||X&&de)){const R={};["status","statusText","headers"].forEach(oe=>{R[oe]=ne[oe]});const U=se.toFiniteNumber(ne.headers.get("content-length")),[re,ye]=$&&Sm(U,uc(Cm($),!0))||[];ne=new a(Em(ne.body,_m,re,()=>{ye&&ye(),de&&de()}),R)}z=z||"text";let ae=await y[se.findKey(y,z)||"text"](ne,v);return!X&&de&&de(),await new Promise((R,U)=>{wm(R,U,{data:ae,headers:On.from(ne.headers),status:ne.status,statusText:ne.statusText,config:v,request:le})})}catch(W){throw de&&de(),W&&W.name==="TypeError"&&/Load failed|fetch/i.test(W.message)?Object.assign(new nt("Network Error",nt.ERR_NETWORK,v,le),{cause:W.cause||W}):nt.from(W,W&&W.code,v,le)}}},t7=new Map,Rm=r=>{let e=r?r.env:{};const{fetch:t,Request:a,Response:i}=e,o=[a,i,t];let d=o.length,g=d,h,f,p=t7;for(;g--;)h=o[g],f=p.get(h),f===void 0&&p.set(h,f=g?new Map:e7(e)),p=f;return f};Rm();const ng={http:CS,xhr:WS,fetch:{get:Rm}};se.forEach(ng,(r,e)=>{if(r){try{Object.defineProperty(r,"name",{value:e})}catch{}Object.defineProperty(r,"adapterName",{value:e})}});const Om=r=>`- ${r}`,n7=r=>se.isFunction(r)||r===null||r===!1,Lm={getAdapter:(r,e)=>{r=se.isArray(r)?r:[r];const{length:t}=r;let a,i;const o={};for(let d=0;d`adapter ${h} `+(f===!1?"is not supported by the environment":"is not available in the build"));let g=t?d.length>1?`since : +`+u.stack}}var Ge=Object.prototype.hasOwnProperty,at=r.unstable_scheduleCallback,pt=r.unstable_cancelCallback,bt=r.unstable_shouldYield,_t=r.unstable_requestPaint,mt=r.unstable_now,tt=r.unstable_getCurrentPriorityLevel,bn=r.unstable_ImmediatePriority,wt=r.unstable_UserBlockingPriority,Tt=r.unstable_NormalPriority,qt=r.unstable_LowPriority,Yn=r.unstable_IdlePriority,dn=r.log,Ta=r.unstable_setDisableYieldValue,ca=null,V=null;function me(n){if(typeof dn=="function"&&Ta(n),V&&typeof V.setStrictMode=="function")try{V.setStrictMode(ca,n)}catch{}}var ue=Math.clz32?Math.clz32:Ae,ne=Math.log,_e=Math.LN2;function Ae(n){return n>>>=0,n===0?32:31-(ne(n)/_e|0)|0}var Re=256,Be=262144,Ue=4194304;function Le(n){var s=n&42;if(s!==0)return s;switch(n&-n){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return n&261888;case 262144:case 524288:case 1048576:case 2097152:return n&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return n&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return n}}function Fe(n,s,c){var u=n.pendingLanes;if(u===0)return 0;var m=0,b=n.suspendedLanes,E=n.pingedLanes;n=n.warmLanes;var L=u&134217727;return L!==0?(u=L&~b,u!==0?m=Le(u):(E&=L,E!==0?m=Le(E):c||(c=L&~n,c!==0&&(m=Le(c))))):(L=u&~b,L!==0?m=Le(L):E!==0?m=Le(E):c||(c=u&~n,c!==0&&(m=Le(c)))),m===0?0:s!==0&&s!==m&&(s&b)===0&&(b=m&-m,c=s&-s,b>=c||b===32&&(c&4194048)!==0)?s:m}function We(n,s){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&s)===0}function Je(n,s){switch(n){case 1:case 2:case 4:case 8:case 64:return s+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return s+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function st(){var n=Ue;return Ue<<=1,(Ue&62914560)===0&&(Ue=4194304),n}function He(n){for(var s=[],c=0;31>c;c++)s.push(n);return s}function De(n,s){n.pendingLanes|=s,s!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function $e(n,s,c,u,m,b){var E=n.pendingLanes;n.pendingLanes=c,n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0,n.expiredLanes&=c,n.entangledLanes&=c,n.errorRecoveryDisabledLanes&=c,n.shellSuspendCounter=0;var L=n.entanglements,B=n.expirationTimes,Z=n.hiddenUpdates;for(c=E&~c;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var Tr=/[\n"\\]/g;function Pn(n){return n.replace(Tr,function(s){return"\\"+s.charCodeAt(0).toString(16)+" "})}function hs(n,s,c,u,m,b,E,L){n.name="",E!=null&&typeof E!="function"&&typeof E!="symbol"&&typeof E!="boolean"?n.type=E:n.removeAttribute("type"),s!=null?E==="number"?(s===0&&n.value===""||n.value!=s)&&(n.value=""+Hn(s)):n.value!==""+Hn(s)&&(n.value=""+Hn(s)):E!=="submit"&&E!=="reset"||n.removeAttribute("value"),s!=null?tl(n,E,Hn(s)):c!=null?tl(n,E,Hn(c)):u!=null&&n.removeAttribute("value"),m==null&&b!=null&&(n.defaultChecked=!!b),m!=null&&(n.checked=m&&typeof m!="function"&&typeof m!="symbol"),L!=null&&typeof L!="function"&&typeof L!="symbol"&&typeof L!="boolean"?n.name=""+Hn(L):n.removeAttribute("name")}function md(n,s,c,u,m,b,E,L){if(b!=null&&typeof b!="function"&&typeof b!="symbol"&&typeof b!="boolean"&&(n.type=b),s!=null||c!=null){if(!(b!=="submit"&&b!=="reset"||s!=null)){Zo(n);return}c=c!=null?""+Hn(c):"",s=s!=null?""+Hn(s):c,L||s===n.value||(n.value=s),n.defaultValue=s}u=u??m,u=typeof u!="function"&&typeof u!="symbol"&&!!u,n.checked=L?n.checked:!!u,n.defaultChecked=!!u,E!=null&&typeof E!="function"&&typeof E!="symbol"&&typeof E!="boolean"&&(n.name=E),Zo(n)}function tl(n,s,c){s==="number"&&gs(n.ownerDocument)===n||n.defaultValue===""+c||(n.defaultValue=""+c)}function qs(n,s,c,u){if(n=n.options,s){s={};for(var m=0;m"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),rl=!1;if(Oa)try{var Rr={};Object.defineProperty(Rr,"passive",{get:function(){rl=!0}}),window.addEventListener("test",Rr,Rr),window.removeEventListener("test",Rr,Rr)}catch{rl=!1}var La=null,il=null,Ei=null;function Xe(){if(Ei)return Ei;var n,s=il,c=s.length,u,m="value"in La?La.value:La.textContent,b=m.length;for(n=0;n=yt),kd=" ",gl=!1;function Nd(n,s){switch(n){case"keyup":return Qe.indexOf(s.keyCode)!==-1;case"keydown":return s.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function hl(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var Ws=!1;function Ed(n,s){switch(n){case"compositionend":return hl(s);case"keypress":return s.which!==32?null:(gl=!0,kd);case"textInput":return n=s.data,n===kd&&gl?null:n;default:return null}}function Mh(n,s){if(Ws)return n==="compositionend"||!ut&&Nd(n,s)?(n=Xe(),Ei=il=La=null,Ws=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(s.ctrlKey||s.altKey||s.metaKey)||s.ctrlKey&&s.altKey){if(s.char&&1=s)return{node:c,offset:s-n};n=u}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=ab(c)}}function rb(n,s){return n&&s?n===s?!0:n&&n.nodeType===3?!1:s&&s.nodeType===3?rb(n,s.parentNode):"contains"in n?n.contains(s):n.compareDocumentPosition?!!(n.compareDocumentPosition(s)&16):!1:!1}function ib(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var s=gs(n.document);s instanceof n.HTMLIFrameElement;){try{var c=typeof s.contentWindow.location.href=="string"}catch{c=!1}if(c)n=s.contentWindow;else break;s=gs(n.document)}return s}function Ih(n){var s=n&&n.nodeName&&n.nodeName.toLowerCase();return s&&(s==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||s==="textarea"||n.contentEditable==="true")}var l_=Oa&&"documentMode"in document&&11>=document.documentMode,Di=null,zh=null,wl=null,Hh=!1;function ob(n,s,c){var u=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Hh||Di==null||Di!==gs(u)||(u=Di,"selectionStart"in u&&Ih(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),wl&&vl(wl,u)||(wl=u,u=yu(zh,"onSelect"),0>=E,m-=E,Ya=1<<32-ue(s)+m|c<ot?(ht=Pe,Pe=null):ht=Pe.sibling;var jt=te(Y,Pe,Q[ot],pe);if(jt===null){Pe===null&&(Pe=ht);break}n&&Pe&&jt.alternate===null&&s(Y,Pe),F=b(jt,F,ot),Ct===null?Ve=jt:Ct.sibling=jt,Ct=jt,Pe=ht}if(ot===Q.length)return c(Y,Pe),xt&&ys(Y,ot),Ve;if(Pe===null){for(;otot?(ht=Pe,Pe=null):ht=Pe.sibling;var yr=te(Y,Pe,jt.value,pe);if(yr===null){Pe===null&&(Pe=ht);break}n&&Pe&&yr.alternate===null&&s(Y,Pe),F=b(yr,F,ot),Ct===null?Ve=yr:Ct.sibling=yr,Ct=yr,Pe=ht}if(jt.done)return c(Y,Pe),xt&&ys(Y,ot),Ve;if(Pe===null){for(;!jt.done;ot++,jt=Q.next())jt=be(Y,jt.value,pe),jt!==null&&(F=b(jt,F,ot),Ct===null?Ve=jt:Ct.sibling=jt,Ct=jt);return xt&&ys(Y,ot),Ve}for(Pe=u(Pe);!jt.done;ot++,jt=Q.next())jt=ie(Pe,Y,ot,jt.value,pe),jt!==null&&(n&&jt.alternate!==null&&Pe.delete(jt.key===null?ot:jt.key),F=b(jt,F,ot),Ct===null?Ve=jt:Ct.sibling=jt,Ct=jt);return n&&Pe.forEach(function(_1){return s(Y,_1)}),xt&&ys(Y,ot),Ve}function zt(Y,F,Q,pe){if(typeof Q=="object"&&Q!==null&&Q.type===w&&Q.key===null&&(Q=Q.props.children),typeof Q=="object"&&Q!==null){switch(Q.$$typeof){case S:e:{for(var Ve=Q.key;F!==null;){if(F.key===Ve){if(Ve=Q.type,Ve===w){if(F.tag===7){c(Y,F.sibling),pe=m(F,Q.props.children),pe.return=Y,Y=pe;break e}}else if(F.elementType===Ve||typeof Ve=="object"&&Ve!==null&&Ve.$$typeof===K&&Gr(Ve)===F.type){c(Y,F.sibling),pe=m(F,Q.props),El(pe,Q),pe.return=Y,Y=pe;break e}c(Y,F);break}else s(Y,F);F=F.sibling}Q.type===w?(pe=Hr(Q.props.children,Y.mode,pe,Q.key),pe.return=Y,Y=pe):(pe=Ld(Q.type,Q.key,Q.props,null,Y.mode,pe),El(pe,Q),pe.return=Y,Y=pe)}return E(Y);case v:e:{for(Ve=Q.key;F!==null;){if(F.key===Ve)if(F.tag===4&&F.stateNode.containerInfo===Q.containerInfo&&F.stateNode.implementation===Q.implementation){c(Y,F.sibling),pe=m(F,Q.children||[]),pe.return=Y,Y=pe;break e}else{c(Y,F);break}else s(Y,F);F=F.sibling}pe=Vh(Q,Y.mode,pe),pe.return=Y,Y=pe}return E(Y);case K:return Q=Gr(Q),zt(Y,F,Q,pe)}if(je(Q))return Me(Y,F,Q,pe);if(ve(Q)){if(Ve=ve(Q),typeof Ve!="function")throw Error(a(150));return Q=Ve.call(Q),Ye(Y,F,Q,pe)}if(typeof Q.then=="function")return zt(Y,F,Bd(Q),pe);if(Q.$$typeof===N)return zt(Y,F,Id(Y,Q),pe);Ud(Y,Q)}return typeof Q=="string"&&Q!==""||typeof Q=="number"||typeof Q=="bigint"?(Q=""+Q,F!==null&&F.tag===6?(c(Y,F.sibling),pe=m(F,Q),pe.return=Y,Y=pe):(c(Y,F),pe=Fh(Q,Y.mode,pe),pe.return=Y,Y=pe),E(Y)):c(Y,F)}return function(Y,F,Q,pe){try{Nl=0;var Ve=zt(Y,F,Q,pe);return Ui=null,Ve}catch(Pe){if(Pe===Bi||Pe===Hd)throw Pe;var Ct=Zn(29,Pe,null,Y.mode);return Ct.lanes=pe,Ct.return=Y,Ct}finally{}}}var Vr=Tb(!0),Db=Tb(!1),er=!1;function sf(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function rf(n,s){n=n.updateQueue,s.updateQueue===n&&(s.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function tr(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function nr(n,s,c){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(At&2)!==0){var m=u.pending;return m===null?s.next=s:(s.next=m.next,m.next=s),u.pending=s,s=Od(n),fb(n,null,c),s}return Rd(n,u,s,c),Od(n)}function _l(n,s,c){if(s=s.updateQueue,s!==null&&(s=s.shared,(c&4194048)!==0)){var u=s.lanes;u&=n.pendingLanes,c|=u,s.lanes=c,Dt(n,c)}}function of(n,s){var c=n.updateQueue,u=n.alternate;if(u!==null&&(u=u.updateQueue,c===u)){var m=null,b=null;if(c=c.firstBaseUpdate,c!==null){do{var E={lane:c.lane,tag:c.tag,payload:c.payload,callback:null,next:null};b===null?m=b=E:b=b.next=E,c=c.next}while(c!==null);b===null?m=b=s:b=b.next=s}else m=b=s;c={baseState:u.baseState,firstBaseUpdate:m,lastBaseUpdate:b,shared:u.shared,callbacks:u.callbacks},n.updateQueue=c;return}n=c.lastBaseUpdate,n===null?c.firstBaseUpdate=s:n.next=s,c.lastBaseUpdate=s}var lf=!1;function Al(){if(lf){var n=Pi;if(n!==null)throw n}}function Tl(n,s,c,u){lf=!1;var m=n.updateQueue;er=!1;var b=m.firstBaseUpdate,E=m.lastBaseUpdate,L=m.shared.pending;if(L!==null){m.shared.pending=null;var B=L,Z=B.next;B.next=null,E===null?b=Z:E.next=Z,E=B;var ce=n.alternate;ce!==null&&(ce=ce.updateQueue,L=ce.lastBaseUpdate,L!==E&&(L===null?ce.firstBaseUpdate=Z:L.next=Z,ce.lastBaseUpdate=B))}if(b!==null){var be=m.baseState;E=0,ce=Z=B=null,L=b;do{var te=L.lane&-536870913,ie=te!==L.lane;if(ie?(gt&te)===te:(u&te)===te){te!==0&&te===Hi&&(lf=!0),ce!==null&&(ce=ce.next={lane:0,tag:L.tag,payload:L.payload,callback:null,next:null});e:{var Me=n,Ye=L;te=s;var zt=c;switch(Ye.tag){case 1:if(Me=Ye.payload,typeof Me=="function"){be=Me.call(zt,be,te);break e}be=Me;break e;case 3:Me.flags=Me.flags&-65537|128;case 0:if(Me=Ye.payload,te=typeof Me=="function"?Me.call(zt,be,te):Me,te==null)break e;be=y({},be,te);break e;case 2:er=!0}}te=L.callback,te!==null&&(n.flags|=64,ie&&(n.flags|=8192),ie=m.callbacks,ie===null?m.callbacks=[te]:ie.push(te))}else ie={lane:te,tag:L.tag,payload:L.payload,callback:L.callback,next:null},ce===null?(Z=ce=ie,B=be):ce=ce.next=ie,E|=te;if(L=L.next,L===null){if(L=m.shared.pending,L===null)break;ie=L,L=ie.next,ie.next=null,m.lastBaseUpdate=ie,m.shared.pending=null}}while(!0);ce===null&&(B=be),m.baseState=B,m.firstBaseUpdate=Z,m.lastBaseUpdate=ce,b===null&&(m.shared.lanes=0),or|=E,n.lanes=E,n.memoizedState=be}}function Rb(n,s){if(typeof n!="function")throw Error(a(191,n));n.call(s)}function Ob(n,s){var c=n.callbacks;if(c!==null)for(n.callbacks=null,n=0;nb?b:8;var E=W.T,L={};W.T=L,Ef(n,!1,s,c);try{var B=m(),Z=W.S;if(Z!==null&&Z(L,B),B!==null&&typeof B=="object"&&typeof B.then=="function"){var ce=y_(B,u);Ol(n,s,ce,sa(n))}else Ol(n,s,u,sa(n))}catch(be){Ol(n,s,{then:function(){},status:"rejected",reason:be},sa())}finally{he.p=b,E!==null&&L.types!==null&&(E.types=L.types),W.T=E}}function C_(){}function kf(n,s,c,u){if(n.tag!==5)throw Error(a(476));var m=u0(n).queue;d0(n,m,s,ee,c===null?C_:function(){return g0(n),c(u)})}function u0(n){var s=n.memoizedState;if(s!==null)return s;s={memoizedState:ee,baseState:ee,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ws,lastRenderedState:ee},next:null};var c={};return s.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ws,lastRenderedState:c},next:null},n.memoizedState=s,n=n.alternate,n!==null&&(n.memoizedState=s),s}function g0(n){var s=u0(n);s.next===null&&(s=n.alternate.memoizedState),Ol(n,s.next.queue,{},sa())}function Nf(){return Sn(Jl)}function h0(){return en().memoizedState}function f0(){return en().memoizedState}function j_(n){for(var s=n.return;s!==null;){switch(s.tag){case 24:case 3:var c=sa();n=tr(c);var u=nr(s,n,c);u!==null&&(Fn(u,s,c),_l(u,s,c)),s={cache:ef()},n.payload=s;return}s=s.return}}function k_(n,s,c){var u=sa();c={lane:u,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Qd(n)?m0(s,c):(c=qh(n,s,c,u),c!==null&&(Fn(c,n,u),y0(c,s,u)))}function p0(n,s,c){var u=sa();Ol(n,s,c,u)}function Ol(n,s,c,u){var m={lane:u,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null};if(Qd(n))m0(s,m);else{var b=n.alternate;if(n.lanes===0&&(b===null||b.lanes===0)&&(b=s.lastRenderedReducer,b!==null))try{var E=s.lastRenderedState,L=b(E,c);if(m.hasEagerState=!0,m.eagerState=L,Qn(L,E))return Rd(n,s,m,0),Ht===null&&Dd(),!1}catch{}finally{}if(c=qh(n,s,m,u),c!==null)return Fn(c,n,u),y0(c,s,u),!0}return!1}function Ef(n,s,c,u){if(u={lane:2,revertLane:rp(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Qd(n)){if(s)throw Error(a(479))}else s=qh(n,c,u,2),s!==null&&Fn(s,n,2)}function Qd(n){var s=n.alternate;return n===rt||s!==null&&s===rt}function m0(n,s){Gi=Fd=!0;var c=n.pending;c===null?s.next=s:(s.next=c.next,c.next=s),n.pending=s}function y0(n,s,c){if((c&4194048)!==0){var u=s.lanes;u&=n.pendingLanes,c|=u,s.lanes=c,Dt(n,c)}}var Ll={readContext:Sn,use:Wd,useCallback:Wt,useContext:Wt,useEffect:Wt,useImperativeHandle:Wt,useLayoutEffect:Wt,useInsertionEffect:Wt,useMemo:Wt,useReducer:Wt,useRef:Wt,useState:Wt,useDebugValue:Wt,useDeferredValue:Wt,useTransition:Wt,useSyncExternalStore:Wt,useId:Wt,useHostTransitionStatus:Wt,useFormState:Wt,useActionState:Wt,useOptimistic:Wt,useMemoCache:Wt,useCacheRefresh:Wt};Ll.useEffectEvent=Wt;var x0={readContext:Sn,use:Wd,useCallback:function(n,s){return Dn().memoizedState=[n,s===void 0?null:s],n},useContext:Sn,useEffect:t0,useImperativeHandle:function(n,s,c){c=c!=null?c.concat([n]):null,Jd(4194308,4,r0.bind(null,s,n),c)},useLayoutEffect:function(n,s){return Jd(4194308,4,n,s)},useInsertionEffect:function(n,s){Jd(4,2,n,s)},useMemo:function(n,s){var c=Dn();s=s===void 0?null:s;var u=n();if(Kr){me(!0);try{n()}finally{me(!1)}}return c.memoizedState=[u,s],u},useReducer:function(n,s,c){var u=Dn();if(c!==void 0){var m=c(s);if(Kr){me(!0);try{c(s)}finally{me(!1)}}}else m=s;return u.memoizedState=u.baseState=m,n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:m},u.queue=n,n=n.dispatch=k_.bind(null,rt,n),[u.memoizedState,n]},useRef:function(n){var s=Dn();return n={current:n},s.memoizedState=n},useState:function(n){n=vf(n);var s=n.queue,c=p0.bind(null,rt,s);return s.dispatch=c,[n.memoizedState,c]},useDebugValue:Cf,useDeferredValue:function(n,s){var c=Dn();return jf(c,n,s)},useTransition:function(){var n=vf(!1);return n=d0.bind(null,rt,n.queue,!0,!1),Dn().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,s,c){var u=rt,m=Dn();if(xt){if(c===void 0)throw Error(a(407));c=c()}else{if(c=s(),Ht===null)throw Error(a(349));(gt&127)!==0||Hb(u,s,c)}m.memoizedState=c;var b={value:c,getSnapshot:s};return m.queue=b,t0(Bb.bind(null,u,b,n),[n]),u.flags|=2048,Vi(9,{destroy:void 0},Pb.bind(null,u,b,c,s),null),c},useId:function(){var n=Dn(),s=Ht.identifierPrefix;if(xt){var c=Ja,u=Ya;c=(u&~(1<<32-ue(u)-1)).toString(32)+c,s="_"+s+"R_"+c,c=Vd++,0<\/script>",b=b.removeChild(b.firstChild);break;case"select":b=typeof u.is=="string"?E.createElement("select",{is:u.is}):E.createElement("select"),u.multiple?b.multiple=!0:u.size&&(b.size=u.size);break;default:b=typeof u.is=="string"?E.createElement(m,{is:u.is}):E.createElement(m)}}b[un]=s,b[vn]=u;e:for(E=s.child;E!==null;){if(E.tag===5||E.tag===6)b.appendChild(E.stateNode);else if(E.tag!==4&&E.tag!==27&&E.child!==null){E.child.return=E,E=E.child;continue}if(E===s)break e;for(;E.sibling===null;){if(E.return===null||E.return===s)break e;E=E.return}E.sibling.return=E.return,E=E.sibling}s.stateNode=b;e:switch(jn(b,m,u),m){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&Cs(s)}}return Bt(s),Bf(s,s.type,n===null?null:n.memoizedProps,s.pendingProps,c),null;case 6:if(n&&s.stateNode!=null)n.memoizedProps!==u&&Cs(s);else{if(typeof u!="string"&&s.stateNode===null)throw Error(a(166));if(n=ke.current,Ii(s)){if(n=s.stateNode,c=s.memoizedProps,u=null,m=wn,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[un]=s,n=!!(n.nodeValue===c||u!==null&&u.suppressHydrationWarning===!0||Iv(n.nodeValue,c)),n||Qs(s,!0)}else n=xu(n).createTextNode(u),n[un]=s,s.stateNode=n}return Bt(s),null;case 31:if(c=s.memoizedState,n===null||n.memoizedState!==null){if(u=Ii(s),c!==null){if(n===null){if(!u)throw Error(a(318));if(n=s.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(a(557));n[un]=s}else Pr(),(s.flags&128)===0&&(s.memoizedState=null),s.flags|=4;Bt(s),n=!1}else c=Jh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=c),n=!0;if(!n)return s.flags&256?(ta(s),s):(ta(s),null);if((s.flags&128)!==0)throw Error(a(558))}return Bt(s),null;case 13:if(u=s.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=Ii(s),u!==null&&u.dehydrated!==null){if(n===null){if(!m)throw Error(a(318));if(m=s.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(a(317));m[un]=s}else Pr(),(s.flags&128)===0&&(s.memoizedState=null),s.flags|=4;Bt(s),m=!1}else m=Jh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return s.flags&256?(ta(s),s):(ta(s),null)}return ta(s),(s.flags&128)!==0?(s.lanes=c,s):(c=u!==null,n=n!==null&&n.memoizedState!==null,c&&(u=s.child,m=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(m=u.alternate.memoizedState.cachePool.pool),b=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(b=u.memoizedState.cachePool.pool),b!==m&&(u.flags|=2048)),c!==n&&c&&(s.child.flags|=8192),au(s,s.updateQueue),Bt(s),null);case 4:return qe(),n===null&&cp(s.stateNode.containerInfo),Bt(s),null;case 10:return bs(s.type),Bt(s),null;case 19:if(U(Zt),u=s.memoizedState,u===null)return Bt(s),null;if(m=(s.flags&128)!==0,b=u.rendering,b===null)if(m)$l(u,!1);else{if(Yt!==0||n!==null&&(n.flags&128)!==0)for(n=s.child;n!==null;){if(b=Gd(n),b!==null){for(s.flags|=128,$l(u,!1),n=b.updateQueue,s.updateQueue=n,au(s,n),s.subtreeFlags=0,n=c,c=s.child;c!==null;)pb(c,n),c=c.sibling;return re(Zt,Zt.current&1|2),xt&&ys(s,u.treeForkCount),s.child}n=n.sibling}u.tail!==null&&mt()>lu&&(s.flags|=128,m=!0,$l(u,!1),s.lanes=4194304)}else{if(!m)if(n=Gd(b),n!==null){if(s.flags|=128,m=!0,n=n.updateQueue,s.updateQueue=n,au(s,n),$l(u,!0),u.tail===null&&u.tailMode==="hidden"&&!b.alternate&&!xt)return Bt(s),null}else 2*mt()-u.renderingStartTime>lu&&c!==536870912&&(s.flags|=128,m=!0,$l(u,!1),s.lanes=4194304);u.isBackwards?(b.sibling=s.child,s.child=b):(n=u.last,n!==null?n.sibling=b:s.child=b,u.last=b)}return u.tail!==null?(n=u.tail,u.rendering=n,u.tail=n.sibling,u.renderingStartTime=mt(),n.sibling=null,c=Zt.current,re(Zt,m?c&1|2:c&1),xt&&ys(s,u.treeForkCount),n):(Bt(s),null);case 22:case 23:return ta(s),df(),u=s.memoizedState!==null,n!==null?n.memoizedState!==null!==u&&(s.flags|=8192):u&&(s.flags|=8192),u?(c&536870912)!==0&&(s.flags&128)===0&&(Bt(s),s.subtreeFlags&6&&(s.flags|=8192)):Bt(s),c=s.updateQueue,c!==null&&au(s,c.retryQueue),c=null,n!==null&&n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(c=n.memoizedState.cachePool.pool),u=null,s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(u=s.memoizedState.cachePool.pool),u!==c&&(s.flags|=2048),n!==null&&U(qr),null;case 24:return c=null,n!==null&&(c=n.memoizedState.cache),s.memoizedState.cache!==c&&(s.flags|=2048),bs(an),Bt(s),null;case 25:return null;case 30:return null}throw Error(a(156,s.tag))}function T_(n,s){switch(Wh(s),s.tag){case 1:return n=s.flags,n&65536?(s.flags=n&-65537|128,s):null;case 3:return bs(an),qe(),n=s.flags,(n&65536)!==0&&(n&128)===0?(s.flags=n&-65537|128,s):null;case 26:case 27:case 5:return Nt(s),null;case 31:if(s.memoizedState!==null){if(ta(s),s.alternate===null)throw Error(a(340));Pr()}return n=s.flags,n&65536?(s.flags=n&-65537|128,s):null;case 13:if(ta(s),n=s.memoizedState,n!==null&&n.dehydrated!==null){if(s.alternate===null)throw Error(a(340));Pr()}return n=s.flags,n&65536?(s.flags=n&-65537|128,s):null;case 19:return U(Zt),null;case 4:return qe(),null;case 10:return bs(s.type),null;case 22:case 23:return ta(s),df(),n!==null&&U(qr),n=s.flags,n&65536?(s.flags=n&-65537|128,s):null;case 24:return bs(an),null;case 25:return null;default:return null}}function U0(n,s){switch(Wh(s),s.tag){case 3:bs(an),qe();break;case 26:case 27:case 5:Nt(s);break;case 4:qe();break;case 31:s.memoizedState!==null&&ta(s);break;case 13:ta(s);break;case 19:U(Zt);break;case 10:bs(s.type);break;case 22:case 23:ta(s),df(),n!==null&&U(qr);break;case 24:bs(an)}}function Il(n,s){try{var c=s.updateQueue,u=c!==null?c.lastEffect:null;if(u!==null){var m=u.next;c=m;do{if((c.tag&n)===n){u=void 0;var b=c.create,E=c.inst;u=b(),E.destroy=u}c=c.next}while(c!==m)}}catch(L){Lt(s,s.return,L)}}function rr(n,s,c){try{var u=s.updateQueue,m=u!==null?u.lastEffect:null;if(m!==null){var b=m.next;u=b;do{if((u.tag&n)===n){var E=u.inst,L=E.destroy;if(L!==void 0){E.destroy=void 0,m=s;var B=c,Z=L;try{Z()}catch(ce){Lt(m,B,ce)}}}u=u.next}while(u!==b)}}catch(ce){Lt(s,s.return,ce)}}function q0(n){var s=n.updateQueue;if(s!==null){var c=n.stateNode;try{Ob(s,c)}catch(u){Lt(n,n.return,u)}}}function G0(n,s,c){c.props=Wr(n.type,n.memoizedProps),c.state=n.memoizedState;try{c.componentWillUnmount()}catch(u){Lt(n,s,u)}}function zl(n,s){try{var c=n.ref;if(c!==null){switch(n.tag){case 26:case 27:case 5:var u=n.stateNode;break;case 30:u=n.stateNode;break;default:u=n.stateNode}typeof c=="function"?n.refCleanup=c(u):c.current=u}}catch(m){Lt(n,s,m)}}function Xa(n,s){var c=n.ref,u=n.refCleanup;if(c!==null)if(typeof u=="function")try{u()}catch(m){Lt(n,s,m)}finally{n.refCleanup=null,n=n.alternate,n!=null&&(n.refCleanup=null)}else if(typeof c=="function")try{c(null)}catch(m){Lt(n,s,m)}else c.current=null}function F0(n){var s=n.type,c=n.memoizedProps,u=n.stateNode;try{e:switch(s){case"button":case"input":case"select":case"textarea":c.autoFocus&&u.focus();break e;case"img":c.src?u.src=c.src:c.srcSet&&(u.srcset=c.srcSet)}}catch(m){Lt(n,n.return,m)}}function Uf(n,s,c){try{var u=n.stateNode;Q_(u,n.type,c,s),u[vn]=s}catch(m){Lt(n,n.return,m)}}function V0(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&gr(n.type)||n.tag===4}function qf(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||V0(n.return))return null;n=n.return}for(n.sibling.return=n.return,n=n.sibling;n.tag!==5&&n.tag!==6&&n.tag!==18;){if(n.tag===27&&gr(n.type)||n.flags&2||n.child===null||n.tag===4)continue e;n.child.return=n,n=n.child}if(!(n.flags&2))return n.stateNode}}function Gf(n,s,c){var u=n.tag;if(u===5||u===6)n=n.stateNode,s?(c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c).insertBefore(n,s):(s=c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c,s.appendChild(n),c=c._reactRootContainer,c!=null||s.onclick!==null||(s.onclick=da));else if(u!==4&&(u===27&&gr(n.type)&&(c=n.stateNode,s=null),n=n.child,n!==null))for(Gf(n,s,c),n=n.sibling;n!==null;)Gf(n,s,c),n=n.sibling}function su(n,s,c){var u=n.tag;if(u===5||u===6)n=n.stateNode,s?c.insertBefore(n,s):c.appendChild(n);else if(u!==4&&(u===27&&gr(n.type)&&(c=n.stateNode),n=n.child,n!==null))for(su(n,s,c),n=n.sibling;n!==null;)su(n,s,c),n=n.sibling}function K0(n){var s=n.stateNode,c=n.memoizedProps;try{for(var u=n.type,m=s.attributes;m.length;)s.removeAttributeNode(m[0]);jn(s,u,c),s[un]=n,s[vn]=c}catch(b){Lt(n,n.return,b)}}var js=!1,on=!1,Ff=!1,W0=typeof WeakSet=="function"?WeakSet:Set,xn=null;function D_(n,s){if(n=n.containerInfo,gp=ku,n=ib(n),Ih(n)){if("selectionStart"in n)var c={start:n.selectionStart,end:n.selectionEnd};else e:{c=(c=n.ownerDocument)&&c.defaultView||window;var u=c.getSelection&&c.getSelection();if(u&&u.rangeCount!==0){c=u.anchorNode;var m=u.anchorOffset,b=u.focusNode;u=u.focusOffset;try{c.nodeType,b.nodeType}catch{c=null;break e}var E=0,L=-1,B=-1,Z=0,ce=0,be=n,te=null;t:for(;;){for(var ie;be!==c||m!==0&&be.nodeType!==3||(L=E+m),be!==b||u!==0&&be.nodeType!==3||(B=E+u),be.nodeType===3&&(E+=be.nodeValue.length),(ie=be.firstChild)!==null;)te=be,be=ie;for(;;){if(be===n)break t;if(te===c&&++Z===m&&(L=E),te===b&&++ce===u&&(B=E),(ie=be.nextSibling)!==null)break;be=te,te=be.parentNode}be=ie}c=L===-1||B===-1?null:{start:L,end:B}}else c=null}c=c||{start:0,end:0}}else c=null;for(hp={focusedElem:n,selectionRange:c},ku=!1,xn=s;xn!==null;)if(s=xn,n=s.child,(s.subtreeFlags&1028)!==0&&n!==null)n.return=s,xn=n;else for(;xn!==null;){switch(s=xn,b=s.alternate,n=s.flags,s.tag){case 0:if((n&4)!==0&&(n=s.updateQueue,n=n!==null?n.events:null,n!==null))for(c=0;c title"))),jn(b,u,c),b[un]=n,nn(b),u=b;break e;case"link":var E=ew("link","href",m).get(u+(c.href||""));if(E){for(var L=0;Lzt&&(E=zt,zt=Ye,Ye=E);var Y=sb(L,Ye),F=sb(L,zt);if(Y&&F&&(ie.rangeCount!==1||ie.anchorNode!==Y.node||ie.anchorOffset!==Y.offset||ie.focusNode!==F.node||ie.focusOffset!==F.offset)){var Q=be.createRange();Q.setStart(Y.node,Y.offset),ie.removeAllRanges(),Ye>zt?(ie.addRange(Q),ie.extend(F.node,F.offset)):(Q.setEnd(F.node,F.offset),ie.addRange(Q))}}}}for(be=[],ie=L;ie=ie.parentNode;)ie.nodeType===1&&be.push({element:ie,left:ie.scrollLeft,top:ie.scrollTop});for(typeof L.focus=="function"&&L.focus(),L=0;Lc?32:c,W.T=null,c=Qf,Qf=null;var b=cr,E=As;if(hn=0,Xi=cr=null,As=0,(At&6)!==0)throw Error(a(331));var L=At;if(At|=4,rv(b.current),nv(b,b.current,E,c),At=L,Gl(0,!1),V&&typeof V.onPostCommitFiberRoot=="function")try{V.onPostCommitFiberRoot(ca,b)}catch{}return!0}finally{he.p=m,W.T=u,Cv(n,s)}}function kv(n,s,c){s=ga(c,s),s=Df(n.stateNode,s,2),n=nr(n,s,2),n!==null&&(De(n,2),Qa(n))}function Lt(n,s,c){if(n.tag===3)kv(n,n,c);else for(;s!==null;){if(s.tag===3){kv(s,n,c);break}else if(s.tag===1){var u=s.stateNode;if(typeof s.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(lr===null||!lr.has(u))){n=ga(c,n),c=N0(2),u=nr(s,c,2),u!==null&&(E0(c,u,s,n),De(u,2),Qa(u));break}}s=s.return}}function np(n,s,c){var u=n.pingCache;if(u===null){u=n.pingCache=new L_;var m=new Set;u.set(s,m)}else m=u.get(s),m===void 0&&(m=new Set,u.set(s,m));m.has(c)||(Wf=!0,m.add(c),n=H_.bind(null,n,s,c),s.then(n,n))}function H_(n,s,c){var u=n.pingCache;u!==null&&u.delete(s),n.pingedLanes|=n.suspendedLanes&c,n.warmLanes&=~c,Ht===n&&(gt&c)===c&&(Yt===4||Yt===3&&(gt&62914560)===gt&&300>mt()-ou?(At&2)===0&&Qi(n,0):Yf|=c,Ji===gt&&(Ji=0)),Qa(n)}function Nv(n,s){s===0&&(s=st()),n=zr(n,s),n!==null&&(De(n,s),Qa(n))}function P_(n){var s=n.memoizedState,c=0;s!==null&&(c=s.retryLane),Nv(n,c)}function B_(n,s){var c=0;switch(n.tag){case 31:case 13:var u=n.stateNode,m=n.memoizedState;m!==null&&(c=m.retryLane);break;case 19:u=n.stateNode;break;case 22:u=n.stateNode._retryCache;break;default:throw Error(a(314))}u!==null&&u.delete(s),Nv(n,c)}function U_(n,s){return at(n,s)}var fu=null,eo=null,ap=!1,pu=!1,sp=!1,ur=0;function Qa(n){n!==eo&&n.next===null&&(eo===null?fu=eo=n:eo=eo.next=n),pu=!0,ap||(ap=!0,G_())}function Gl(n,s){if(!sp&&pu){sp=!0;do for(var c=!1,u=fu;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var b=0;else{var E=u.suspendedLanes,L=u.pingedLanes;b=(1<<31-ue(42|n)+1)-1,b&=m&~(E&~L),b=b&201326741?b&201326741|1:b?b|2:0}b!==0&&(c=!0,Tv(u,b))}else b=gt,b=Fe(u,u===Ht?b:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(b&3)===0||We(u,b)||(c=!0,Tv(u,b));u=u.next}while(c);sp=!1}}function q_(){Ev()}function Ev(){pu=ap=!1;var n=0;ur!==0&&e1()&&(n=ur);for(var s=mt(),c=null,u=fu;u!==null;){var m=u.next,b=_v(u,s);b===0?(u.next=null,c===null?fu=m:c.next=m,m===null&&(eo=c)):(c=u,(n!==0||(b&3)!==0)&&(pu=!0)),u=m}hn!==0&&hn!==5||Gl(n),ur!==0&&(ur=0)}function _v(n,s){for(var c=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,b=n.pendingLanes&-62914561;0L)break;var ce=B.transferSize,be=B.initiatorType;ce&&zv(be)&&(B=B.responseEnd,E+=ce*(B"u"?null:document;function Jv(n,s,c){var u=to;if(u&&typeof s=="string"&&s){var m=Pn(s);m='link[rel="'+n+'"][href="'+m+'"]',typeof c=="string"&&(m+='[crossorigin="'+c+'"]'),Yv.has(m)||(Yv.add(m),n={rel:n,crossOrigin:c,href:s},u.querySelector(m)===null&&(s=u.createElement("link"),jn(s,"link",n),nn(s),u.head.appendChild(s)))}}function c1(n){Ts.D(n),Jv("dns-prefetch",n,null)}function d1(n,s){Ts.C(n,s),Jv("preconnect",n,s)}function u1(n,s,c){Ts.L(n,s,c);var u=to;if(u&&n&&s){var m='link[rel="preload"][as="'+Pn(s)+'"]';s==="image"&&c&&c.imageSrcSet?(m+='[imagesrcset="'+Pn(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(m+='[imagesizes="'+Pn(c.imageSizes)+'"]')):m+='[href="'+Pn(n)+'"]';var b=m;switch(s){case"style":b=no(n);break;case"script":b=ao(n)}xa.has(b)||(n=y({rel:"preload",href:s==="image"&&c&&c.imageSrcSet?void 0:n,as:s},c),xa.set(b,n),u.querySelector(m)!==null||s==="style"&&u.querySelector(Wl(b))||s==="script"&&u.querySelector(Yl(b))||(s=u.createElement("link"),jn(s,"link",n),nn(s),u.head.appendChild(s)))}}function g1(n,s){Ts.m(n,s);var c=to;if(c&&n){var u=s&&typeof s.as=="string"?s.as:"script",m='link[rel="modulepreload"][as="'+Pn(u)+'"][href="'+Pn(n)+'"]',b=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":b=ao(n)}if(!xa.has(b)&&(n=y({rel:"modulepreload",href:n},s),xa.set(b,n),c.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(Yl(b)))return}u=c.createElement("link"),jn(u,"link",n),nn(u),c.head.appendChild(u)}}}function h1(n,s,c){Ts.S(n,s,c);var u=to;if(u&&n){var m=Fa(u).hoistableStyles,b=no(n);s=s||"default";var E=m.get(b);if(!E){var L={loading:0,preload:null};if(E=u.querySelector(Wl(b)))L.loading=5;else{n=y({rel:"stylesheet",href:n,"data-precedence":s},c),(c=xa.get(b))&&vp(n,c);var B=E=u.createElement("link");nn(B),jn(B,"link",n),B._p=new Promise(function(Z,ce){B.onload=Z,B.onerror=ce}),B.addEventListener("load",function(){L.loading|=1}),B.addEventListener("error",function(){L.loading|=2}),L.loading|=4,vu(E,s,u)}E={type:"stylesheet",instance:E,count:1,state:L},m.set(b,E)}}}function f1(n,s){Ts.X(n,s);var c=to;if(c&&n){var u=Fa(c).hoistableScripts,m=ao(n),b=u.get(m);b||(b=c.querySelector(Yl(m)),b||(n=y({src:n,async:!0},s),(s=xa.get(m))&&wp(n,s),b=c.createElement("script"),nn(b),jn(b,"link",n),c.head.appendChild(b)),b={type:"script",instance:b,count:1,state:null},u.set(m,b))}}function p1(n,s){Ts.M(n,s);var c=to;if(c&&n){var u=Fa(c).hoistableScripts,m=ao(n),b=u.get(m);b||(b=c.querySelector(Yl(m)),b||(n=y({src:n,async:!0,type:"module"},s),(s=xa.get(m))&&wp(n,s),b=c.createElement("script"),nn(b),jn(b,"link",n),c.head.appendChild(b)),b={type:"script",instance:b,count:1,state:null},u.set(m,b))}}function Xv(n,s,c,u){var m=(m=ke.current)?bu(m):null;if(!m)throw Error(a(446));switch(n){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(s=no(c.href),c=Fa(m).hoistableStyles,u=c.get(s),u||(u={type:"style",instance:null,count:0,state:null},c.set(s,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){n=no(c.href);var b=Fa(m).hoistableStyles,E=b.get(n);if(E||(m=m.ownerDocument||m,E={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},b.set(n,E),(b=m.querySelector(Wl(n)))&&!b._p&&(E.instance=b,E.state.loading=5),xa.has(n)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},xa.set(n,c),b||m1(m,n,c,E.state))),s&&u===null)throw Error(a(528,""));return E}if(s&&u!==null)throw Error(a(529,""));return null;case"script":return s=c.async,c=c.src,typeof c=="string"&&s&&typeof s!="function"&&typeof s!="symbol"?(s=ao(c),c=Fa(m).hoistableScripts,u=c.get(s),u||(u={type:"script",instance:null,count:0,state:null},c.set(s,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(a(444,n))}}function no(n){return'href="'+Pn(n)+'"'}function Wl(n){return'link[rel="stylesheet"]['+n+"]"}function Qv(n){return y({},n,{"data-precedence":n.precedence,precedence:null})}function m1(n,s,c,u){n.querySelector('link[rel="preload"][as="style"]['+s+"]")?u.loading=1:(s=n.createElement("link"),u.preload=s,s.addEventListener("load",function(){return u.loading|=1}),s.addEventListener("error",function(){return u.loading|=2}),jn(s,"link",c),nn(s),n.head.appendChild(s))}function ao(n){return'[src="'+Pn(n)+'"]'}function Yl(n){return"script[async]"+n}function Zv(n,s,c){if(s.count++,s.instance===null)switch(s.type){case"style":var u=n.querySelector('style[data-href~="'+Pn(c.href)+'"]');if(u)return s.instance=u,nn(u),u;var m=y({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return u=(n.ownerDocument||n).createElement("style"),nn(u),jn(u,"style",m),vu(u,c.precedence,n),s.instance=u;case"stylesheet":m=no(c.href);var b=n.querySelector(Wl(m));if(b)return s.state.loading|=4,s.instance=b,nn(b),b;u=Qv(c),(m=xa.get(m))&&vp(u,m),b=(n.ownerDocument||n).createElement("link"),nn(b);var E=b;return E._p=new Promise(function(L,B){E.onload=L,E.onerror=B}),jn(b,"link",u),s.state.loading|=4,vu(b,c.precedence,n),s.instance=b;case"script":return b=ao(c.src),(m=n.querySelector(Yl(b)))?(s.instance=m,nn(m),m):(u=c,(m=xa.get(b))&&(u=y({},c),wp(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),nn(m),jn(m,"link",u),n.head.appendChild(m),s.instance=m);case"void":return null;default:throw Error(a(443,s.type))}else s.type==="stylesheet"&&(s.state.loading&4)===0&&(u=s.instance,s.state.loading|=4,vu(u,c.precedence,n));return s.instance}function vu(n,s,c){for(var u=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),m=u.length?u[u.length-1]:null,b=m,E=0;E title"):null)}function y1(n,s,c){if(c===1||s.itemProp!=null)return!1;switch(n){case"meta":case"title":return!0;case"style":if(typeof s.precedence!="string"||typeof s.href!="string"||s.href==="")break;return!0;case"link":if(typeof s.rel!="string"||typeof s.href!="string"||s.href===""||s.onLoad||s.onError)break;switch(s.rel){case"stylesheet":return n=s.disabled,typeof s.precedence=="string"&&n==null;default:return!0}case"script":if(s.async&&typeof s.async!="function"&&typeof s.async!="symbol"&&!s.onLoad&&!s.onError&&s.src&&typeof s.src=="string")return!0}return!1}function nw(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function x1(n,s,c,u){if(c.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var m=no(u.href),b=s.querySelector(Wl(m));if(b){s=b._p,s!==null&&typeof s=="object"&&typeof s.then=="function"&&(n.count++,n=Su.bind(n),s.then(n,n)),c.state.loading|=4,c.instance=b,nn(b);return}b=s.ownerDocument||s,u=Qv(u),(m=xa.get(m))&&vp(u,m),b=b.createElement("link"),nn(b);var E=b;E._p=new Promise(function(L,B){E.onload=L,E.onerror=B}),jn(b,"link",u),c.instance=b}n.stylesheets===null&&(n.stylesheets=new Map),n.stylesheets.set(c,s),(s=c.state.preload)&&(c.state.loading&3)===0&&(n.count++,c=Su.bind(n),s.addEventListener("load",c),s.addEventListener("error",c))}}var Sp=0;function b1(n,s){return n.stylesheets&&n.count===0&&ju(n,n.stylesheets),0Sp?50:800)+s);return n.unsuspend=c,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function Su(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)ju(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Cu=null;function ju(n,s){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Cu=new Map,s.forEach(v1,n),Cu=null,Su.call(n))}function v1(n,s){if(!(s.state.loading&4)){var c=Cu.get(n);if(c)var u=c.get(null);else{c=new Map,Cu.set(n,c);for(var m=n.querySelectorAll("link[data-precedence],style[data-precedence]"),b=0;b"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(r)}catch(e){console.error(e)}}return r(),Lu.exports=Sw(),Lu.exports}var zu=Cw();const Hu=es(zu),io=[],jw=50;let Pu=!1;function zp(){try{return window.G7Core?.devTools}catch{return}}function Xr(r,e,t){const a=zp();if(Pu&&a?.isEnabled?.()){a.trackLog?.(r,e,t);return}Pu||(r==="error"||r==="warn")&&io.length{t.isDebugEnabled()&&console.log(e,...a),Xr("log",r,a)},warn:(...a)=>{t.isDebugEnabled()&&console.warn(e,...a),Xr("warn",r,a)},error:(...a)=>{t.isDebugEnabled()&&console.error(e,...a),Xr("error",r,a)}}}oo.getInstance();const za=it("ComponentRegistry");class fn extends Error{constructor(e,t,a){super(e),this.code=t,this.details=a,this.name="ComponentRegistryError"}}const la=class la{constructor(){H(this,"registry",{});H(this,"manifest",null);H(this,"loadingState","idle");H(this,"error",null);H(this,"templateId",null);H(this,"templateType",null)}static getInstance(){return la.instance||(la.instance=new la),la.instance}static resetInstance(){la.instance=null}async loadComponents(e,t){if(this.loadingState==="loading")throw new fn("Components are already being loaded","LOADING_IN_PROGRESS");if(this.loadingState==="loaded"&&this.templateId===e&&this.templateType===t){za.log("Components already loaded for template:",e,t);return}this.loadingState="loading",this.templateId=e,this.templateType=t,this.error=null;try{await this.loadManifest(),await this.loadComponentBundle(),this.loadingState="loaded",za.log("Successfully loaded components:",Object.keys(this.registry).length)}catch(a){throw this.loadingState="error",this.error=a instanceof Error?a:new Error(String(a)),new fn(`Failed to load components: ${this.error.message}`,"LOAD_FAILED",{originalError:this.error})}}async loadManifest(){try{if(!this.templateId)throw new fn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=`${this.templateId}:${this.templateType}`;if(la.manifestCache.has(e)){this.manifest=la.manifestCache.get(e),za.log("Manifest loaded from cache:",this.manifest.templateId);return}const t=`/api/templates/${this.templateId}/components.json`,a=await fetch(t);if(!a.ok)throw new fn(`Failed to fetch manifest: ${a.status} ${a.statusText}`,"MANIFEST_FETCH_FAILED",{status:a.status,statusText:a.statusText});const i=await a.json();this.validateManifest(i),this.manifest=i,la.manifestCache.set(e,i),za.log("Manifest loaded and cached:",i.templateId)}catch(e){throw e instanceof fn?e:new fn("Failed to load component manifest","MANIFEST_LOAD_FAILED",{originalError:e})}}validateManifest(e){if(!e.version)throw new fn("Manifest missing required field: version","MANIFEST_INVALID",{field:"version"});if(!e.templateId)throw new fn("Manifest missing required field: templateId","MANIFEST_INVALID",{field:"templateId"});if(!e.components||typeof e.components!="object")throw new fn("Manifest missing required field: components","MANIFEST_INVALID",{field:"components"});const t=["basic","composite","layout"];for(const a of t){if(!Array.isArray(e.components[a]))throw new fn(`Manifest field 'components.${a}' must be an array`,"MANIFEST_INVALID",{field:`components.${a}`,value:e.components[a]});e.components[a].forEach((i,o)=>{if(!i.name||typeof i.name!="string")throw new fn(`Invalid component metadata at ${a}[${o}]: missing or invalid 'name'`,"MANIFEST_INVALID",{type:a,index:o,metadata:i});if(!i.type||typeof i.type!="string")throw new fn(`Invalid component metadata at ${a}[${o}]: missing or invalid 'type'`,"MANIFEST_INVALID",{type:a,index:o,metadata:i})})}za.log("Manifest validation passed")}async loadComponentBundle(){try{if(!this.templateId)throw new fn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=this.getGlobalVariableName(),t=window[e];if(!t||typeof t!="object")throw new fn(`Component bundle not loaded. Expected global variable: ${e}. Ensure admin.blade.php includes the IIFE bundle script.`,"BUNDLE_NOT_LOADED",{expectedVariable:e});await this.registerComponentsFromManifest(t),za.log("Component bundle loaded from global variable:",e)}catch(e){throw e instanceof fn?e:new fn("Failed to load component bundle","BUNDLE_LOAD_FAILED",{originalError:e})}}getGlobalVariableName(){if(!this.templateId)throw new fn("Template ID not set","TEMPLATE_ID_NOT_SET");return this.templateId.split(/[-_]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}async registerComponentsFromManifest(e){if(!this.manifest)throw new fn("Manifest not loaded","MANIFEST_NOT_LOADED");const t=["basic","composite","layout"];for(const a of t){const i=this.manifest.components[a]||[];for(const o of i){const d=o.name,g=e[d];if(!g){za.warn(`Component '${d}' not found in bundle`);continue}this.registerComponent(d,g,o)}}}registerComponent(e,t,a){this.registry[e]&&za.warn(`Component '${e}' already registered, overwriting`);const i=Ke.memo(t);this.registry[e]={component:i,metadata:a},za.log(`[ComponentRegistry] Registered component: ${e} (${a.type})`)}getComponent(e){const t=this.registry[e];return t?t.component:null}getMetadata(e){const t=this.registry[e];return t?t.metadata:null}hasComponent(e){return e in this.registry}getComponentsByType(e){return Object.entries(this.registry).filter(([t,a])=>a.metadata.type===e).map(([t,a])=>t)}getAllComponents(){return Object.keys(this.registry)}getComponentMap(){const e={};for(const[t,a]of Object.entries(this.registry))e[t]=a.component;return e}getLoadingState(){return this.loadingState}getError(){return this.error}getTemplateId(){return this.templateId}getManifest(){return this.manifest}clear(){this.registry={},this.manifest=null,this.loadingState="idle",this.error=null,this.templateId=null,this.templateType=null,za.log("Registry cleared")}};H(la,"instance",null),H(la,"manifestCache",new Map);let ba=la;const Pp=it("TranslationEngine");class Bu extends Error{constructor(e,t,a){super(e),this.key=t,this.locale=a,this.name="TranslationError"}}const $n=class $n{constructor(e={}){H(this,"cache",new Map);H(this,"translations",new Map);H(this,"options");H(this,"cacheVersion",0);this.options={defaultLocale:e.defaultLocale||"ko",fallbackLocale:e.fallbackLocale||"en",cacheTTL:e.cacheTTL||3e5}}static getInstance(e={}){return $n.instance||($n.instance=new $n(e)),$n.instance}static resetInstance(){$n.instance=null}setCacheVersion(e){this.cacheVersion!==e&&(Pp.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.cache.clear())}getCacheVersion(){return this.cacheVersion}async loadTranslations(e,t,a="/api",i=!1){const o=`${e}:${t}`;if(!i){const d=this.getFromCache(o);if(d)return this.translations.set(o,d),d}try{let d=`${a}/templates/${e}/lang/${t}.json`;const g=[];this.cacheVersion>0&&g.push(`v=${this.cacheVersion}`),i&&g.push(`_=${Date.now()}`),g.length>0&&(d+=`?${g.join("&")}`);const h=await fetch(d);if(!h.ok)throw new Bu(`Failed to load translations: ${h.statusText}`,void 0,t);const p=await h.json();return this.saveToCache(o,p),this.translations.set(o,p),p}catch(d){throw new Bu(`Failed to fetch translations for ${t}: ${d instanceof Error?d.message:String(d)}`,void 0,t)}}resolveTranslations(e,t,a){let i=e;const o=5;let d=0;for(;d"="+this.translate(p,t,void 0,a)),i===g)break;d++}return i.replace($n.TRANSLATION_PATTERN,(g,h,f)=>{const{cleanedParams:p,trailing:y}=this.separateTrailingText(f);return this.translate(h,t,p,a)+y})}translate(e,t,a,i){const o=this.getTranslation(e,t),d=a&&this.cleanParamsStr(a);if(d){const g=this.parseParams(d,i);return this.replaceParams(o,g)}return o}getTranslation(e,t){const{templateId:a,locale:i}=t,o=`${a}:${i}`,d=this.translations.get(o);if(d){const g=this.getNestedValue(d,e);if(g!==null)return g}if(i!==this.options.fallbackLocale){const g=`${a}:${this.options.fallbackLocale}`,h=this.translations.get(g);if(h){const f=this.getNestedValue(h,e);if(f!==null)return f}}return e}getNestedValue(e,t){const a=t.split(".");let i=e;for(const o of a){if(i==null||typeof i!="object")return null;i=i[o]}return typeof i=="string"?i:null}parseParams(e,t){const a={},i=e.startsWith("|")?e.slice(1):e,o=[],g=i.replace(/\{\{(?:[^}]|\}(?!\}))*\}\}/g,h=>(o.push(h),`__PLACEHOLDER_${o.length-1}__`)).matchAll($n.PARAM_PATTERN);for(const h of g){const[,f,p]=h,y=p.replace(/__PLACEHOLDER_(\d+)__/g,(x,S)=>o[parseInt(S,10)]);a[f.trim()]=this.resolveParamValue(y.trim(),t)}return a}resolveParamValue(e,t){if(e.startsWith("{{")&&e.endsWith("}}")){const a=e.slice(2,-2).trim();if(/[|&()[\]!?:+\-*/%<>=\s]/.test(a)&&t)try{const d=new Function(...Object.keys(t),`return ${a}`)(...Object.values(t));return String(d??"")}catch(o){return Pp.error("Expression evaluation failed:",a,o),""}else{const o=this.getNestedDataValue(t,a);return String(o??"")}}return e}separateTrailingText(e){if(!e)return{cleanedParams:void 0,trailing:""};if(e.trimEnd().endsWith("}}"))return{cleanedParams:e,trailing:""};if(!(e.startsWith("|")?e.slice(1):e).includes("="))return{cleanedParams:void 0,trailing:e};const a=e.match(/(\s+[^\p{L}\w=|&\s][^\p{L}\w=]*\s*)$/u);return a?{cleanedParams:e.slice(0,-a[1].length),trailing:a[1]}:{cleanedParams:e,trailing:""}}cleanParamsStr(e){return this.separateTrailingText(e).cleanedParams||""}getNestedDataValue(e,t){if(!e)return;const a=t.split(".");let i=e;for(const o of a){if(i==null)return;i=i[o]}return i}replaceParams(e,t){let a=e;for(const[i,o]of Object.entries(t)){const d=new RegExp(`\\{\\{${i}\\}\\}`,"g");a=a.replace(d,String(o));const g=new RegExp(`\\{${i}\\}`,"g");a=a.replace(g,String(o))}return a}getFromCache(e){const t=this.cache.get(e);return t?Date.now()-t.timestamp>this.options.cacheTTL?(this.cache.delete(e),null):t.data:null}saveToCache(e,t){this.cache.set(e,{data:t,timestamp:Date.now()})}clearCache(){this.cache.clear(),this.translations.clear()}pruneCache(){const e=Date.now(),t=[];for(const[a,i]of this.cache.entries())e-i.timestamp>this.options.cacheTTL&&t.push(a);for(const a of t)this.cache.delete(a)}getCacheStats(){const e=Date.now();let t=0;for(const a of this.cache.values())e-a.timestamp>this.options.cacheTTL&&t++;return{size:this.cache.size,expired:t}}};H($n,"instance",null),H($n,"TRANSLATION_PATTERN",/\$t:([a-zA-Z0-9._-]+)(\|(?:(?!\$t:).)+)?/g),H($n,"NESTED_TRANSLATION_PARAM_PATTERN",/=(\$t:([a-zA-Z0-9._-]+))(?=[|&\s]|$)/g),H($n,"PARAM_PATTERN",/([^=|&]+)=([^|&]+)/g);let xr=$n;const Bp=Object.freeze(Object.defineProperty({__proto__:null,TranslationEngine:xr,TranslationError:Bu},Symbol.toStringTag,{value:"Module"})),Qr=it("PipeRegistry");function Up(r,e){const t=r.getFullYear(),a=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0"),o=String(r.getHours()).padStart(2,"0"),d=String(r.getMinutes()).padStart(2,"0"),g=String(r.getSeconds()).padStart(2,"0");return e.replace("YYYY",String(t)).replace("YY",String(t).slice(-2)).replace("MM",a).replace("M",String(r.getMonth()+1)).replace("DD",i).replace("D",String(r.getDate())).replace("HH",o).replace("H",String(r.getHours())).replace("mm",d).replace("m",String(r.getMinutes())).replace("ss",g).replace("s",String(r.getSeconds()))}function kw(r,e="ko"){const a=new Date().getTime()-r.getTime(),i=Math.floor(a/1e3),o=Math.floor(i/60),d=Math.floor(o/60),g=Math.floor(d/24),h=Math.floor(g/7),f=Math.floor(g/30),p=Math.floor(g/365);return e==="ko"?i<60?"방금 전":o<60?`${o}분 전`:d<24?`${d}시간 전`:g<7?`${g}일 전`:h<4?`${h}주 전`:f<12?`${f}개월 전`:`${p}년 전`:i<60?"just now":o<60?`${o} minute${o===1?"":"s"} ago`:d<24?`${d} hour${d===1?"":"s"} ago`:g<7?`${g} day${g===1?"":"s"} ago`:h<4?`${h} week${h===1?"":"s"} ago`:f<12?`${f} month${f===1?"":"s"} ago`:`${p} year${p===1?"":"s"} ago`}function Uu(r){if(r==null)return null;if(r instanceof Date)return r;if(typeof r=="number")return new Date(r);if(typeof r=="string"){const e=new Date(r);return isNaN(e.getTime())?null:e}return null}const lo={date:{fn:(r,e="YYYY-MM-DD")=>{const t=Uu(r);return t?Up(t,e):""},description:"날짜 포맷 (기본: YYYY-MM-DD)"},datetime:{fn:(r,e="YYYY-MM-DD HH:mm")=>{const t=Uu(r);return t?Up(t,e):""},description:"날짜+시간 포맷 (기본: YYYY-MM-DD HH:mm)"},relativeTime:{fn:(r,e="ko")=>{const t=Uu(r);return t?kw(t,e):""},description:'상대 시간 표시 (예: "3분 전")'},number:{fn:(r,e)=>{const t=Number(r);if(isNaN(t))return String(r??"");const a={};return e!==void 0&&(a.minimumFractionDigits=e,a.maximumFractionDigits=e),t.toLocaleString(void 0,a)},description:"숫자 포맷 (천단위 구분, 선택적 소수점)"},truncate:{fn:(r,e=100,t="...")=>typeof r!="string"?String(r??""):r.length<=e?r:r.slice(0,e)+t,description:'문자열 자르기 (기본: 100자, 접미사: "...")'},uppercase:{fn:r=>typeof r!="string"?String(r??""):r.toUpperCase(),description:"대문자 변환"},lowercase:{fn:r=>typeof r!="string"?String(r??""):r.toLowerCase(),description:"소문자 변환"},stripHtml:{fn:r=>typeof r!="string"?String(r??""):r.replace(/<[^>]*>/g,""),description:"HTML 태그 제거"},default:{fn:(r,e="")=>r==null||r===""?e:r,description:"기본값 설정 (null, undefined, 빈문자열 시)"},fallback:{fn:(r,e)=>r??e,description:"폴백 값 설정 (null, undefined 시만)"},first:{fn:r=>{if(Array.isArray(r))return r[0]},description:"배열의 첫 번째 요소"},last:{fn:r=>{if(Array.isArray(r))return r[r.length-1]},description:"배열의 마지막 요소"},join:{fn:(r,e=", ")=>Array.isArray(r)?r.join(e):"",description:'배열을 문자열로 결합 (기본 구분자: ", ")'},length:{fn:r=>Array.isArray(r)||typeof r=="string"?r.length:0,description:"배열/문자열 길이"},filterBy:{fn:(r,e,t)=>Array.isArray(r)?Array.isArray(e)?r.filter(a=>{const i=t?a?.[t]:a;return e.includes(i)}):r:[],description:"배열 필터링 (allowList에 포함된 항목만 반환)"},keys:{fn:r=>r==null||typeof r!="object"?[]:Object.keys(r),description:"객체의 키 배열"},values:{fn:r=>r==null||typeof r!="object"?[]:Object.values(r),description:"객체의 값 배열"},json:{fn:(r,e)=>{try{return JSON.stringify(r,null,e)}catch{return""}},description:"JSON 문자열로 변환"},localized:{fn:(r,e)=>r==null?"":typeof r=="string"?r:typeof r!="object"?String(r):r[e||"ko"]||r.ko||r.en||Object.values(r)[0]||"",description:"다국어 객체에서 로케일에 맞는 값 추출"}},Zr=new Map,Nr=class Nr{static getInstance(){return Nr.instance||(Nr.instance=new Nr),Nr.instance}register(e,t,a){if(lo[e]){Qr.warn(`[PipeRegistry] 내장 파이프를 덮어쓸 수 없습니다: ${e}`);return}Zr.set(e,{fn:t,description:a}),Qr.log(`[PipeRegistry] 커스텀 파이프 등록됨: ${e}`)}unregister(e){if(lo[e])return Qr.warn(`[PipeRegistry] 내장 파이프는 해제할 수 없습니다: ${e}`),!1;const t=Zr.delete(e);return t&&Qr.log(`[PipeRegistry] 커스텀 파이프 해제됨: ${e}`),t}get(e){const t=lo[e];return t?t.fn:Zr.get(e)?.fn}has(e){return!!lo[e]||Zr.has(e)}execute(e,t,a=[]){const i=this.get(e);if(!i)return Qr.warn(`[PipeRegistry] 알 수 없는 파이프: ${e}`),t;try{return i(t,...a)}catch(o){return Qr.error(`[PipeRegistry] 파이프 실행 오류 (${e}):`,o),t}}list(){const e=[];for(const[t,a]of Object.entries(lo))e.push({name:t,description:a.description,type:"built-in"});for(const[t,a]of Zr.entries())e.push({name:t,description:a.description,type:"custom"});return e.sort((t,a)=>t.name.localeCompare(a.name))}clearCustomPipes(){Zr.clear()}};H(Nr,"instance",null);let ec=Nr;ec.getInstance();function Nw(r){const e=r.trim(),t=e.indexOf("(");if(t===-1)return{name:e,args:[]};const a=e.slice(0,t).trim(),i=e.slice(t+1,-1);if(!i.trim())return{name:a,args:[]};const o=[];let d="",g=null,h=0;for(let f=0;f0?i[f-1]:"")==="\\"){d+=p;continue}if((p==='"'||p==="'")&&!g){g=p;continue}if(p===g){g=null;continue}if(g){d+=p;continue}if(p==="("||p==="["||p==="{"){h++,d+=p;continue}if(p===")"||p==="]"||p==="}"){h--,d+=p;continue}if(p===","&&h===0){o.push(qp(d.trim())),d="";continue}d+=p}return d.trim()&&o.push(qp(d.trim())),{name:a,args:o}}function qp(r){if(r==="null")return null;if(r==="undefined")return;if(r==="true")return!0;if(r==="false")return!1;const e=Number(r);return!isNaN(e)&&r!==""?e:r}function Ew(r){const e=[];let t="",a=null,i=0;for(let o=0;o0?r[o-1]:"",h=o0?r[a-1]:"",d=a=2&&r.charCodeAt(0)===64976&&r.charCodeAt(r.length-1)===64977}function Vp(r){return r.includes(tc)}function Kp(r){return r.slice(1,-1)}function go(r){if(typeof r=="string")return uo(r);if(Array.isArray(r))return r.map(go);if(r&&typeof r=="object"){const e={};for(const[t,a]of Object.entries(r))e[t]=go(a);return e}return r}const ho=it("DataBindingEngine");function nc(){try{return window.G7Core?.devTools}catch{return}}class qu extends Error{constructor(e,t,a){super(e),this.path=t,this.context=a,this.name="DataBindingError"}}const Ea=class Ea{constructor(e){H(this,"cache",new Map);H(this,"expressionFnCache",new Map);H(this,"renderCycleCache",new Map);H(this,"currentRenderCycleId",0);H(this,"defaultOptions",{defaultValue:void 0,nullSafe:!0,detectCircular:!0,maxDepth:10});e&&(this.defaultOptions={...this.defaultOptions,...e})}startRenderCycle(){this.currentRenderCycleId++,this.renderCycleCache.clear()}isRenderCycleCacheActive(){return this.currentRenderCycleId>0}getFromRenderCycleCache(e){if(this.isRenderCycleCacheActive())return this.renderCycleCache.get(e)}saveToRenderCycleCache(e,t){this.isRenderCycleCacheActive()&&this.renderCycleCache.set(e,t)}resolveBindings(e,t,a,i){const o={...this.defaultOptions,...a},d=nc(),g=t._computed&&!t.$computed?{...t,$computed:t._computed}:t;return e.replace(Ea.BINDING_PATTERN,(h,f)=>{const p=f.trim();let y=!1,x=p;if(p.startsWith(Ds)&&(y=!0,x=p.slice(Ds.length)),Gp(x)){const N=d?.isEnabled()?performance.now():0;try{const[D,$]=Ew(x);let M,z=!1;const K=/[?:|&!+\-*/<>=()]/.test(D)||/\[['"]/.test(D),ye=D.startsWith("_global")||D.startsWith("_local")||D.startsWith("_isolated")||D.startsWith("$parent");if(o.skipCache)K?M=this.evaluateExpression(D,g):M=this.resolvePath(D,g,o);else if(K){const ve=this.getFromRenderCycleCache(`expr:${D}`);ve!==void 0?(M=ve,z=!0):(M=this.evaluateExpression(D,g),this.saveToRenderCycleCache(`expr:${D}`,M))}else if(ye){const ve=this.getFromRenderCycleCache(D);ve!==void 0?(M=ve,z=!0):(M=this.resolvePath(D,g,o),this.saveToRenderCycleCache(D,M))}else{const ve=this.getFromCache(D);ve!==void 0?(M=ve,z=!0):(M=this.resolvePath(D,g,o),this.saveToCache(D,M))}const we=_w(M,$);if(d?.isEnabled()){const ve=performance.now()-N;d.trackExpressionEval({expression:`{{${p}}}`,result:this.sanitizeResultForTracking(we),resultType:this.getResultType(we),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:z,duration:ve,method:"resolveBindings",skipCache:o.skipCache})}const J=this.formatValue(we);return y?uo(J):J}catch(D){return ho.error("Pipe expression evaluation failed:",x,D),h}}if(/[?:&!+\-*/<>=()]/.test(x)||/\|\|/.test(x)||/\[['"]/.test(x)){const N=d?.isEnabled()?performance.now():0;try{let D,$=!1;if(o.skipCache)D=this.evaluateExpression(x,g);else{const z=`expr:${x}`,K=this.getFromRenderCycleCache(z);K!==void 0?(D=K,$=!0):(D=this.evaluateExpression(x,g),this.saveToRenderCycleCache(z,D))}if(d?.isEnabled()){const z=performance.now()-N;d.trackExpressionEval({expression:`{{${p}}}`,result:this.sanitizeResultForTracking(D),resultType:this.getResultType(D),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:$,duration:z,method:"resolveBindings",skipCache:o.skipCache})}const M=this.formatValue(D);return y?uo(M):M}catch(D){return ho.error("Expression evaluation failed:",x,D),h}}if(o.skipCache){const N=d?.isEnabled()?performance.now():0,D=this.resolvePath(x,g,o);if(d?.isEnabled()){const M=performance.now()-N;d.trackExpressionEval({expression:`{{${p}}}`,result:this.sanitizeResultForTracking(D),resultType:this.getResultType(D),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:M,method:"resolveBindings",skipCache:!0})}const $=this.formatValue(D);return y?uo($):$}const v=x.startsWith("_global")||x.startsWith("_local")||x.startsWith("_isolated")||x.startsWith("$parent"),w=d?.isEnabled()?performance.now():0;let k,A=!1;if(v){const N=this.getFromRenderCycleCache(x);N!==void 0?(k=N,A=!0):(k=this.resolvePath(x,g,o),this.saveToRenderCycleCache(x,k))}else{const N=this.getFromCache(x);N!==void 0?(k=N,A=!0):(k=this.resolvePath(x,g,o),this.saveToCache(x,k))}if(d?.isEnabled()){const N=performance.now()-w;d.trackExpressionEval({expression:`{{${p}}}`,result:this.sanitizeResultForTracking(k),resultType:this.getResultType(k),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:A,duration:N,method:"resolveBindings",skipCache:o.skipCache})}const O=this.formatValue(k);return y?uo(O):O})}resolve(e,t,a,i){const o={...this.defaultOptions,...a},d=nc(),g=d?.isEnabled()?performance.now():0;if(o.skipCache){const y=this.resolvePath(e,t,o);return d?.isEnabled()&&d.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(y),resultType:this.getResultType(y),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:performance.now()-g,method:"resolve",skipCache:!0}),y}const h=e.startsWith("_global")||e.startsWith("_local")||e.startsWith("_isolated")||e.startsWith("$parent");let f=!1;if(h){const y=this.getFromRenderCycleCache(e);if(y!==void 0)return f=!0,d?.isEnabled()&&d.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(y),resultType:this.getResultType(y),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!0,duration:performance.now()-g,method:"resolve",skipCache:o.skipCache}),y}else{const y=this.getFromCache(e);if(y!==void 0)return f=!0,d?.isEnabled()&&d.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(y),resultType:this.getResultType(y),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!0,duration:performance.now()-g,method:"resolve",skipCache:o.skipCache}),y}const p=this.resolvePath(e,t,o);return h?this.saveToRenderCycleCache(e,p):this.saveToCache(e,p),d?.isEnabled()&&d.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(p),resultType:this.getResultType(p),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:f,duration:performance.now()-g,method:"resolve",skipCache:o.skipCache}),p}resolvePath(e,t,a,i=0,o=new WeakSet){if(a.maxDepth&&i>a.maxDepth){if(a.detectCircular)throw new qu(`Maximum depth exceeded (${a.maxDepth}). Possible circular reference.`,e,t);return a.defaultValue}const d=this.parsePath(e);let g=t;for(let h=0;hEa.CACHE_EXPIRY){this.cache.delete(e),a?.isEnabled()&&a.recordCacheMiss();return}return a?.isEnabled()&&a.recordCacheHit(),t.value}saveToCache(e,t){this.cache.set(e,{value:t,timestamp:Date.now()})}isActionDefinition(e){return typeof e.handler!="string"?!1:e.params!==void 0||Array.isArray(e.actions)||typeof e.target=="string"||e.onSuccess!==void 0||e.onError!==void 0}resolveObject(e,t,a){if(this.isSwitchExpression(e)){const g=e;return this.resolveSwitch(g,t,a)}if(this.isActionDefinition(e))return{...e};if("iteration"in e)return{...e};const i={},d=[...["cellChildren","expandChildren","expandContext","render"],...a?.skipBindingKeys||[]];for(const[g,h]of Object.entries(e)){if(d.includes(g)){i[g]=h;continue}if(typeof h=="string"){const f=h.match(/^\{\{([^}]+)\}\}$/);if(f){const p=f[1].trim();let y=!1,x=p;p.startsWith(Ds)&&(y=!0,x=p.slice(Ds.length));const v=/[?:|&!+\-*/<>=()]/.test(x)||/\[['"]/.test(x)?this.evaluateExpression(x,t,a):this.resolve(x,t,a);i[g]=y&&v!=null?go(v):v}else i[g]=this.resolveBindings(h,t,a)}else Array.isArray(h)?i[g]=h.map(f=>typeof f=="string"?this.resolveBindings(f,t,a):typeof f=="object"&&f!==null?this.resolveObject(f,t,a):f):h&&typeof h=="object"?i[g]=this.resolveObject(h,t,a):i[g]=h}return i}clearCache(){this.cache.clear(),this.expressionFnCache.clear()}invalidateCacheByKeys(e){for(const t of this.cache.keys())for(const a of e)if(t===a||t.startsWith(`${a}.`)||t.startsWith(`${a}[`)){this.cache.delete(t);break}}pruneCache(){const e=Date.now();for(const[t,a]of this.cache.entries())e-a.timestamp>Ea.CACHE_EXPIRY&&this.cache.delete(t)}getCacheStats(){const e=Date.now();let t=0;for(const a of this.cache.values())e-a.timestamp>Ea.CACHE_EXPIRY&&t++;return{size:this.cache.size,expired:t}}evaluateExpression(e,t,a){const i=nc(),o=i?.isEnabled()?performance.now():0;i?.isEnabled()&&i.trackBindingEval();try{let d=this.preprocessOptionalChaining(e);d=this.preprocessTranslationTokens(d);const g=this.extractVariablesFromExpression(d),h={...t};for(const D of g)D in h||(h[D]=void 0);t._computed&&!h.$computed&&(h.$computed=t._computed);const f=t.$locale||"ko";h.$localized=D=>D==null?"":typeof D=="string"?D:typeof D=="object"?D[f]||D.ko||D.en||Object.values(D)[0]||"":String(D);const p=typeof window<"u"?window.G7Core:void 0;h.$uuid=()=>p?.uuid?p.uuid():typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,D=>{const $=Math.random()*16|0;return(D==="x"?$:$&3|8).toString(16)});let y=t.$templateId,x=f;if(!y&&typeof window<"u"){const $=window.__templateApp?.getConfig?.();$?.templateId&&(y=$.templateId,!t.$locale&&$.locale&&(x=$.locale))}const S={templateId:y||"",locale:x};h.$t=D=>{if(!D||typeof D!="string")return"";try{return xr.getInstance().translate(D,S)}catch($){return ho.warn("$t() translation failed for key:",D,$),D}},h.$get=(D,$,M=void 0)=>{if(D==null)return M;const z=Array.isArray($)?$:[$];if(z.length===0)return D;let K=D;for(const ye of z){if(K==null||ye==null)return M;K=K[ye]}return K??M};const v=Object.keys(h),w=Object.values(h),k=`${d}|${v.join(",")}`;let A=this.expressionFnCache.get(k);const O=!!A;A||(A=new Function(...v,`return (${d});`),this.expressionFnCache.set(k,A));const N=A(...w);if(i?.isEnabled()){const D=performance.now()-o;i.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(N),resultType:this.getResultType(N),componentId:a?.componentId,componentName:a?.componentName,propName:a?.propName,fromCache:O,duration:D,method:"evaluateExpression",skipCache:a?.skipCache})}return N}catch(d){throw new Error(`Failed to evaluate expression "${e}": ${d instanceof Error?d.message:String(d)}`)}}getResultType(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}sanitizeResultForTracking(e){if(e==null||typeof e!="object")return e;try{if(Array.isArray(e))return e.length>10?`[Array(${e.length})]`:e.slice(0,10);const t=Object.keys(e);return t.length>20?`{Object(${t.length} keys)}`:(JSON.stringify(e),e)}catch{return"[Complex Object]"}}preprocessTranslationTokens(e){return e=e.replace(/(['"])(\$t:([a-zA-Z_][a-zA-Z0-9_.\-]*))\1/g,(t,a,i,o)=>`$t('${o}')`),e.replace(/(?(t.push(o),`__STRING_LITERAL_${t.length-1}__`));const i=[];return a=a.replace(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*(?:\|[^'"\s,)]+)?/g,o=>(i.push(o),`__TRANSLATION_TOKEN_${i.length-1}__`)),a=a.replace(/([a-zA-Z_$][a-zA-Z0-9_$]*)\.(?!\?)/g,"$1?."),a=a.replace(/__TRANSLATION_TOKEN_(\d+)__/g,(o,d)=>i[parseInt(d,10)]),a=a.replace(/__STRING_LITERAL_(\d+)__/g,(o,d)=>t[parseInt(d,10)]),a}extractVariablesFromExpression(e){const t=new Set(["true","false","null","undefined","NaN","Infinity","if","else","for","while","do","switch","case","break","continue","return","function","class","const","let","var","new","delete","typeof","instanceof","this","super","import","export","default","try","catch","finally","throw","Math","Date","JSON","Array","Object","String","Number","Boolean","RegExp","parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent"]),a=/(?{t!==null&&clearTimeout(t),t=setTimeout(()=>{r(...a)},e)})}class Tw{constructor(){H(this,"subscribers",new Set);H(this,"currentWidth",1024);H(this,"debouncedHandler",null);H(this,"isInitialized",!1);this.initialize()}initialize(){typeof window>"u"||(this.currentWidth=window.innerWidth,this.isInitialized=!0,this.debouncedHandler=Aw(()=>{this.currentWidth=window.innerWidth,this.notifySubscribers()},150),window.addEventListener("resize",this.debouncedHandler))}notifySubscribers(){this.subscribers.forEach(e=>{e(this.currentWidth)})}subscribe(e){return this.subscribers.add(e),e(this.currentWidth),()=>{this.subscribers.delete(e)}}getWidth(){return this.currentWidth}parseRange(e){if(ac.has(e))return ac.get(e)??null;let t=null;if(Gu[e])t={...Gu[e]};else{const a=e.match(/^(-?\d*)-(-?\d*)$/);if(a){const[,i,o]=a,d=i===""?0:parseInt(i,10),g=o===""?1/0:parseInt(o,10);!isNaN(d)&&!isNaN(g)&&d<=g&&(t={min:d,max:g})}}return ac.set(e,t),t}getMatchingKey(e,t){const a=[];for(const i of Object.keys(e)){const o=this.parseRange(i);o&&t>=o.min&&t<=o.max&&a.push({key:i,range:o,isPreset:!!Gu[i]})}return a.length===0?null:(a.sort((i,o)=>{if(i.isPreset!==o.isPreset)return i.isPreset?1:-1;const d=i.range.max-i.range.min,g=o.range.max-o.range.min;return d-g}),a[0].key)}matches(e){const t=this.parseRange(e);return t?this.currentWidth>=t.min&&this.currentWidth<=t.max:!1}clearSubscribers(){this.subscribers.clear()}destroy(){this.debouncedHandler&&typeof window<"u"&&window.removeEventListener("resize",this.debouncedHandler),this.clearSubscribers(),ac.clear()}_setWidthForTesting(e){this.currentWidth=e,this.notifySubscribers()}}const ei=new Tw,sc=it("ConditionEvaluator");function Dw(r){switch(r){case"true":return{value:!0};case"false":return{value:!1};case"null":return{value:null};case"undefined":return{value:void 0};default:return}}function Rw(r){return/[?:|&!+\-*/<>=()]/.test(r)}function Ow(r){if(!r.startsWith("{{")||!r.endsWith("}}"))return null;const e=r.slice(2,-2);let t=null,a=0;for(let i=0;i0?e[i-1]:"")!=="\\"&&((o==='"'||o==="'")&&!t?t=o:o===t&&(t=null),!t&&(o==="{"&&a++,o==="}"&&a--,a<0)))return null}return a===0?e.trim():null}function Lw(r,e,t){if(!r)return!0;try{const a=Ow(r);let i;if(a!==null){const o=Dw(a);o!==void 0?i=o.value:Rw(a)?i=t.evaluateExpression(a,e):i=t.resolve(a,e,{skipCache:!0})}else i=t.resolveBindings(r,e,{skipCache:!0});if(typeof i=="string"){const o=i.toLowerCase().trim();if(o==="false"||o==="0"||o===""||o==="null"||o==="undefined")return!1}return!!i}catch(a){return sc.warn(`evaluateStringCondition: 조건 평가 실패: ${r}`,a),!1}}function rc(r,e,t){if(typeof r=="string")return Lw(r,e,t);if("and"in r){if(!Array.isArray(r.and)||r.and.length===0)return sc.warn("evaluateConditionExpression: AND 그룹이 비어있습니다"),!0;for(const a of r.and)if(!rc(a,e,t))return!1;return!0}if("or"in r){if(!Array.isArray(r.or)||r.or.length===0)return sc.warn("evaluateConditionExpression: OR 그룹이 비어있습니다"),!1;for(const a of r.or)if(rc(a,e,t))return!0;return!1}return sc.warn("evaluateConditionExpression: 알 수 없는 조건 형식",r),!1}function Wp(r,e,t){if(!Array.isArray(r)||r.length===0)return{matched:!1,branchIndex:-1};for(let a=0;a=()]/.test(r)}function Xp(r){if(!r.startsWith("{{")||!r.endsWith("}}"))return null;const e=r.slice(2,-2);let t=null,a=0;for(let i=0;i0?e[i-1]:"")!=="\\"&&((o==='"'||o==="'")&&!t?t=o:o===t&&(t=null),!t&&(o==="{"&&a++,o==="}"&&a--,a<0)))return null}return a===0?e.trim():null}function Vu(r,e,t){let a=r;if(r.startsWith("{{")&&r.endsWith("}}")&&(a=r.slice(2,-2).trim()),Fu(a))try{return t.evaluateExpression(a,e)}catch(i){ts.warn(`resolveIterationSource: 표현식 평가 실패: ${r}`,i);return}return t.resolve(a,e,{skipCache:!0})}function zw(r,e){const t={...r};if(e?.parentDataContext)for(const[a,i]of Object.entries(e.parentDataContext))a in t||(t[a]=i);if(e?.state){const a=t._local||{};t._local={...a,...e.state}}return e?.isolatedContext?.state&&(t._isolated=e.isolatedContext.state),t}function Ku(r,e,t,a){if(!e||!Array.isArray(e)||e.length===0)return r;const i=a?.actionDispatcher??Fm(),o={...r,actions:e},d=i.bindActionsToProps(o,t,a?.componentContext);return delete d.actions,d}function Qp(r,e,t,a){if(typeof r=="boolean")return r;if(!r)return!0;try{const i=Xp(r);let o;if(i!==null){const d=Iw.get(i);d!==void 0?o=d:Fu(i)?o=t.evaluateExpression(i,e):o=t.resolve(i,e,{skipCache:!0})}else o=t.resolveBindings(r,e,{skipCache:!0});if(typeof o=="string"){const d=o.toLowerCase().trim();if(d==="false"||d==="0"||d===""||d==="null"||d==="undefined")return!1}return!!o}catch(i){return ts.warn(`evaluateIfCondition: 조건 평가 실패 (컴포넌트: ${a||"unknown"}):`,i),!1}}function ti(r,e,t,a){if(r.if!==void 0)return Qp(r.if,e,t,a);if(r.condition!==void 0)return Qp(r.condition,e,t,a);if(r.conditions===void 0)return!0;const i=r.conditions;try{return Mw(i)?rc(i,e,t):$w(i)?Wp(i,e,t).matched:(ts.warn(`evaluateRenderCondition: 알 수 없는 conditions 형식 (컴포넌트: ${a||"unknown"})`),!0)}catch(o){return ts.warn(`evaluateRenderCondition: conditions 평가 실패 (컴포넌트: ${a||"unknown"}):`,o),!1}}function Zp(r){if(!r.responsive)return r;const e=ei.getWidth(),t=ei.getMatchingKey(r.responsive,e);if(!t)return r;const a=r.responsive[t];return{...r,props:{...r.props,...a.props},children:a.children??r.children,text:a.text??r.text,if:a.if??r.if,iteration:a.iteration??r.iteration}}function fo(r,e,t,a,i){if(!r||r.length===0)return[];const o=i?.bindingEngine??new _n,d=i?.translationEngine??xr.getInstance(),g=i?.translationContext??{templateId:"",locale:"ko"},h=zw(e,i?.componentContext),f=(x,S)=>{if(typeof x=="string"){if(Fp(x))return Kp(x);if(Vp(x)){const w=[],k=x.replace(new RegExp(`${tc}([^${co}]*)${co}`,"g"),(O,N)=>(w.push(N),`${Rs}${w.length-1}${Rs}`));let A=k;return/\$t:[a-zA-Z0-9._-]+/.test(k)&&(A=d.resolveTranslations(k,g,S)),A.replace(new RegExp(`${Rs}(\\d+)${Rs}`,"g"),(O,N)=>w[parseInt(N)])}if(x.startsWith("$t:defer:")){const w="$t:"+x.slice(9);return d.resolveTranslations(w,g,S)}if(x.startsWith("$t:"))return d.resolveTranslations(x,g,S);const v=Xp(x);if(v!==null){let w=!1,k=v;v.startsWith(Ds)&&(w=!0,k=v.slice(Ds.length));let A;if(Fu(k))try{A=o.evaluateExpression(k,S)}catch(O){ts.warn("renderItemChildren: 표현식 평가 실패:",O);return}else A=o.resolve(k,S,{skipCache:!0});return!w&&typeof A=="string"&&/\$t:[a-zA-Z0-9._-]+/.test(A)&&(A=d.resolveTranslations(A,g,S)),w&&A!=null?go(A):A}if(x.includes("{{")){const w=o.resolveBindings(x,S,{skipCache:!0});return typeof w=="string"&&/\$t:[a-zA-Z0-9._-]+/.test(w)?d.resolveTranslations(w,g,S):w}return x}if(Array.isArray(x))return x.map(v=>f(v,S));if(x&&typeof x=="object"){const v={};for(const[w,k]of Object.entries(x))v[w]=f(k,S);return v}return x},p=(x,S)=>{if(!x)return{};const v={};for(const[w,k]of Object.entries(x))v[w]=f(k,S);return v},y=(x,S,v)=>{const w=Zp(x),k=w.iteration;if(!k)return[];const A=Vu(k.source,v,o);if(!Array.isArray(A))return ts.warn(`renderItemChildren: iteration.source가 배열이 아닙니다: ${k.source}`),[];const O=Yp();if(O?.isEnabled()){const D=`${S}-iteration`;O.trackIteration(D,k.source,k.item_var,k.index_var,A.length)}const N=t[w.name];return N?A.flatMap((D,$)=>{const M={...v,[k.item_var]:D,[`${k.item_var}_index`]:$,...k.index_var?{[k.index_var]:$}:{}},z=ti({if:w.if,condition:w.condition,conditions:w.conditions},M,o,w.id);if(w.if&&O?.isEnabled()){const de=`${S}-iter-${$}-if`;O.trackIfCondition(de,w.if,z,w.name)}if(!z)return[];const K=w.id?String(f(w.id,M)):void 0,ye=`${S}-iter-${$}`,we=i?.getRemountKey?i.getRemountKey(K,ye):ye,J=p(w.props,M),ve=Ku(J,w.actions,M,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let le=null;return w.text!==void 0?le=f(w.text,M):w.children&&w.children.length>0&&(le=fo(w.children,M,t,we,i)),O?.isEnabled()&&O.trackRender(w.name),[Ke.createElement(N,{key:we,...ve},le)]}):(ts.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${w.name}`),[])};return r.flatMap((x,S)=>{const v=Zp(x),w=v.id?String(f(v.id,h)):void 0,k=a?`${a}-${w||S}`:w||`child-${S}`,A=i?.getRemountKey?i.getRemountKey(w,k):k;if(v.iteration)return y(v,A,h);const O=ti({if:v.if,condition:v.condition,conditions:v.conditions},h,o,v.id),N=Yp();if(v.if&&N?.isEnabled()){const K=`${A}-if`;N.trackIfCondition(K,v.if,O,v.name)}if(!O)return[];const D=t[v.name];if(!D)return ts.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${v.name}`),[];const $=p(v.props,h),M=Ku($,v.actions,h,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let z=null;return v.text!==void 0?z=f(v.text,h):v.children&&v.children.length>0&&(z=fo(v.children,h,t,A,i)),N?.isEnabled()&&N.trackRender(v.name),[Ke.createElement(D,{key:A,...M},z)]})}function ni(r,e,t,a){let i,o;return t instanceof _n?(i=t,o=a):(i=Jp,o=t),i.resolveBindings(r,e,o)}function Hw(r,e,t,a){const i=t??Jp,o={skipCache:!0,...a};let d;try{d=i.resolveBindings(r.key,e,{skipCache:o.skipCache})?.toString()?.trim()??""}catch(f){ts.warn("resolveClassMap: key 평가 실패:",r.key,f),d=""}let g="";d&&r.variants&&d in r.variants?g=r.variants[d]:r.default&&(g=r.default);const h=[];return r.base?.trim()&&h.push(r.base.trim()),g?.trim()&&h.push(g.trim()),h.join(" ")}function em(r,e){return function(){return r.apply(e,arguments)}}const{toString:Pw}=Object.prototype,{getPrototypeOf:Wu}=Object,{iterator:ic,toStringTag:tm}=Symbol,oc=(r=>e=>{const t=Pw.call(e);return r[t]||(r[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),va=r=>(r=r.toLowerCase(),e=>oc(e)===r),lc=r=>e=>typeof e===r,{isArray:ai}=Array,si=lc("undefined");function po(r){return r!==null&&!si(r)&&r.constructor!==null&&!si(r.constructor)&&Rn(r.constructor.isBuffer)&&r.constructor.isBuffer(r)}const nm=va("ArrayBuffer");function Bw(r){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(r):e=r&&r.buffer&&nm(r.buffer),e}const Uw=lc("string"),Rn=lc("function"),am=lc("number"),mo=r=>r!==null&&typeof r=="object",qw=r=>r===!0||r===!1,cc=r=>{if(oc(r)!=="object")return!1;const e=Wu(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(tm in r)&&!(ic in r)},Gw=r=>{if(!mo(r)||po(r))return!1;try{return Object.keys(r).length===0&&Object.getPrototypeOf(r)===Object.prototype}catch{return!1}},Fw=va("Date"),Vw=va("File"),Kw=va("Blob"),Ww=va("FileList"),Yw=r=>mo(r)&&Rn(r.pipe),Jw=r=>{let e;return r&&(typeof FormData=="function"&&r instanceof FormData||Rn(r.append)&&((e=oc(r))==="formdata"||e==="object"&&Rn(r.toString)&&r.toString()==="[object FormData]"))},Xw=va("URLSearchParams"),[Qw,Zw,eS,tS]=["ReadableStream","Request","Response","Headers"].map(va),nS=r=>r.trim?r.trim():r.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function yo(r,e,{allOwnKeys:t=!1}={}){if(r===null||typeof r>"u")return;let a,i;if(typeof r!="object"&&(r=[r]),ai(r))for(a=0,i=r.length;a0;)if(i=t[a],e===i.toLowerCase())return i;return null}const br=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,rm=r=>!si(r)&&r!==br;function Yu(){const{caseless:r,skipUndefined:e}=rm(this)&&this||{},t={},a=(i,o)=>{const d=r&&sm(t,o)||o;cc(t[d])&&cc(i)?t[d]=Yu(t[d],i):cc(i)?t[d]=Yu({},i):ai(i)?t[d]=i.slice():(!e||!si(i))&&(t[d]=i)};for(let i=0,o=arguments.length;i(yo(e,(i,o)=>{t&&Rn(i)?r[o]=em(i,t):r[o]=i},{allOwnKeys:a}),r),sS=r=>(r.charCodeAt(0)===65279&&(r=r.slice(1)),r),rS=(r,e,t,a)=>{r.prototype=Object.create(e.prototype,a),r.prototype.constructor=r,Object.defineProperty(r,"super",{value:e.prototype}),t&&Object.assign(r.prototype,t)},iS=(r,e,t,a)=>{let i,o,d;const g={};if(e=e||{},r==null)return e;do{for(i=Object.getOwnPropertyNames(r),o=i.length;o-- >0;)d=i[o],(!a||a(d,r,e))&&!g[d]&&(e[d]=r[d],g[d]=!0);r=t!==!1&&Wu(r)}while(r&&(!t||t(r,e))&&r!==Object.prototype);return e},oS=(r,e,t)=>{r=String(r),(t===void 0||t>r.length)&&(t=r.length),t-=e.length;const a=r.indexOf(e,t);return a!==-1&&a===t},lS=r=>{if(!r)return null;if(ai(r))return r;let e=r.length;if(!am(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=r[e];return t},cS=(r=>e=>r&&e instanceof r)(typeof Uint8Array<"u"&&Wu(Uint8Array)),dS=(r,e)=>{const a=(r&&r[ic]).call(r);let i;for(;(i=a.next())&&!i.done;){const o=i.value;e.call(r,o[0],o[1])}},uS=(r,e)=>{let t;const a=[];for(;(t=r.exec(e))!==null;)a.push(t);return a},gS=va("HTMLFormElement"),hS=r=>r.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,a,i){return a.toUpperCase()+i}),im=(({hasOwnProperty:r})=>(e,t)=>r.call(e,t))(Object.prototype),fS=va("RegExp"),om=(r,e)=>{const t=Object.getOwnPropertyDescriptors(r),a={};yo(t,(i,o)=>{let d;(d=e(i,o,r))!==!1&&(a[o]=d||i)}),Object.defineProperties(r,a)},pS=r=>{om(r,(e,t)=>{if(Rn(r)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const a=r[t];if(Rn(a)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},mS=(r,e)=>{const t={},a=i=>{i.forEach(o=>{t[o]=!0})};return ai(r)?a(r):a(String(r).split(e)),t},yS=()=>{},xS=(r,e)=>r!=null&&Number.isFinite(r=+r)?r:e;function bS(r){return!!(r&&Rn(r.append)&&r[tm]==="FormData"&&r[ic])}const vS=r=>{const e=new Array(10),t=(a,i)=>{if(mo(a)){if(e.indexOf(a)>=0)return;if(po(a))return a;if(!("toJSON"in a)){e[i]=a;const o=ai(a)?[]:{};return yo(a,(d,g)=>{const h=t(d,i+1);!si(h)&&(o[g]=h)}),e[i]=void 0,o}}return a};return t(r,0)},wS=va("AsyncFunction"),SS=r=>r&&(mo(r)||Rn(r))&&Rn(r.then)&&Rn(r.catch),lm=((r,e)=>r?setImmediate:e?((t,a)=>(br.addEventListener("message",({source:i,data:o})=>{i===br&&o===t&&a.length&&a.shift()()},!1),i=>{a.push(i),br.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",Rn(br.postMessage)),CS=typeof queueMicrotask<"u"?queueMicrotask.bind(br):typeof process<"u"&&process.nextTick||lm,se={isArray:ai,isArrayBuffer:nm,isBuffer:po,isFormData:Jw,isArrayBufferView:Bw,isString:Uw,isNumber:am,isBoolean:qw,isObject:mo,isPlainObject:cc,isEmptyObject:Gw,isReadableStream:Qw,isRequest:Zw,isResponse:eS,isHeaders:tS,isUndefined:si,isDate:Fw,isFile:Vw,isBlob:Kw,isRegExp:fS,isFunction:Rn,isStream:Yw,isURLSearchParams:Xw,isTypedArray:cS,isFileList:Ww,forEach:yo,merge:Yu,extend:aS,trim:nS,stripBOM:sS,inherits:rS,toFlatObject:iS,kindOf:oc,kindOfTest:va,endsWith:oS,toArray:lS,forEachEntry:dS,matchAll:uS,isHTMLForm:gS,hasOwnProperty:im,hasOwnProp:im,reduceDescriptors:om,freezeMethods:pS,toObjectSet:mS,toCamelCase:hS,noop:yS,toFiniteNumber:xS,findKey:sm,global:br,isContextDefined:rm,isSpecCompliantForm:bS,toJSONObject:vS,isAsyncFn:wS,isThenable:SS,setImmediate:lm,asap:CS,isIterable:r=>r!=null&&Rn(r[ic])};function nt(r,e,t,a,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=r,this.name="AxiosError",e&&(this.code=e),t&&(this.config=t),a&&(this.request=a),i&&(this.response=i,this.status=i.status?i.status:null)}se.inherits(nt,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:se.toJSONObject(this.config),code:this.code,status:this.status}}});const cm=nt.prototype,dm={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(r=>{dm[r]={value:r}}),Object.defineProperties(nt,dm),Object.defineProperty(cm,"isAxiosError",{value:!0}),nt.from=(r,e,t,a,i,o)=>{const d=Object.create(cm);se.toFlatObject(r,d,function(p){return p!==Error.prototype},f=>f!=="isAxiosError");const g=r&&r.message?r.message:"Error",h=e==null&&r?r.code:e;return nt.call(d,g,h,t,a,i),r&&d.cause==null&&Object.defineProperty(d,"cause",{value:r,configurable:!0}),d.name=r&&r.name||"Error",o&&Object.assign(d,o),d};const jS=null;function Ju(r){return se.isPlainObject(r)||se.isArray(r)}function um(r){return se.endsWith(r,"[]")?r.slice(0,-2):r}function gm(r,e,t){return r?r.concat(e).map(function(i,o){return i=um(i),!t&&o?"["+i+"]":i}).join(t?".":""):e}function kS(r){return se.isArray(r)&&!r.some(Ju)}const NS=se.toFlatObject(se,{},null,function(e){return/^is[A-Z]/.test(e)});function dc(r,e,t){if(!se.isObject(r))throw new TypeError("target must be an object");e=e||new FormData,t=se.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(w,k){return!se.isUndefined(k[w])});const a=t.metaTokens,i=t.visitor||p,o=t.dots,d=t.indexes,h=(t.Blob||typeof Blob<"u"&&Blob)&&se.isSpecCompliantForm(e);if(!se.isFunction(i))throw new TypeError("visitor must be a function");function f(v){if(v===null)return"";if(se.isDate(v))return v.toISOString();if(se.isBoolean(v))return v.toString();if(!h&&se.isBlob(v))throw new nt("Blob is not supported. Use a Buffer instead.");return se.isArrayBuffer(v)||se.isTypedArray(v)?h&&typeof Blob=="function"?new Blob([v]):Buffer.from(v):v}function p(v,w,k){let A=v;if(v&&!k&&typeof v=="object"){if(se.endsWith(w,"{}"))w=a?w:w.slice(0,-2),v=JSON.stringify(v);else if(se.isArray(v)&&kS(v)||(se.isFileList(v)||se.endsWith(w,"[]"))&&(A=se.toArray(v)))return w=um(w),A.forEach(function(N,D){!(se.isUndefined(N)||N===null)&&e.append(d===!0?gm([w],D,o):d===null?w:w+"[]",f(N))}),!1}return Ju(v)?!0:(e.append(gm(k,w,o),f(v)),!1)}const y=[],x=Object.assign(NS,{defaultVisitor:p,convertValue:f,isVisitable:Ju});function S(v,w){if(!se.isUndefined(v)){if(y.indexOf(v)!==-1)throw Error("Circular reference detected in "+w.join("."));y.push(v),se.forEach(v,function(A,O){(!(se.isUndefined(A)||A===null)&&i.call(e,A,se.isString(O)?O.trim():O,w,x))===!0&&S(A,w?w.concat(O):[O])}),y.pop()}}if(!se.isObject(r))throw new TypeError("data must be an object");return S(r),e}function hm(r){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(r).replace(/[!'()~]|%20|%00/g,function(a){return e[a]})}function Xu(r,e){this._pairs=[],r&&dc(r,this,e)}const fm=Xu.prototype;fm.append=function(e,t){this._pairs.push([e,t])},fm.toString=function(e){const t=e?function(a){return e.call(this,a,hm)}:hm;return this._pairs.map(function(i){return t(i[0])+"="+t(i[1])},"").join("&")};function ES(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function pm(r,e,t){if(!e)return r;const a=t&&t.encode||ES;se.isFunction(t)&&(t={serialize:t});const i=t&&t.serialize;let o;if(i?o=i(e,t):o=se.isURLSearchParams(e)?e.toString():new Xu(e,t).toString(a),o){const d=r.indexOf("#");d!==-1&&(r=r.slice(0,d)),r+=(r.indexOf("?")===-1?"?":"&")+o}return r}class mm{constructor(){this.handlers=[]}use(e,t,a){return this.handlers.push({fulfilled:e,rejected:t,synchronous:a?a.synchronous:!1,runWhen:a?a.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){se.forEach(this.handlers,function(a){a!==null&&e(a)})}}const ym={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},_S={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:Xu,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},Qu=typeof window<"u"&&typeof document<"u",Zu=typeof navigator=="object"&&navigator||void 0,AS=Qu&&(!Zu||["ReactNative","NativeScript","NS"].indexOf(Zu.product)<0),TS=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",DS=Qu&&window.location.href||"http://localhost",Nn={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Qu,hasStandardBrowserEnv:AS,hasStandardBrowserWebWorkerEnv:TS,navigator:Zu,origin:DS},Symbol.toStringTag,{value:"Module"})),..._S};function RS(r,e){return dc(r,new Nn.classes.URLSearchParams,{visitor:function(t,a,i,o){return Nn.isNode&&se.isBuffer(t)?(this.append(a,t.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...e})}function OS(r){return se.matchAll(/\w+|\[(\w*)]/g,r).map(e=>e[0]==="[]"?"":e[1]||e[0])}function LS(r){const e={},t=Object.keys(r);let a;const i=t.length;let o;for(a=0;a=t.length;return d=!d&&se.isArray(i)?i.length:d,h?(se.hasOwnProp(i,d)?i[d]=[i[d],a]:i[d]=a,!g):((!i[d]||!se.isObject(i[d]))&&(i[d]=[]),e(t,a,i[d],o)&&se.isArray(i[d])&&(i[d]=LS(i[d])),!g)}if(se.isFormData(r)&&se.isFunction(r.entries)){const t={};return se.forEachEntry(r,(a,i)=>{e(OS(a),i,t,0)}),t}return null}function MS(r,e,t){if(se.isString(r))try{return(e||JSON.parse)(r),se.trim(r)}catch(a){if(a.name!=="SyntaxError")throw a}return(t||JSON.stringify)(r)}const xo={transitional:ym,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const a=t.getContentType()||"",i=a.indexOf("application/json")>-1,o=se.isObject(e);if(o&&se.isHTMLForm(e)&&(e=new FormData(e)),se.isFormData(e))return i?JSON.stringify(xm(e)):e;if(se.isArrayBuffer(e)||se.isBuffer(e)||se.isStream(e)||se.isFile(e)||se.isBlob(e)||se.isReadableStream(e))return e;if(se.isArrayBufferView(e))return e.buffer;if(se.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let g;if(o){if(a.indexOf("application/x-www-form-urlencoded")>-1)return RS(e,this.formSerializer).toString();if((g=se.isFileList(e))||a.indexOf("multipart/form-data")>-1){const h=this.env&&this.env.FormData;return dc(g?{"files[]":e}:e,h&&new h,this.formSerializer)}}return o||i?(t.setContentType("application/json",!1),MS(e)):e}],transformResponse:[function(e){const t=this.transitional||xo.transitional,a=t&&t.forcedJSONParsing,i=this.responseType==="json";if(se.isResponse(e)||se.isReadableStream(e))return e;if(e&&se.isString(e)&&(a&&!this.responseType||i)){const d=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e,this.parseReviver)}catch(g){if(d)throw g.name==="SyntaxError"?nt.from(g,nt.ERR_BAD_RESPONSE,this,null,this.response):g}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Nn.classes.FormData,Blob:Nn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};se.forEach(["delete","get","head","post","put","patch"],r=>{xo.headers[r]={}});const $S=se.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),IS=r=>{const e={};let t,a,i;return r&&r.split(` +`).forEach(function(d){i=d.indexOf(":"),t=d.substring(0,i).trim().toLowerCase(),a=d.substring(i+1).trim(),!(!t||e[t]&&$S[t])&&(t==="set-cookie"?e[t]?e[t].push(a):e[t]=[a]:e[t]=e[t]?e[t]+", "+a:a)}),e},bm=Symbol("internals");function bo(r){return r&&String(r).trim().toLowerCase()}function uc(r){return r===!1||r==null?r:se.isArray(r)?r.map(uc):String(r)}function zS(r){const e=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let a;for(;a=t.exec(r);)e[a[1]]=a[2];return e}const HS=r=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(r.trim());function eg(r,e,t,a,i){if(se.isFunction(a))return a.call(this,e,t);if(i&&(e=t),!!se.isString(e)){if(se.isString(a))return e.indexOf(a)!==-1;if(se.isRegExp(a))return a.test(e)}}function PS(r){return r.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,a)=>t.toUpperCase()+a)}function BS(r,e){const t=se.toCamelCase(" "+e);["get","set","has"].forEach(a=>{Object.defineProperty(r,a+t,{value:function(i,o,d){return this[a].call(this,e,i,o,d)},configurable:!0})})}let On=class{constructor(e){e&&this.set(e)}set(e,t,a){const i=this;function o(g,h,f){const p=bo(h);if(!p)throw new Error("header name must be a non-empty string");const y=se.findKey(i,p);(!y||i[y]===void 0||f===!0||f===void 0&&i[y]!==!1)&&(i[y||h]=uc(g))}const d=(g,h)=>se.forEach(g,(f,p)=>o(f,p,h));if(se.isPlainObject(e)||e instanceof this.constructor)d(e,t);else if(se.isString(e)&&(e=e.trim())&&!HS(e))d(IS(e),t);else if(se.isObject(e)&&se.isIterable(e)){let g={},h,f;for(const p of e){if(!se.isArray(p))throw TypeError("Object iterator must return a key-value pair");g[f=p[0]]=(h=g[f])?se.isArray(h)?[...h,p[1]]:[h,p[1]]:p[1]}d(g,t)}else e!=null&&o(t,e,a);return this}get(e,t){if(e=bo(e),e){const a=se.findKey(this,e);if(a){const i=this[a];if(!t)return i;if(t===!0)return zS(i);if(se.isFunction(t))return t.call(this,i,a);if(se.isRegExp(t))return t.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=bo(e),e){const a=se.findKey(this,e);return!!(a&&this[a]!==void 0&&(!t||eg(this,this[a],a,t)))}return!1}delete(e,t){const a=this;let i=!1;function o(d){if(d=bo(d),d){const g=se.findKey(a,d);g&&(!t||eg(a,a[g],g,t))&&(delete a[g],i=!0)}}return se.isArray(e)?e.forEach(o):o(e),i}clear(e){const t=Object.keys(this);let a=t.length,i=!1;for(;a--;){const o=t[a];(!e||eg(this,this[o],o,e,!0))&&(delete this[o],i=!0)}return i}normalize(e){const t=this,a={};return se.forEach(this,(i,o)=>{const d=se.findKey(a,o);if(d){t[d]=uc(i),delete t[o];return}const g=e?PS(o):String(o).trim();g!==o&&delete t[o],t[g]=uc(i),a[g]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return se.forEach(this,(a,i)=>{a!=null&&a!==!1&&(t[i]=e&&se.isArray(a)?a.join(", "):a)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join(` +`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const a=new this(e);return t.forEach(i=>a.set(i)),a}static accessor(e){const a=(this[bm]=this[bm]={accessors:{}}).accessors,i=this.prototype;function o(d){const g=bo(d);a[g]||(BS(i,d),a[g]=!0)}return se.isArray(e)?e.forEach(o):o(e),this}};On.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),se.reduceDescriptors(On.prototype,({value:r},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>r,set(a){this[t]=a}}}),se.freezeMethods(On);function tg(r,e){const t=this||xo,a=e||t,i=On.from(a.headers);let o=a.data;return se.forEach(r,function(g){o=g.call(t,o,i.normalize(),e?e.status:void 0)}),i.normalize(),o}function vm(r){return!!(r&&r.__CANCEL__)}function ri(r,e,t){nt.call(this,r??"canceled",nt.ERR_CANCELED,e,t),this.name="CanceledError"}se.inherits(ri,nt,{__CANCEL__:!0});function wm(r,e,t){const a=t.config.validateStatus;!t.status||!a||a(t.status)?r(t):e(new nt("Request failed with status code "+t.status,[nt.ERR_BAD_REQUEST,nt.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function US(r){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(r);return e&&e[1]||""}function qS(r,e){r=r||10;const t=new Array(r),a=new Array(r);let i=0,o=0,d;return e=e!==void 0?e:1e3,function(h){const f=Date.now(),p=a[o];d||(d=f),t[i]=h,a[i]=f;let y=o,x=0;for(;y!==i;)x+=t[y++],y=y%r;if(i=(i+1)%r,i===o&&(o=(o+1)%r),f-d{t=p,i=null,o&&(clearTimeout(o),o=null),r(...f)};return[(...f)=>{const p=Date.now(),y=p-t;y>=a?d(f,p):(i=f,o||(o=setTimeout(()=>{o=null,d(i)},a-y)))},()=>i&&d(i)]}const gc=(r,e,t=3)=>{let a=0;const i=qS(50,250);return GS(o=>{const d=o.loaded,g=o.lengthComputable?o.total:void 0,h=d-a,f=i(h),p=d<=g;a=d;const y={loaded:d,total:g,progress:g?d/g:void 0,bytes:h,rate:f||void 0,estimated:f&&g&&p?(g-d)/f:void 0,event:o,lengthComputable:g!=null,[e?"download":"upload"]:!0};r(y)},t)},Sm=(r,e)=>{const t=r!=null;return[a=>e[0]({lengthComputable:t,total:r,loaded:a}),e[1]]},Cm=r=>(...e)=>se.asap(()=>r(...e)),FS=Nn.hasStandardBrowserEnv?((r,e)=>t=>(t=new URL(t,Nn.origin),r.protocol===t.protocol&&r.host===t.host&&(e||r.port===t.port)))(new URL(Nn.origin),Nn.navigator&&/(msie|trident)/i.test(Nn.navigator.userAgent)):()=>!0,VS=Nn.hasStandardBrowserEnv?{write(r,e,t,a,i,o){const d=[r+"="+encodeURIComponent(e)];se.isNumber(t)&&d.push("expires="+new Date(t).toGMTString()),se.isString(a)&&d.push("path="+a),se.isString(i)&&d.push("domain="+i),o===!0&&d.push("secure"),document.cookie=d.join("; ")},read(r){const e=document.cookie.match(new RegExp("(^|;\\s*)("+r+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(r){this.write(r,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function KS(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function WS(r,e){return e?r.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):r}function jm(r,e,t){let a=!KS(e);return r&&(a||t==!1)?WS(r,e):e}const km=r=>r instanceof On?{...r}:r;function vr(r,e){e=e||{};const t={};function a(f,p,y,x){return se.isPlainObject(f)&&se.isPlainObject(p)?se.merge.call({caseless:x},f,p):se.isPlainObject(p)?se.merge({},p):se.isArray(p)?p.slice():p}function i(f,p,y,x){if(se.isUndefined(p)){if(!se.isUndefined(f))return a(void 0,f,y,x)}else return a(f,p,y,x)}function o(f,p){if(!se.isUndefined(p))return a(void 0,p)}function d(f,p){if(se.isUndefined(p)){if(!se.isUndefined(f))return a(void 0,f)}else return a(void 0,p)}function g(f,p,y){if(y in e)return a(f,p);if(y in r)return a(void 0,f)}const h={url:o,method:o,data:o,baseURL:d,transformRequest:d,transformResponse:d,paramsSerializer:d,timeout:d,timeoutMessage:d,withCredentials:d,withXSRFToken:d,adapter:d,responseType:d,xsrfCookieName:d,xsrfHeaderName:d,onUploadProgress:d,onDownloadProgress:d,decompress:d,maxContentLength:d,maxBodyLength:d,beforeRedirect:d,transport:d,httpAgent:d,httpsAgent:d,cancelToken:d,socketPath:d,responseEncoding:d,validateStatus:g,headers:(f,p,y)=>i(km(f),km(p),y,!0)};return se.forEach(Object.keys({...r,...e}),function(p){const y=h[p]||i,x=y(r[p],e[p],p);se.isUndefined(x)&&y!==g||(t[p]=x)}),t}const Nm=r=>{const e=vr({},r);let{data:t,withXSRFToken:a,xsrfHeaderName:i,xsrfCookieName:o,headers:d,auth:g}=e;if(e.headers=d=On.from(d),e.url=pm(jm(e.baseURL,e.url,e.allowAbsoluteUrls),r.params,r.paramsSerializer),g&&d.set("Authorization","Basic "+btoa((g.username||"")+":"+(g.password?unescape(encodeURIComponent(g.password)):""))),se.isFormData(t)){if(Nn.hasStandardBrowserEnv||Nn.hasStandardBrowserWebWorkerEnv)d.setContentType(void 0);else if(se.isFunction(t.getHeaders)){const h=t.getHeaders(),f=["content-type","content-length"];Object.entries(h).forEach(([p,y])=>{f.includes(p.toLowerCase())&&d.set(p,y)})}}if(Nn.hasStandardBrowserEnv&&(a&&se.isFunction(a)&&(a=a(e)),a||a!==!1&&FS(e.url))){const h=i&&o&&VS.read(o);h&&d.set(i,h)}return e},YS=typeof XMLHttpRequest<"u"&&function(r){return new Promise(function(t,a){const i=Nm(r);let o=i.data;const d=On.from(i.headers).normalize();let{responseType:g,onUploadProgress:h,onDownloadProgress:f}=i,p,y,x,S,v;function w(){S&&S(),v&&v(),i.cancelToken&&i.cancelToken.unsubscribe(p),i.signal&&i.signal.removeEventListener("abort",p)}let k=new XMLHttpRequest;k.open(i.method.toUpperCase(),i.url,!0),k.timeout=i.timeout;function A(){if(!k)return;const N=On.from("getAllResponseHeaders"in k&&k.getAllResponseHeaders()),$={data:!g||g==="text"||g==="json"?k.responseText:k.response,status:k.status,statusText:k.statusText,headers:N,config:r,request:k};wm(function(z){t(z),w()},function(z){a(z),w()},$),k=null}"onloadend"in k?k.onloadend=A:k.onreadystatechange=function(){!k||k.readyState!==4||k.status===0&&!(k.responseURL&&k.responseURL.indexOf("file:")===0)||setTimeout(A)},k.onabort=function(){k&&(a(new nt("Request aborted",nt.ECONNABORTED,r,k)),k=null)},k.onerror=function(D){const $=D&&D.message?D.message:"Network Error",M=new nt($,nt.ERR_NETWORK,r,k);M.event=D||null,a(M),k=null},k.ontimeout=function(){let D=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const $=i.transitional||ym;i.timeoutErrorMessage&&(D=i.timeoutErrorMessage),a(new nt(D,$.clarifyTimeoutError?nt.ETIMEDOUT:nt.ECONNABORTED,r,k)),k=null},o===void 0&&d.setContentType(null),"setRequestHeader"in k&&se.forEach(d.toJSON(),function(D,$){k.setRequestHeader($,D)}),se.isUndefined(i.withCredentials)||(k.withCredentials=!!i.withCredentials),g&&g!=="json"&&(k.responseType=i.responseType),f&&([x,v]=gc(f,!0),k.addEventListener("progress",x)),h&&k.upload&&([y,S]=gc(h),k.upload.addEventListener("progress",y),k.upload.addEventListener("loadend",S)),(i.cancelToken||i.signal)&&(p=N=>{k&&(a(!N||N.type?new ri(null,r,k):N),k.abort(),k=null)},i.cancelToken&&i.cancelToken.subscribe(p),i.signal&&(i.signal.aborted?p():i.signal.addEventListener("abort",p)));const O=US(i.url);if(O&&Nn.protocols.indexOf(O)===-1){a(new nt("Unsupported protocol "+O+":",nt.ERR_BAD_REQUEST,r));return}k.send(o||null)})},JS=(r,e)=>{const{length:t}=r=r?r.filter(Boolean):[];if(e||t){let a=new AbortController,i;const o=function(f){if(!i){i=!0,g();const p=f instanceof Error?f:this.reason;a.abort(p instanceof nt?p:new ri(p instanceof Error?p.message:p))}};let d=e&&setTimeout(()=>{d=null,o(new nt(`timeout ${e} of ms exceeded`,nt.ETIMEDOUT))},e);const g=()=>{r&&(d&&clearTimeout(d),d=null,r.forEach(f=>{f.unsubscribe?f.unsubscribe(o):f.removeEventListener("abort",o)}),r=null)};r.forEach(f=>f.addEventListener("abort",o));const{signal:h}=a;return h.unsubscribe=()=>se.asap(g),h}},XS=function*(r,e){let t=r.byteLength;if(t{const i=QS(r,e);let o=0,d,g=h=>{d||(d=!0,a&&a(h))};return new ReadableStream({async pull(h){try{const{done:f,value:p}=await i.next();if(f){g(),h.close();return}let y=p.byteLength;if(t){let x=o+=y;t(x)}h.enqueue(new Uint8Array(p))}catch(f){throw g(f),f}},cancel(h){return g(h),i.return()}},{highWaterMark:2})},_m=64*1024,{isFunction:hc}=se,e7=(({Request:r,Response:e})=>({Request:r,Response:e}))(se.global),{ReadableStream:Am,TextEncoder:Tm}=se.global,Dm=(r,...e)=>{try{return!!r(...e)}catch{return!1}},t7=r=>{r=se.merge.call({skipUndefined:!0},e7,r);const{fetch:e,Request:t,Response:a}=r,i=e?hc(e):typeof fetch=="function",o=hc(t),d=hc(a);if(!i)return!1;const g=i&&hc(Am),h=i&&(typeof Tm=="function"?(v=>w=>v.encode(w))(new Tm):async v=>new Uint8Array(await new t(v).arrayBuffer())),f=o&&g&&Dm(()=>{let v=!1;const w=new t(Nn.origin,{body:new Am,method:"POST",get duplex(){return v=!0,"half"}}).headers.has("Content-Type");return v&&!w}),p=d&&g&&Dm(()=>se.isReadableStream(new a("").body)),y={stream:p&&(v=>v.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(v=>{!y[v]&&(y[v]=(w,k)=>{let A=w&&w[v];if(A)return A.call(w);throw new nt(`Response type '${v}' is not supported`,nt.ERR_NOT_SUPPORT,k)})});const x=async v=>{if(v==null)return 0;if(se.isBlob(v))return v.size;if(se.isSpecCompliantForm(v))return(await new t(Nn.origin,{method:"POST",body:v}).arrayBuffer()).byteLength;if(se.isArrayBufferView(v)||se.isArrayBuffer(v))return v.byteLength;if(se.isURLSearchParams(v)&&(v=v+""),se.isString(v))return(await h(v)).byteLength},S=async(v,w)=>{const k=se.toFiniteNumber(v.getContentLength());return k??x(w)};return async v=>{let{url:w,method:k,data:A,signal:O,cancelToken:N,timeout:D,onDownloadProgress:$,onUploadProgress:M,responseType:z,headers:K,withCredentials:ye="same-origin",fetchOptions:we}=Nm(v),J=e||fetch;z=z?(z+"").toLowerCase():"text";let ve=JS([O,N&&N.toAbortSignal()],D),le=null;const de=ve&&ve.unsubscribe&&(()=>{ve.unsubscribe()});let je;try{if(M&&f&&k!=="get"&&k!=="head"&&(je=await S(K,A))!==0){let R=new t(w,{method:"POST",body:A,duplex:"half"}),U;if(se.isFormData(A)&&(U=R.headers.get("content-type"))&&K.setContentType(U),R.body){const[re,xe]=Sm(je,gc(Cm(M)));A=Em(R.body,_m,re,xe)}}se.isString(ye)||(ye=ye?"include":"omit");const W=o&&"credentials"in t.prototype,he={...we,signal:ve,method:k.toUpperCase(),headers:K.normalize().toJSON(),body:A,duplex:"half",credentials:W?ye:void 0};le=o&&new t(w,he);let ee=await(o?J(le,we):J(w,he));const X=p&&(z==="stream"||z==="response");if(p&&($||X&&de)){const R={};["status","statusText","headers"].forEach(oe=>{R[oe]=ee[oe]});const U=se.toFiniteNumber(ee.headers.get("content-length")),[re,xe]=$&&Sm(U,gc(Cm($),!0))||[];ee=new a(Em(ee.body,_m,re,()=>{xe&&xe(),de&&de()}),R)}z=z||"text";let ae=await y[se.findKey(y,z)||"text"](ee,v);return!X&&de&&de(),await new Promise((R,U)=>{wm(R,U,{data:ae,headers:On.from(ee.headers),status:ee.status,statusText:ee.statusText,config:v,request:le})})}catch(W){throw de&&de(),W&&W.name==="TypeError"&&/Load failed|fetch/i.test(W.message)?Object.assign(new nt("Network Error",nt.ERR_NETWORK,v,le),{cause:W.cause||W}):nt.from(W,W&&W.code,v,le)}}},n7=new Map,Rm=r=>{let e=r?r.env:{};const{fetch:t,Request:a,Response:i}=e,o=[a,i,t];let d=o.length,g=d,h,f,p=n7;for(;g--;)h=o[g],f=p.get(h),f===void 0&&p.set(h,f=g?new Map:t7(e)),p=f;return f};Rm();const ng={http:jS,xhr:YS,fetch:{get:Rm}};se.forEach(ng,(r,e)=>{if(r){try{Object.defineProperty(r,"name",{value:e})}catch{}Object.defineProperty(r,"adapterName",{value:e})}});const Om=r=>`- ${r}`,a7=r=>se.isFunction(r)||r===null||r===!1,Lm={getAdapter:(r,e)=>{r=se.isArray(r)?r:[r];const{length:t}=r;let a,i;const o={};for(let d=0;d`adapter ${h} `+(f===!1?"is not supported by the environment":"is not available in the build"));let g=t?d.length>1?`since : `+d.map(Om).join(` -`):" "+Om(d[0]):"as no adapter specified";throw new nt("There is no suitable adapter to dispatch the request "+g,"ERR_NOT_SUPPORT")}return i},adapters:ng};function ag(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new ri(null,r)}function Mm(r){return ag(r),r.headers=On.from(r.headers),r.data=tg.call(r,r.transformRequest),["post","put","patch"].indexOf(r.method)!==-1&&r.headers.setContentType("application/x-www-form-urlencoded",!1),Lm.getAdapter(r.adapter||xo.adapter,r)(r).then(function(a){return ag(r),a.data=tg.call(r,r.transformResponse,a),a.headers=On.from(a.headers),a},function(a){return vm(a)||(ag(r),a&&a.response&&(a.response.data=tg.call(r,r.transformResponse,a.response),a.response.headers=On.from(a.response.headers))),Promise.reject(a)})}const $m="1.12.2",hc={};["object","boolean","number","function","string","symbol"].forEach((r,e)=>{hc[r]=function(a){return typeof a===r||"a"+(e<1?"n ":" ")+r}});const Im={};hc.transitional=function(e,t,a){function i(o,d){return"[Axios v"+$m+"] Transitional option '"+o+"'"+d+(a?". "+a:"")}return(o,d,g)=>{if(e===!1)throw new nt(i(d," has been removed"+(t?" in "+t:"")),nt.ERR_DEPRECATED);return t&&!Im[d]&&(Im[d]=!0,console.warn(i(d," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(o,d,g):!0}},hc.spelling=function(e){return(t,a)=>(console.warn(`${a} is likely a misspelling of ${e}`),!0)};function a7(r,e,t){if(typeof r!="object")throw new nt("options must be an object",nt.ERR_BAD_OPTION_VALUE);const a=Object.keys(r);let i=a.length;for(;i-- >0;){const o=a[i],d=e[o];if(d){const g=r[o],h=g===void 0||d(g,o,r);if(h!==!0)throw new nt("option "+o+" must be "+h,nt.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new nt("Unknown option "+o,nt.ERR_BAD_OPTION)}}const fc={assertOptions:a7,validators:hc},Ha=fc.validators;let wr=class{constructor(e){this.defaults=e||{},this.interceptors={request:new mm,response:new mm}}async request(e,t){try{return await this._request(e,t)}catch(a){if(a instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const o=i.stack?i.stack.replace(/^.+\n/,""):"";try{a.stack?o&&!String(a.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(a.stack+=` -`+o):a.stack=o}catch{}}throw a}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=vr(this.defaults,t);const{transitional:a,paramsSerializer:i,headers:o}=t;a!==void 0&&fc.assertOptions(a,{silentJSONParsing:Ha.transitional(Ha.boolean),forcedJSONParsing:Ha.transitional(Ha.boolean),clarifyTimeoutError:Ha.transitional(Ha.boolean)},!1),i!=null&&(se.isFunction(i)?t.paramsSerializer={serialize:i}:fc.assertOptions(i,{encode:Ha.function,serialize:Ha.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),fc.assertOptions(t,{baseUrl:Ha.spelling("baseURL"),withXsrfToken:Ha.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let d=o&&se.merge(o.common,o[t.method]);o&&se.forEach(["delete","get","head","post","put","patch","common"],v=>{delete o[v]}),t.headers=On.concat(d,o);const g=[];let h=!0;this.interceptors.request.forEach(function(w){typeof w.runWhen=="function"&&w.runWhen(t)===!1||(h=h&&w.synchronous,g.unshift(w.fulfilled,w.rejected))});const f=[];this.interceptors.response.forEach(function(w){f.push(w.fulfilled,w.rejected)});let p,y=0,x;if(!h){const v=[Mm.bind(this),void 0];for(v.unshift(...g),v.push(...f),x=v.length,p=Promise.resolve(t);y{if(!a._listeners)return;let o=a._listeners.length;for(;o-- >0;)a._listeners[o](i);a._listeners=null}),this.promise.then=i=>{let o;const d=new Promise(g=>{a.subscribe(g),o=g}).then(i);return d.cancel=function(){a.unsubscribe(o)},d},e(function(o,d,g){a.reason||(a.reason=new ri(o,d,g),t(a.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=a=>{e.abort(a)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new pw(function(i){e=i}),cancel:e}}};function r7(r){return function(t){return r.apply(null,t)}}function i7(r){return se.isObject(r)&&r.isAxiosError===!0}const sg={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(sg).forEach(([r,e])=>{sg[e]=r});function zm(r){const e=new wr(r),t=em(wr.prototype.request,e);return se.extend(t,wr.prototype,e,{allOwnKeys:!0}),se.extend(t,e,null,{allOwnKeys:!0}),t.create=function(i){return zm(vr(r,i))},t}const Jt=zm(xo);Jt.Axios=wr,Jt.CanceledError=ri,Jt.CancelToken=s7,Jt.isCancel=vm,Jt.VERSION=$m,Jt.toFormData=cc,Jt.AxiosError=nt,Jt.Cancel=Jt.CanceledError,Jt.all=function(e){return Promise.all(e)},Jt.spread=r7,Jt.isAxiosError=i7,Jt.mergeConfig=vr,Jt.AxiosHeaders=On,Jt.formToJSON=r=>xm(se.isHTMLForm(r)?new FormData(r):r),Jt.getAdapter=Lm.getAdapter,Jt.HttpStatusCode=sg,Jt.default=Jt;const{Axios:$1,AxiosError:I1,CanceledError:z1,isCancel:H1,CancelToken:P1,VERSION:B1,all:U1,Cancel:q1,isAxiosError:G1,spread:F1,toFormData:V1,AxiosHeaders:K1,HttpStatusCode:W1,formToJSON:Y1,getAdapter:J1,mergeConfig:X1}=Jt,o7=it("ApiClient");function rg(){return typeof window<"u"&&window.__G7_DEVTOOLS__?window.__G7_DEVTOOLS__:null}class l7{constructor(e={}){H(this,"client");H(this,"config");H(this,"TOKEN_KEY","auth_token");this.config={baseURL:e.baseURL||"/api",timeout:e.timeout||3e4,onTokenExpired:e.onTokenExpired,onUnauthorized:e.onUnauthorized,onError:e.onError},this.client=Jt.create({baseURL:this.config.baseURL,timeout:this.config.timeout,headers:{"Content-Type":"application/json",Accept:"application/json"},paramsSerializer:{serialize:t=>{const a=[];for(const[i,o]of Object.entries(t))if(o!=null)if(Array.isArray(o)){const d=i.endsWith("[]")?i:`${i}[]`;for(const g of o)a.push(`${encodeURIComponent(d)}=${encodeURIComponent(String(g))}`)}else a.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(o))}`);return a.join("&")}}}),this.setupInterceptors()}setToken(e){typeof window<"u"&&localStorage.setItem(this.TOKEN_KEY,e)}getToken(){return typeof window<"u"?localStorage.getItem(this.TOKEN_KEY):null}removeToken(){typeof window<"u"&&localStorage.removeItem(this.TOKEN_KEY)}setupInterceptors(){this.client.interceptors.request.use(e=>{e.url?.startsWith("/api")&&e.baseURL==="/api"&&(e.baseURL="");const t=this.getToken();if(t&&e.headers&&(e.headers.Authorization=`Bearer ${t}`),typeof window<"u"&&e.headers){const i=localStorage.getItem("g7_locale");i&&(e.headers["Accept-Language"]=i)}const a=rg();if(a?.isEnabled()){const i=this.buildFullUrl(e),o=(e.method||"GET").toUpperCase(),d=a.trackRequest(i,o,{requestBody:e.data});e._devToolsRequestId=d}return e},e=>Promise.reject(e)),this.client.interceptors.response.use(e=>{const t=e.config,a=t._devToolsRequestId;if(a){const i=rg();i?.isEnabled()&&i.completeRequest(a,e.status,e.data),t._devToolsRequestId=null}return e},async e=>{const t=e.config,a=t?.url||"",o=["/auth/","/layouts/"].some(d=>a.includes(d));if(e.response?.status===401&&!t?._retry&&!o){if(t._retry=!0,await as.getInstance().refreshToken()){const h=this.getToken();return h&&(t.headers.Authorization=`Bearer ${h}`),t._devToolsRequestId=null,this.client(t)}return this.completeDevToolsRequest(t,e),this.removeToken(),this.config.onUnauthorized&&this.config.onUnauthorized(),Promise.reject(e)}return e.response?.status===401&&o?(this.completeDevToolsRequest(t,e),Promise.reject(e)):e.response?.status===403?(this.completeDevToolsRequest(t,e),this.callOnError(e),Promise.reject(e)):(this.completeDevToolsRequest(t,e),e.response&&this.callOnError(e),Promise.reject(e))})}async get(e,t){return(await this.client.get(e,t)).data}async post(e,t,a){return(await this.client.post(e,t,a)).data}async put(e,t,a){return(await this.client.put(e,t,a)).data}async patch(e,t,a){return(await this.client.patch(e,t,a)).data}async delete(e,t){return(await this.client.delete(e,t)).data}getInstance(){return this.client}setOnUnauthorized(e){this.config.onUnauthorized=e}setOnError(e){this.config.onError=e}completeDevToolsRequest(e,t){if(!e?._devToolsRequestId)return;const a=rg();if(!a?.isEnabled())return;const i=e._devToolsRequestId;e._devToolsRequestId=null,t.response?a.completeRequest(i,t.response.status,t.response.data):t.request?a.failRequest(i,t.message||"Network error"):a.failRequest(i,t.message||"Request error")}buildFullUrl(e){let t=e.url||"";if(e.baseURL&&!t.startsWith("http")&&(t=`${e.baseURL}${t.startsWith("/")?"":"/"}${t}`),e.params&&typeof e.params=="object"){const a=e.params,i=[];for(const[o,d]of Object.entries(a))if(d!=null)if(Array.isArray(d)){const g=o.endsWith("[]")?o:`${o}[]`;for(const h of d)i.push(`${encodeURIComponent(g)}=${encodeURIComponent(String(h))}`)}else i.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(d))}`);i.length>0&&(t+=(t.includes("?")?"&":"?")+i.join("&"))}return t}callOnError(e){if(!this.config.onError)return;const t={status:e.response?.status||0,message:e.response?.data?.message||e.message||"Unknown error",data:e.response?.data,statusText:e.response?.statusText};try{this.config.onError(t)}catch(a){o7.error("Error in onError handler:",a)}}}let ig=null;function ns(){return ig||(ig=new l7),ig}const vo=it("AuthManager");function ii(r,e,t,a){try{window.G7Core?.devTools?.trackAuthEvent?.(r,e,t,a)}catch{}}const pc={admin:{type:"admin",loginPath:"/admin/login",defaultPath:"/admin",userEndpoint:"/admin/auth/user",loginEndpoint:"/auth/admin/login",logoutEndpoint:"/admin/auth/logout",refreshEndpoint:"/admin/auth/refresh"},user:{type:"user",loginPath:"/login",defaultPath:"/",userEndpoint:"/auth/user",loginEndpoint:"/auth/login",logoutEndpoint:"/auth/logout",refreshEndpoint:"/auth/refresh"}},_a=class _a{constructor(){H(this,"state");H(this,"config");H(this,"isRefreshing",!1);H(this,"refreshPromise",null);H(this,"eventHandlers",new Map);this.state={isAuthenticated:!1,user:null,type:null},this.config=new Map,this.config.set("admin",pc.admin),this.config.set("user",pc.user)}static getInstance(){return _a.instance||(_a.instance=new _a),_a.instance}on(e,t){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(t)}emit(e,...t){const a=this.eventHandlers.get(e);a&&a.forEach(i=>i(...t))}isAuthenticated(){return this.state.isAuthenticated}getUser(){return this.state.user}getAuthType(){return this.state.type}async checkAuth(e){const t=ns();if(!t.getToken())return this.clearState(),!1;const i=this.config.get(e);if(!i)return vo.error(`Unknown auth type: ${e}`),!1;try{const o=await t.get(i.userEndpoint);return o.success&&o.data?(this.state={isAuthenticated:!0,user:o.data,type:e},this.emit("authStateChange",this.state),!0):(this.clearState(),!1)}catch(o){return o.response?.status===401&&await this.refreshToken()?this.checkAuth(e):(this.clearState(),!1)}}async preloadAuth(e){try{return await this.checkAuth(e)}catch(t){return vo.warn(`Preload auth failed for type ${e}:`,t),!1}}async login(e,t,a){const i=ns();if(!this.config.get(e))throw new Error(`Unknown auth type: ${e}`);const d=e==="admin"?pc.admin.loginEndpoint:pc.user.loginEndpoint;try{const g=a?.headers?{headers:a.headers}:void 0,h=await i.post(d,t,g);if(h.success&&h.data){i.setToken(h.data.token);const f=h.data.user.language,p=localStorage.getItem(_a.LOCALE_STORAGE_KEY),y=f&&f!==p;if(f)try{localStorage.setItem(_a.LOCALE_STORAGE_KEY,f)}catch(x){vo.warn("Failed to save user language to localStorage:",x)}return this.state={isAuthenticated:!0,user:h.data.user,type:e},this.emit("login",this.state),this.emit("authStateChange",this.state),ii("login",!0,void 0,{userId:h.data.user.uuid,email:h.data.user.email,type:e}),y&&window.__templateApp&&window.__templateApp.changeLocale(f),h.data.user}throw new Error("Login failed")}catch(g){this.clearState();const h=g.response?.data?.message,f=new Error(h||g.message||"Login failed");throw f.response=g.response,f.status=g.response?.status,ii("login",!1,f.message,{type:e,status:g.response?.status}),f}}async logout(){const e=ns(),t=this.state.type?this.config.get(this.state.type):null;try{t&&await e.post(t.logoutEndpoint)}catch(a){vo.warn("Logout API call failed:",a)}finally{e.removeToken();const a={...this.state};if(this.clearState(),this.emit("logout",a),this.emit("authStateChange",this.state),ii("logout",!0,void 0,{previousType:a.type}),t&&a.type){const i=window.location.pathname+window.location.search;window.location.href=this.getLoginRedirectUrl(a.type,i)}}}async refreshToken(){if(this.isRefreshing&&this.refreshPromise)return this.refreshPromise;this.isRefreshing=!0,this.refreshPromise=this.doRefreshToken();try{return await this.refreshPromise}finally{this.isRefreshing=!1,this.refreshPromise=null}}async doRefreshToken(){const e=this.state.type;if(!e)return!1;const t=this.config.get(e);if(!t)return!1;const a=ns();try{const i=await a.post(t.refreshEndpoint);return i.success&&i.data?.token?(a.setToken(i.data.token),this.emit("tokenRefreshed"),ii("token-refresh",!0,void 0,{type:e}),!0):(ii("token-refresh",!1,"No token in response",{type:e}),!1)}catch(i){return vo.error("Token refresh failed:",i),ii("token-refresh",!1,i instanceof Error?i.message:"Unknown error",{type:e}),!1}}getLoginRedirectUrl(e,t){const a=this.config.get(e);if(!a)return"/login";const i=encodeURIComponent(t);return`${a.loginPath}?redirect=${i}`}getRedirectUrl(e){const a=this.config.get(e)?.defaultPath||"/",o=new URLSearchParams(window.location.search).get("redirect");if(o)try{const d=decodeURIComponent(o);if(d.startsWith("/"))return d}catch{}return a}getConfig(e){return this.config.get(e)}clearState(){this.state={isAuthenticated:!1,user:null,type:null}}static resetInstance(){_a.instance=null}};H(_a,"instance"),H(_a,"LOCALE_STORAGE_KEY","g7_locale");let as=_a;const Hm={401:{handler:"navigate",params:{path:"{{auth.loginPath}}"}},403:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},404:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},422:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},default:{handler:"toast",params:{type:"error",message:"{{error.message}}"}}},ss={findHandler(r,e){if(r){if(r[e])return r[e];if(r[String(e)])return r[String(e)];if(r.default)return r.default}},normalizeOnError(r){return r?Array.isArray(r)?r:[r]:[]},injectErrorCode(r,e,t){if(r.handler!=="showErrorPage"||r.params?.errorCode!==void 0)return r;const a=typeof e=="string"?parseInt(e,10):e,i=isNaN(a)?t:a;return i===void 0?r:{...r,params:{...r.params,errorCode:i}}}},wa=it("ErrorHandlingResolver"),Hs=class Hs{constructor(){H(this,"templateErrorHandling",null);H(this,"layoutErrorHandling",null);H(this,"executeAction",null)}static getInstance(){return Hs.instance||(Hs.instance=new Hs),Hs.instance}static resetInstance(){Hs.instance=null}setTemplateConfig(e){this.templateErrorHandling=e,wa.log("Template config set:",e)}setLayoutConfig(e){this.layoutErrorHandling=e,wa.log("Layout config set:",e)}setActionExecutor(e){this.executeAction=e}resolve(e,t={}){const{errorHandling:a,onError:i}=t;wa.log("Resolving error:",e,{hasActionErrorHandling:!!a,hasActionOnError:!!i,hasLayoutConfig:!!this.layoutErrorHandling,hasTemplateConfig:!!this.templateErrorHandling});let o=ss.findHandler(a,e);if(o){const d=this.getMatchedKey(a,e);return{handler:ss.injectErrorCode(o,d,e),level:"action",matchedKey:d}}if(i){const d=ss.normalizeOnError(i);if(d.length>0)return{handler:d.length===1?d[0]:{handler:"sequence",actions:d},level:"action",matchedKey:"onError"}}if(o=ss.findHandler(this.layoutErrorHandling||void 0,e),o){const d=this.getMatchedKey(this.layoutErrorHandling,e);return{handler:ss.injectErrorCode(o,d,e),level:"layout",matchedKey:d}}if(o=ss.findHandler(this.templateErrorHandling||void 0,e),o){const d=this.getMatchedKey(this.templateErrorHandling,e);return{handler:ss.injectErrorCode(o,d,e),level:"template",matchedKey:d}}if(o=ss.findHandler(Hm,e),o){const d=this.getMatchedKey(Hm,e);return{handler:ss.injectErrorCode(o,d,e),level:"system",matchedKey:d}}return{handler:null,level:null,matchedKey:null}}async execute(e,t){if(!this.executeAction){wa.error("Action executor is not set");return}wa.log("Executing handler:",e.handler,{errorContext:t});try{return await this.executeAction(e,{error:t})}catch(a){throw wa.error("Failed to execute handler:",a),a}}async resolveAndExecute(e,t,a={}){const i=this.resolve(e,a);if(wa.log("Resolve result:",{errorCode:e,handler:i.handler?.handler,level:i.level,matchedKey:i.matchedKey}),!i.handler)return wa.warn("No handler found for error:",e),{handled:!1};try{return{handled:!0,result:await this.execute(i.handler,t)}}catch(o){return wa.error("Handler execution failed:",o),{handled:!1}}}getMatchedKey(e,t){return e[t]?t:e[String(t)]?String(t):"default"}clearLayoutConfig(){this.layoutErrorHandling=null,wa.log("Layout config cleared")}clearAllConfig(){this.templateErrorHandling=null,this.layoutErrorHandling=null,wa.log("All config cleared")}getConfigStatus(){return{hasTemplate:this.templateErrorHandling!==null,hasLayout:this.layoutErrorHandling!==null,hasExecutor:this.executeAction!==null}}};H(Hs,"instance",null);let og=Hs;function Sa(){return og.getInstance()}var lg={exports:{}},wo={};/** +`):" "+Om(d[0]):"as no adapter specified";throw new nt("There is no suitable adapter to dispatch the request "+g,"ERR_NOT_SUPPORT")}return i},adapters:ng};function ag(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new ri(null,r)}function Mm(r){return ag(r),r.headers=On.from(r.headers),r.data=tg.call(r,r.transformRequest),["post","put","patch"].indexOf(r.method)!==-1&&r.headers.setContentType("application/x-www-form-urlencoded",!1),Lm.getAdapter(r.adapter||xo.adapter,r)(r).then(function(a){return ag(r),a.data=tg.call(r,r.transformResponse,a),a.headers=On.from(a.headers),a},function(a){return vm(a)||(ag(r),a&&a.response&&(a.response.data=tg.call(r,r.transformResponse,a.response),a.response.headers=On.from(a.response.headers))),Promise.reject(a)})}const $m="1.12.2",fc={};["object","boolean","number","function","string","symbol"].forEach((r,e)=>{fc[r]=function(a){return typeof a===r||"a"+(e<1?"n ":" ")+r}});const Im={};fc.transitional=function(e,t,a){function i(o,d){return"[Axios v"+$m+"] Transitional option '"+o+"'"+d+(a?". "+a:"")}return(o,d,g)=>{if(e===!1)throw new nt(i(d," has been removed"+(t?" in "+t:"")),nt.ERR_DEPRECATED);return t&&!Im[d]&&(Im[d]=!0,console.warn(i(d," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(o,d,g):!0}},fc.spelling=function(e){return(t,a)=>(console.warn(`${a} is likely a misspelling of ${e}`),!0)};function s7(r,e,t){if(typeof r!="object")throw new nt("options must be an object",nt.ERR_BAD_OPTION_VALUE);const a=Object.keys(r);let i=a.length;for(;i-- >0;){const o=a[i],d=e[o];if(d){const g=r[o],h=g===void 0||d(g,o,r);if(h!==!0)throw new nt("option "+o+" must be "+h,nt.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new nt("Unknown option "+o,nt.ERR_BAD_OPTION)}}const pc={assertOptions:s7,validators:fc},Ha=pc.validators;let wr=class{constructor(e){this.defaults=e||{},this.interceptors={request:new mm,response:new mm}}async request(e,t){try{return await this._request(e,t)}catch(a){if(a instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const o=i.stack?i.stack.replace(/^.+\n/,""):"";try{a.stack?o&&!String(a.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(a.stack+=` +`+o):a.stack=o}catch{}}throw a}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=vr(this.defaults,t);const{transitional:a,paramsSerializer:i,headers:o}=t;a!==void 0&&pc.assertOptions(a,{silentJSONParsing:Ha.transitional(Ha.boolean),forcedJSONParsing:Ha.transitional(Ha.boolean),clarifyTimeoutError:Ha.transitional(Ha.boolean)},!1),i!=null&&(se.isFunction(i)?t.paramsSerializer={serialize:i}:pc.assertOptions(i,{encode:Ha.function,serialize:Ha.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),pc.assertOptions(t,{baseUrl:Ha.spelling("baseURL"),withXsrfToken:Ha.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let d=o&&se.merge(o.common,o[t.method]);o&&se.forEach(["delete","get","head","post","put","patch","common"],v=>{delete o[v]}),t.headers=On.concat(d,o);const g=[];let h=!0;this.interceptors.request.forEach(function(w){typeof w.runWhen=="function"&&w.runWhen(t)===!1||(h=h&&w.synchronous,g.unshift(w.fulfilled,w.rejected))});const f=[];this.interceptors.response.forEach(function(w){f.push(w.fulfilled,w.rejected)});let p,y=0,x;if(!h){const v=[Mm.bind(this),void 0];for(v.unshift(...g),v.push(...f),x=v.length,p=Promise.resolve(t);y{if(!a._listeners)return;let o=a._listeners.length;for(;o-- >0;)a._listeners[o](i);a._listeners=null}),this.promise.then=i=>{let o;const d=new Promise(g=>{a.subscribe(g),o=g}).then(i);return d.cancel=function(){a.unsubscribe(o)},d},e(function(o,d,g){a.reason||(a.reason=new ri(o,d,g),t(a.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=a=>{e.abort(a)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new mw(function(i){e=i}),cancel:e}}};function i7(r){return function(t){return r.apply(null,t)}}function o7(r){return se.isObject(r)&&r.isAxiosError===!0}const sg={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(sg).forEach(([r,e])=>{sg[e]=r});function zm(r){const e=new wr(r),t=em(wr.prototype.request,e);return se.extend(t,wr.prototype,e,{allOwnKeys:!0}),se.extend(t,e,null,{allOwnKeys:!0}),t.create=function(i){return zm(vr(r,i))},t}const Jt=zm(xo);Jt.Axios=wr,Jt.CanceledError=ri,Jt.CancelToken=r7,Jt.isCancel=vm,Jt.VERSION=$m,Jt.toFormData=dc,Jt.AxiosError=nt,Jt.Cancel=Jt.CanceledError,Jt.all=function(e){return Promise.all(e)},Jt.spread=i7,Jt.isAxiosError=o7,Jt.mergeConfig=vr,Jt.AxiosHeaders=On,Jt.formToJSON=r=>xm(se.isHTMLForm(r)?new FormData(r):r),Jt.getAdapter=Lm.getAdapter,Jt.HttpStatusCode=sg,Jt.default=Jt;const{Axios:I1,AxiosError:z1,CanceledError:H1,isCancel:P1,CancelToken:B1,VERSION:U1,all:q1,Cancel:G1,isAxiosError:F1,spread:V1,toFormData:K1,AxiosHeaders:W1,HttpStatusCode:Y1,formToJSON:J1,getAdapter:X1,mergeConfig:Q1}=Jt,l7=it("ApiClient");function rg(){return typeof window<"u"&&window.__G7_DEVTOOLS__?window.__G7_DEVTOOLS__:null}class c7{constructor(e={}){H(this,"client");H(this,"config");H(this,"TOKEN_KEY","auth_token");this.config={baseURL:e.baseURL||"/api",timeout:e.timeout||3e4,onTokenExpired:e.onTokenExpired,onUnauthorized:e.onUnauthorized,onError:e.onError},this.client=Jt.create({baseURL:this.config.baseURL,timeout:this.config.timeout,headers:{"Content-Type":"application/json",Accept:"application/json"},paramsSerializer:{serialize:t=>{const a=[];for(const[i,o]of Object.entries(t))if(o!=null)if(Array.isArray(o)){const d=i.endsWith("[]")?i:`${i}[]`;for(const g of o)a.push(`${encodeURIComponent(d)}=${encodeURIComponent(String(g))}`)}else a.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(o))}`);return a.join("&")}}}),this.setupInterceptors()}setToken(e){typeof window<"u"&&localStorage.setItem(this.TOKEN_KEY,e)}getToken(){return typeof window<"u"?localStorage.getItem(this.TOKEN_KEY):null}removeToken(){typeof window<"u"&&localStorage.removeItem(this.TOKEN_KEY)}setupInterceptors(){this.client.interceptors.request.use(e=>{e.url?.startsWith("/api")&&e.baseURL==="/api"&&(e.baseURL="");const t=this.getToken();if(t&&e.headers&&(e.headers.Authorization=`Bearer ${t}`),typeof window<"u"&&e.headers){const i=localStorage.getItem("g7_locale");i&&(e.headers["Accept-Language"]=i)}const a=rg();if(a?.isEnabled()){const i=this.buildFullUrl(e),o=(e.method||"GET").toUpperCase(),d=a.trackRequest(i,o,{requestBody:e.data});e._devToolsRequestId=d}return e},e=>Promise.reject(e)),this.client.interceptors.response.use(e=>{const t=e.config,a=t._devToolsRequestId;if(a){const i=rg();i?.isEnabled()&&i.completeRequest(a,e.status,e.data),t._devToolsRequestId=null}return e},async e=>{const t=e.config,a=t?.url||"",o=["/auth/","/layouts/"].some(d=>a.includes(d));if(e.response?.status===401&&!t?._retry&&!o){if(t._retry=!0,await as.getInstance().refreshToken()){const h=this.getToken();return h&&(t.headers.Authorization=`Bearer ${h}`),t._devToolsRequestId=null,this.client(t)}return this.completeDevToolsRequest(t,e),this.removeToken(),this.config.onUnauthorized&&this.config.onUnauthorized(),Promise.reject(e)}return e.response?.status===401&&o?(this.completeDevToolsRequest(t,e),Promise.reject(e)):e.response?.status===403?(this.completeDevToolsRequest(t,e),this.callOnError(e),Promise.reject(e)):(this.completeDevToolsRequest(t,e),e.response&&this.callOnError(e),Promise.reject(e))})}async get(e,t){return(await this.client.get(e,t)).data}async post(e,t,a){return(await this.client.post(e,t,a)).data}async put(e,t,a){return(await this.client.put(e,t,a)).data}async patch(e,t,a){return(await this.client.patch(e,t,a)).data}async delete(e,t){return(await this.client.delete(e,t)).data}getInstance(){return this.client}setOnUnauthorized(e){this.config.onUnauthorized=e}setOnError(e){this.config.onError=e}completeDevToolsRequest(e,t){if(!e?._devToolsRequestId)return;const a=rg();if(!a?.isEnabled())return;const i=e._devToolsRequestId;e._devToolsRequestId=null,t.response?a.completeRequest(i,t.response.status,t.response.data):t.request?a.failRequest(i,t.message||"Network error"):a.failRequest(i,t.message||"Request error")}buildFullUrl(e){let t=e.url||"";if(e.baseURL&&!t.startsWith("http")&&(t=`${e.baseURL}${t.startsWith("/")?"":"/"}${t}`),e.params&&typeof e.params=="object"){const a=e.params,i=[];for(const[o,d]of Object.entries(a))if(d!=null)if(Array.isArray(d)){const g=o.endsWith("[]")?o:`${o}[]`;for(const h of d)i.push(`${encodeURIComponent(g)}=${encodeURIComponent(String(h))}`)}else i.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(d))}`);i.length>0&&(t+=(t.includes("?")?"&":"?")+i.join("&"))}return t}callOnError(e){if(!this.config.onError)return;const t={status:e.response?.status||0,message:e.response?.data?.message||e.message||"Unknown error",data:e.response?.data,statusText:e.response?.statusText};try{this.config.onError(t)}catch(a){l7.error("Error in onError handler:",a)}}}let ig=null;function ns(){return ig||(ig=new c7),ig}const vo=it("AuthManager");function ii(r,e,t,a){try{window.G7Core?.devTools?.trackAuthEvent?.(r,e,t,a)}catch{}}const mc={admin:{type:"admin",loginPath:"/admin/login",defaultPath:"/admin",userEndpoint:"/admin/auth/user",loginEndpoint:"/auth/admin/login",logoutEndpoint:"/admin/auth/logout",refreshEndpoint:"/admin/auth/refresh"},user:{type:"user",loginPath:"/login",defaultPath:"/",userEndpoint:"/auth/user",loginEndpoint:"/auth/login",logoutEndpoint:"/auth/logout",refreshEndpoint:"/auth/refresh"}},_a=class _a{constructor(){H(this,"state");H(this,"config");H(this,"isRefreshing",!1);H(this,"refreshPromise",null);H(this,"eventHandlers",new Map);this.state={isAuthenticated:!1,user:null,type:null},this.config=new Map,this.config.set("admin",mc.admin),this.config.set("user",mc.user)}static getInstance(){return _a.instance||(_a.instance=new _a),_a.instance}on(e,t){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(t)}emit(e,...t){const a=this.eventHandlers.get(e);a&&a.forEach(i=>i(...t))}isAuthenticated(){return this.state.isAuthenticated}getUser(){return this.state.user}getAuthType(){return this.state.type}async checkAuth(e){const t=ns();if(!t.getToken())return this.clearState(),!1;const i=this.config.get(e);if(!i)return vo.error(`Unknown auth type: ${e}`),!1;try{const o=await t.get(i.userEndpoint);return o.success&&o.data?(this.state={isAuthenticated:!0,user:o.data,type:e},this.emit("authStateChange",this.state),!0):(this.clearState(),!1)}catch(o){return o.response?.status===401&&await this.refreshToken()?this.checkAuth(e):(this.clearState(),!1)}}async preloadAuth(e){try{return await this.checkAuth(e)}catch(t){return vo.warn(`Preload auth failed for type ${e}:`,t),!1}}async login(e,t,a){const i=ns();if(!this.config.get(e))throw new Error(`Unknown auth type: ${e}`);const d=e==="admin"?mc.admin.loginEndpoint:mc.user.loginEndpoint;try{const g=a?.headers?{headers:a.headers}:void 0,h=await i.post(d,t,g);if(h.success&&h.data){i.setToken(h.data.token);const f=h.data.user.language,p=localStorage.getItem(_a.LOCALE_STORAGE_KEY),y=f&&f!==p;if(f)try{localStorage.setItem(_a.LOCALE_STORAGE_KEY,f)}catch(x){vo.warn("Failed to save user language to localStorage:",x)}return this.state={isAuthenticated:!0,user:h.data.user,type:e},this.emit("login",this.state),this.emit("authStateChange",this.state),ii("login",!0,void 0,{userId:h.data.user.uuid,email:h.data.user.email,type:e}),y&&window.__templateApp&&window.__templateApp.changeLocale(f),h.data.user}throw new Error("Login failed")}catch(g){this.clearState();const h=g.response?.data?.message,f=new Error(h||g.message||"Login failed");throw f.response=g.response,f.status=g.response?.status,ii("login",!1,f.message,{type:e,status:g.response?.status}),f}}async logout(){const e=ns(),t=this.state.type?this.config.get(this.state.type):null;try{t&&await e.post(t.logoutEndpoint)}catch(a){vo.warn("Logout API call failed:",a)}finally{e.removeToken();const a={...this.state};if(this.clearState(),this.emit("logout",a),this.emit("authStateChange",this.state),ii("logout",!0,void 0,{previousType:a.type}),t&&a.type){const i=window.location.pathname+window.location.search;window.location.href=this.getLoginRedirectUrl(a.type,i)}}}async refreshToken(){if(this.isRefreshing&&this.refreshPromise)return this.refreshPromise;this.isRefreshing=!0,this.refreshPromise=this.doRefreshToken();try{return await this.refreshPromise}finally{this.isRefreshing=!1,this.refreshPromise=null}}async doRefreshToken(){const e=this.state.type;if(!e)return!1;const t=this.config.get(e);if(!t)return!1;const a=ns();try{const i=await a.post(t.refreshEndpoint);return i.success&&i.data?.token?(a.setToken(i.data.token),this.emit("tokenRefreshed"),ii("token-refresh",!0,void 0,{type:e}),!0):(ii("token-refresh",!1,"No token in response",{type:e}),!1)}catch(i){return vo.error("Token refresh failed:",i),ii("token-refresh",!1,i instanceof Error?i.message:"Unknown error",{type:e}),!1}}getLoginRedirectUrl(e,t){const a=this.config.get(e);if(!a)return"/login";const i=encodeURIComponent(t);return`${a.loginPath}?redirect=${i}`}getRedirectUrl(e){const a=this.config.get(e)?.defaultPath||"/",o=new URLSearchParams(window.location.search).get("redirect");if(o)try{const d=decodeURIComponent(o);if(d.startsWith("/"))return d}catch{}return a}getConfig(e){return this.config.get(e)}clearState(){this.state={isAuthenticated:!1,user:null,type:null}}static resetInstance(){_a.instance=null}};H(_a,"instance"),H(_a,"LOCALE_STORAGE_KEY","g7_locale");let as=_a;const Hm={401:{handler:"navigate",params:{path:"{{auth.loginPath}}"}},403:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},404:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},422:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},default:{handler:"toast",params:{type:"error",message:"{{error.message}}"}}},ss={findHandler(r,e){if(r){if(r[e])return r[e];if(r[String(e)])return r[String(e)];if(r.default)return r.default}},normalizeOnError(r){return r?Array.isArray(r)?r:[r]:[]},injectErrorCode(r,e,t){if(r.handler!=="showErrorPage"||r.params?.errorCode!==void 0)return r;const a=typeof e=="string"?parseInt(e,10):e,i=isNaN(a)?t:a;return i===void 0?r:{...r,params:{...r.params,errorCode:i}}}},wa=it("ErrorHandlingResolver"),Hs=class Hs{constructor(){H(this,"templateErrorHandling",null);H(this,"layoutErrorHandling",null);H(this,"executeAction",null)}static getInstance(){return Hs.instance||(Hs.instance=new Hs),Hs.instance}static resetInstance(){Hs.instance=null}setTemplateConfig(e){this.templateErrorHandling=e,wa.log("Template config set:",e)}setLayoutConfig(e){this.layoutErrorHandling=e,wa.log("Layout config set:",e)}setActionExecutor(e){this.executeAction=e}resolve(e,t={}){const{errorHandling:a,onError:i}=t;wa.log("Resolving error:",e,{hasActionErrorHandling:!!a,hasActionOnError:!!i,hasLayoutConfig:!!this.layoutErrorHandling,hasTemplateConfig:!!this.templateErrorHandling});let o=ss.findHandler(a,e);if(o){const d=this.getMatchedKey(a,e);return{handler:ss.injectErrorCode(o,d,e),level:"action",matchedKey:d}}if(i){const d=ss.normalizeOnError(i);if(d.length>0)return{handler:d.length===1?d[0]:{handler:"sequence",actions:d},level:"action",matchedKey:"onError"}}if(o=ss.findHandler(this.layoutErrorHandling||void 0,e),o){const d=this.getMatchedKey(this.layoutErrorHandling,e);return{handler:ss.injectErrorCode(o,d,e),level:"layout",matchedKey:d}}if(o=ss.findHandler(this.templateErrorHandling||void 0,e),o){const d=this.getMatchedKey(this.templateErrorHandling,e);return{handler:ss.injectErrorCode(o,d,e),level:"template",matchedKey:d}}if(o=ss.findHandler(Hm,e),o){const d=this.getMatchedKey(Hm,e);return{handler:ss.injectErrorCode(o,d,e),level:"system",matchedKey:d}}return{handler:null,level:null,matchedKey:null}}async execute(e,t){if(!this.executeAction){wa.error("Action executor is not set");return}wa.log("Executing handler:",e.handler,{errorContext:t});try{return await this.executeAction(e,{error:t})}catch(a){throw wa.error("Failed to execute handler:",a),a}}async resolveAndExecute(e,t,a={}){const i=this.resolve(e,a);if(wa.log("Resolve result:",{errorCode:e,handler:i.handler?.handler,level:i.level,matchedKey:i.matchedKey}),!i.handler)return wa.warn("No handler found for error:",e),{handled:!1};try{return{handled:!0,result:await this.execute(i.handler,t)}}catch(o){return wa.error("Handler execution failed:",o),{handled:!1}}}getMatchedKey(e,t){return e[t]?t:e[String(t)]?String(t):"default"}clearLayoutConfig(){this.layoutErrorHandling=null,wa.log("Layout config cleared")}clearAllConfig(){this.templateErrorHandling=null,this.layoutErrorHandling=null,wa.log("All config cleared")}getConfigStatus(){return{hasTemplate:this.templateErrorHandling!==null,hasLayout:this.layoutErrorHandling!==null,hasExecutor:this.executeAction!==null}}};H(Hs,"instance",null);let og=Hs;function Sa(){return og.getInstance()}var lg={exports:{}},wo={};/** * @license React * react-jsx-runtime.production.js * @@ -51,7 +51,7 @@ Error generating stack: `+u.message+` * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var Pm;function c7(){if(Pm)return wo;Pm=1;var r=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function t(a,i,o){var d=null;if(o!==void 0&&(d=""+o),i.key!==void 0&&(d=""+i.key),"key"in i){o={};for(var g in i)g!=="key"&&(o[g]=i[g])}else o=i;return i=o.ref,{$$typeof:r,type:a,key:d,ref:i!==void 0?i:null,props:o}}return wo.Fragment=e,wo.jsx=t,wo.jsxs=t,wo}var Bm;function d7(){return Bm||(Bm=1,lg.exports=c7()),lg.exports}var l=d7();const u7=Za({__proto__:null,default:es(l)},[l]),cg=it("ParentContextProvider"),Um=j.createContext(null);let mc=null;function dg(){mc?(cg.log("[triggerModalParentUpdate] 모달 부모 컨텍스트 업데이트 트리거"),mc()):cg.warn("[triggerModalParentUpdate] Provider가 아직 마운트되지 않음")}const qm=({children:r})=>{const[e,t]=j.useState(0),a=j.useRef(!0),i=j.useCallback(()=>{const d=window.__g7LayoutContextStack||[];return d[d.length-1]?.dataContext},[]);j.useEffect(()=>(a.current=!0,mc=()=>{a.current&&(t(d=>d+1),cg.log("[ParentContextProvider] 버전 업데이트됨"))},()=>{a.current=!1,mc=null}),[]);const o={version:e,getParentDataContext:i};return l.jsx(Um.Provider,{value:o,children:r})};function g7(){return j.useContext(Um)}const q=it("ActionDispatcher"),Gm=new Set(["navigate","navigateBack","navigateForward","replaceUrl","refresh","logout"]),h7=new Set(["redirect"]);function Vn(){try{return window.G7Core?.devTools}catch{return}}class Gt extends Error{constructor(e,t,a){super(e),this.action=t,this.originalError=a,this.name="ActionError"}}const bi=class bi{constructor(e={},t,a){H(this,"bindingEngine");H(this,"translationEngine");H(this,"translationContext");H(this,"customHandlers",new Map);H(this,"defaultContext");H(this,"globalStateUpdater");H(this,"errorHandlingSetup",!1);H(this,"debounceTimers",new Map);H(this,"pendingDebounceFlushers",new Map);H(this,"debounceAccumulatedValues",new Map);H(this,"globalHeaders",[]);H(this,"namedActions",{});H(this,"previewMode",!1);this.bindingEngine=new _n,this.translationEngine=t,this.translationContext=a,this.defaultContext=e,this.registerDefaultHandlers(),this.setupErrorHandling()}setGlobalHeaders(e){this.globalHeaders=e||[]}setNamedActions(e){this.namedActions=e||{};const t=Vn();t?.isEnabled?.()&&t.setNamedActionDefinitions?.(this.namedActions),q.log("[setNamedActions] registered:",Object.keys(this.namedActions))}getNamedActions(){return this.namedActions}setPreviewMode(e){this.previewMode=e,q.log("Preview mode:",e?"enabled":"disabled")}isPreviewMode(){return this.previewMode}static getPreviewSuppressedHandlers(){return Gm}static getPreviewSuppressedLayoutFeatures(){return h7}resolveActionRef(e){if(!e.actionRef)return e;const t=this.namedActions[e.actionRef];if(!t)return q.warn(`[resolveActionRef] named action not found: "${e.actionRef}"`),e;const a=Vn();a?.isEnabled?.()&&a.trackNamedActionRef?.({actionRefName:e.actionRef,resolvedHandler:t.handler,timestamp:Date.now()});const{actionRef:i,type:o,key:d,event:g,...h}=e,f={...t,...Object.fromEntries(Object.entries(h).filter(([,p])=>p!==void 0)),type:o??t.type};return d!==void 0&&(f.key=d),g!==void 0&&(f.event=g),f}matchesPattern(e,t){if(t==="*")return!0;const a=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${a}$`).test(e)}getMatchingGlobalHeaders(e,t){const a={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([o,d])=>{const g=ni(d,t,{skipCache:!0});g!=null&&g!==""&&(a[o]=String(g))});return a}setupErrorHandling(){if(this.errorHandlingSetup)return;Sa().setActionExecutor(async(t,a)=>{const i={type:"click",handler:t.handler,target:t.target,params:t.params,actions:t.actions},o={data:{...this.defaultContext.data,error:a.error}};return await this.dispatchAction(i,o)}),this.errorHandlingSetup=!0}registerDefaultHandlers(){this.registerHandler("refetchDataSource",async(t,a)=>{const i=t.params?.dataSourceId,o=t.params?.sync;if(!i){q.warn("refetchDataSource: dataSourceId is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.refetch){const d=window.G7Core?.state?.get?.()||{},g={...a.state?._global,...d},h=window.G7Core?.state?.getLocal?.()||{},f=a.data?._local||a.state||{},p={...h,...f},y=a.isolatedContext?.state;q.log("[refetchDataSource] localStateOverride:",p),await window.G7Core.dataSource.refetch(i,{...o?{sync:!0}:{},...g?{globalStateOverride:g}:{},...p?{localStateOverride:p}:{},...y?{isolatedStateOverride:y}:{}})}else q.warn("refetchDataSource: G7Core.dataSource.refetch is not available")}),this.registerHandler("appendDataSource",async(t,a)=>{const{dataSourceId:i,dataPath:o,newData:d}=t.params||{};if(!i){q.warn("appendDataSource: dataSourceId is required");return}if(d===void 0){q.warn("appendDataSource: newData is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.updateData){if(!Array.isArray(d)){q.warn("appendDataSource: newData must be an array, got:",typeof d,d);return}await window.G7Core.dataSource.updateData(i,o||null,d,"append")}else q.warn("appendDataSource: G7Core.dataSource.updateData is not available")}),this.registerHandler("updateDataSource",async(t,a)=>{const{dataSourceId:i,data:o,merge:d=!1}=t.params||{};if(!i){q.warn("updateDataSource: dataSourceId is required");return}if(o===void 0){q.warn("updateDataSource: data is required");return}typeof window<"u"&&window.G7Core?.dataSource?.set?(q.log(`[updateDataSource] Updating dataSource '${i}' with:`,o),window.G7Core.dataSource.set(i,o,{merge:d})):q.warn("updateDataSource: G7Core.dataSource.set is not available")}),this.registerHandler("scrollIntoView",async(t,a)=>{const{selector:i,behavior:o="smooth",block:d="nearest",inline:g="nearest",waitForElement:h=!1,timeout:f=2e3,delay:p=0,retryCount:y=0,retryInterval:x=50,scrollContainer:S}=t.params||{};if(!i){q.warn("scrollIntoView: selector is required");return}if(typeof window>"u"||typeof document>"u"){q.warn("scrollIntoView: window/document is not available");return}let v=null;if(h){if(v=await new Promise(w=>{const k=document.querySelector(i);if(k){w(k);return}const A=setTimeout(()=>{O.disconnect(),w(null)},f),O=new MutationObserver(()=>{const N=document.querySelector(i);N&&(clearTimeout(A),O.disconnect(),w(N))});O.observe(document.body,{childList:!0,subtree:!0})}),!v){q.warn(`scrollIntoView: element not found for selector "${i}" after ${f}ms timeout`);return}}else{p>0&&await new Promise(k=>setTimeout(k,p)),v=document.querySelector(i);let w=0;for(;!v&&wsetTimeout(k,x)),v=document.querySelector(i),w++;if(!v){q.warn(`scrollIntoView: element not found for selector "${i}" after ${w+1} attempts`);return}}if(S){const w=document.querySelector(S);if(!w){q.warn(`scrollIntoView: container not found for selector "${S}"`);return}const k=v.getBoundingClientRect(),A=w.getBoundingClientRect(),O=k.top-A.top+w.scrollTop,N=O+k.height;let D;switch(d){case"start":D=O;break;case"center":D=O-w.clientHeight/2+k.height/2;break;case"end":D=N-w.clientHeight;break;case"nearest":default:const $=k.topA.bottom;if($)D=O;else if(M)D=N-w.clientHeight;else return;break}w.scrollTo({top:Math.max(0,D),behavior:o});return}v.scrollIntoView({behavior:o,block:d,inline:g})}),this.registerHandler("reloadExtensions",async(t,a)=>{if(typeof window>"u"){q.warn("reloadExtensions: window is not available");return}const i=window.__templateApp;if(!i){q.warn("reloadExtensions: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState()}catch(g){throw q.error("reloadExtensions: reloadExtensionState failed",g),g}else q.warn("reloadExtensions: TemplateApp.reloadExtensionState unavailable");const{moduleInfo:o,pluginInfo:d}=t.params||{};if(o)try{await this.executeAction({handler:"reloadModuleHandlers",params:t.params},a)}catch(g){q.error("reloadExtensions: reloadModuleHandlers failed",g)}if(d)try{await this.executeAction({handler:"reloadPluginHandlers",params:t.params},a)}catch(g){q.error("reloadExtensions: reloadPluginHandlers failed",g)}q.log("reloadExtensions: done")}),this.registerHandler("reloadRoutes",async(t,a)=>{if(typeof window>"u"){q.warn("reloadRoutes: window is not available");return}const i=window.__templateApp;if(!i){q.warn("reloadRoutes: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),q.log("reloadRoutes: delegated to reloadExtensionState")}catch(o){throw q.error("reloadRoutes: Failed to reload routes",o),o}else{const o=i.getRouter?.();o&&(await o.loadRoutes(),q.log("reloadRoutes: Routes reloaded (legacy fallback)"))}}),this.registerHandler("refresh",async(t,a)=>{if(typeof window>"u"){q.warn("refresh: window is not available");return}window.location.reload()}),this.registerHandler("remount",async(t,a)=>{const{componentId:i}=t.params||{};if(!i){q.warn("remount: componentId parameter is required");return}if(!this.globalStateUpdater){q.warn("remount: globalStateUpdater is not set");return}const g=(window.G7Core?.state?.get()||{})._global?._remountKeys||{},h=g[i]||0;this.globalStateUpdater({_remountKeys:{...g,[i]:h+1}}),q.log(`remount: ${i} key incremented to ${h+1}`)}),this.registerHandler("reloadTranslations",async(t,a)=>{if(typeof window>"u"){q.warn("reloadTranslations: window is not available");return}const i=window.__templateApp;if(!i){q.warn("reloadTranslations: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),q.log("reloadTranslations: delegated to reloadExtensionState")}catch(o){throw q.error("reloadTranslations: Failed to reload translations",o),o}}),this.registerHandler("reloadModuleHandlers",async(t,a)=>{if(typeof window>"u"){q.warn("reloadModuleHandlers: window is not available");return}const{moduleInfo:i,action:o}=t.params||{};if(!i){q.warn("reloadModuleHandlers: moduleInfo is required");return}const d=i.data||i;if(!d.identifier){q.warn("reloadModuleHandlers: moduleInfo with identifier is required");return}if(!o||o!=="add"&&o!=="remove"){q.warn('reloadModuleHandlers: action must be "add" or "remove"');return}const g=window.G7Config;if(!g){q.warn("reloadModuleHandlers: G7Config not available");return}const h=d.identifier;try{if(o==="add"){if(d.assets&&(g.moduleAssets=g.moduleAssets||{},g.moduleAssets[h]=d.assets,q.log(`reloadModuleHandlers: Added assets for ${h}`),d.assets.js)){const f=d.assets.js,p=`module-${h}`;if(document.getElementById(p)){q.warn(`reloadModuleHandlers: Script ${p} already loaded`);return}const y=document.createElement("script");if(y.id=p,y.src=f,y.async=!0,await new Promise((x,S)=>{y.onload=()=>{q.log(`reloadModuleHandlers: Script loaded successfully for ${h}`),x()},y.onerror=()=>{q.error(`reloadModuleHandlers: Failed to load script for ${h}`),S(new Error(`Failed to load module script: ${f}`))},document.head.appendChild(y)}),d.assets.css){const x=d.assets.css,S=`module-css-${h}`;if(!document.getElementById(S)){const v=document.createElement("link");v.id=S,v.rel="stylesheet",v.href=x,document.head.appendChild(v),q.log(`reloadModuleHandlers: CSS loaded for ${h}`)}}}}else if(o==="remove"){g.moduleAssets&&g.moduleAssets[h]&&(delete g.moduleAssets[h],q.log(`reloadModuleHandlers: Removed assets for ${h}`));const f=`module-${h}`,p=document.getElementById(f);p&&(p.remove(),q.log(`reloadModuleHandlers: Removed script for ${h}`));const y=`module-css-${h}`,x=document.getElementById(y);x&&(x.remove(),q.log(`reloadModuleHandlers: Removed CSS for ${h}`))}}catch(f){throw q.error(`reloadModuleHandlers: Failed to ${o} module assets`,f),f}}),this.registerHandler("reloadPluginHandlers",async(t,a)=>{if(typeof window>"u"){q.warn("reloadPluginHandlers: window is not available");return}const{pluginInfo:i,action:o}=t.params||{};if(!i){q.warn("reloadPluginHandlers: pluginInfo is required");return}const d=i.data||i;if(!d.identifier){q.warn("reloadPluginHandlers: pluginInfo with identifier is required");return}if(!o||o!=="add"&&o!=="remove"){q.warn('reloadPluginHandlers: action must be "add" or "remove"');return}const g=window.G7Config;if(!g){q.warn("reloadPluginHandlers: G7Config not available");return}const h=d.identifier;try{if(o==="add"){if(d.assets&&(g.pluginAssets=g.pluginAssets||{},g.pluginAssets[h]=d.assets,q.log(`reloadPluginHandlers: Added assets for ${h}`),d.assets.js)){const f=d.assets.js,p=`plugin-${h}`;if(document.getElementById(p)){q.warn(`reloadPluginHandlers: Script ${p} already loaded`);return}const y=document.createElement("script");if(y.id=p,y.src=f,y.async=!0,await new Promise((x,S)=>{y.onload=()=>{q.log(`reloadPluginHandlers: Script loaded successfully for ${h}`),x()},y.onerror=()=>{q.error(`reloadPluginHandlers: Failed to load script for ${h}`),S(new Error(`Failed to load plugin script: ${f}`))},document.head.appendChild(y)}),d.assets.css){const x=d.assets.css,S=`plugin-css-${h}`;if(!document.getElementById(S)){const v=document.createElement("link");v.id=S,v.rel="stylesheet",v.href=x,document.head.appendChild(v),q.log(`reloadPluginHandlers: CSS loaded for ${h}`)}}}}else if(o==="remove"){g.pluginAssets&&g.pluginAssets[h]&&(delete g.pluginAssets[h],q.log(`reloadPluginHandlers: Removed assets for ${h}`));const f=`plugin-${h}`,p=document.getElementById(f);p&&(p.remove(),q.log(`reloadPluginHandlers: Removed script for ${h}`));const y=`plugin-css-${h}`,x=document.getElementById(y);x&&(x.remove(),q.log(`reloadPluginHandlers: Removed CSS for ${h}`))}}catch(f){throw q.error(`reloadPluginHandlers: Failed to ${o} plugin assets`,f),f}});let e=!1;this.registerHandler("showErrorPage",async(t,a)=>{if(e){q.log("showErrorPage: Already active, skipping duplicate call");return}if(e=!0,typeof window>"u"){e=!1,q.warn("showErrorPage: window is not available");return}const i=window.__templateApp;if(!i){e=!1,q.warn("showErrorPage: TemplateApp not initialized");return}const o=i.getErrorPageHandler?.();if(!o){e=!1,q.warn("showErrorPage: ErrorPageHandler not available");return}const d=t.params?.errorCode||500,g=t.params?.target||"content";let h=t.params?.containerId;h||(h=g==="full"?"app":"main_content"),q.log("showErrorPage:",{errorCode:d,target:g,containerId:h});const f=(p,y=6e4)=>new Promise((x,S)=>{const v=document.getElementById(p);if(v){x(v);return}q.log(`showErrorPage: Waiting for container #${p}...`);let w;const k=new MutationObserver((A,O)=>{const N=document.getElementById(p);N&&(q.log(`showErrorPage: Container #${p} found`),O.disconnect(),clearTimeout(w),x(N))});k.observe(document.body,{childList:!0,subtree:!0}),w=setTimeout(()=>{k.disconnect(),S(new Error(`Container #${p} not found within ${y}ms`))},y)});try{await f(h);const p=Sa(),y=p.layoutErrorHandling;p.clearLayoutConfig();try{await o.renderError(d,h)||q.warn(`showErrorPage: Failed to render error page for code ${d}`)}finally{p.setLayoutConfig(y)}}catch(p){throw q.error("showErrorPage: Error rendering error page:",p),p}finally{e=!1}}),this.registerHandler("emitEvent",async(t,a)=>{const i=t.params?.event,o=t.params?.data;if(!i){q.warn("emitEvent: event parameter is required");return}if(typeof window>"u"){q.warn("emitEvent: window is not available");return}const d=window.G7Core;if(!d?.componentEvent?.emit){q.warn("emitEvent: G7Core.componentEvent is not available");return}try{q.log(`emitEvent: Emitting "${i}"`,o);const g={...o,_context:{data:a.data,state:a.state}},h=await d.componentEvent.emit(i,g);if(!h||h.length===0?q.warn(`emitEvent: No listeners found for "${i}"`):q.log(`emitEvent: Event "${i}" completed with ${h.length} listener(s)`,h),this.globalStateUpdater){const f=d?.state?.get()||{};this.globalStateUpdater({_local:{...f._local,_eventResult:{event:i,success:!0,data:h.length===1?h[0]:h,listeners:h.length}}})}}catch(g){if(q.error(`emitEvent: Event "${i}" failed`,g),this.globalStateUpdater){const h=d?.state?.get()||{};this.globalStateUpdater({_local:{...h._local,_eventResult:{event:i,success:!1,error:g instanceof Error?g.message:String(g)}}})}throw g}}),this.registerHandler("updateProductField",async(t,a)=>{const{productId:i,field:o,value:d}=t.params||{};if(!i||!o){q.warn("updateProductField: productId and field are required");return}if(typeof window>"u"){q.warn("updateProductField: window is not available");return}const g=window.G7Core;if(!g?.state?.get||!this.globalStateUpdater){q.warn("updateProductField: G7Core.state or globalStateUpdater is not available");return}try{const h=g.state.get()||{},p=(h.products?.data?.data||[]).map(x=>x.id===i?{...x,[o]:d,_modified:!0}:x),y=new Set(h._local?.modifiedProductIds||[]);y.add(i),this.globalStateUpdater({products:{...h.products,data:{...h.products?.data,data:p}},_local:{...h._local,modifiedProductIds:Array.from(y)}}),q.log(`updateProductField: Updated product ${i}, field: ${o}, value:`,d)}catch(h){throw q.error("updateProductField: Error updating product field",h),h}}),this.registerHandler("updateOptionField",async(t,a)=>{const{productId:i,optionId:o,field:d,value:g}=t.params||{};if(!i||!o||!d){q.warn("updateOptionField: productId, optionId and field are required");return}if(typeof window>"u"){q.warn("updateOptionField: window is not available");return}const h=window.G7Core;if(!h?.state?.get||!this.globalStateUpdater){q.warn("updateOptionField: G7Core.state or globalStateUpdater is not available");return}try{const f=h.state.get()||{},y=(f.products?.data?.data||[]).map(S=>{if(S.id===i&&S.options){const v=S.options.map(w=>w.id===o?{...w,[d]:g,_modified:!0}:w);return{...S,options:v,_modified:!0}}return S}),x=new Set(f._local?.modifiedProductIds||[]);x.add(i),this.globalStateUpdater({products:{...f.products,data:{...f.products?.data,data:y}},_local:{...f._local,modifiedProductIds:Array.from(x)}}),q.log(`updateOptionField: Updated product ${i} option ${o}, field: ${d}, value:`,g)}catch(f){throw q.error("updateOptionField: Error updating option field",f),f}}),this.registerHandler("setLocale",async(t,a)=>{const i=t.target;if(!i||typeof i!="string"){q.warn("setLocale: Invalid locale:",i);return}const o=window.__templateApp;if(o&&typeof o.changeLocale=="function")try{await o.changeLocale(i),q.log("setLocale: Locale changed to",i)}catch(d){q.error("setLocale: Failed to change locale:",d),window.location.reload()}else{q.warn("setLocale: TemplateApp not found, falling back to page reload");try{localStorage.setItem("g7_locale",i)}catch{}window.location.reload()}}),this.registerHandler("suppress",async()=>{q.log("suppress: Error intentionally suppressed")}),this.registerBuiltInHandlerMetadata()}registerBuiltInHandlerMetadata(){const e=Vn();if(!e?.isEnabled())return;const t=[{name:"refetchDataSource",description:"데이터 소스를 다시 fetch합니다"},{name:"appendDataSource",description:"데이터 소스에 새 데이터를 병합합니다 (무한 스크롤용)"},{name:"updateDataSource",description:"API 응답으로 데이터 소스를 직접 업데이트합니다 (refetch 대체)"},{name:"reloadRoutes",description:"라우트를 다시 로드합니다"},{name:"refresh",description:"현재 페이지를 새로고침합니다"},{name:"remount",description:"컴포넌트를 리마운트합니다"},{name:"reloadTranslations",description:"다국어 파일을 다시 로드합니다"},{name:"showErrorPage",description:"에러 페이지를 표시합니다"},{name:"emitEvent",description:"이벤트를 발생시킵니다"},{name:"updateProductField",description:"상품 필드를 인라인 수정합니다"},{name:"updateOptionField",description:"상품 옵션 필드를 인라인 수정합니다"},{name:"setLocale",description:"언어를 변경합니다 (DB 저장 + UI 리렌더링)"}];for(const a of t)e.trackHandlerRegistration(a.name,"built-in",a.description)}createHandler(e,t,a){q.log("createHandler called for:",e.handler,e.type);const i=window.__g7DevTools,o=Date.now(),d=a?.state?{...a.state}:null,g=`handler_${e.handler}_${o}`;return async h=>{if(q.log("Handler invoked for:",e.handler,"event:",h.type),i?.isEnabled?.()&&d){const p=window.G7Core?.state?.getLocal?.()??a?.state??{},y=Date.now()-o;for(const x of Object.keys(d)){const S=d[x],v=p[x];S!==v&&y>100&&(i.trackStaleClosureWarning?.({type:"event-handler-stale",location:`createHandler(${e.handler})`,capturedPath:`_local.${x}`,capturedValue:S,capturedAt:o,currentValue:v,actionId:g,stackTrace:new Error().stack}),q.warn(`[Stale Closure] _local.${x} changed after handler creation:`,`captured="${S}" → current="${v}" (${y}ms ago)`))}}try{h.type!=="change"&&h.preventDefault();let f={};if(h.type==="submit"&&h.target instanceof HTMLFormElement){const x=h.target;new FormData(x).forEach((v,w)=>{f[w]=v})}const p={...this.defaultContext,data:{...t,form:f,_local:a?.state||{},$event:h},event:h,...a&&{state:a.state,setState:a.setState},isolatedContext:a?.isolatedContext};if(e.confirm){let x=this.resolveValue(e.confirm,p.data);if(this.translationEngine&&this.translationContext&&x.startsWith("$t:")&&(x=this.translationEngine.resolveTranslations(x,this.translationContext,p.data)),!confirm(x))return}const y=window.__g7ActionContext;window.__g7ActionContext={...a,data:p.data};try{await this.executeAction(e,p)}finally{window.__g7ActionContext=y}}catch(f){if(q.error("Action execution failed:",f),e.onError){const p=f instanceof Gt&&f.originalError?f.originalError:f,y={...this.defaultContext,data:{...t,error:p,_local:a?.state||{},$event:h},event:h,...a&&{state:a.state,setState:a.setState}},x=Array.isArray(e.onError)?e.onError:[e.onError];for(const S of x)await this.executeAction(S,y)}}}}generateActionId(e,t){const a=e.handler,i=t||"no-target",o=Date.now(),d=Math.random().toString(36).substring(2,9);return`${a}_${i.replace(/[^a-zA-Z0-9]/g,"_")}_${o}_${d}`}async executeAction(e,t){e=this.resolveActionRef(e);const a=Vn(),i=a?.isEnabled()?`action_${Date.now()}_${Math.random().toString(36).substring(2,11)}`:void 0,o=performance.now();let d;if(i&&a&&a.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),context:this.sanitizeForDevTools({hasState:!!t.state,hasSetState:!!t.setState,dataKeys:t.data?Object.keys(t.data):[]}),startTime:o,status:"started"}),e.if!==void 0)try{const h=this.resolveValue(e.if,t.data),f=h===!0||h==="true"||h&&h!=="false"&&h!=="0"&&h!==!1;if(q.log("[executeAction] if condition result:",e.handler,f),!f)return i&&a&&a.logAction({id:i,type:e.handler,startTime:o,endTime:performance.now(),duration:performance.now()-o,status:"success",result:{skipped:!0,reason:"if condition false"}}),{success:!0,data:void 0}}catch(h){return q.error("[executeAction] if condition error:",e.handler,h),i&&a&&a.logAction({id:i,type:e.handler,startTime:o,endTime:performance.now(),duration:performance.now()-o,status:"error",error:{name:"ConditionEvaluationError",message:h instanceof Error?h.message:String(h),stack:h instanceof Error?h.stack:void 0}}),{success:!0,data:void 0}}let g;try{const h=this.resolveParams(e.params,t.data);i&&(d=this.sanitizeForDevTools(h));const f=e.target?this.resolveValue(e.target,t.data):void 0;if(e.handler==="apiCall"&&t.setState){g=this.generateActionId(e,f);const y=t.state?.loadingActions||{};t.setState({loadingActions:{...y,[g]:!0}})}if(this.previewMode&&Gm.has(e.handler))return q.warn(`Preview mode: "${e.handler}" suppressed`,f||h),i&&a&&a.logAction({id:i,type:e.handler,startTime:o,endTime:performance.now(),duration:performance.now()-o,status:"skipped",metadata:{reason:"preview_mode_suppressed"}}),{success:!0,data:void 0};let p;switch(e.handler){case"navigate":const y=h.path||f;p=await this.handleNavigate(y,h,t);break;case"navigateBack":p=await this.handleNavigateBack();break;case"navigateForward":p=await this.handleNavigateForward();break;case"openWindow":{const S=h.path||f;p=await this.handleOpenWindow(S,h);break}case"replaceUrl":{const S=h.path||f||window.location.pathname;p=await this.handleReplaceUrl(S,h);break}case"apiCall":if(e.onSuccess&&a?.isEnabled()&&i){const S=window.G7Core,v={};if(S?.state?.get){const w=S.state.get();v._global=w}t.state&&(v._local=t.state),a.registerStateCaptureForHandler?.(i,["_global","_local"],v)}const x=e.auth_mode??(e.auth_required?"required":"none");p=await this.handleApiCall(f,h,t,x);break;case"login":p=await this.handleLogin(f,h,t);break;case"logout":p=await this.handleLogout(f,t);break;case"setState":q.log("[executeAction] setState resolvedParams:",h),p=await this.handleSetState(e.render!==void 0?{...h,__render:e.render}:h,t);break;case"setError":p=await this.handleSetError(f,h,t);break;case"openModal":p=await this.handleOpenModal(f,t);break;case"closeModal":p=await this.handleCloseModal(t);break;case"showAlert":p=await this.handleShowAlert(f,t);break;case"toast":p=await this.handleToast(h,t);break;case"switch":p=await this.handleSwitch(e,t);break;case"conditions":p=await this.handleConditions(e,t);break;case"sequence":p=await this.handleSequence(e,t);break;case"parallel":p=await this.handleParallel(e,t);break;case"loadScript":p=await this.handleLoadScript(h,e,t);break;case"callExternal":p=await this.handleCallExternal(h,e,t);break;case"callExternalEmbed":p=await this.handleCallExternalEmbed(h,e,t);break;case"saveToLocalStorage":p=await this.handleSaveToLocalStorage(h,t);break;case"loadFromLocalStorage":p=await this.handleLoadFromLocalStorage(h,t);break;default:p=await this.handleCustomAction({...e,target:f,params:h},t);break}if(e.resultTo&&p!==void 0){const{target:y,key:x,merge:S}=e.resultTo,v=this.resolveValue(x,t.data),w=S==="replace"?"replace":S==="shallow"?"shallow":"deep";if(y==="_local"&&t.setState){const k=this.buildNestedUpdate(v,p),A=w!=="deep"?{...k,__mergeMode:w}:k;t.setState(A),q.log(`[resultTo] Saved to _local.${v} (merge=${w}):`,p)}else if(y==="_local"&&this.globalStateUpdater){const O=(window.G7Core?.state?.get()||{})._local||{},N=this.buildNestedUpdate(v,p);let D;w==="replace"?D=N:w==="shallow"?D={...O,...N}:D=this.deepMergeWithState(N,O),this.globalStateUpdater({_local:D}),q.log(`[resultTo] Saved to _local.${v} via globalStateUpdater (merge=${w}):`,p)}else if(y==="_global"&&this.globalStateUpdater){const k=this.buildNestedUpdate(v,p);this.globalStateUpdater(k),q.log(`[resultTo] Saved to _global.${v}:`,p)}else if(y==="_isolated"&&t.isolatedContext){const k=this.buildNestedUpdate(v,p);t.isolatedContext.mergeState(k,w),q.log(`[resultTo] Saved to _isolated.${v} (merge=${w}):`,p)}else q.warn(`[resultTo] Cannot save result: target=${y}, setState=${!!t.setState}, globalStateUpdater=${!!this.globalStateUpdater}, isolatedContext=${!!t.isolatedContext}`)}if(e.onSuccess){if(a?.isEnabled()&&i&&e.handler==="apiCall"){const S=window.G7Core,v={};S?.state?.get&&(v._global=S.state.get()),t.state&&(v._local=t.state),a.detectStaleClosure?.(i,`${e.handler} → onSuccess`,v,"callback-state-capture",i)}const y={...t,data:{...t.data,result:p,response:p}},x=Array.isArray(e.onSuccess)?e.onSuccess:[e.onSuccess];x.length>1?await this.handleSequence({handler:"sequence",type:"click",actions:x},y):x.length===1&&await this.executeAction(x[0],y)}return i&&a&&a.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),resolvedParams:d,startTime:o,endTime:performance.now(),duration:performance.now()-o,status:"success",result:this.sanitizeForDevTools(p)}),{success:!0,data:p}}catch(h){const f=h instanceof Gt?h:new Gt(`Failed to execute action: ${e.handler}`,e,h instanceof Error?h:void 0),p=f.originalError?.response||{},y=p.data||{},x=f.originalError?.status||p.status||500,S=y.message||f.message,v={status:x,message:S,errors:y.errors||p.errors,data:y,statusText:f.originalError?.statusText},k=Sa().resolve(x,{errorHandling:e.errorHandling,onError:e.onError});if(k.handler){if(a?.isEnabled()&&i&&e.handler==="apiCall"){const O=window.G7Core,N={};O?.state?.get&&(N._global=O.state.get()),t.state&&(N._local=t.state),a.detectStaleClosure?.(i,`${e.handler} → onError`,N,"callback-state-capture",i)}const A={...t,data:{...t.data,error:v}};try{const O={type:"click",handler:k.handler.handler,target:k.handler.target,params:k.handler.params,actions:k.handler.actions};return await this.executeAction(O,A),{success:!1,error:f}}catch(O){return q.error("Error executing error handler:",O),{success:!1,error:f}}}throw i&&a&&a.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),resolvedParams:d,startTime:o,endTime:performance.now(),duration:performance.now()-o,status:"error",error:{name:f.name,message:f.message,stack:f.stack}}),f}finally{if(e.handler==="apiCall"&&t.setState&&g){const h=t.state?.loadingActions||{},{[g]:f,...p}=h;t.setState({loadingActions:p})}}}async handleNavigate(e,t,a){let i=e;if(t.query)if(t.mergeQuery===!0)i=this.buildMergedQueryPath(e,t.query);else{const d=new URLSearchParams;for(const[h,f]of Object.entries(t.query))if(f!=null&&f!=="")if(Array.isArray(f)){const p=h.endsWith("[]")?h:`${h}[]`;for(const y of f)y!=null&&y!==""&&d.append(p,String(y))}else d.set(h,String(f));const g=d.toString();g&&(i=`${e}?${g}`)}if(q.log("handleNavigate:",{target:e,params:t,finalPath:i,replace:t.replace,windowLocationSearch:window.location.search}),t.replace===!0){const d=window.G7Core;if(d?.updateQueryParams){const g=typeof t.transition_overlay_target=="string"?t.transition_overlay_target:void 0;await d.updateQueryParams(i,g?{transitionOverlayTarget:g}:void 0),q.log("handleNavigate: Used updateQueryParams for replace mode",g?{transitionOverlayTarget:g}:void 0),this.applyScrollOption(t.scroll,t.scrollBehavior,"top");return}q.warn("handleNavigate: G7Core.updateQueryParams not available, falling back to React Router")}const o=this.resolveNavigateFallbackAction(i,t);if(o){q.warn(`handleNavigate: No route matched, falling back to "${o.handler}"`),await this.dispatchAction({type:"click",handler:o.handler,params:o.params},a),this.applyScrollOption(t.scroll,t.scrollBehavior,"top");return}if(!a.navigate)throw new Gt("Navigate function is not provided in context");a.navigate(i,{replace:t.replace===!0}),this.applyScrollOption(t.scroll,t.scrollBehavior,"top")}resolveNavigateFallbackAction(e,t){const a=t.fallback;if(a===!1||t.replace===!0)return null;const o=window.__templateApp?.getRouter?.();if(!o||typeof o.match!="function"||typeof o.getRoutes=="function"&&o.getRoutes().length===0)return null;const d=e.split("?")[0];return o.match(d)?null:this.resolveNavigateFallback(a,e,t)}resolveNavigateFallback(e,t,a){return e==null?{handler:"openWindow",params:{path:t,target:"_blank"}}:typeof e=="string"?{handler:e,params:{path:t}}:typeof e=="object"&&typeof e.handler=="string"?{handler:e.handler,params:{path:t,...e.params||{}}}:(q.warn("resolveNavigateFallback: unrecognized fallback option, using openWindow",e),{handler:"openWindow",params:{path:t,target:"_blank"}})}applyScrollOption(e,t,a){const i=e===void 0?a:e;if(i==="preserve")return;const o=t==="smooth"?"smooth":"instant",d=y=>{if(typeof y!="object"||y===null)return!1;const x=y;return"container"in x||"to"in x||"block"in x||"offset"in x},g=(y,x,S=0)=>{y===window?window.scrollTo({top:x,left:S,behavior:o}):y.scrollTo({top:x,left:S,behavior:o})},h=(y,x,S,v)=>{if(x===window){y.scrollIntoView({behavior:o,block:S}),v&&window.scrollBy({top:-v,left:0,behavior:o});return}const w=x,k=y.getBoundingClientRect(),A=w.getBoundingClientRect(),O=w.scrollTop+(k.top-A.top);let N;S==="center"?N=O-(w.clientHeight-y.clientHeight)/2:S==="end"?N=O-(w.clientHeight-y.clientHeight):N=O,N-=v,w.scrollTo({top:Math.max(0,N),left:0,behavior:o})},f=()=>{window.scrollTo({top:0,left:0,behavior:o});const y=document.getElementById("app")??document.body;if(!y)return;y.querySelectorAll("*").forEach(S=>{if(S.scrollTop===0&&S.scrollLeft===0)return;const v=window.getComputedStyle(S),w=v.overflowY,k=v.overflowX;(w==="auto"||w==="scroll"||k==="auto"||k==="scroll")&&S.scrollTo({top:0,left:0,behavior:o})})},p=()=>{try{if(d(i)){const y=i,x=y.block??"start",S=typeof y.offset=="number"?y.offset:0;let v=window;if(typeof y.container=="string"&&y.container.length>0){const k=document.querySelector(y.container);if(!k){q.warn(`applyScrollOption: container not found: ${y.container}`);return}v=k}const w=y.to??"top";if(w==="top"){v===window?f():g(v,0);return}if(typeof w=="number"){g(v,w-S);return}if(typeof w=="object"&&w!==null&&("x"in w||"y"in w)){const{x:k=0,y:A=0}=w;g(v,A-S,k);return}if(typeof w=="string"&&(w.startsWith("#")||w.startsWith("."))){const k=document.querySelector(w);k?h(k,v,x,S):q.warn(`applyScrollOption: target element not found: ${w}`);return}q.warn('applyScrollOption: invalid "to" value in extended form',w);return}if(i==="top"){f();return}if(typeof i=="number"){window.scrollTo({top:i,left:0,behavior:o});return}if(typeof i=="object"&&i!==null&&("x"in i||"y"in i)){const{x:y=0,y:x=0}=i;window.scrollTo({top:x,left:y,behavior:o});return}if(typeof i=="string"&&(i.startsWith("#")||i.startsWith("."))){const y=document.querySelector(i);y&&y.scrollIntoView({behavior:o,block:"start"});return}}catch(y){q.warn("applyScrollOption: failed to apply scroll",y)}};typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(p):p()}async handleOpenWindow(e,t){let a=e;if(t.query){const i=new URLSearchParams;for(const[d,g]of Object.entries(t.query))g!=null&&g!==""&&i.set(d,String(g));const o=i.toString();o&&(a=`${e}?${o}`)}q.log("handleOpenWindow:",{target:e,params:t,finalPath:a}),window.open(a,"_blank")}async handleNavigateBack(){q.log("handleNavigateBack"),window.history.back()}async handleNavigateForward(){q.log("handleNavigateForward"),window.history.forward()}async handleReplaceUrl(e,t){let a=e;if(t.query)if(t.mergeQuery===!0)a=this.buildMergedQueryPath(e,t.query);else{const i=new URLSearchParams;for(const[d,g]of Object.entries(t.query))if(g!=null&&g!=="")if(Array.isArray(g)){const h=d.endsWith("[]")?d:`${d}[]`;for(const f of g)f!=null&&f!==""&&i.append(h,String(f))}else i.set(d,String(g));const o=i.toString();o&&(a=`${e}?${o}`)}q.log("handleReplaceUrl:",{target:e,params:t,finalPath:a}),window.history.replaceState(null,"",a),this.applyScrollOption(t.scroll,t.scrollBehavior,"preserve")}buildMergedQueryPath(e,t){const a=new URLSearchParams(window.location.search);for(const[d,g]of Object.entries(t))if(g==null||g==="")a.delete(d);else if(Array.isArray(g)){const h=d.endsWith("[]")?d:`${d}[]`;a.delete(d),a.delete(h);for(const f of g)f!=null&&f!==""&&a.append(h,String(f))}else a.set(d,String(g));const i=a.toString(),o=e.split("?")[0];return i?`${o}?${i}`:o}async ensureCsrfToken(){try{await fetch("/sanctum/csrf-cookie",{credentials:"include"})}catch(e){throw new Gt("Failed to fetch CSRF token",void 0,e instanceof Error?e:void 0)}}getCsrfTokenFromCookie(){const a=`; ${document.cookie}`.split("; XSRF-TOKEN=");if(a.length===2){const i=a.pop()?.split(";").shift();return i?decodeURIComponent(i):null}return null}buildQueryString(e){const t=new URLSearchParams;for(const[a,i]of Object.entries(e))if(!(i==null||i===""))if(Array.isArray(i))for(const o of i)o!=null&&o!==""&&t.append(`${a}[]`,String(o));else typeof i=="object"?t.append(a,JSON.stringify(i)):t.append(a,String(i));return t.toString()}async handleApiCall(e,t,a,i="none"){const{method:o="GET",body:d,headers:g,contentType:h}=t;o!=="GET"&&o!=="HEAD"&&await this.ensureCsrfToken();const f=this.getCsrfTokenFromCookie();let p={};if(i==="required"||i==="optional"){const z=ns().getToken();z&&(p={Authorization:`Bearer ${z}`})}let y=e;const x=t.query||(o==="GET"?d:null);if(x&&typeof x=="object"){const M=this.buildQueryString(x);if(M){const z=e.includes("?")?"&":"?";y=`${e}${z}${M}`}}const S=window.G7Core?.state?.getGlobal?.()||a.state?._global||{},v=window.G7Core?.state?.getLocal?.()||a.state?._local||{},w={_global:S,_local:v},k=this.getMatchingGlobalHeaders(e,w),A={};if(typeof window<"u"){const M=localStorage.getItem("g7_locale");M&&(A["Accept-Language"]=M)}const O=h==="multipart/form-data",N={method:o,headers:{...O?{}:{"Content-Type":"application/json"},Accept:"application/json",...A,...f&&{"X-XSRF-TOKEN":f},...p,...k,...g},credentials:"include"};if(d&&o!=="GET")if(O){const M=new FormData;for(const[z,K]of Object.entries(d))K instanceof File||K instanceof Blob?M.append(z,K):K!=null&&M.append(z,typeof K=="object"?JSON.stringify(K):String(K));N.body=M}else N.body=JSON.stringify(d);const D=Vn();let $=null;D?.isEnabled()&&($=D.trackRequest(y,o));try{const M=await fetch(y,N);let z;try{z=await M.json()}catch{z=null}if($&&D?.isEnabled()&&(D.completeRequest($,M.status,z),$=null),!M.ok){const K=z||{},pe=new Error(K.message||`API call failed: ${M.statusText}`);throw pe.response=K,pe.status=M.status,pe.statusText=M.statusText,new Gt(K.message||`API call failed: ${M.statusText}`,void 0,pe)}return z}catch(M){throw $&&D?.isEnabled()&&D.failRequest($,M instanceof Error?M.message:String(M)),M}}async handleLogin(e,t,a){const{body:i}=t;if(!i||!i.email||!i.password)throw new Gt("Login requires email and password in body params");const o=e==="user"?"user":"admin",d=o==="admin"?"/api/auth/admin/login":"/api/auth/login",g=window.G7Core?.state?.getGlobal?.()||a.state?._global||{},h=window.G7Core?.state?.getLocal?.()||a.state?._local||{},f={_global:g,_local:h},p=this.getMatchingGlobalHeaders(d,f),y=as.getInstance();try{const x=Object.keys(p).length>0?{headers:p}:void 0;return{user:await y.login(o,{email:i.email,password:i.password},x)}}catch(x){const S=x.message||"Login failed",v=new Error(S);throw v.response=x.response?.data||{},v.status=x.status||x.response?.status||500,new Gt(S,void 0,v)}}async handleLogout(e,t){await as.getInstance().logout()}async handleSetState(e,t){q.log("[handleSetState] START, params:",e);const{target:a="component",scope:i,merge:o,__render:d,...g}=e,h=Vn(),f=window.G7Core;if(typeof a=="string"&&(a.startsWith("$parent.")||a.startsWith("$root.")))return this.handleParentScopeSetState(a,g,o,t);const p=t.state&&Object.keys(t.state).length>0?t.state:f?.state?.get()||{},y=a==="global"?"_global":a.startsWith("_local.")?a:"_local",x=y==="_global"?p._global:y.startsWith("_local.")?this.getNestedProperty(p._local||{},y.slice(7)):p._local,S=h?.isEnabled()?h.startStateChange(y,x,g,{actionId:t.actionId,handlerType:"setState",source:`target=${a}`}):void 0,v=o==="replace"?"replace":o==="shallow"?"shallow":"deep",w=v!=="deep"?{...g,__mergeMode:v,...S?{__setStateId:S}:{}}:{...g,...S?{__setStateId:S}:{}};if(a==="global"){if(!this.globalStateUpdater){q.warn("Global state updater is not set"),S&&h&&h.completeStateChange(S);return}const k=f?.state?.get()||{},{__setStateId:A,__mergeMode:O,...N}=w,D=v==="deep"?this.deepMergeWithState(N,k):N,$={...D,...S?{__setStateId:S}:{},...v!=="deep"?{__mergeMode:v}:{}};return q.log("setState global:",$),this.globalStateUpdater($,{render:d}),S&&h&&setTimeout(()=>h.completeStateChange(S),0),{__target:"global",...v!=="deep"?{__mergeMode:v}:{},...D}}else if(a==="isolated"){const k=t.isolatedContext;if(k){const{__mergeMode:A,__setStateId:O,...N}=w;return k.mergeState(N,v),q.log("[handleSetState] isolated state updated:",N,"mergeMode:",v),S&&h&&setTimeout(()=>h.completeStateChange(S),0),{__target:"isolated",...N}}else if(q.warn('[handleSetState] isolated target used but no IsolatedStateContext found. Make sure the component has "isolatedState" attribute. Falling back to local state.'),t.setState){const O=window.__g7PendingLocalState||t.state||{},N=v==="deep"?this.deepMergeWithState(w,O):w;return t.setState(N),S&&h&&setTimeout(()=>h.completeStateChange(S),0),N}else throw S&&h&&h.completeStateChange(S),new Gt("isolated target used but no IsolatedStateContext found and no setState function in context")}else if(a==="local"||a==="component"||a==="_local"){if(i==="parent"||i==="root"){const A=window.__g7LayoutContextStack||[];if(A.length>0){const O=i==="parent"?A[A.length-1]:A[0];if(O?.setState){const{__mergeMode:N,__setStateId:D,...$}=w,M=v==="deep"?this.deepMergeWithState($,O.state||{}):$;return q.log(`[handleSetState] scope=${i}: 타겟 컨텍스트에 상태 업데이트`,M),O.setState(M),S&&h&&setTimeout(()=>h.completeStateChange(S),0),M}}q.warn(`[handleSetState] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const k=t.setState&&!t._isDispatchFallbackContext;if(q.log("[handleSetState] isRealComponentContext:",k,"context.setState:",!!t.setState,"_isDispatchFallbackContext:",t._isDispatchFallbackContext),k){q.log("[handleSetState] Using COMPONENT setState path"),q.log("[handleSetState] resolvedPayload:",w),q.log("[handleSetState] context.state:",t.state),q.log("[handleSetState] mergeMode:",v);const O=window.__g7PendingLocalState||t.state||{},N=v==="deep"?this.deepMergeWithState(w,{}):w;q.log("[handleSetState] convertedPayload (변경 필드만, dot notation 변환):",N),t.setState(N);const D=v==="deep"?this.deepMergeWithState(w,O):v==="shallow"?{...t.state||{},...w}:w,{__mergeMode:$,__setStateId:M,...z}=D;window.__g7PendingLocalState=z,q.log("[handleSetState] __g7PendingLocalState updated:",z);const{__mergeMode:K,__setStateId:pe,...we}=w;if(v==="replace")window.__g7ForcedLocalFields=we;else{const J=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=this.deepMergeWithState(we,J)}return q.log("[handleSetState] __g7ForcedLocalFields updated:",we),S&&h&&setTimeout(()=>h.completeStateChange(S),0),{__target:"local",...D}}else if(this.globalStateUpdater){q.log("[handleSetState] Using GLOBAL STATE UPDATER path for _local");const O=window.__g7PendingLocalState||p._local||{};q.log("[handleSetState] currentLocal (with pending):",O);const N=v==="deep"?this.deepMergeWithState(w,O):w;return q.log("[handleSetState] finalLocal (merged):",N),this.globalStateUpdater({_local:N},{render:d}),window.__g7PendingLocalState=N,q.log("[handleSetState] __g7PendingLocalState updated for globalStateUpdater path"),S&&h&&setTimeout(()=>h.completeStateChange(S),0),{__target:"local",...N}}else throw S&&h&&h.completeStateChange(S),new Gt("setState function is not provided in context and globalStateUpdater is not set")}else if(a.startsWith("_local.")){const k=a.slice(7),{__mergeMode:A,__setStateId:O,...N}=w,D=N.value!==void 0?N.value:Object.values(N)[0];if(t.setState){const M=window.__g7PendingLocalState||t.state||{},z=this.createNestedUpdate(k,D,M),K={...M,...z};return t.setState(z),S&&h&&setTimeout(()=>h.completeStateChange(S),0),K}else throw S&&h&&h.completeStateChange(S),new Gt("setState function is not provided in context")}else{if(!t.setState)throw S&&h&&h.completeStateChange(S),new Gt("setState function is not provided in context");const A=window.__g7PendingLocalState||t.state||{},O=v==="deep"?this.deepMergeWithState(w,A):w;return t.setState(O),S&&h&&setTimeout(()=>h.completeStateChange(S),0),O}}async handleParentScopeSetState(e,t,a,i){const o=Vn(),d=window.G7Core,g=a==="replace"?"replace":a==="shallow"?"shallow":"deep",h=e.startsWith("$parent."),f=h?"$parent.":"$root.",p=e.slice(f.length);let y,x;if(p==="_local"||p==="_global")y=p,x=void 0;else if(p.startsWith("_local."))y="_local",x=p.slice(7);else if(p.startsWith("_global."))y="_global",x=p.slice(8);else{q.warn(`[handleParentScopeSetState] 지원하지 않는 타겟 형식: ${e}. _local 또는 _global으로 시작해야 합니다.`);return}const S=window.__g7LayoutContextStack||[];if(S.length===0){q.warn(`[handleParentScopeSetState] 레이아웃 컨텍스트 스택이 비어있습니다. target=${e}`);return}const v=h?S[S.length-1]:S[0];if(!v){q.warn(`[handleParentScopeSetState] 타겟 컨텍스트를 찾을 수 없습니다. target=${e}`);return}const w=y==="_global"?v.state?._global:v.state?._local,k=o?.isEnabled()?o.startStateChange(e,w,t,{actionId:i.actionId,handlerType:"setState",source:`target=${e}`}):void 0,{__mergeMode:A,__setStateId:O,...N}=t;if(y==="_global"){if(!this.globalStateUpdater){q.warn("[handleParentScopeSetState] globalStateUpdater가 설정되지 않았습니다."),k&&o&&o.completeStateChange(k);return}const D=d?.state?.get()||{};if(x){const $=N.value!==void 0?N.value:Object.values(N)[0],M=this.createNestedUpdate(x,$,D),z={...D,...M};q.log(`[handleParentScopeSetState] ${e}: 전역 상태 중첩 경로 업데이트`,z),this.globalStateUpdater(z)}else{const $=g==="deep"?this.deepMergeWithState(N,D):N;q.log(`[handleParentScopeSetState] ${e}: 전역 상태 업데이트 (mergeMode=${g})`,$),this.globalStateUpdater(g!=="deep"?{...$,__mergeMode:g}:$)}return k&&o&&setTimeout(()=>o.completeStateChange(k),0),{__target:e,...N}}else{if(!v.setState){q.warn(`[handleParentScopeSetState] 타겟 컨텍스트에 setState가 없습니다. target=${e}`),k&&o&&o.completeStateChange(k);return}const D=v.state||{};if(x){const $=N.value!==void 0?N.value:Object.values(N)[0],M=this.createNestedUpdate(x,$,D),z={...D,...M};return q.log(`[handleParentScopeSetState] ${e}: 로컬 상태 중첩 경로 업데이트`,M),v.setState(M),v.state=z,v.dataContext&&(v.dataContext._local=z),dg(),k&&o&&setTimeout(()=>o.completeStateChange(k),0),z}else{const $=g!=="deep"?{...N,__mergeMode:g}:N,M=g==="replace"?N:g==="shallow"?{...D,...N}:this.deepMergeWithState(N,D);return q.log(`[handleParentScopeSetState] ${e}: 로컬 상태 업데이트 (mergeMode=${g})`,M),v.setState($),v.state=M,v.dataContext&&(v.dataContext._local=M),dg(),k&&o&&setTimeout(()=>o.completeStateChange(k),0),M}}}deepMergeWithState(e,t){const a=["errors"];let i=e;if("..."in e){const d=e["..."];if(d&&typeof d=="object"&&!Array.isArray(d)){const{"...":g,...h}=e;i={...d,...h}}else{const{"...":g,...h}=e;i=h}}const o={...t};for(const[d,g]of Object.entries(i)){if(a.includes(d)){o[d]=g;continue}if(d.includes(".")&&d!=="..."){const h=this.createNestedUpdate(d,g,o);this.deepMergeInto(o,h,o);continue}if(g!==null&&typeof g=="object"&&!Array.isArray(g)&&Object.getPrototypeOf(g)!==Object.prototype&&Object.getPrototypeOf(g)!==null){o[d]=g;continue}g!==null&&typeof g=="object"&&!Array.isArray(g)&&t[d]!==null&&typeof t[d]=="object"&&!Array.isArray(t[d])?o[d]=this.deepMergeWithState(g,t[d]):o[d]=g}return o}deepMergeInto(e,t,a){for(const[i,o]of Object.entries(t)){if(o===null){e[i]=o;continue}if(e[i]===null){e[i]=o;continue}typeof o=="object"&&!Array.isArray(o)&&e[i]!==void 0&&e[i]!==null&&typeof e[i]=="object"&&!Array.isArray(e[i])?(e[i]===a[i]&&(e[i]={...e[i]}),this.deepMergeInto(e[i],o,a[i]||{})):typeof o=="object"&&!Array.isArray(o)&&e[i]===void 0&&a[i]!==null&&typeof a[i]=="object"&&!Array.isArray(a[i])?e[i]={...a[i],...o}:e[i]=o}}createNestedUpdate(e,t,a){const i=e.split(".");if(i.length===1)return{[i[0]]:t};const o={};let d=o,g=a;for(let h=0;h{this.globalStateUpdater({_local:S})};p.push({state:y,setState:x,dataContext:{_local:y||t.data?._local,_global:o?t.data?._global:t.data?._global||i?.state?.get?.(),_computed:t.data?._computed}}),window.__g7LayoutContextStack=p,q.log(`[handleOpenModal] 레이아웃 컨텍스트 스택에 push, 스택 크기: ${p.length}, state:`,y,o?"(direct)":"(fallback via G7Core)")}else q.warn(`[handleOpenModal] 컨텍스트 스택에 push 실패 - setState: ${!!t.setState}, state: ${t.state!==void 0}, G7Core: ${!!i?.state?.getLocal}`);const h=[...a,e];this.globalStateUpdater({modalStack:h,activeModal:e});const f=Vn();if(f?.isEnabled()){const p=a.length>0?a[a.length-1]:void 0;f.trackModalOpen?.({modalId:e,modalName:e,scopeType:"isolated",parentModalId:p,initialState:t.state?{...t.state}:{}})}}async handleCloseModal(e){if(!this.globalStateUpdater){q.warn("Global state updater is not set for closeModal");return}const t=e?.data?._global?.modalStack||[],a=t.length>0?t[t.length-1]:null,i=t.slice(0,-1),o=i.length>0?i[i.length-1]:null,d=window.__g7LayoutContextStack||[];if(d.length>0){const g=d[d.length-1];g&&(g.dataContext=void 0),d.pop(),window.__g7LayoutContextStack=d,q.log(`[handleCloseModal] 레이아웃 컨텍스트 스택에서 pop, 스택 크기: ${d.length}`)}if(a){const g=Vn();g?.isEnabled()&&g.trackModalClose?.(a,e?.state)}this.globalStateUpdater({modalStack:i,activeModal:o})}async handleShowAlert(e,t){let a=e;this.translationEngine&&this.translationContext&&e.startsWith("$t:")&&(a=this.translationEngine.resolveTranslations(e,this.translationContext,t.data)),alert(a)}async handleToast(e,t){const{type:a="info",message:i,icon:o,duration:d}=e;let g=i;if(this.translationEngine&&this.translationContext&&i?.startsWith("$t:")&&(g=this.translationEngine.resolveTranslations(i,this.translationContext,t.data)),this.globalStateUpdater){const f={id:`toast_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,type:a,message:g,...o&&{icon:o},...d&&{duration:d}},S=[...window.G7Core?.state?.get()?.toasts||[],f];this.globalStateUpdater({toasts:S})}else q.log(`[Toast ${a}] ${g}`)}async handleSwitch(e,t){const{cases:a}=e;if(!a){q.warn("switch handler requires cases property");return}const i=this.resolveParams(e.params,t.data);let o;if(i?.value!==void 0?(o=i.value,q.log("switch handler: using params.value as case key:",o)):(o=t.data?.$args?.[0],q.log("switch handler: using $args[0] as case key:",o)),o==null){if(a.default)return q.log("switch handler: case key is undefined, using default case"),await this.executeAction(a.default,t);q.warn("switch handler: case key is not defined and no default case");return}const d=String(o);let g=a[d];if(!g&&a.default&&(q.log(`switch handler: no case found for key "${d}", using default case`),g=a.default),!g){q.warn(`switch handler: no case found for key "${d}" and no default case`);return}return await this.executeAction(g,t)}async handleConditions(e,t){const{conditions:a}=e;if(!a||!Array.isArray(a)){q.warn("conditions handler requires conditions array");return}const i=t.data||{},o=Wp(a,i,this.bindingEngine);if(!o.matched){q.log("conditions handler: no matching branch found");return}const d=a[o.branchIndex];if(q.log(`conditions handler: matched branch ${o.branchIndex}`),!d.then){q.warn('conditions handler: matched branch has no "then" action');return}return Array.isArray(d.then)?await this.handleSequence({...e,actions:d.then},t):await this.executeAction(d.then,t)}async handleSequence(e,t){const a=e.actions||e.params?.actions;if(!a||!Array.isArray(a)||a.length===0)return q.warn("sequence handler requires non-empty actions array"),[];const i=Vn(),o=i?.isEnabled()&&i.startSequenceExecution?.({eventType:e.type})||"";window.__g7SequenceLocalSync=void 0;const d=[];let g,h=t.state?{...t.state}:{},f=t.isolatedContext?.state?{...t.isolatedContext.state}:{},p=t.data?._computed||{};const y=window.G7Core,x=()=>({_global:y?.state?.get()||{},_local:{...h},_isolated:Object.keys(f).length>0?{...f}:void 0});for(let S=0;S0){const N={},D={...t.data,_local:h,_computed:N,$computed:N,_isolated:f};for(const[$,M]of Object.entries(O))if(typeof M=="string"){const z=M.trim();if(z.startsWith("{{")&&z.endsWith("}}"))try{const K=z.slice(2,-2).trim();N[$]=this.bindingEngine.evaluateExpression(K,D,{skipCache:!0})}catch{N[$]=p[$]}}p=N,q.log("[handleSequence] _computed recalculated after setState:",p)}}if(v.handler!=="setState"){const O=window.__g7SequenceLocalSync;if(O&&O!==h){h=O,window.__g7SequenceLocalSync=void 0,q.log("[handleSequence] currentState synchronized from __g7SequenceLocalSync after custom handler:",v.handler);const N=t.data?._computedDefinitions;if(N&&Object.keys(N).length>0){const D={},$={...t.data,_local:h,_computed:D,$computed:D,_isolated:f};for(const[M,z]of Object.entries(N))if(typeof z=="string"){const K=z.trim();if(K.startsWith("{{")&&K.endsWith("}}"))try{const pe=K.slice(2,-2).trim();D[M]=this.bindingEngine.evaluateExpression(pe,$,{skipCache:!0})}catch{D[M]=p[M]}}p=D,q.log("[handleSequence] _computed recalculated after custom handler:",p)}}}o&&i?.isEnabled()&&i.captureSequenceActionAfter?.(o,S,x(),Date.now()-w,A.data)}catch(A){throw o&&i?.isEnabled()&&(i.captureSequenceActionAfter?.(o,S,x(),Date.now()-w,void 0,A),i.endSequenceExecution?.(o,A)),q.error(`sequence handler: action[${S}] failed:`,A),A}}return window.__g7SequenceLocalSync=void 0,o&&i?.isEnabled()&&i.endSequenceExecution?.(o),d}async handleParallel(e,t){const a=e.actions||e.params?.actions;if(!a||!Array.isArray(a)||a.length===0)return q.warn("parallel handler requires non-empty actions array"),[];q.log(`parallel handler: executing ${a.length} actions in parallel`);const i=t.isolatedContext?{...t.isolatedContext,state:{...t.isolatedContext.state}}:null,o=a.map((h,f)=>{const p={...t,isolatedContext:i};return this.executeAction(h,p).catch(y=>{throw q.error(`parallel handler: action[${f}] failed:`,y),y})}),d=await Promise.allSettled(o),g=d.filter(h=>h.status==="rejected").length;return g>0&&q.warn(`parallel handler: ${g}/${a.length} actions failed`),d}async handleLoadScript(e,t,a){const{src:i,id:o,async:d=!0,defer:g=!1}=e;if(!i)throw new Gt('loadScript handler requires "src" parameter',t);const h=o||`script_${i.replace(/[^a-zA-Z0-9]/g,"_")}`;return bi.loadedScripts.has(h)?(q.log(`loadScript: script already loaded, skipping: ${h}`),t.onLoad&&await this.executeAction(t.onLoad,a),!0):document.getElementById(h)?(q.log(`loadScript: script element already exists: ${h}`),bi.loadedScripts.add(h),t.onLoad&&await this.executeAction(t.onLoad,a),!0):(q.log(`loadScript: loading script: ${i}`),new Promise((p,y)=>{const x=document.createElement("script");x.id=h,x.src=i,x.async=d,x.defer=g,x.onload=async()=>{if(q.log(`loadScript: script loaded successfully: ${h}`),bi.loadedScripts.add(h),t.onLoad)try{await this.executeAction(t.onLoad,a)}catch(S){q.error("loadScript: onLoad action failed:",S)}p(!0)},x.onerror=S=>{q.error(`loadScript: failed to load script: ${i}`,S),y(new Gt(`Failed to load script: ${i}`,t))},document.head.appendChild(x)}))}async handleCallExternal(e,t,a){const i=e.constructor,o=e.args||{},d=e.method,g=e.methodArgs||[],h=e.callbackEvent,f=e.embedTarget,p=e.callbackSetState,y=e.callbackAction;if(!i)throw new Gt('callExternal handler requires "constructor" parameter',t);const x=this.getNestedProperty(window,i);if(!x||typeof x!="function")throw new Gt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first using loadScript handler.`,t);q.log(`callExternal: calling constructor ${i}`);const S={...o};for(const[w,k]of Object.entries(o))k===!0&&(S[w]=A=>{if(q.log(`callExternal: callback triggered for ${w}`,A),h&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(h,A),p&&a.setState){const O=$=>{const M={};for(const[z,K]of Object.entries($))typeof K=="string"?M[z]=this.getNestedProperty(A,K):typeof K=="object"&&K!==null&&(M[z]=O(K));return M},N=O(p);q.log("callExternal: callbackSetState mapping result",N);const D=this.deepMergeWithState(N,a.state||{});q.log("callExternal: merged with existing state",D),a.setState(D)}else h&&a.setState&&a.setState({[`${h.replace(/:/g,"_")}_result`]:A});if(y){const O={...a,data:{...a.data,$event:A}},N=Array.isArray(y)?y:[y];for(const D of N)try{this.executeAction(D,O)}catch($){q.error("callExternal: callbackAction failed:",$)}}});const v=new x(S);if(d&&typeof v[d]=="function"){if(q.log(`callExternal: calling method ${d}`),d==="embed"&&f){const w=document.querySelector(f);if(w)return v[d](w,...g);throw new Gt(`Embed target element not found: ${f}`,t)}return v[d](...g)}return v}async handleCallExternalEmbed(e,t,a){const i=e.constructor,o=e.args||{},d=e.callbackSetState,g=e.callbackEvent,h=e.layerClassName,f=e.callbackAction;if(!i)throw new Gt('callExternalEmbed handler requires "constructor" parameter',t);const p=this.getNestedProperty(window,i);if(!p||typeof p!="function")throw new Gt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first.`,t);q.log(`callExternalEmbed: creating layer for ${i}`);const{layer:y,closeLayer:x}=this.createEmbedLayer(h),S={...o};for(const[w,k]of Object.entries(o))k===!0&&(S[w]=A=>{if(q.log(`callExternalEmbed: callback triggered for ${w}`,A),x(),g&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(g,A),d&&a.setState){const O=$=>{const M={};for(const[z,K]of Object.entries($))typeof K=="string"?M[z]=this.getNestedProperty(A,K):typeof K=="object"&&K!==null&&(M[z]=O(K));return M},N=O(d);q.log("callExternalEmbed: callbackSetState mapping result",N);const D=this.deepMergeWithState(N,a.state||{});q.log("callExternalEmbed: merged with existing state",D),a.setState(D)}if(f){const O={...a,data:{...a.data,$event:A}},N=Array.isArray(f)?f:[f];for(const D of N)try{this.executeAction(D,O)}catch($){q.error("callExternalEmbed: callbackAction failed:",$)}}});const v=new p(S);if(typeof v.embed=="function")v.embed(y),q.log("callExternalEmbed: embedded in layer");else throw x(),new Gt(`Constructor ${i} does not have embed method`,t);return v}createEmbedLayer(e){const t=document.createElement("div");t.id="g7-embed-overlay",t.style.cssText=` + */var Pm;function d7(){if(Pm)return wo;Pm=1;var r=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function t(a,i,o){var d=null;if(o!==void 0&&(d=""+o),i.key!==void 0&&(d=""+i.key),"key"in i){o={};for(var g in i)g!=="key"&&(o[g]=i[g])}else o=i;return i=o.ref,{$$typeof:r,type:a,key:d,ref:i!==void 0?i:null,props:o}}return wo.Fragment=e,wo.jsx=t,wo.jsxs=t,wo}var Bm;function u7(){return Bm||(Bm=1,lg.exports=d7()),lg.exports}var l=u7();const g7=Za({__proto__:null,default:es(l)},[l]),cg=it("ParentContextProvider"),Um=j.createContext(null);let yc=null;function dg(){yc?(cg.log("[triggerModalParentUpdate] 모달 부모 컨텍스트 업데이트 트리거"),yc()):cg.warn("[triggerModalParentUpdate] Provider가 아직 마운트되지 않음")}const qm=({children:r})=>{const[e,t]=j.useState(0),a=j.useRef(!0),i=j.useCallback(()=>{const d=window.__g7LayoutContextStack||[];return d[d.length-1]?.dataContext},[]);j.useEffect(()=>(a.current=!0,yc=()=>{a.current&&(t(d=>d+1),cg.log("[ParentContextProvider] 버전 업데이트됨"))},()=>{a.current=!1,yc=null}),[]);const o={version:e,getParentDataContext:i};return l.jsx(Um.Provider,{value:o,children:r})};function h7(){return j.useContext(Um)}const q=it("ActionDispatcher"),Gm=new Set(["navigate","navigateBack","navigateForward","replaceUrl","refresh","logout"]),f7=new Set(["redirect"]);function Vn(){try{return window.G7Core?.devTools}catch{return}}class Gt extends Error{constructor(e,t,a){super(e),this.action=t,this.originalError=a,this.name="ActionError"}}const bi=class bi{constructor(e={},t,a){H(this,"bindingEngine");H(this,"translationEngine");H(this,"translationContext");H(this,"customHandlers",new Map);H(this,"defaultContext");H(this,"globalStateUpdater");H(this,"errorHandlingSetup",!1);H(this,"debounceTimers",new Map);H(this,"pendingDebounceFlushers",new Map);H(this,"debounceAccumulatedValues",new Map);H(this,"globalHeaders",[]);H(this,"namedActions",{});H(this,"previewMode",!1);this.bindingEngine=new _n,this.translationEngine=t,this.translationContext=a,this.defaultContext=e,this.registerDefaultHandlers(),this.setupErrorHandling()}setGlobalHeaders(e){this.globalHeaders=e||[]}setNamedActions(e){this.namedActions=e||{};const t=Vn();t?.isEnabled?.()&&t.setNamedActionDefinitions?.(this.namedActions),q.log("[setNamedActions] registered:",Object.keys(this.namedActions))}getNamedActions(){return this.namedActions}setPreviewMode(e){this.previewMode=e,q.log("Preview mode:",e?"enabled":"disabled")}isPreviewMode(){return this.previewMode}static getPreviewSuppressedHandlers(){return Gm}static getPreviewSuppressedLayoutFeatures(){return f7}resolveActionRef(e){if(!e.actionRef)return e;const t=this.namedActions[e.actionRef];if(!t)return q.warn(`[resolveActionRef] named action not found: "${e.actionRef}"`),e;const a=Vn();a?.isEnabled?.()&&a.trackNamedActionRef?.({actionRefName:e.actionRef,resolvedHandler:t.handler,timestamp:Date.now()});const{actionRef:i,type:o,key:d,event:g,...h}=e,f={...t,...Object.fromEntries(Object.entries(h).filter(([,p])=>p!==void 0)),type:o??t.type};return d!==void 0&&(f.key=d),g!==void 0&&(f.event=g),f}matchesPattern(e,t){if(t==="*")return!0;const a=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${a}$`).test(e)}getMatchingGlobalHeaders(e,t){const a={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([o,d])=>{const g=ni(d,t,{skipCache:!0});g!=null&&g!==""&&(a[o]=String(g))});return a}setupErrorHandling(){if(this.errorHandlingSetup)return;Sa().setActionExecutor(async(t,a)=>{const i={type:"click",handler:t.handler,target:t.target,params:t.params,actions:t.actions},o={data:{...this.defaultContext.data,error:a.error}};return await this.dispatchAction(i,o)}),this.errorHandlingSetup=!0}registerDefaultHandlers(){this.registerHandler("refetchDataSource",async(t,a)=>{const i=t.params?.dataSourceId,o=t.params?.sync;if(!i){q.warn("refetchDataSource: dataSourceId is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.refetch){const d=window.G7Core?.state?.get?.()||{},g={...a.state?._global,...d},h=window.G7Core?.state?.getLocal?.()||{},f=a.data?._local||a.state||{},p={...h,...f},y=a.isolatedContext?.state;q.log("[refetchDataSource] localStateOverride:",p),await window.G7Core.dataSource.refetch(i,{...o?{sync:!0}:{},...g?{globalStateOverride:g}:{},...p?{localStateOverride:p}:{},...y?{isolatedStateOverride:y}:{}})}else q.warn("refetchDataSource: G7Core.dataSource.refetch is not available")}),this.registerHandler("appendDataSource",async(t,a)=>{const{dataSourceId:i,dataPath:o,newData:d}=t.params||{};if(!i){q.warn("appendDataSource: dataSourceId is required");return}if(d===void 0){q.warn("appendDataSource: newData is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.updateData){if(!Array.isArray(d)){q.warn("appendDataSource: newData must be an array, got:",typeof d,d);return}await window.G7Core.dataSource.updateData(i,o||null,d,"append")}else q.warn("appendDataSource: G7Core.dataSource.updateData is not available")}),this.registerHandler("updateDataSource",async(t,a)=>{const{dataSourceId:i,data:o,merge:d=!1}=t.params||{};if(!i){q.warn("updateDataSource: dataSourceId is required");return}if(o===void 0){q.warn("updateDataSource: data is required");return}typeof window<"u"&&window.G7Core?.dataSource?.set?(q.log(`[updateDataSource] Updating dataSource '${i}' with:`,o),window.G7Core.dataSource.set(i,o,{merge:d})):q.warn("updateDataSource: G7Core.dataSource.set is not available")}),this.registerHandler("scrollIntoView",async(t,a)=>{const{selector:i,behavior:o="smooth",block:d="nearest",inline:g="nearest",waitForElement:h=!1,timeout:f=2e3,delay:p=0,retryCount:y=0,retryInterval:x=50,scrollContainer:S}=t.params||{};if(!i){q.warn("scrollIntoView: selector is required");return}if(typeof window>"u"||typeof document>"u"){q.warn("scrollIntoView: window/document is not available");return}let v=null;if(h){if(v=await new Promise(w=>{const k=document.querySelector(i);if(k){w(k);return}const A=setTimeout(()=>{O.disconnect(),w(null)},f),O=new MutationObserver(()=>{const N=document.querySelector(i);N&&(clearTimeout(A),O.disconnect(),w(N))});O.observe(document.body,{childList:!0,subtree:!0})}),!v){q.warn(`scrollIntoView: element not found for selector "${i}" after ${f}ms timeout`);return}}else{p>0&&await new Promise(k=>setTimeout(k,p)),v=document.querySelector(i);let w=0;for(;!v&&wsetTimeout(k,x)),v=document.querySelector(i),w++;if(!v){q.warn(`scrollIntoView: element not found for selector "${i}" after ${w+1} attempts`);return}}if(S){const w=document.querySelector(S);if(!w){q.warn(`scrollIntoView: container not found for selector "${S}"`);return}const k=v.getBoundingClientRect(),A=w.getBoundingClientRect(),O=k.top-A.top+w.scrollTop,N=O+k.height;let D;switch(d){case"start":D=O;break;case"center":D=O-w.clientHeight/2+k.height/2;break;case"end":D=N-w.clientHeight;break;case"nearest":default:const $=k.topA.bottom;if($)D=O;else if(M)D=N-w.clientHeight;else return;break}w.scrollTo({top:Math.max(0,D),behavior:o});return}v.scrollIntoView({behavior:o,block:d,inline:g})}),this.registerHandler("reloadExtensions",async(t,a)=>{if(typeof window>"u"){q.warn("reloadExtensions: window is not available");return}const i=window.__templateApp;if(!i){q.warn("reloadExtensions: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState()}catch(g){throw q.error("reloadExtensions: reloadExtensionState failed",g),g}else q.warn("reloadExtensions: TemplateApp.reloadExtensionState unavailable");const{moduleInfo:o,pluginInfo:d}=t.params||{};if(o)try{await this.executeAction({handler:"reloadModuleHandlers",params:t.params},a)}catch(g){q.error("reloadExtensions: reloadModuleHandlers failed",g)}if(d)try{await this.executeAction({handler:"reloadPluginHandlers",params:t.params},a)}catch(g){q.error("reloadExtensions: reloadPluginHandlers failed",g)}q.log("reloadExtensions: done")}),this.registerHandler("reloadRoutes",async(t,a)=>{if(typeof window>"u"){q.warn("reloadRoutes: window is not available");return}const i=window.__templateApp;if(!i){q.warn("reloadRoutes: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),q.log("reloadRoutes: delegated to reloadExtensionState")}catch(o){throw q.error("reloadRoutes: Failed to reload routes",o),o}else{const o=i.getRouter?.();o&&(await o.loadRoutes(),q.log("reloadRoutes: Routes reloaded (legacy fallback)"))}}),this.registerHandler("refresh",async(t,a)=>{if(typeof window>"u"){q.warn("refresh: window is not available");return}window.location.reload()}),this.registerHandler("remount",async(t,a)=>{const{componentId:i}=t.params||{};if(!i){q.warn("remount: componentId parameter is required");return}if(!this.globalStateUpdater){q.warn("remount: globalStateUpdater is not set");return}const g=(window.G7Core?.state?.get()||{})._global?._remountKeys||{},h=g[i]||0;this.globalStateUpdater({_remountKeys:{...g,[i]:h+1}}),q.log(`remount: ${i} key incremented to ${h+1}`)}),this.registerHandler("reloadTranslations",async(t,a)=>{if(typeof window>"u"){q.warn("reloadTranslations: window is not available");return}const i=window.__templateApp;if(!i){q.warn("reloadTranslations: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),q.log("reloadTranslations: delegated to reloadExtensionState")}catch(o){throw q.error("reloadTranslations: Failed to reload translations",o),o}}),this.registerHandler("reloadModuleHandlers",async(t,a)=>{if(typeof window>"u"){q.warn("reloadModuleHandlers: window is not available");return}const{moduleInfo:i,action:o}=t.params||{};if(!i){q.warn("reloadModuleHandlers: moduleInfo is required");return}const d=i.data||i;if(!d.identifier){q.warn("reloadModuleHandlers: moduleInfo with identifier is required");return}if(!o||o!=="add"&&o!=="remove"){q.warn('reloadModuleHandlers: action must be "add" or "remove"');return}const g=window.G7Config;if(!g){q.warn("reloadModuleHandlers: G7Config not available");return}const h=d.identifier;try{if(o==="add"){if(d.assets&&(g.moduleAssets=g.moduleAssets||{},g.moduleAssets[h]=d.assets,q.log(`reloadModuleHandlers: Added assets for ${h}`),d.assets.js)){const f=d.assets.js,p=`module-${h}`;if(document.getElementById(p)){q.warn(`reloadModuleHandlers: Script ${p} already loaded`);return}const y=document.createElement("script");if(y.id=p,y.src=f,y.async=!0,await new Promise((x,S)=>{y.onload=()=>{q.log(`reloadModuleHandlers: Script loaded successfully for ${h}`),x()},y.onerror=()=>{q.error(`reloadModuleHandlers: Failed to load script for ${h}`),S(new Error(`Failed to load module script: ${f}`))},document.head.appendChild(y)}),d.assets.css){const x=d.assets.css,S=`module-css-${h}`;if(!document.getElementById(S)){const v=document.createElement("link");v.id=S,v.rel="stylesheet",v.href=x,document.head.appendChild(v),q.log(`reloadModuleHandlers: CSS loaded for ${h}`)}}}}else if(o==="remove"){g.moduleAssets&&g.moduleAssets[h]&&(delete g.moduleAssets[h],q.log(`reloadModuleHandlers: Removed assets for ${h}`));const f=`module-${h}`,p=document.getElementById(f);p&&(p.remove(),q.log(`reloadModuleHandlers: Removed script for ${h}`));const y=`module-css-${h}`,x=document.getElementById(y);x&&(x.remove(),q.log(`reloadModuleHandlers: Removed CSS for ${h}`))}}catch(f){throw q.error(`reloadModuleHandlers: Failed to ${o} module assets`,f),f}}),this.registerHandler("reloadPluginHandlers",async(t,a)=>{if(typeof window>"u"){q.warn("reloadPluginHandlers: window is not available");return}const{pluginInfo:i,action:o}=t.params||{};if(!i){q.warn("reloadPluginHandlers: pluginInfo is required");return}const d=i.data||i;if(!d.identifier){q.warn("reloadPluginHandlers: pluginInfo with identifier is required");return}if(!o||o!=="add"&&o!=="remove"){q.warn('reloadPluginHandlers: action must be "add" or "remove"');return}const g=window.G7Config;if(!g){q.warn("reloadPluginHandlers: G7Config not available");return}const h=d.identifier;try{if(o==="add"){if(d.assets&&(g.pluginAssets=g.pluginAssets||{},g.pluginAssets[h]=d.assets,q.log(`reloadPluginHandlers: Added assets for ${h}`),d.assets.js)){const f=d.assets.js,p=`plugin-${h}`;if(document.getElementById(p)){q.warn(`reloadPluginHandlers: Script ${p} already loaded`);return}const y=document.createElement("script");if(y.id=p,y.src=f,y.async=!0,await new Promise((x,S)=>{y.onload=()=>{q.log(`reloadPluginHandlers: Script loaded successfully for ${h}`),x()},y.onerror=()=>{q.error(`reloadPluginHandlers: Failed to load script for ${h}`),S(new Error(`Failed to load plugin script: ${f}`))},document.head.appendChild(y)}),d.assets.css){const x=d.assets.css,S=`plugin-css-${h}`;if(!document.getElementById(S)){const v=document.createElement("link");v.id=S,v.rel="stylesheet",v.href=x,document.head.appendChild(v),q.log(`reloadPluginHandlers: CSS loaded for ${h}`)}}}}else if(o==="remove"){g.pluginAssets&&g.pluginAssets[h]&&(delete g.pluginAssets[h],q.log(`reloadPluginHandlers: Removed assets for ${h}`));const f=`plugin-${h}`,p=document.getElementById(f);p&&(p.remove(),q.log(`reloadPluginHandlers: Removed script for ${h}`));const y=`plugin-css-${h}`,x=document.getElementById(y);x&&(x.remove(),q.log(`reloadPluginHandlers: Removed CSS for ${h}`))}}catch(f){throw q.error(`reloadPluginHandlers: Failed to ${o} plugin assets`,f),f}});let e=!1;this.registerHandler("showErrorPage",async(t,a)=>{if(e){q.log("showErrorPage: Already active, skipping duplicate call");return}if(e=!0,typeof window>"u"){e=!1,q.warn("showErrorPage: window is not available");return}const i=window.__templateApp;if(!i){e=!1,q.warn("showErrorPage: TemplateApp not initialized");return}const o=i.getErrorPageHandler?.();if(!o){e=!1,q.warn("showErrorPage: ErrorPageHandler not available");return}const d=t.params?.errorCode||500,g=t.params?.target||"content";let h=t.params?.containerId;h||(h=g==="full"?"app":"main_content"),q.log("showErrorPage:",{errorCode:d,target:g,containerId:h});const f=(p,y=6e4)=>new Promise((x,S)=>{const v=document.getElementById(p);if(v){x(v);return}q.log(`showErrorPage: Waiting for container #${p}...`);let w;const k=new MutationObserver((A,O)=>{const N=document.getElementById(p);N&&(q.log(`showErrorPage: Container #${p} found`),O.disconnect(),clearTimeout(w),x(N))});k.observe(document.body,{childList:!0,subtree:!0}),w=setTimeout(()=>{k.disconnect(),S(new Error(`Container #${p} not found within ${y}ms`))},y)});try{await f(h);const p=Sa(),y=p.layoutErrorHandling;p.clearLayoutConfig();try{await o.renderError(d,h)||q.warn(`showErrorPage: Failed to render error page for code ${d}`)}finally{p.setLayoutConfig(y)}}catch(p){throw q.error("showErrorPage: Error rendering error page:",p),p}finally{e=!1}}),this.registerHandler("emitEvent",async(t,a)=>{const i=t.params?.event,o=t.params?.data;if(!i){q.warn("emitEvent: event parameter is required");return}if(typeof window>"u"){q.warn("emitEvent: window is not available");return}const d=window.G7Core;if(!d?.componentEvent?.emit){q.warn("emitEvent: G7Core.componentEvent is not available");return}try{q.log(`emitEvent: Emitting "${i}"`,o);const g={...o,_context:{data:a.data,state:a.state}},h=await d.componentEvent.emit(i,g);if(!h||h.length===0?q.warn(`emitEvent: No listeners found for "${i}"`):q.log(`emitEvent: Event "${i}" completed with ${h.length} listener(s)`,h),this.globalStateUpdater){const f=d?.state?.get()||{};this.globalStateUpdater({_local:{...f._local,_eventResult:{event:i,success:!0,data:h.length===1?h[0]:h,listeners:h.length}}})}}catch(g){if(q.error(`emitEvent: Event "${i}" failed`,g),this.globalStateUpdater){const h=d?.state?.get()||{};this.globalStateUpdater({_local:{...h._local,_eventResult:{event:i,success:!1,error:g instanceof Error?g.message:String(g)}}})}throw g}}),this.registerHandler("updateProductField",async(t,a)=>{const{productId:i,field:o,value:d}=t.params||{};if(!i||!o){q.warn("updateProductField: productId and field are required");return}if(typeof window>"u"){q.warn("updateProductField: window is not available");return}const g=window.G7Core;if(!g?.state?.get||!this.globalStateUpdater){q.warn("updateProductField: G7Core.state or globalStateUpdater is not available");return}try{const h=g.state.get()||{},p=(h.products?.data?.data||[]).map(x=>x.id===i?{...x,[o]:d,_modified:!0}:x),y=new Set(h._local?.modifiedProductIds||[]);y.add(i),this.globalStateUpdater({products:{...h.products,data:{...h.products?.data,data:p}},_local:{...h._local,modifiedProductIds:Array.from(y)}}),q.log(`updateProductField: Updated product ${i}, field: ${o}, value:`,d)}catch(h){throw q.error("updateProductField: Error updating product field",h),h}}),this.registerHandler("updateOptionField",async(t,a)=>{const{productId:i,optionId:o,field:d,value:g}=t.params||{};if(!i||!o||!d){q.warn("updateOptionField: productId, optionId and field are required");return}if(typeof window>"u"){q.warn("updateOptionField: window is not available");return}const h=window.G7Core;if(!h?.state?.get||!this.globalStateUpdater){q.warn("updateOptionField: G7Core.state or globalStateUpdater is not available");return}try{const f=h.state.get()||{},y=(f.products?.data?.data||[]).map(S=>{if(S.id===i&&S.options){const v=S.options.map(w=>w.id===o?{...w,[d]:g,_modified:!0}:w);return{...S,options:v,_modified:!0}}return S}),x=new Set(f._local?.modifiedProductIds||[]);x.add(i),this.globalStateUpdater({products:{...f.products,data:{...f.products?.data,data:y}},_local:{...f._local,modifiedProductIds:Array.from(x)}}),q.log(`updateOptionField: Updated product ${i} option ${o}, field: ${d}, value:`,g)}catch(f){throw q.error("updateOptionField: Error updating option field",f),f}}),this.registerHandler("setLocale",async(t,a)=>{const i=t.target;if(!i||typeof i!="string"){q.warn("setLocale: Invalid locale:",i);return}const o=window.__templateApp;if(o&&typeof o.changeLocale=="function")try{await o.changeLocale(i),q.log("setLocale: Locale changed to",i)}catch(d){q.error("setLocale: Failed to change locale:",d),window.location.reload()}else{q.warn("setLocale: TemplateApp not found, falling back to page reload");try{localStorage.setItem("g7_locale",i)}catch{}window.location.reload()}}),this.registerHandler("suppress",async()=>{q.log("suppress: Error intentionally suppressed")}),this.registerBuiltInHandlerMetadata()}registerBuiltInHandlerMetadata(){const e=Vn();if(!e?.isEnabled())return;const t=[{name:"refetchDataSource",description:"데이터 소스를 다시 fetch합니다"},{name:"appendDataSource",description:"데이터 소스에 새 데이터를 병합합니다 (무한 스크롤용)"},{name:"updateDataSource",description:"API 응답으로 데이터 소스를 직접 업데이트합니다 (refetch 대체)"},{name:"reloadRoutes",description:"라우트를 다시 로드합니다"},{name:"refresh",description:"현재 페이지를 새로고침합니다"},{name:"remount",description:"컴포넌트를 리마운트합니다"},{name:"reloadTranslations",description:"다국어 파일을 다시 로드합니다"},{name:"showErrorPage",description:"에러 페이지를 표시합니다"},{name:"emitEvent",description:"이벤트를 발생시킵니다"},{name:"updateProductField",description:"상품 필드를 인라인 수정합니다"},{name:"updateOptionField",description:"상품 옵션 필드를 인라인 수정합니다"},{name:"setLocale",description:"언어를 변경합니다 (DB 저장 + UI 리렌더링)"}];for(const a of t)e.trackHandlerRegistration(a.name,"built-in",a.description)}createHandler(e,t,a){q.log("createHandler called for:",e.handler,e.type);const i=window.__g7DevTools,o=Date.now(),d=a?.state?{...a.state}:null,g=`handler_${e.handler}_${o}`;return async h=>{if(q.log("Handler invoked for:",e.handler,"event:",h.type),i?.isEnabled?.()&&d){const p=window.G7Core?.state?.getLocal?.()??a?.state??{},y=Date.now()-o;for(const x of Object.keys(d)){const S=d[x],v=p[x];S!==v&&y>100&&(i.trackStaleClosureWarning?.({type:"event-handler-stale",location:`createHandler(${e.handler})`,capturedPath:`_local.${x}`,capturedValue:S,capturedAt:o,currentValue:v,actionId:g,stackTrace:new Error().stack}),q.warn(`[Stale Closure] _local.${x} changed after handler creation:`,`captured="${S}" → current="${v}" (${y}ms ago)`))}}try{h.type!=="change"&&h.preventDefault();let f={};if(h.type==="submit"&&h.target instanceof HTMLFormElement){const x=h.target;new FormData(x).forEach((v,w)=>{f[w]=v})}const p={...this.defaultContext,data:{...t,form:f,_local:a?.state||{},$event:h},event:h,...a&&{state:a.state,setState:a.setState},isolatedContext:a?.isolatedContext};if(e.confirm){let x=this.resolveValue(e.confirm,p.data);if(this.translationEngine&&this.translationContext&&x.startsWith("$t:")&&(x=this.translationEngine.resolveTranslations(x,this.translationContext,p.data)),!confirm(x))return}const y=window.__g7ActionContext;window.__g7ActionContext={...a,data:p.data};try{await this.executeAction(e,p)}finally{window.__g7ActionContext=y}}catch(f){if(q.error("Action execution failed:",f),e.onError){const p=f instanceof Gt&&f.originalError?f.originalError:f,y={...this.defaultContext,data:{...t,error:p,_local:a?.state||{},$event:h},event:h,...a&&{state:a.state,setState:a.setState}},x=Array.isArray(e.onError)?e.onError:[e.onError];for(const S of x)await this.executeAction(S,y)}}}}generateActionId(e,t){const a=e.handler,i=t||"no-target",o=Date.now(),d=Math.random().toString(36).substring(2,9);return`${a}_${i.replace(/[^a-zA-Z0-9]/g,"_")}_${o}_${d}`}async executeAction(e,t){e=this.resolveActionRef(e);const a=Vn(),i=a?.isEnabled()?`action_${Date.now()}_${Math.random().toString(36).substring(2,11)}`:void 0,o=performance.now();let d;if(i&&a&&a.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),context:this.sanitizeForDevTools({hasState:!!t.state,hasSetState:!!t.setState,dataKeys:t.data?Object.keys(t.data):[]}),startTime:o,status:"started"}),e.if!==void 0)try{const h=this.resolveValue(e.if,t.data),f=h===!0||h==="true"||h&&h!=="false"&&h!=="0"&&h!==!1;if(q.log("[executeAction] if condition result:",e.handler,f),!f)return i&&a&&a.logAction({id:i,type:e.handler,startTime:o,endTime:performance.now(),duration:performance.now()-o,status:"success",result:{skipped:!0,reason:"if condition false"}}),{success:!0,data:void 0}}catch(h){return q.error("[executeAction] if condition error:",e.handler,h),i&&a&&a.logAction({id:i,type:e.handler,startTime:o,endTime:performance.now(),duration:performance.now()-o,status:"error",error:{name:"ConditionEvaluationError",message:h instanceof Error?h.message:String(h),stack:h instanceof Error?h.stack:void 0}}),{success:!0,data:void 0}}let g;try{const h=this.resolveParams(e.params,t.data);i&&(d=this.sanitizeForDevTools(h));const f=e.target?this.resolveValue(e.target,t.data):void 0;if(e.handler==="apiCall"&&t.setState){g=this.generateActionId(e,f);const y=t.state?.loadingActions||{};t.setState({loadingActions:{...y,[g]:!0}})}if(this.previewMode&&Gm.has(e.handler))return q.warn(`Preview mode: "${e.handler}" suppressed`,f||h),i&&a&&a.logAction({id:i,type:e.handler,startTime:o,endTime:performance.now(),duration:performance.now()-o,status:"skipped",metadata:{reason:"preview_mode_suppressed"}}),{success:!0,data:void 0};let p;switch(e.handler){case"navigate":const y=h.path||f;p=await this.handleNavigate(y,h,t);break;case"navigateBack":p=await this.handleNavigateBack();break;case"navigateForward":p=await this.handleNavigateForward();break;case"openWindow":{const S=h.path||f;p=await this.handleOpenWindow(S,h);break}case"replaceUrl":{const S=h.path||f||window.location.pathname;p=await this.handleReplaceUrl(S,h);break}case"apiCall":if(e.onSuccess&&a?.isEnabled()&&i){const S=window.G7Core,v={};if(S?.state?.get){const w=S.state.get();v._global=w}t.state&&(v._local=t.state),a.registerStateCaptureForHandler?.(i,["_global","_local"],v)}const x=e.auth_mode??(e.auth_required?"required":"none");p=await this.handleApiCall(f,h,t,x);break;case"login":p=await this.handleLogin(f,h,t);break;case"logout":p=await this.handleLogout(f,t);break;case"setState":q.log("[executeAction] setState resolvedParams:",h),p=await this.handleSetState(e.render!==void 0?{...h,__render:e.render}:h,t);break;case"setError":p=await this.handleSetError(f,h,t);break;case"openModal":p=await this.handleOpenModal(f,t);break;case"closeModal":p=await this.handleCloseModal(t);break;case"showAlert":p=await this.handleShowAlert(f,t);break;case"toast":p=await this.handleToast(h,t);break;case"switch":p=await this.handleSwitch(e,t);break;case"conditions":p=await this.handleConditions(e,t);break;case"sequence":p=await this.handleSequence(e,t);break;case"parallel":p=await this.handleParallel(e,t);break;case"loadScript":p=await this.handleLoadScript(h,e,t);break;case"callExternal":p=await this.handleCallExternal(h,e,t);break;case"callExternalEmbed":p=await this.handleCallExternalEmbed(h,e,t);break;case"saveToLocalStorage":p=await this.handleSaveToLocalStorage(h,t);break;case"loadFromLocalStorage":p=await this.handleLoadFromLocalStorage(h,t);break;default:p=await this.handleCustomAction({...e,target:f,params:h},t);break}if(e.resultTo&&p!==void 0){const{target:y,key:x,merge:S}=e.resultTo,v=this.resolveValue(x,t.data),w=S==="replace"?"replace":S==="shallow"?"shallow":"deep";if(y==="_local"&&t.setState){const k=this.buildNestedUpdate(v,p),A=w!=="deep"?{...k,__mergeMode:w}:k;t.setState(A),q.log(`[resultTo] Saved to _local.${v} (merge=${w}):`,p)}else if(y==="_local"&&this.globalStateUpdater){const O=(window.G7Core?.state?.get()||{})._local||{},N=this.buildNestedUpdate(v,p);let D;w==="replace"?D=N:w==="shallow"?D={...O,...N}:D=this.deepMergeWithState(N,O),this.globalStateUpdater({_local:D}),q.log(`[resultTo] Saved to _local.${v} via globalStateUpdater (merge=${w}):`,p)}else if(y==="_global"&&this.globalStateUpdater){const k=this.buildNestedUpdate(v,p);this.globalStateUpdater(k),q.log(`[resultTo] Saved to _global.${v}:`,p)}else if(y==="_isolated"&&t.isolatedContext){const k=this.buildNestedUpdate(v,p);t.isolatedContext.mergeState(k,w),q.log(`[resultTo] Saved to _isolated.${v} (merge=${w}):`,p)}else q.warn(`[resultTo] Cannot save result: target=${y}, setState=${!!t.setState}, globalStateUpdater=${!!this.globalStateUpdater}, isolatedContext=${!!t.isolatedContext}`)}if(e.onSuccess){if(a?.isEnabled()&&i&&e.handler==="apiCall"){const S=window.G7Core,v={};S?.state?.get&&(v._global=S.state.get()),t.state&&(v._local=t.state),a.detectStaleClosure?.(i,`${e.handler} → onSuccess`,v,"callback-state-capture",i)}const y={...t,data:{...t.data,result:p,response:p}},x=Array.isArray(e.onSuccess)?e.onSuccess:[e.onSuccess];x.length>1?await this.handleSequence({handler:"sequence",type:"click",actions:x},y):x.length===1&&await this.executeAction(x[0],y)}return i&&a&&a.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),resolvedParams:d,startTime:o,endTime:performance.now(),duration:performance.now()-o,status:"success",result:this.sanitizeForDevTools(p)}),{success:!0,data:p}}catch(h){const f=h instanceof Gt?h:new Gt(`Failed to execute action: ${e.handler}`,e,h instanceof Error?h:void 0),p=f.originalError?.response||{},y=p.data||{},x=f.originalError?.status||p.status||500,S=y.message||f.message,v={status:x,message:S,errors:y.errors||p.errors,data:y,statusText:f.originalError?.statusText},k=Sa().resolve(x,{errorHandling:e.errorHandling,onError:e.onError});if(k.handler){if(a?.isEnabled()&&i&&e.handler==="apiCall"){const O=window.G7Core,N={};O?.state?.get&&(N._global=O.state.get()),t.state&&(N._local=t.state),a.detectStaleClosure?.(i,`${e.handler} → onError`,N,"callback-state-capture",i)}const A={...t,data:{...t.data,error:v}};try{const O={type:"click",handler:k.handler.handler,target:k.handler.target,params:k.handler.params,actions:k.handler.actions};return await this.executeAction(O,A),{success:!1,error:f}}catch(O){return q.error("Error executing error handler:",O),{success:!1,error:f}}}throw i&&a&&a.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),resolvedParams:d,startTime:o,endTime:performance.now(),duration:performance.now()-o,status:"error",error:{name:f.name,message:f.message,stack:f.stack}}),f}finally{if(e.handler==="apiCall"&&t.setState&&g){const h=t.state?.loadingActions||{},{[g]:f,...p}=h;t.setState({loadingActions:p})}}}async handleNavigate(e,t,a){let i=e;if(t.query)if(t.mergeQuery===!0)i=this.buildMergedQueryPath(e,t.query);else{const d=new URLSearchParams;for(const[h,f]of Object.entries(t.query))if(f!=null&&f!=="")if(Array.isArray(f)){const p=h.endsWith("[]")?h:`${h}[]`;for(const y of f)y!=null&&y!==""&&d.append(p,String(y))}else d.set(h,String(f));const g=d.toString();g&&(i=`${e}?${g}`)}if(q.log("handleNavigate:",{target:e,params:t,finalPath:i,replace:t.replace,windowLocationSearch:window.location.search}),t.replace===!0){const d=window.G7Core;if(d?.updateQueryParams){const g=typeof t.transition_overlay_target=="string"?t.transition_overlay_target:void 0;await d.updateQueryParams(i,g?{transitionOverlayTarget:g}:void 0),q.log("handleNavigate: Used updateQueryParams for replace mode",g?{transitionOverlayTarget:g}:void 0),this.applyScrollOption(t.scroll,t.scrollBehavior,"top");return}q.warn("handleNavigate: G7Core.updateQueryParams not available, falling back to React Router")}const o=this.resolveNavigateFallbackAction(i,t);if(o){q.warn(`handleNavigate: No route matched, falling back to "${o.handler}"`),await this.dispatchAction({type:"click",handler:o.handler,params:o.params},a),this.applyScrollOption(t.scroll,t.scrollBehavior,"top");return}if(!a.navigate)throw new Gt("Navigate function is not provided in context");a.navigate(i,{replace:t.replace===!0}),this.applyScrollOption(t.scroll,t.scrollBehavior,"top")}resolveNavigateFallbackAction(e,t){const a=t.fallback;if(a===!1||t.replace===!0)return null;const o=window.__templateApp?.getRouter?.();if(!o||typeof o.match!="function"||typeof o.getRoutes=="function"&&o.getRoutes().length===0)return null;const d=e.split("?")[0];return o.match(d)?null:this.resolveNavigateFallback(a,e,t)}resolveNavigateFallback(e,t,a){return e==null?{handler:"openWindow",params:{path:t,target:"_blank"}}:typeof e=="string"?{handler:e,params:{path:t}}:typeof e=="object"&&typeof e.handler=="string"?{handler:e.handler,params:{path:t,...e.params||{}}}:(q.warn("resolveNavigateFallback: unrecognized fallback option, using openWindow",e),{handler:"openWindow",params:{path:t,target:"_blank"}})}applyScrollOption(e,t,a){const i=e===void 0?a:e;if(i==="preserve")return;const o=t==="smooth"?"smooth":"instant",d=y=>{if(typeof y!="object"||y===null)return!1;const x=y;return"container"in x||"to"in x||"block"in x||"offset"in x},g=(y,x,S=0)=>{y===window?window.scrollTo({top:x,left:S,behavior:o}):y.scrollTo({top:x,left:S,behavior:o})},h=(y,x,S,v)=>{if(x===window){y.scrollIntoView({behavior:o,block:S}),v&&window.scrollBy({top:-v,left:0,behavior:o});return}const w=x,k=y.getBoundingClientRect(),A=w.getBoundingClientRect(),O=w.scrollTop+(k.top-A.top);let N;S==="center"?N=O-(w.clientHeight-y.clientHeight)/2:S==="end"?N=O-(w.clientHeight-y.clientHeight):N=O,N-=v,w.scrollTo({top:Math.max(0,N),left:0,behavior:o})},f=()=>{window.scrollTo({top:0,left:0,behavior:o});const y=document.getElementById("app")??document.body;if(!y)return;y.querySelectorAll("*").forEach(S=>{if(S.scrollTop===0&&S.scrollLeft===0)return;const v=window.getComputedStyle(S),w=v.overflowY,k=v.overflowX;(w==="auto"||w==="scroll"||k==="auto"||k==="scroll")&&S.scrollTo({top:0,left:0,behavior:o})})},p=()=>{try{if(d(i)){const y=i,x=y.block??"start",S=typeof y.offset=="number"?y.offset:0;let v=window;if(typeof y.container=="string"&&y.container.length>0){const k=document.querySelector(y.container);if(!k){q.warn(`applyScrollOption: container not found: ${y.container}`);return}v=k}const w=y.to??"top";if(w==="top"){v===window?f():g(v,0);return}if(typeof w=="number"){g(v,w-S);return}if(typeof w=="object"&&w!==null&&("x"in w||"y"in w)){const{x:k=0,y:A=0}=w;g(v,A-S,k);return}if(typeof w=="string"&&(w.startsWith("#")||w.startsWith("."))){const k=document.querySelector(w);k?h(k,v,x,S):q.warn(`applyScrollOption: target element not found: ${w}`);return}q.warn('applyScrollOption: invalid "to" value in extended form',w);return}if(i==="top"){f();return}if(typeof i=="number"){window.scrollTo({top:i,left:0,behavior:o});return}if(typeof i=="object"&&i!==null&&("x"in i||"y"in i)){const{x:y=0,y:x=0}=i;window.scrollTo({top:x,left:y,behavior:o});return}if(typeof i=="string"&&(i.startsWith("#")||i.startsWith("."))){const y=document.querySelector(i);y&&y.scrollIntoView({behavior:o,block:"start"});return}}catch(y){q.warn("applyScrollOption: failed to apply scroll",y)}};typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(p):p()}async handleOpenWindow(e,t){let a=e;if(t.query){const i=new URLSearchParams;for(const[d,g]of Object.entries(t.query))g!=null&&g!==""&&i.set(d,String(g));const o=i.toString();o&&(a=`${e}?${o}`)}q.log("handleOpenWindow:",{target:e,params:t,finalPath:a}),window.open(a,"_blank")}async handleNavigateBack(){q.log("handleNavigateBack"),window.history.back()}async handleNavigateForward(){q.log("handleNavigateForward"),window.history.forward()}async handleReplaceUrl(e,t){let a=e;if(t.query)if(t.mergeQuery===!0)a=this.buildMergedQueryPath(e,t.query);else{const i=new URLSearchParams;for(const[d,g]of Object.entries(t.query))if(g!=null&&g!=="")if(Array.isArray(g)){const h=d.endsWith("[]")?d:`${d}[]`;for(const f of g)f!=null&&f!==""&&i.append(h,String(f))}else i.set(d,String(g));const o=i.toString();o&&(a=`${e}?${o}`)}q.log("handleReplaceUrl:",{target:e,params:t,finalPath:a}),window.history.replaceState(null,"",a),this.applyScrollOption(t.scroll,t.scrollBehavior,"preserve")}buildMergedQueryPath(e,t){const a=new URLSearchParams(window.location.search);for(const[d,g]of Object.entries(t))if(g==null||g==="")a.delete(d);else if(Array.isArray(g)){const h=d.endsWith("[]")?d:`${d}[]`;a.delete(d),a.delete(h);for(const f of g)f!=null&&f!==""&&a.append(h,String(f))}else a.set(d,String(g));const i=a.toString(),o=e.split("?")[0];return i?`${o}?${i}`:o}async ensureCsrfToken(){try{await fetch("/sanctum/csrf-cookie",{credentials:"include"})}catch(e){throw new Gt("Failed to fetch CSRF token",void 0,e instanceof Error?e:void 0)}}getCsrfTokenFromCookie(){const a=`; ${document.cookie}`.split("; XSRF-TOKEN=");if(a.length===2){const i=a.pop()?.split(";").shift();return i?decodeURIComponent(i):null}return null}buildQueryString(e){const t=new URLSearchParams;for(const[a,i]of Object.entries(e))if(!(i==null||i===""))if(Array.isArray(i))for(const o of i)o!=null&&o!==""&&t.append(`${a}[]`,String(o));else typeof i=="object"?t.append(a,JSON.stringify(i)):t.append(a,String(i));return t.toString()}async handleApiCall(e,t,a,i="none"){const{method:o="GET",body:d,headers:g,contentType:h}=t;o!=="GET"&&o!=="HEAD"&&await this.ensureCsrfToken();const f=this.getCsrfTokenFromCookie();let p={};if(i==="required"||i==="optional"){const z=ns().getToken();z&&(p={Authorization:`Bearer ${z}`})}let y=e;const x=t.query||(o==="GET"?d:null);if(x&&typeof x=="object"){const M=this.buildQueryString(x);if(M){const z=e.includes("?")?"&":"?";y=`${e}${z}${M}`}}const S=window.G7Core?.state?.getGlobal?.()||a.state?._global||{},v=window.G7Core?.state?.getLocal?.()||a.state?._local||{},w={_global:S,_local:v},k=this.getMatchingGlobalHeaders(e,w),A={};if(typeof window<"u"){const M=localStorage.getItem("g7_locale");M&&(A["Accept-Language"]=M)}const O=h==="multipart/form-data",N={method:o,headers:{...O?{}:{"Content-Type":"application/json"},Accept:"application/json",...A,...f&&{"X-XSRF-TOKEN":f},...p,...k,...g},credentials:"include"};if(d&&o!=="GET")if(O){const M=new FormData;for(const[z,K]of Object.entries(d))K instanceof File||K instanceof Blob?M.append(z,K):K!=null&&M.append(z,typeof K=="object"?JSON.stringify(K):String(K));N.body=M}else N.body=JSON.stringify(d);const D=Vn();let $=null;D?.isEnabled()&&($=D.trackRequest(y,o));try{const M=await fetch(y,N);let z;try{z=await M.json()}catch{z=null}if($&&D?.isEnabled()&&(D.completeRequest($,M.status,z),$=null),!M.ok){const K=z||{},ye=new Error(K.message||`API call failed: ${M.statusText}`);throw ye.response=K,ye.status=M.status,ye.statusText=M.statusText,new Gt(K.message||`API call failed: ${M.statusText}`,void 0,ye)}return z}catch(M){throw $&&D?.isEnabled()&&D.failRequest($,M instanceof Error?M.message:String(M)),M}}async handleLogin(e,t,a){const{body:i}=t;if(!i||!i.email||!i.password)throw new Gt("Login requires email and password in body params");const o=e==="user"?"user":"admin",d=o==="admin"?"/api/auth/admin/login":"/api/auth/login",g=window.G7Core?.state?.getGlobal?.()||a.state?._global||{},h=window.G7Core?.state?.getLocal?.()||a.state?._local||{},f={_global:g,_local:h},p=this.getMatchingGlobalHeaders(d,f),y=as.getInstance();try{const x=Object.keys(p).length>0?{headers:p}:void 0;return{user:await y.login(o,{email:i.email,password:i.password},x)}}catch(x){const S=x.message||"Login failed",v=new Error(S);throw v.response=x.response?.data||{},v.status=x.status||x.response?.status||500,new Gt(S,void 0,v)}}async handleLogout(e,t){await as.getInstance().logout()}async handleSetState(e,t){q.log("[handleSetState] START, params:",e);const{target:a="component",scope:i,merge:o,__render:d,...g}=e,h=Vn(),f=window.G7Core;if(typeof a=="string"&&(a.startsWith("$parent.")||a.startsWith("$root.")))return this.handleParentScopeSetState(a,g,o,t);const p=t.state&&Object.keys(t.state).length>0?t.state:f?.state?.get()||{},y=a==="global"?"_global":a.startsWith("_local.")?a:"_local",x=y==="_global"?p._global:y.startsWith("_local.")?this.getNestedProperty(p._local||{},y.slice(7)):p._local,S=h?.isEnabled()?h.startStateChange(y,x,g,{actionId:t.actionId,handlerType:"setState",source:`target=${a}`}):void 0,v=o==="replace"?"replace":o==="shallow"?"shallow":"deep",w=v!=="deep"?{...g,__mergeMode:v,...S?{__setStateId:S}:{}}:{...g,...S?{__setStateId:S}:{}};if(a==="global"){if(!this.globalStateUpdater){q.warn("Global state updater is not set"),S&&h&&h.completeStateChange(S);return}const k=f?.state?.get()||{},{__setStateId:A,__mergeMode:O,...N}=w,D=v==="deep"?this.deepMergeWithState(N,k):N,$={...D,...S?{__setStateId:S}:{},...v!=="deep"?{__mergeMode:v}:{}};return q.log("setState global:",$),this.globalStateUpdater($,{render:d}),S&&h&&setTimeout(()=>h.completeStateChange(S),0),{__target:"global",...v!=="deep"?{__mergeMode:v}:{},...D}}else if(a==="isolated"){const k=t.isolatedContext;if(k){const{__mergeMode:A,__setStateId:O,...N}=w;return k.mergeState(N,v),q.log("[handleSetState] isolated state updated:",N,"mergeMode:",v),S&&h&&setTimeout(()=>h.completeStateChange(S),0),{__target:"isolated",...N}}else if(q.warn('[handleSetState] isolated target used but no IsolatedStateContext found. Make sure the component has "isolatedState" attribute. Falling back to local state.'),t.setState){const O=window.__g7PendingLocalState||t.state||{},N=v==="deep"?this.deepMergeWithState(w,O):w;return t.setState(N),S&&h&&setTimeout(()=>h.completeStateChange(S),0),N}else throw S&&h&&h.completeStateChange(S),new Gt("isolated target used but no IsolatedStateContext found and no setState function in context")}else if(a==="local"||a==="component"||a==="_local"){if(i==="parent"||i==="root"){const A=window.__g7LayoutContextStack||[];if(A.length>0){const O=i==="parent"?A[A.length-1]:A[0];if(O?.setState){const{__mergeMode:N,__setStateId:D,...$}=w,M=v==="deep"?this.deepMergeWithState($,O.state||{}):$;return q.log(`[handleSetState] scope=${i}: 타겟 컨텍스트에 상태 업데이트`,M),O.setState(M),S&&h&&setTimeout(()=>h.completeStateChange(S),0),M}}q.warn(`[handleSetState] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const k=t.setState&&!t._isDispatchFallbackContext;if(q.log("[handleSetState] isRealComponentContext:",k,"context.setState:",!!t.setState,"_isDispatchFallbackContext:",t._isDispatchFallbackContext),k){q.log("[handleSetState] Using COMPONENT setState path"),q.log("[handleSetState] resolvedPayload:",w),q.log("[handleSetState] context.state:",t.state),q.log("[handleSetState] mergeMode:",v);const O=window.__g7PendingLocalState||t.state||{},N=v==="deep"?this.deepMergeWithState(w,{}):w;q.log("[handleSetState] convertedPayload (변경 필드만, dot notation 변환):",N),t.setState(N);const D=v==="deep"?this.deepMergeWithState(w,O):v==="shallow"?{...t.state||{},...w}:w,{__mergeMode:$,__setStateId:M,...z}=D;window.__g7PendingLocalState=z,q.log("[handleSetState] __g7PendingLocalState updated:",z);const{__mergeMode:K,__setStateId:ye,...we}=w;if(v==="replace")window.__g7ForcedLocalFields=we;else{const J=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=this.deepMergeWithState(we,J)}return q.log("[handleSetState] __g7ForcedLocalFields updated:",we),S&&h&&setTimeout(()=>h.completeStateChange(S),0),{__target:"local",...D}}else if(this.globalStateUpdater){q.log("[handleSetState] Using GLOBAL STATE UPDATER path for _local");const O=window.__g7PendingLocalState||p._local||{};q.log("[handleSetState] currentLocal (with pending):",O);const N=v==="deep"?this.deepMergeWithState(w,O):w;return q.log("[handleSetState] finalLocal (merged):",N),this.globalStateUpdater({_local:N},{render:d}),window.__g7PendingLocalState=N,q.log("[handleSetState] __g7PendingLocalState updated for globalStateUpdater path"),S&&h&&setTimeout(()=>h.completeStateChange(S),0),{__target:"local",...N}}else throw S&&h&&h.completeStateChange(S),new Gt("setState function is not provided in context and globalStateUpdater is not set")}else if(a.startsWith("_local.")){const k=a.slice(7),{__mergeMode:A,__setStateId:O,...N}=w,D=N.value!==void 0?N.value:Object.values(N)[0];if(t.setState){const M=window.__g7PendingLocalState||t.state||{},z=this.createNestedUpdate(k,D,M),K={...M,...z};return t.setState(z),S&&h&&setTimeout(()=>h.completeStateChange(S),0),K}else throw S&&h&&h.completeStateChange(S),new Gt("setState function is not provided in context")}else{if(!t.setState)throw S&&h&&h.completeStateChange(S),new Gt("setState function is not provided in context");const A=window.__g7PendingLocalState||t.state||{},O=v==="deep"?this.deepMergeWithState(w,A):w;return t.setState(O),S&&h&&setTimeout(()=>h.completeStateChange(S),0),O}}async handleParentScopeSetState(e,t,a,i){const o=Vn(),d=window.G7Core,g=a==="replace"?"replace":a==="shallow"?"shallow":"deep",h=e.startsWith("$parent."),f=h?"$parent.":"$root.",p=e.slice(f.length);let y,x;if(p==="_local"||p==="_global")y=p,x=void 0;else if(p.startsWith("_local."))y="_local",x=p.slice(7);else if(p.startsWith("_global."))y="_global",x=p.slice(8);else{q.warn(`[handleParentScopeSetState] 지원하지 않는 타겟 형식: ${e}. _local 또는 _global으로 시작해야 합니다.`);return}const S=window.__g7LayoutContextStack||[];if(S.length===0){q.warn(`[handleParentScopeSetState] 레이아웃 컨텍스트 스택이 비어있습니다. target=${e}`);return}const v=h?S[S.length-1]:S[0];if(!v){q.warn(`[handleParentScopeSetState] 타겟 컨텍스트를 찾을 수 없습니다. target=${e}`);return}const w=y==="_global"?v.state?._global:v.state?._local,k=o?.isEnabled()?o.startStateChange(e,w,t,{actionId:i.actionId,handlerType:"setState",source:`target=${e}`}):void 0,{__mergeMode:A,__setStateId:O,...N}=t;if(y==="_global"){if(!this.globalStateUpdater){q.warn("[handleParentScopeSetState] globalStateUpdater가 설정되지 않았습니다."),k&&o&&o.completeStateChange(k);return}const D=d?.state?.get()||{};if(x){const $=N.value!==void 0?N.value:Object.values(N)[0],M=this.createNestedUpdate(x,$,D),z={...D,...M};q.log(`[handleParentScopeSetState] ${e}: 전역 상태 중첩 경로 업데이트`,z),this.globalStateUpdater(z)}else{const $=g==="deep"?this.deepMergeWithState(N,D):N;q.log(`[handleParentScopeSetState] ${e}: 전역 상태 업데이트 (mergeMode=${g})`,$),this.globalStateUpdater(g!=="deep"?{...$,__mergeMode:g}:$)}return k&&o&&setTimeout(()=>o.completeStateChange(k),0),{__target:e,...N}}else{if(!v.setState){q.warn(`[handleParentScopeSetState] 타겟 컨텍스트에 setState가 없습니다. target=${e}`),k&&o&&o.completeStateChange(k);return}const D=v.state||{};if(x){const $=N.value!==void 0?N.value:Object.values(N)[0],M=this.createNestedUpdate(x,$,D),z={...D,...M};return q.log(`[handleParentScopeSetState] ${e}: 로컬 상태 중첩 경로 업데이트`,M),v.setState(M),v.state=z,v.dataContext&&(v.dataContext._local=z),dg(),k&&o&&setTimeout(()=>o.completeStateChange(k),0),z}else{const $=g!=="deep"?{...N,__mergeMode:g}:N,M=g==="replace"?N:g==="shallow"?{...D,...N}:this.deepMergeWithState(N,D);return q.log(`[handleParentScopeSetState] ${e}: 로컬 상태 업데이트 (mergeMode=${g})`,M),v.setState($),v.state=M,v.dataContext&&(v.dataContext._local=M),dg(),k&&o&&setTimeout(()=>o.completeStateChange(k),0),M}}}deepMergeWithState(e,t){const a=["errors"];let i=e;if("..."in e){const d=e["..."];if(d&&typeof d=="object"&&!Array.isArray(d)){const{"...":g,...h}=e;i={...d,...h}}else{const{"...":g,...h}=e;i=h}}const o={...t};for(const[d,g]of Object.entries(i)){if(a.includes(d)){o[d]=g;continue}if(d.includes(".")&&d!=="..."){const h=this.createNestedUpdate(d,g,o);this.deepMergeInto(o,h,o);continue}if(g!==null&&typeof g=="object"&&!Array.isArray(g)&&Object.getPrototypeOf(g)!==Object.prototype&&Object.getPrototypeOf(g)!==null){o[d]=g;continue}g!==null&&typeof g=="object"&&!Array.isArray(g)&&t[d]!==null&&typeof t[d]=="object"&&!Array.isArray(t[d])?o[d]=this.deepMergeWithState(g,t[d]):o[d]=g}return o}deepMergeInto(e,t,a){for(const[i,o]of Object.entries(t)){if(o===null){e[i]=o;continue}if(e[i]===null){e[i]=o;continue}typeof o=="object"&&!Array.isArray(o)&&e[i]!==void 0&&e[i]!==null&&typeof e[i]=="object"&&!Array.isArray(e[i])?(e[i]===a[i]&&(e[i]={...e[i]}),this.deepMergeInto(e[i],o,a[i]||{})):typeof o=="object"&&!Array.isArray(o)&&e[i]===void 0&&a[i]!==null&&typeof a[i]=="object"&&!Array.isArray(a[i])?e[i]={...a[i],...o}:e[i]=o}}createNestedUpdate(e,t,a){const i=e.split(".");if(i.length===1)return{[i[0]]:t};const o={};let d=o,g=a;for(let h=0;h{this.globalStateUpdater({_local:S})};p.push({state:y,setState:x,dataContext:{_local:y||t.data?._local,_global:o?t.data?._global:t.data?._global||i?.state?.get?.(),_computed:t.data?._computed}}),window.__g7LayoutContextStack=p,q.log(`[handleOpenModal] 레이아웃 컨텍스트 스택에 push, 스택 크기: ${p.length}, state:`,y,o?"(direct)":"(fallback via G7Core)")}else q.warn(`[handleOpenModal] 컨텍스트 스택에 push 실패 - setState: ${!!t.setState}, state: ${t.state!==void 0}, G7Core: ${!!i?.state?.getLocal}`);const h=[...a,e];this.globalStateUpdater({modalStack:h,activeModal:e});const f=Vn();if(f?.isEnabled()){const p=a.length>0?a[a.length-1]:void 0;f.trackModalOpen?.({modalId:e,modalName:e,scopeType:"isolated",parentModalId:p,initialState:t.state?{...t.state}:{}})}}async handleCloseModal(e){if(!this.globalStateUpdater){q.warn("Global state updater is not set for closeModal");return}const t=e?.data?._global?.modalStack||[],a=t.length>0?t[t.length-1]:null,i=t.slice(0,-1),o=i.length>0?i[i.length-1]:null,d=window.__g7LayoutContextStack||[];if(d.length>0){const g=d[d.length-1];g&&(g.dataContext=void 0),d.pop(),window.__g7LayoutContextStack=d,q.log(`[handleCloseModal] 레이아웃 컨텍스트 스택에서 pop, 스택 크기: ${d.length}`)}if(a){const g=Vn();g?.isEnabled()&&g.trackModalClose?.(a,e?.state)}this.globalStateUpdater({modalStack:i,activeModal:o})}async handleShowAlert(e,t){let a=e;this.translationEngine&&this.translationContext&&e.startsWith("$t:")&&(a=this.translationEngine.resolveTranslations(e,this.translationContext,t.data)),alert(a)}async handleToast(e,t){const{type:a="info",message:i,icon:o,duration:d}=e;let g=i;if(this.translationEngine&&this.translationContext&&i?.startsWith("$t:")&&(g=this.translationEngine.resolveTranslations(i,this.translationContext,t.data)),this.globalStateUpdater){const f={id:`toast_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,type:a,message:g,...o&&{icon:o},...d&&{duration:d}},S=[...window.G7Core?.state?.get()?.toasts||[],f];this.globalStateUpdater({toasts:S})}else q.log(`[Toast ${a}] ${g}`)}async handleSwitch(e,t){const{cases:a}=e;if(!a){q.warn("switch handler requires cases property");return}const i=this.resolveParams(e.params,t.data);let o;if(i?.value!==void 0?(o=i.value,q.log("switch handler: using params.value as case key:",o)):(o=t.data?.$args?.[0],q.log("switch handler: using $args[0] as case key:",o)),o==null){if(a.default)return q.log("switch handler: case key is undefined, using default case"),await this.executeAction(a.default,t);q.warn("switch handler: case key is not defined and no default case");return}const d=String(o);let g=a[d];if(!g&&a.default&&(q.log(`switch handler: no case found for key "${d}", using default case`),g=a.default),!g){q.warn(`switch handler: no case found for key "${d}" and no default case`);return}return await this.executeAction(g,t)}async handleConditions(e,t){const{conditions:a}=e;if(!a||!Array.isArray(a)){q.warn("conditions handler requires conditions array");return}const i=t.data||{},o=Wp(a,i,this.bindingEngine);if(!o.matched){q.log("conditions handler: no matching branch found");return}const d=a[o.branchIndex];if(q.log(`conditions handler: matched branch ${o.branchIndex}`),!d.then){q.warn('conditions handler: matched branch has no "then" action');return}return Array.isArray(d.then)?await this.handleSequence({...e,actions:d.then},t):await this.executeAction(d.then,t)}async handleSequence(e,t){const a=e.actions||e.params?.actions;if(!a||!Array.isArray(a)||a.length===0)return q.warn("sequence handler requires non-empty actions array"),[];const i=Vn(),o=i?.isEnabled()&&i.startSequenceExecution?.({eventType:e.type})||"";window.__g7SequenceLocalSync=void 0;const d=[];let g,h=t.state?{...t.state}:{},f=t.isolatedContext?.state?{...t.isolatedContext.state}:{},p=t.data?._computed||{};const y=window.G7Core,x=()=>({_global:y?.state?.get()||{},_local:{...h},_isolated:Object.keys(f).length>0?{...f}:void 0});for(let S=0;S0){const N={},D={...t.data,_local:h,_computed:N,$computed:N,_isolated:f};for(const[$,M]of Object.entries(O))if(typeof M=="string"){const z=M.trim();if(z.startsWith("{{")&&z.endsWith("}}"))try{const K=z.slice(2,-2).trim();N[$]=this.bindingEngine.evaluateExpression(K,D,{skipCache:!0})}catch{N[$]=p[$]}}p=N,q.log("[handleSequence] _computed recalculated after setState:",p)}}if(v.handler!=="setState"){const O=window.__g7SequenceLocalSync;if(O&&O!==h){h=O,window.__g7SequenceLocalSync=void 0,q.log("[handleSequence] currentState synchronized from __g7SequenceLocalSync after custom handler:",v.handler);const N=t.data?._computedDefinitions;if(N&&Object.keys(N).length>0){const D={},$={...t.data,_local:h,_computed:D,$computed:D,_isolated:f};for(const[M,z]of Object.entries(N))if(typeof z=="string"){const K=z.trim();if(K.startsWith("{{")&&K.endsWith("}}"))try{const ye=K.slice(2,-2).trim();D[M]=this.bindingEngine.evaluateExpression(ye,$,{skipCache:!0})}catch{D[M]=p[M]}}p=D,q.log("[handleSequence] _computed recalculated after custom handler:",p)}}}o&&i?.isEnabled()&&i.captureSequenceActionAfter?.(o,S,x(),Date.now()-w,A.data)}catch(A){throw o&&i?.isEnabled()&&(i.captureSequenceActionAfter?.(o,S,x(),Date.now()-w,void 0,A),i.endSequenceExecution?.(o,A)),q.error(`sequence handler: action[${S}] failed:`,A),A}}return window.__g7SequenceLocalSync=void 0,o&&i?.isEnabled()&&i.endSequenceExecution?.(o),d}async handleParallel(e,t){const a=e.actions||e.params?.actions;if(!a||!Array.isArray(a)||a.length===0)return q.warn("parallel handler requires non-empty actions array"),[];q.log(`parallel handler: executing ${a.length} actions in parallel`);const i=t.isolatedContext?{...t.isolatedContext,state:{...t.isolatedContext.state}}:null,o=a.map((h,f)=>{const p={...t,isolatedContext:i};return this.executeAction(h,p).catch(y=>{throw q.error(`parallel handler: action[${f}] failed:`,y),y})}),d=await Promise.allSettled(o),g=d.filter(h=>h.status==="rejected").length;return g>0&&q.warn(`parallel handler: ${g}/${a.length} actions failed`),d}async handleLoadScript(e,t,a){const{src:i,id:o,async:d=!0,defer:g=!1}=e;if(!i)throw new Gt('loadScript handler requires "src" parameter',t);const h=o||`script_${i.replace(/[^a-zA-Z0-9]/g,"_")}`;return bi.loadedScripts.has(h)?(q.log(`loadScript: script already loaded, skipping: ${h}`),t.onLoad&&await this.executeAction(t.onLoad,a),!0):document.getElementById(h)?(q.log(`loadScript: script element already exists: ${h}`),bi.loadedScripts.add(h),t.onLoad&&await this.executeAction(t.onLoad,a),!0):(q.log(`loadScript: loading script: ${i}`),new Promise((p,y)=>{const x=document.createElement("script");x.id=h,x.src=i,x.async=d,x.defer=g,x.onload=async()=>{if(q.log(`loadScript: script loaded successfully: ${h}`),bi.loadedScripts.add(h),t.onLoad)try{await this.executeAction(t.onLoad,a)}catch(S){q.error("loadScript: onLoad action failed:",S)}p(!0)},x.onerror=S=>{q.error(`loadScript: failed to load script: ${i}`,S),y(new Gt(`Failed to load script: ${i}`,t))},document.head.appendChild(x)}))}async handleCallExternal(e,t,a){const i=e.constructor,o=e.args||{},d=e.method,g=e.methodArgs||[],h=e.callbackEvent,f=e.embedTarget,p=e.callbackSetState,y=e.callbackAction;if(!i)throw new Gt('callExternal handler requires "constructor" parameter',t);const x=this.getNestedProperty(window,i);if(!x||typeof x!="function")throw new Gt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first using loadScript handler.`,t);q.log(`callExternal: calling constructor ${i}`);const S={...o};for(const[w,k]of Object.entries(o))k===!0&&(S[w]=A=>{if(q.log(`callExternal: callback triggered for ${w}`,A),h&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(h,A),p&&a.setState){const O=$=>{const M={};for(const[z,K]of Object.entries($))typeof K=="string"?M[z]=this.getNestedProperty(A,K):typeof K=="object"&&K!==null&&(M[z]=O(K));return M},N=O(p);q.log("callExternal: callbackSetState mapping result",N);const D=this.deepMergeWithState(N,a.state||{});q.log("callExternal: merged with existing state",D),a.setState(D)}else h&&a.setState&&a.setState({[`${h.replace(/:/g,"_")}_result`]:A});if(y){const O={...a,data:{...a.data,$event:A}},N=Array.isArray(y)?y:[y];for(const D of N)try{this.executeAction(D,O)}catch($){q.error("callExternal: callbackAction failed:",$)}}});const v=new x(S);if(d&&typeof v[d]=="function"){if(q.log(`callExternal: calling method ${d}`),d==="embed"&&f){const w=document.querySelector(f);if(w)return v[d](w,...g);throw new Gt(`Embed target element not found: ${f}`,t)}return v[d](...g)}return v}async handleCallExternalEmbed(e,t,a){const i=e.constructor,o=e.args||{},d=e.callbackSetState,g=e.callbackEvent,h=e.layerClassName,f=e.callbackAction;if(!i)throw new Gt('callExternalEmbed handler requires "constructor" parameter',t);const p=this.getNestedProperty(window,i);if(!p||typeof p!="function")throw new Gt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first.`,t);q.log(`callExternalEmbed: creating layer for ${i}`);const{layer:y,closeLayer:x}=this.createEmbedLayer(h),S={...o};for(const[w,k]of Object.entries(o))k===!0&&(S[w]=A=>{if(q.log(`callExternalEmbed: callback triggered for ${w}`,A),x(),g&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(g,A),d&&a.setState){const O=$=>{const M={};for(const[z,K]of Object.entries($))typeof K=="string"?M[z]=this.getNestedProperty(A,K):typeof K=="object"&&K!==null&&(M[z]=O(K));return M},N=O(d);q.log("callExternalEmbed: callbackSetState mapping result",N);const D=this.deepMergeWithState(N,a.state||{});q.log("callExternalEmbed: merged with existing state",D),a.setState(D)}if(f){const O={...a,data:{...a.data,$event:A}},N=Array.isArray(f)?f:[f];for(const D of N)try{this.executeAction(D,O)}catch($){q.error("callExternalEmbed: callbackAction failed:",$)}}});const v=new p(S);if(typeof v.embed=="function")v.embed(y),q.log("callExternalEmbed: embedded in layer");else throw x(),new Gt(`Constructor ${i} does not have embed method`,t);return v}createEmbedLayer(e){const t=document.createElement("div");t.id="g7-embed-overlay",t.style.cssText=` position: fixed; inset: 0; background-color: rgba(0, 0, 0, 0.5); @@ -84,11 +84,11 @@ Error generating stack: `+u.message+` justify-content: center; color: #666; transition: background-color 0.2s; - `,i.onmouseenter=()=>{i.style.backgroundColor="rgba(0, 0, 0, 0.2)"},i.onmouseleave=()=>{i.style.backgroundColor="rgba(0, 0, 0, 0.1)"};const o=()=>{t.parentNode&&t.parentNode.removeChild(t)};i.onclick=o;const d=g=>{g.key==="Escape"&&(o(),document.removeEventListener("keydown",d))};return document.addEventListener("keydown",d),t.onclick=g=>{g.target===t&&o()},a.appendChild(i),t.appendChild(a),document.body.appendChild(t),{overlay:t,layer:a,closeLayer:o}}getNestedProperty(e,t){return t.split(".").reduce((a,i)=>a&&a[i]!==void 0?a[i]:void 0,e)}async handleSaveToLocalStorage(e,t){const{key:a,value:i}=e;if(!a)return q.error("saveToLocalStorage: key parameter is required"),!1;try{const o=typeof i=="string"?i:JSON.stringify(i);return localStorage.setItem(a,o),q.log(`saveToLocalStorage: saved ${a}`,i),!0}catch(o){return q.error("saveToLocalStorage: failed to save",{key:a,error:o}),!1}}async handleLoadFromLocalStorage(e,t){const{key:a,target:i,stateKey:o,defaultValue:d}=e;if(!a)return q.error("loadFromLocalStorage: key parameter is required"),d;try{const g=localStorage.getItem(a);if(g===null)return q.log(`loadFromLocalStorage: no value found for ${a}, using default`),o&&t.setState&&t.setState({[o]:d}),d;let h;try{h=JSON.parse(g)}catch{h=g}return q.log(`loadFromLocalStorage: loaded ${a}`,h),o&&t.setState&&t.setState({[o]:h}),h}catch(g){return q.error("loadFromLocalStorage: failed to load",{key:a,error:g}),d}}async handleCustomAction(e,t){const a=this.customHandlers.get(e.handler);if(!a)throw new Gt(`Unknown action handler: ${e.handler}`,e);return await a(e,t)}resolveParams(e,t){if(!e)return{};const a={};for(const[i,o]of Object.entries(e))i.includes("{{")&&q.warn(`[resolveParams] setState params의 키에 표현식이 포함되어 있습니다: "${i}". 키는 해석되지 않습니다. 배열 항목 수정은 .map()/.filter() 패턴을 사용하세요.`),typeof o=="string"&&o.includes("{{")?a[i]=this.evaluateExpression(o,t):typeof o=="string"?a[i]=o:Array.isArray(o)?a[i]=o.map(d=>typeof d=="string"&&d.includes("{{")?this.evaluateExpression(d,t):d):typeof o=="object"&&o!==null&&!Array.isArray(o)&&Object.getPrototypeOf(o)!==Object.prototype&&Object.getPrototypeOf(o)!==null?a[i]=o:typeof o=="object"&&o!==null?a[i]=this.resolveParams(o,t):a[i]=o;return a}resolveValue(e,t){return t?this.bindingEngine.resolveBindings(e,t,{skipCache:!0}):e}evaluateExpressions(e,t){let a={};for(const[i,o]of Object.entries(e))if(i==="..."){let d=o;typeof o=="string"&&o.includes("{{")&&(d=this.evaluateExpression(o,t)),d&&typeof d=="object"&&!Array.isArray(d)&&(a={...a,...d})}else typeof o=="string"&&o.includes("{{")?a[i]=this.evaluateExpression(o,t):typeof o=="object"&&o!==null&&!Array.isArray(o)?a[i]=this.evaluateExpressions(o,t):a[i]=o;return a}evaluateExpressionsIfNeeded(e,t){const a={};for(const[i,o]of Object.entries(e))typeof o=="string"&&o.includes("{{")?a[i]=this.evaluateExpression(o,t):a[i]=o;return a}evaluateExpression(e,t){if(!t)return e;const a=e.match(/^\{\{(.+)\}\}$/);if(!(a&&!a[1].includes("}}")&&!a[1].includes("{{"))){let g=t;if(e.includes("_global")){const f=window.G7Core?.state?.get()?._global;f&&(g={...t,_global:f})}if(e.includes("_computed")||e.includes("$computed")){const f=window.__g7ActionContext?.computedRef?.current;f&&Object.keys(f).length>0&&(g={...g,_computed:f,$computed:f})}return this.bindingEngine.resolveBindings(e,g,{skipCache:!0})}let o=a[1].trim();o=o.replace(/\$args\.(\d+)/g,"$args[$1]");let d=t;if(o.includes("_global")){const h=window.G7Core?.state?.get()?._global;h&&(d={...t,_global:h})}if(o.includes("_computed")||o.includes("$computed")){const h=window.__g7ActionContext?.computedRef?.current;h&&Object.keys(h).length>0&&(d={...d,_computed:h,$computed:h})}o.includes("_global.modules")&&(q.log("[evaluateExpression] expression:",o),q.log("[evaluateExpression] dataContext._global:",d._global),q.log("[evaluateExpression] dataContext._global?.modules:",d._global?.modules));try{const g=this.bindingEngine.evaluateExpression(o,d);return o.includes("_global.modules")&&q.log("[evaluateExpression] result:",g),typeof g=="string"&&g.startsWith("$t:")&&this.translationEngine&&this.translationContext?this.translationEngine.resolveTranslations(g,this.translationContext,t):g}catch(g){return q.error("Expression evaluation failed:",e,g),e}}setDefaultContext(e){this.defaultContext={...this.defaultContext,...e}}setGlobalStateUpdater(e){this.globalStateUpdater=e}getGlobalStateUpdater(){return this.globalStateUpdater}async dispatchAction(e,t){const a={...this.defaultContext,...t,data:{...this.defaultContext.data,...t?.data}};if(e.confirm){let i=this.resolveValue(e.confirm,a.data);if(this.translationEngine&&this.translationContext&&i.startsWith("$t:")&&(i=this.translationEngine.resolveTranslations(i,this.translationContext,a.data)),!confirm(i))return{success:!1}}try{return await this.executeAction(e,a)}catch(i){if(q.error("dispatchAction failed:",i),e.onError){const o=i instanceof Gt&&i.originalError?{message:i.originalError.message,response:i.originalError.response}:{message:i instanceof Error?i.message:String(i)},d={...a,data:{...a.data,error:o}},g=Array.isArray(e.onError)?e.onError:[e.onError];for(const h of g)await this.executeAction(h,d)}return{success:!1,error:i instanceof Error?i:new Error(String(i))}}}registerHandler(e,t,a){this.customHandlers.set(e,t);const i=Vn();i?.isEnabled()&&i.trackHandlerRegistration(e,a?.category??"custom",a?.description,a?.source)}unregisterHandler(e){this.customHandlers.delete(e);const t=Vn();t?.isEnabled()&&t.trackHandlerUnregistration(e)}getRegisteredHandlers(){return Array.from(this.customHandlers.keys())}normalizeDebounceConfig(e){return typeof e=="number"?{delay:e,leading:!1,trailing:!0}:{delay:e.delay,leading:e.leading??!1,trailing:e.trailing??!0}}extractEventData(e){const t=e.target;if(t&&!("tagName"in t)){const o={type:e.type??"custom",target:{value:t.value,name:t.name??""}};return e._changedKeys&&(o._changedKeys=e._changedKeys),o}const i=t?{value:t.value,name:t.name??"",checked:t.checked??!1,type:t.type??"",tagName:t.tagName}:{};if(e.type==="scroll"&&t){const o=t;i.scrollHeight=o.scrollHeight??0,i.scrollTop=o.scrollTop??0,i.clientHeight=o.clientHeight??0,i.scrollLeft=o.scrollLeft??0,i.clientWidth=o.clientWidth??0,i.scrollWidth=o.scrollWidth??0}return{type:e.type,target:t?i:null}}executeDebouncedAction(e,t,a,i,o){const d={...a,$event:t,$args:o},g={type:t.type,target:t.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(e,d,i)(g)}handleDebouncedAction(e,t,a,i,o,d){const g=this.normalizeDebounceConfig(e.debounce),h=o||`default-${e.handler}-${Date.now()}`,f=this.extractEventData(t),p=f._changedKeys;if(p&&Array.isArray(p)&&f?.target?.value&&typeof f.target.value=="object"&&!Array.isArray(f.target.value)){const v=this.debounceAccumulatedValues.get(h);if(v){const w={...v};for(const k of p)w[k]=f.target.value[k];f.target.value=w}this.debounceAccumulatedValues.set(h,f.target.value)}const y=this.debounceTimers.get(h);y&&(clearTimeout(y),this.debounceTimers.delete(h));const x=Vn();x?.isEnabled()&&x.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"pending",params:e.params,debounce:{delay:g.delay,status:"pending",scheduledAt:Date.now()}});const S=!this.debounceTimers.has(h+"_leading");if(g.leading&&S&&(this.debounceTimers.set(h+"_leading",setTimeout(()=>{},0)),this.executeDebouncedAction(e,f,a,i,d),x?.isEnabled()&&x.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"success",params:e.params,debounce:{delay:g.delay,status:"executed",executedAt:Date.now(),mode:"leading"}})),g.trailing){const v=()=>{this.executeDebouncedAction(e,f,a,i,d),x?.isEnabled()&&x.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"success",params:e.params,debounce:{delay:g.delay,status:"executed",executedAt:Date.now(),mode:"trailing"}})},w=setTimeout(()=>{this.debounceTimers.delete(h),this.debounceTimers.delete(h+"_leading"),this.pendingDebounceFlushers.delete(h),this.debounceAccumulatedValues.delete(h),v()},g.delay);this.debounceTimers.set(h,w),this.pendingDebounceFlushers.set(h,v)}}clearDebounceTimers(e){if(e)for(const[t,a]of this.debounceTimers)t.startsWith(e+"-")&&(clearTimeout(a),this.debounceTimers.delete(t),this.pendingDebounceFlushers.delete(t),this.debounceAccumulatedValues.delete(t));else{for(const t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.pendingDebounceFlushers.clear(),this.debounceAccumulatedValues.clear()}}debouncedCall(e,t,a){const i=this.debounceTimers.get(e);i&&(clearTimeout(i),this.debounceTimers.delete(e));const o=setTimeout(()=>{this.debounceTimers.delete(e),this.pendingDebounceFlushers.delete(e),a()},t);this.debounceTimers.set(e,o),this.pendingDebounceFlushers.set(e,a)}flushPendingDebounceTimers(){if(this.pendingDebounceFlushers.size===0)return;const e=new Map(this.pendingDebounceFlushers);for(const[t,a]of e){const i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t)),this.debounceTimers.delete(t+"_leading"),this.pendingDebounceFlushers.delete(t),a()}this.globalStateUpdater&&this.globalStateUpdater({})}bindActionsToProps(e,t,a){const i={...e};if(e.actions&&Array.isArray(e.actions)){const o=new Map;for(const p of e.actions){const y=this.resolveActionRef(p),x=y.event||this.getEventHandlerName(y.type);o.has(x)||o.set(x,[]),o.get(x).push(y)}const d=e.name||e.id||"unknown",g=o.has("onDrop"),h=o.has("onDragOver"),f=o.has("onDragEnter");g&&!h&&(i.onDragOver=p=>{p.preventDefault()}),g&&!f&&(i.onDragEnter=p=>{p.preventDefault()});for(const[p,y]of o)i[p]=(...x)=>{for(const S of y){const v=x[0],w=v&&typeof v=="object"&&"preventDefault"in v;if(w&&(p==="onDragOver"||p==="onDrop")&&v.preventDefault(),w&&S.key&&"key"in v){if(v.key!==S.key){q.log("Key filter not matched:",S.key,"actual:",v.key);continue}q.log("Key filter matched:",S.key)}if(S.debounce){const k=`${d}-${S.handler}-${p}`,A=v&&typeof v=="object"&&!("preventDefault"in v)&&"target"in v&&v.target!==null;let O;if(w)O=v;else if(A){const D={type:"custom",target:v.target,preventDefault:()=>{},stopPropagation:()=>{}};v._changedKeys&&(D._changedKeys=v._changedKeys),O=D}else O=new Event("custom");const N=S.event?{...t,$args:x}:t;this.handleDebouncedAction(S,O,N,a,k,x)}else if(this.flushPendingDebounceTimers(),S.event){const k={...t,$args:x},A=w?v:new Event("custom");this.createHandler(S,k,a)(A)}else if(w)this.createHandler(S,t,a)(v);else if(v&&typeof v=="object"&&!("preventDefault"in v)&&"target"in v&&v.target!==null){const A={type:"custom",target:v.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(S,t,a)(A)}}}}return i}getEventHandlerName(e){return{click:"onClick",change:"onChange",input:"onInput",submit:"onSubmit",focus:"onFocus",blur:"onBlur",keydown:"onKeyDown",keyup:"onKeyUp",keypress:"onKeyPress",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",scroll:"onScroll",dragstart:"onDragStart",drag:"onDrag",dragend:"onDragEnd",dragenter:"onDragEnter",dragover:"onDragOver",dragleave:"onDragLeave",drop:"onDrop"}[e]||`on${e.charAt(0).toUpperCase()}${e.slice(1)}`}sanitizeForDevTools(e,t=5){const a=new WeakSet,i=(o,d)=>{if(o==null||typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o;if(d>t)return"[Max Depth Exceeded]";if(typeof o=="function")return`[Function: ${o.name||"anonymous"}]`;if(o instanceof Element)return`[Element: ${o.tagName}${o.className?"."+o.className.split(" ").join("."):""}]`;if(o instanceof Event)return`[Event: ${o.type}]`;if(Array.isArray(o)){if(a.has(o))return"[Circular Array]";a.add(o);const g=o.slice(0,10).map(h=>i(h,d+1));return o.length>10&&g.push(`... ${o.length-10} more items`),g}if(typeof o=="object"){if(a.has(o))return"[Circular Reference]";a.add(o);const g={},h=Object.keys(o),f=h.slice(0,20);for(const p of f)try{g[p]=i(o[p],d+1)}catch{g[p]="[Error accessing property]"}return h.length>20&&(g["..."]=`${h.length-20} more properties`),g}return String(o)};return i(e,0)}};H(bi,"loadedScripts",new Set);let So=bi,yc=null;function Fm(r){return yc||(yc=new So(r)),yc}function f7(r){yc=r}const Vm=it("TransitionManager");class p7{constructor(){H(this,"isPending",!1);H(this,"subscribers",new Set)}setPending(e){this.isPending!==e&&(Vm.log("setPending:",{from:this.isPending,to:e,stack:new Error().stack}),this.isPending=e,this.notifySubscribers())}getIsPending(){return this.isPending}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}notifySubscribers(){Vm.log("notifySubscribers:",{isPending:this.isPending,subscriberCount:this.subscribers.size}),this.subscribers.forEach(e=>{e(this.isPending)})}clearSubscribers(){this.subscribers.clear()}}const Pa=new p7,xc=it("TransitionContext"),Km=j.createContext({isTransitioning:!1}),ug=({children:r})=>{const[e,t]=j.useState(()=>{const i=Pa.getIsPending();return xc.log("Initial state:",i),i});j.useEffect(()=>{xc.log("Subscribing to TransitionManager");const i=Pa.subscribe(o=>{xc.log("Received isPending update:",o),t(o)});return()=>{xc.log("Unsubscribing from TransitionManager"),i()}},[]);const a=j.useMemo(()=>({isTransitioning:e}),[e]);return l.jsx(Km.Provider,{value:a,children:r})},Wm=()=>j.useContext(Km);function m7(r){return r<768?"mobile":r<1024?"tablet":"desktop"}function Ym(r){const e=m7(r);return{width:r,isMobile:e==="mobile",isTablet:e==="tablet",isDesktop:e==="desktop",matchedPreset:e}}const Jm=j.createContext(Ym(1024)),gg=({children:r,overrideWidth:e})=>{const[t,a]=j.useState(()=>ei.getWidth());j.useEffect(()=>{const d=ei.subscribe(g=>{a(g)});return()=>{d()}},[]);const i=e??t,o=j.useMemo(()=>Ym(i),[i]);return l.jsx(Jm.Provider,{value:o,children:r})},Xm=()=>j.useContext(Jm);window.G7Core?.createLogger?.("Core:State");function y7(r,e,t,a){const{syncOnControlledChange:i=!0,isEqual:o}=a??{},d=r!==void 0;j.useRef(d);const[g,h]=j.useState(r!==void 0?r:e),f=g,p=j.useRef(r),y=j.useRef(!1);j.useEffect(()=>{if(y.current){p.current=r;return}i&&d&&r!==p.current&&(o?!o(g,r):g!==r)&&h(r),p.current=r},[r,d,i,o,g]);const x=j.useCallback(S=>{const v=typeof S=="function"?S(f):S;(o?o(f,v):f===v)||(y.current=!0,h(v),t?.(v),requestAnimationFrame(()=>{y.current=!1}))},[f,d,t,o]);return[f,x]}function x7(r,e){return r===e?!0:r.length!==e.length?!1:r.every((t,a)=>t===e[a])}function Qm(r,e){if(r===e)return!0;const t=Object.keys(r),a=Object.keys(e);return t.length!==a.length?!1:t.every(i=>r[i]===e[i])}const Zm=j.createContext({}),b7=({children:r,value:e})=>l.jsx(Zm.Provider,{value:e,children:r}),v7=()=>j.useContext(Zm),w7=(r,e)=>{if(!r)return;const t=e.split(".");let a=r;for(const i of t){if(a==null)return;a=a[i]}return a},S7=(r,e,t)=>{const a=e.split(".");if(a.length===1)return{...r,[a[0]]:t};const i={...r};let o=i;for(let d=0;d{oi.warn("IsolatedStateContext not available: setState called outside IsolatedStateProvider")},getState:()=>{},mergeState:()=>{oi.warn("IsolatedStateContext not available: mergeState called outside IsolatedStateProvider")},stateRef:{current:{}},scopeId:""},ey=j.createContext(C7);let j7=0;function k7(){return`isolated-${++j7}-${Date.now().toString(36)}`}function ty(r,e){if(e==null)return r;if(typeof e!="object"||Array.isArray(e))return e;const t={...r};for(const a of Object.keys(e)){const i=e[a],o=r?.[a];i!==null&&typeof i=="object"&&!Array.isArray(i)&&o!==null&&typeof o=="object"&&!Array.isArray(o)?t[a]=ty(o,i):t[a]=i}return t}function N7(r,e){return e?e.split(".").reduce((t,a)=>t?.[a],r):r}function E7(r,e,t){const a=e.split("."),i={...r};let o=i;for(let d=0;d{const i=j.useRef(e||k7()).current,[o,d]=j.useState(r),g=j.useRef(o);g.current=o;const h=j.useCallback(S=>N7(g.current,S),[]),f=j.useCallback((S,v)=>{d(w=>{const k=E7(w,S,v);return oi.log(`[${i}] setState: ${S} =`,v),k})},[i]),p=j.useCallback((S,v="deep")=>{d(w=>{let k;return v==="replace"?k=S:v==="shallow"?k={...w,...S}:k=ty(w,S),oi.log(`[${i}] mergeState (${v}):`,S),k})},[i]),y=j.useMemo(()=>({state:o,setState:f,getState:h,mergeState:p,stateRef:g,scopeId:i}),[o,f,h,p,i]),x=j.useMemo(()=>({state:g.current,setState:f,getState:h,mergeState:p}),[f,h,p]);return j.useEffect(()=>{const S=window.G7Core,v=window.__g7IsolatedStates||{};return window.__g7IsolatedStates||(window.__g7IsolatedStates=v),v[i]=x,S&&(S._isolatedStates||(S._isolatedStates={}),S._isolatedStates[i]=o),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:created",{id:i,state:o}),oi.log(`[${i}] IsolatedStateProvider mounted with initial state:`,o),()=>{delete v[i],S?._isolatedStates&&delete S._isolatedStates[i],S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:destroyed",{id:i}),oi.log(`[${i}] IsolatedStateProvider unmounted`)}},[i,x]),j.useEffect(()=>{const S=window.G7Core,v=window.__g7IsolatedStates;v?.[i]&&(v[i].state=o),S?._isolatedStates&&(S._isolatedStates[i]=o),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:updated",{id:i,state:o})},[o,i]),l.jsx(ey.Provider,{value:y,children:t})},A7=()=>{const r=j.useContext(ey);return r.scopeId?r:null};var Os=Mp();function T7(){for(var r=arguments.length,e=new Array(r),t=0;ta=>{e.forEach(i=>i(a))},e)}const bc=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function li(r){const e=Object.prototype.toString.call(r);return e==="[object Window]"||e==="[object global]"}function hg(r){return"nodeType"in r}function Ln(r){var e,t;return r?li(r)?r:hg(r)&&(e=(t=r.ownerDocument)==null?void 0:t.defaultView)!=null?e:window:window}function fg(r){const{Document:e}=Ln(r);return r instanceof e}function Co(r){return li(r)?!1:r instanceof Ln(r).HTMLElement}function ny(r){return r instanceof Ln(r).SVGElement}function ci(r){return r?li(r)?r.document:hg(r)?fg(r)?r:Co(r)||ny(r)?r.ownerDocument:document:document:document}const Ba=bc?j.useLayoutEffect:j.useEffect;function pg(r){const e=j.useRef(r);return Ba(()=>{e.current=r}),j.useCallback(function(){for(var t=arguments.length,a=new Array(t),i=0;i{r.current=setInterval(a,i)},[]),t=j.useCallback(()=>{r.current!==null&&(clearInterval(r.current),r.current=null)},[]);return[e,t]}function jo(r,e){e===void 0&&(e=[r]);const t=j.useRef(r);return Ba(()=>{t.current!==r&&(t.current=r)},e),t}function ko(r,e){const t=j.useRef();return j.useMemo(()=>{const a=r(t.current);return t.current=a,a},[...e])}function vc(r){const e=pg(r),t=j.useRef(null),a=j.useCallback(i=>{i!==t.current&&e?.(i,t.current),t.current=i},[]);return[t,a]}function mg(r){const e=j.useRef();return j.useEffect(()=>{e.current=r},[r]),e.current}let yg={};function No(r,e){return j.useMemo(()=>{if(e)return e;const t=yg[r]==null?0:yg[r]+1;return yg[r]=t,r+"-"+t},[r,e])}function ay(r){return function(e){for(var t=arguments.length,a=new Array(t>1?t-1:0),i=1;i{const g=Object.entries(d);for(const[h,f]of g){const p=o[h];p!=null&&(o[h]=p+r*f)}return o},{...e})}}const di=ay(1),Eo=ay(-1);function R7(r){return"clientX"in r&&"clientY"in r}function xg(r){if(!r)return!1;const{KeyboardEvent:e}=Ln(r.target);return e&&r instanceof e}function O7(r){if(!r)return!1;const{TouchEvent:e}=Ln(r.target);return e&&r instanceof e}function bg(r){if(O7(r)){if(r.touches&&r.touches.length){const{clientX:e,clientY:t}=r.touches[0];return{x:e,y:t}}else if(r.changedTouches&&r.changedTouches.length){const{clientX:e,clientY:t}=r.changedTouches[0];return{x:e,y:t}}}return R7(r)?{x:r.clientX,y:r.clientY}:null}const _o=Object.freeze({Translate:{toString(r){if(!r)return;const{x:e,y:t}=r;return"translate3d("+(e?Math.round(e):0)+"px, "+(t?Math.round(t):0)+"px, 0)"}},Scale:{toString(r){if(!r)return;const{scaleX:e,scaleY:t}=r;return"scaleX("+e+") scaleY("+t+")"}},Transform:{toString(r){if(r)return[_o.Translate.toString(r),_o.Scale.toString(r)].join(" ")}},Transition:{toString(r){let{property:e,duration:t,easing:a}=r;return e+" "+t+"ms "+a}}}),sy="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function L7(r){return r.matches(sy)?r:r.querySelector(sy)}const M7={display:"none"};function $7(r){let{id:e,value:t}=r;return Ke.createElement("div",{id:e,style:M7},t)}function I7(r){let{id:e,announcement:t,ariaLiveType:a="assertive"}=r;const i={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Ke.createElement("div",{id:e,style:i,role:"status","aria-live":a,"aria-atomic":!0},t)}function z7(){const[r,e]=j.useState("");return{announce:j.useCallback(a=>{a!=null&&e(a)},[]),announcement:r}}const ry=j.createContext(null);function H7(r){const e=j.useContext(ry);j.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(r)},[r,e])}function P7(){const[r]=j.useState(()=>new Set),e=j.useCallback(a=>(r.add(a),()=>r.delete(a)),[r]);return[j.useCallback(a=>{let{type:i,event:o}=a;r.forEach(d=>{var g;return(g=d[i])==null?void 0:g.call(d,o)})},[r]),e]}const B7={draggable:` + `,i.onmouseenter=()=>{i.style.backgroundColor="rgba(0, 0, 0, 0.2)"},i.onmouseleave=()=>{i.style.backgroundColor="rgba(0, 0, 0, 0.1)"};const o=()=>{t.parentNode&&t.parentNode.removeChild(t)};i.onclick=o;const d=g=>{g.key==="Escape"&&(o(),document.removeEventListener("keydown",d))};return document.addEventListener("keydown",d),t.onclick=g=>{g.target===t&&o()},a.appendChild(i),t.appendChild(a),document.body.appendChild(t),{overlay:t,layer:a,closeLayer:o}}getNestedProperty(e,t){return t.split(".").reduce((a,i)=>a&&a[i]!==void 0?a[i]:void 0,e)}async handleSaveToLocalStorage(e,t){const{key:a,value:i}=e;if(!a)return q.error("saveToLocalStorage: key parameter is required"),!1;try{const o=typeof i=="string"?i:JSON.stringify(i);return localStorage.setItem(a,o),q.log(`saveToLocalStorage: saved ${a}`,i),!0}catch(o){return q.error("saveToLocalStorage: failed to save",{key:a,error:o}),!1}}async handleLoadFromLocalStorage(e,t){const{key:a,target:i,stateKey:o,defaultValue:d}=e;if(!a)return q.error("loadFromLocalStorage: key parameter is required"),d;try{const g=localStorage.getItem(a);if(g===null)return q.log(`loadFromLocalStorage: no value found for ${a}, using default`),o&&t.setState&&t.setState({[o]:d}),d;let h;try{h=JSON.parse(g)}catch{h=g}return q.log(`loadFromLocalStorage: loaded ${a}`,h),o&&t.setState&&t.setState({[o]:h}),h}catch(g){return q.error("loadFromLocalStorage: failed to load",{key:a,error:g}),d}}async handleCustomAction(e,t){const a=this.customHandlers.get(e.handler);if(!a)throw new Gt(`Unknown action handler: ${e.handler}`,e);return await a(e,t)}resolveParams(e,t){if(!e)return{};const a={};for(const[i,o]of Object.entries(e))i.includes("{{")&&q.warn(`[resolveParams] setState params의 키에 표현식이 포함되어 있습니다: "${i}". 키는 해석되지 않습니다. 배열 항목 수정은 .map()/.filter() 패턴을 사용하세요.`),typeof o=="string"&&o.includes("{{")?a[i]=this.evaluateExpression(o,t):typeof o=="string"?a[i]=o:Array.isArray(o)?a[i]=o.map(d=>typeof d=="string"&&d.includes("{{")?this.evaluateExpression(d,t):d):typeof o=="object"&&o!==null&&!Array.isArray(o)&&Object.getPrototypeOf(o)!==Object.prototype&&Object.getPrototypeOf(o)!==null?a[i]=o:typeof o=="object"&&o!==null?a[i]=this.resolveParams(o,t):a[i]=o;return a}resolveValue(e,t){return t?this.bindingEngine.resolveBindings(e,t,{skipCache:!0}):e}evaluateExpressions(e,t){let a={};for(const[i,o]of Object.entries(e))if(i==="..."){let d=o;typeof o=="string"&&o.includes("{{")&&(d=this.evaluateExpression(o,t)),d&&typeof d=="object"&&!Array.isArray(d)&&(a={...a,...d})}else typeof o=="string"&&o.includes("{{")?a[i]=this.evaluateExpression(o,t):typeof o=="object"&&o!==null&&!Array.isArray(o)?a[i]=this.evaluateExpressions(o,t):a[i]=o;return a}evaluateExpressionsIfNeeded(e,t){const a={};for(const[i,o]of Object.entries(e))typeof o=="string"&&o.includes("{{")?a[i]=this.evaluateExpression(o,t):a[i]=o;return a}evaluateExpression(e,t){if(!t)return e;const a=e.match(/^\{\{(.+)\}\}$/);if(!(a&&!a[1].includes("}}")&&!a[1].includes("{{"))){let g=t;if(e.includes("_global")){const f=window.G7Core?.state?.get()?._global;f&&(g={...t,_global:f})}if(e.includes("_computed")||e.includes("$computed")){const f=window.__g7ActionContext?.computedRef?.current;f&&Object.keys(f).length>0&&(g={...g,_computed:f,$computed:f})}return this.bindingEngine.resolveBindings(e,g,{skipCache:!0})}let o=a[1].trim();o=o.replace(/\$args\.(\d+)/g,"$args[$1]");let d=t;if(o.includes("_global")){const h=window.G7Core?.state?.get()?._global;h&&(d={...t,_global:h})}if(o.includes("_computed")||o.includes("$computed")){const h=window.__g7ActionContext?.computedRef?.current;h&&Object.keys(h).length>0&&(d={...d,_computed:h,$computed:h})}o.includes("_global.modules")&&(q.log("[evaluateExpression] expression:",o),q.log("[evaluateExpression] dataContext._global:",d._global),q.log("[evaluateExpression] dataContext._global?.modules:",d._global?.modules));try{const g=this.bindingEngine.evaluateExpression(o,d);return o.includes("_global.modules")&&q.log("[evaluateExpression] result:",g),typeof g=="string"&&g.startsWith("$t:")&&this.translationEngine&&this.translationContext?this.translationEngine.resolveTranslations(g,this.translationContext,t):g}catch(g){return q.error("Expression evaluation failed:",e,g),e}}setDefaultContext(e){this.defaultContext={...this.defaultContext,...e}}setGlobalStateUpdater(e){this.globalStateUpdater=e}getGlobalStateUpdater(){return this.globalStateUpdater}async dispatchAction(e,t){const a={...this.defaultContext,...t,data:{...this.defaultContext.data,...t?.data}};if(e.confirm){let i=this.resolveValue(e.confirm,a.data);if(this.translationEngine&&this.translationContext&&i.startsWith("$t:")&&(i=this.translationEngine.resolveTranslations(i,this.translationContext,a.data)),!confirm(i))return{success:!1}}try{return await this.executeAction(e,a)}catch(i){if(q.error("dispatchAction failed:",i),e.onError){const o=i instanceof Gt&&i.originalError?{message:i.originalError.message,response:i.originalError.response}:{message:i instanceof Error?i.message:String(i)},d={...a,data:{...a.data,error:o}},g=Array.isArray(e.onError)?e.onError:[e.onError];for(const h of g)await this.executeAction(h,d)}return{success:!1,error:i instanceof Error?i:new Error(String(i))}}}registerHandler(e,t,a){this.customHandlers.set(e,t);const i=Vn();i?.isEnabled()&&i.trackHandlerRegistration(e,a?.category??"custom",a?.description,a?.source)}unregisterHandler(e){this.customHandlers.delete(e);const t=Vn();t?.isEnabled()&&t.trackHandlerUnregistration(e)}getRegisteredHandlers(){return Array.from(this.customHandlers.keys())}normalizeDebounceConfig(e){return typeof e=="number"?{delay:e,leading:!1,trailing:!0}:{delay:e.delay,leading:e.leading??!1,trailing:e.trailing??!0}}extractEventData(e){const t=e.target;if(t&&!("tagName"in t)){const o={type:e.type??"custom",target:{value:t.value,name:t.name??""}};return e._changedKeys&&(o._changedKeys=e._changedKeys),o}const i=t?{value:t.value,name:t.name??"",checked:t.checked??!1,type:t.type??"",tagName:t.tagName}:{};if(e.type==="scroll"&&t){const o=t;i.scrollHeight=o.scrollHeight??0,i.scrollTop=o.scrollTop??0,i.clientHeight=o.clientHeight??0,i.scrollLeft=o.scrollLeft??0,i.clientWidth=o.clientWidth??0,i.scrollWidth=o.scrollWidth??0}return{type:e.type,target:t?i:null}}executeDebouncedAction(e,t,a,i,o){const d={...a,$event:t,$args:o},g={type:t.type,target:t.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(e,d,i)(g)}handleDebouncedAction(e,t,a,i,o,d){const g=this.normalizeDebounceConfig(e.debounce),h=o||`default-${e.handler}-${Date.now()}`,f=this.extractEventData(t),p=f._changedKeys;if(p&&Array.isArray(p)&&f?.target?.value&&typeof f.target.value=="object"&&!Array.isArray(f.target.value)){const v=this.debounceAccumulatedValues.get(h);if(v){const w={...v};for(const k of p)w[k]=f.target.value[k];f.target.value=w}this.debounceAccumulatedValues.set(h,f.target.value)}const y=this.debounceTimers.get(h);y&&(clearTimeout(y),this.debounceTimers.delete(h));const x=Vn();x?.isEnabled()&&x.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"pending",params:e.params,debounce:{delay:g.delay,status:"pending",scheduledAt:Date.now()}});const S=!this.debounceTimers.has(h+"_leading");if(g.leading&&S&&(this.debounceTimers.set(h+"_leading",setTimeout(()=>{},0)),this.executeDebouncedAction(e,f,a,i,d),x?.isEnabled()&&x.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"success",params:e.params,debounce:{delay:g.delay,status:"executed",executedAt:Date.now(),mode:"leading"}})),g.trailing){const v=()=>{this.executeDebouncedAction(e,f,a,i,d),x?.isEnabled()&&x.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"success",params:e.params,debounce:{delay:g.delay,status:"executed",executedAt:Date.now(),mode:"trailing"}})},w=setTimeout(()=>{this.debounceTimers.delete(h),this.debounceTimers.delete(h+"_leading"),this.pendingDebounceFlushers.delete(h),this.debounceAccumulatedValues.delete(h),v()},g.delay);this.debounceTimers.set(h,w),this.pendingDebounceFlushers.set(h,v)}}clearDebounceTimers(e){if(e)for(const[t,a]of this.debounceTimers)t.startsWith(e+"-")&&(clearTimeout(a),this.debounceTimers.delete(t),this.pendingDebounceFlushers.delete(t),this.debounceAccumulatedValues.delete(t));else{for(const t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.pendingDebounceFlushers.clear(),this.debounceAccumulatedValues.clear()}}debouncedCall(e,t,a){const i=this.debounceTimers.get(e);i&&(clearTimeout(i),this.debounceTimers.delete(e));const o=setTimeout(()=>{this.debounceTimers.delete(e),this.pendingDebounceFlushers.delete(e),a()},t);this.debounceTimers.set(e,o),this.pendingDebounceFlushers.set(e,a)}flushPendingDebounceTimers(){if(this.pendingDebounceFlushers.size===0)return;const e=new Map(this.pendingDebounceFlushers);for(const[t,a]of e){const i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t)),this.debounceTimers.delete(t+"_leading"),this.pendingDebounceFlushers.delete(t),a()}this.globalStateUpdater&&this.globalStateUpdater({})}bindActionsToProps(e,t,a){const i={...e};if(e.actions&&Array.isArray(e.actions)){const o=new Map;for(const p of e.actions){const y=this.resolveActionRef(p),x=y.event||this.getEventHandlerName(y.type);o.has(x)||o.set(x,[]),o.get(x).push(y)}const d=e.name||e.id||"unknown",g=o.has("onDrop"),h=o.has("onDragOver"),f=o.has("onDragEnter");g&&!h&&(i.onDragOver=p=>{p.preventDefault()}),g&&!f&&(i.onDragEnter=p=>{p.preventDefault()});for(const[p,y]of o)i[p]=(...x)=>{for(const S of y){const v=x[0],w=v&&typeof v=="object"&&"preventDefault"in v;if(w&&(p==="onDragOver"||p==="onDrop")&&v.preventDefault(),w&&S.key&&"key"in v){if(v.key!==S.key){q.log("Key filter not matched:",S.key,"actual:",v.key);continue}q.log("Key filter matched:",S.key)}if(S.debounce){const k=`${d}-${S.handler}-${p}`,A=v&&typeof v=="object"&&!("preventDefault"in v)&&"target"in v&&v.target!==null;let O;if(w)O=v;else if(A){const D={type:"custom",target:v.target,preventDefault:()=>{},stopPropagation:()=>{}};v._changedKeys&&(D._changedKeys=v._changedKeys),O=D}else O=new Event("custom");const N=S.event?{...t,$args:x}:t;this.handleDebouncedAction(S,O,N,a,k,x)}else if(this.flushPendingDebounceTimers(),S.event){const k={...t,$args:x},A=w?v:new Event("custom");this.createHandler(S,k,a)(A)}else if(w)this.createHandler(S,t,a)(v);else if(v&&typeof v=="object"&&!("preventDefault"in v)&&"target"in v&&v.target!==null){const A={type:"custom",target:v.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(S,t,a)(A)}}}}return i}getEventHandlerName(e){return{click:"onClick",change:"onChange",input:"onInput",submit:"onSubmit",focus:"onFocus",blur:"onBlur",keydown:"onKeyDown",keyup:"onKeyUp",keypress:"onKeyPress",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",scroll:"onScroll",dragstart:"onDragStart",drag:"onDrag",dragend:"onDragEnd",dragenter:"onDragEnter",dragover:"onDragOver",dragleave:"onDragLeave",drop:"onDrop"}[e]||`on${e.charAt(0).toUpperCase()}${e.slice(1)}`}sanitizeForDevTools(e,t=5){const a=new WeakSet,i=(o,d)=>{if(o==null||typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o;if(d>t)return"[Max Depth Exceeded]";if(typeof o=="function")return`[Function: ${o.name||"anonymous"}]`;if(o instanceof Element)return`[Element: ${o.tagName}${o.className?"."+o.className.split(" ").join("."):""}]`;if(o instanceof Event)return`[Event: ${o.type}]`;if(Array.isArray(o)){if(a.has(o))return"[Circular Array]";a.add(o);const g=o.slice(0,10).map(h=>i(h,d+1));return o.length>10&&g.push(`... ${o.length-10} more items`),g}if(typeof o=="object"){if(a.has(o))return"[Circular Reference]";a.add(o);const g={},h=Object.keys(o),f=h.slice(0,20);for(const p of f)try{g[p]=i(o[p],d+1)}catch{g[p]="[Error accessing property]"}return h.length>20&&(g["..."]=`${h.length-20} more properties`),g}return String(o)};return i(e,0)}};H(bi,"loadedScripts",new Set);let So=bi,xc=null;function Fm(r){return xc||(xc=new So(r)),xc}function p7(r){xc=r}const Vm=it("TransitionManager");class m7{constructor(){H(this,"isPending",!1);H(this,"subscribers",new Set)}setPending(e){this.isPending!==e&&(Vm.log("setPending:",{from:this.isPending,to:e,stack:new Error().stack}),this.isPending=e,this.notifySubscribers())}getIsPending(){return this.isPending}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}notifySubscribers(){Vm.log("notifySubscribers:",{isPending:this.isPending,subscriberCount:this.subscribers.size}),this.subscribers.forEach(e=>{e(this.isPending)})}clearSubscribers(){this.subscribers.clear()}}const Pa=new m7,bc=it("TransitionContext"),Km=j.createContext({isTransitioning:!1}),ug=({children:r})=>{const[e,t]=j.useState(()=>{const i=Pa.getIsPending();return bc.log("Initial state:",i),i});j.useEffect(()=>{bc.log("Subscribing to TransitionManager");const i=Pa.subscribe(o=>{bc.log("Received isPending update:",o),t(o)});return()=>{bc.log("Unsubscribing from TransitionManager"),i()}},[]);const a=j.useMemo(()=>({isTransitioning:e}),[e]);return l.jsx(Km.Provider,{value:a,children:r})},Wm=()=>j.useContext(Km);function y7(r){return r<768?"mobile":r<1024?"tablet":"desktop"}function Ym(r){const e=y7(r);return{width:r,isMobile:e==="mobile",isTablet:e==="tablet",isDesktop:e==="desktop",matchedPreset:e}}const Jm=j.createContext(Ym(1024)),gg=({children:r,overrideWidth:e})=>{const[t,a]=j.useState(()=>ei.getWidth());j.useEffect(()=>{const d=ei.subscribe(g=>{a(g)});return()=>{d()}},[]);const i=e??t,o=j.useMemo(()=>Ym(i),[i]);return l.jsx(Jm.Provider,{value:o,children:r})},Xm=()=>j.useContext(Jm);window.G7Core?.createLogger?.("Core:State");function x7(r,e,t,a){const{syncOnControlledChange:i=!0,isEqual:o}=a??{},d=r!==void 0;j.useRef(d);const[g,h]=j.useState(r!==void 0?r:e),f=g,p=j.useRef(r),y=j.useRef(!1);j.useEffect(()=>{if(y.current){p.current=r;return}i&&d&&r!==p.current&&(o?!o(g,r):g!==r)&&h(r),p.current=r},[r,d,i,o,g]);const x=j.useCallback(S=>{const v=typeof S=="function"?S(f):S;(o?o(f,v):f===v)||(y.current=!0,h(v),t?.(v),requestAnimationFrame(()=>{y.current=!1}))},[f,d,t,o]);return[f,x]}function b7(r,e){return r===e?!0:r.length!==e.length?!1:r.every((t,a)=>t===e[a])}function Qm(r,e){if(r===e)return!0;const t=Object.keys(r),a=Object.keys(e);return t.length!==a.length?!1:t.every(i=>r[i]===e[i])}const Zm=j.createContext({}),v7=({children:r,value:e})=>l.jsx(Zm.Provider,{value:e,children:r}),w7=()=>j.useContext(Zm),S7=(r,e)=>{if(!r)return;const t=e.split(".");let a=r;for(const i of t){if(a==null)return;a=a[i]}return a},C7=(r,e,t)=>{const a=e.split(".");if(a.length===1)return{...r,[a[0]]:t};const i={...r};let o=i;for(let d=0;d{oi.warn("IsolatedStateContext not available: setState called outside IsolatedStateProvider")},getState:()=>{},mergeState:()=>{oi.warn("IsolatedStateContext not available: mergeState called outside IsolatedStateProvider")},stateRef:{current:{}},scopeId:""},ey=j.createContext(j7);let k7=0;function N7(){return`isolated-${++k7}-${Date.now().toString(36)}`}function ty(r,e){if(e==null)return r;if(typeof e!="object"||Array.isArray(e))return e;const t={...r};for(const a of Object.keys(e)){const i=e[a],o=r?.[a];i!==null&&typeof i=="object"&&!Array.isArray(i)&&o!==null&&typeof o=="object"&&!Array.isArray(o)?t[a]=ty(o,i):t[a]=i}return t}function E7(r,e){return e?e.split(".").reduce((t,a)=>t?.[a],r):r}function _7(r,e,t){const a=e.split("."),i={...r};let o=i;for(let d=0;d{const i=j.useRef(e||N7()).current,[o,d]=j.useState(r),g=j.useRef(o);g.current=o;const h=j.useCallback(S=>E7(g.current,S),[]),f=j.useCallback((S,v)=>{d(w=>{const k=_7(w,S,v);return oi.log(`[${i}] setState: ${S} =`,v),k})},[i]),p=j.useCallback((S,v="deep")=>{d(w=>{let k;return v==="replace"?k=S:v==="shallow"?k={...w,...S}:k=ty(w,S),oi.log(`[${i}] mergeState (${v}):`,S),k})},[i]),y=j.useMemo(()=>({state:o,setState:f,getState:h,mergeState:p,stateRef:g,scopeId:i}),[o,f,h,p,i]),x=j.useMemo(()=>({state:g.current,setState:f,getState:h,mergeState:p}),[f,h,p]);return j.useEffect(()=>{const S=window.G7Core,v=window.__g7IsolatedStates||{};return window.__g7IsolatedStates||(window.__g7IsolatedStates=v),v[i]=x,S&&(S._isolatedStates||(S._isolatedStates={}),S._isolatedStates[i]=o),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:created",{id:i,state:o}),oi.log(`[${i}] IsolatedStateProvider mounted with initial state:`,o),()=>{delete v[i],S?._isolatedStates&&delete S._isolatedStates[i],S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:destroyed",{id:i}),oi.log(`[${i}] IsolatedStateProvider unmounted`)}},[i,x]),j.useEffect(()=>{const S=window.G7Core,v=window.__g7IsolatedStates;v?.[i]&&(v[i].state=o),S?._isolatedStates&&(S._isolatedStates[i]=o),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:updated",{id:i,state:o})},[o,i]),l.jsx(ey.Provider,{value:y,children:t})},T7=()=>{const r=j.useContext(ey);return r.scopeId?r:null};var Os=Mp();function D7(){for(var r=arguments.length,e=new Array(r),t=0;ta=>{e.forEach(i=>i(a))},e)}const vc=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function li(r){const e=Object.prototype.toString.call(r);return e==="[object Window]"||e==="[object global]"}function hg(r){return"nodeType"in r}function Ln(r){var e,t;return r?li(r)?r:hg(r)&&(e=(t=r.ownerDocument)==null?void 0:t.defaultView)!=null?e:window:window}function fg(r){const{Document:e}=Ln(r);return r instanceof e}function Co(r){return li(r)?!1:r instanceof Ln(r).HTMLElement}function ny(r){return r instanceof Ln(r).SVGElement}function ci(r){return r?li(r)?r.document:hg(r)?fg(r)?r:Co(r)||ny(r)?r.ownerDocument:document:document:document}const Ba=vc?j.useLayoutEffect:j.useEffect;function pg(r){const e=j.useRef(r);return Ba(()=>{e.current=r}),j.useCallback(function(){for(var t=arguments.length,a=new Array(t),i=0;i{r.current=setInterval(a,i)},[]),t=j.useCallback(()=>{r.current!==null&&(clearInterval(r.current),r.current=null)},[]);return[e,t]}function jo(r,e){e===void 0&&(e=[r]);const t=j.useRef(r);return Ba(()=>{t.current!==r&&(t.current=r)},e),t}function ko(r,e){const t=j.useRef();return j.useMemo(()=>{const a=r(t.current);return t.current=a,a},[...e])}function wc(r){const e=pg(r),t=j.useRef(null),a=j.useCallback(i=>{i!==t.current&&e?.(i,t.current),t.current=i},[]);return[t,a]}function mg(r){const e=j.useRef();return j.useEffect(()=>{e.current=r},[r]),e.current}let yg={};function No(r,e){return j.useMemo(()=>{if(e)return e;const t=yg[r]==null?0:yg[r]+1;return yg[r]=t,r+"-"+t},[r,e])}function ay(r){return function(e){for(var t=arguments.length,a=new Array(t>1?t-1:0),i=1;i{const g=Object.entries(d);for(const[h,f]of g){const p=o[h];p!=null&&(o[h]=p+r*f)}return o},{...e})}}const di=ay(1),Eo=ay(-1);function O7(r){return"clientX"in r&&"clientY"in r}function xg(r){if(!r)return!1;const{KeyboardEvent:e}=Ln(r.target);return e&&r instanceof e}function L7(r){if(!r)return!1;const{TouchEvent:e}=Ln(r.target);return e&&r instanceof e}function bg(r){if(L7(r)){if(r.touches&&r.touches.length){const{clientX:e,clientY:t}=r.touches[0];return{x:e,y:t}}else if(r.changedTouches&&r.changedTouches.length){const{clientX:e,clientY:t}=r.changedTouches[0];return{x:e,y:t}}}return O7(r)?{x:r.clientX,y:r.clientY}:null}const _o=Object.freeze({Translate:{toString(r){if(!r)return;const{x:e,y:t}=r;return"translate3d("+(e?Math.round(e):0)+"px, "+(t?Math.round(t):0)+"px, 0)"}},Scale:{toString(r){if(!r)return;const{scaleX:e,scaleY:t}=r;return"scaleX("+e+") scaleY("+t+")"}},Transform:{toString(r){if(r)return[_o.Translate.toString(r),_o.Scale.toString(r)].join(" ")}},Transition:{toString(r){let{property:e,duration:t,easing:a}=r;return e+" "+t+"ms "+a}}}),sy="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function M7(r){return r.matches(sy)?r:r.querySelector(sy)}const $7={display:"none"};function I7(r){let{id:e,value:t}=r;return Ke.createElement("div",{id:e,style:$7},t)}function z7(r){let{id:e,announcement:t,ariaLiveType:a="assertive"}=r;const i={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Ke.createElement("div",{id:e,style:i,role:"status","aria-live":a,"aria-atomic":!0},t)}function H7(){const[r,e]=j.useState("");return{announce:j.useCallback(a=>{a!=null&&e(a)},[]),announcement:r}}const ry=j.createContext(null);function P7(r){const e=j.useContext(ry);j.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(r)},[r,e])}function B7(){const[r]=j.useState(()=>new Set),e=j.useCallback(a=>(r.add(a),()=>r.delete(a)),[r]);return[j.useCallback(a=>{let{type:i,event:o}=a;r.forEach(d=>{var g;return(g=d[i])==null?void 0:g.call(d,o)})},[r]),e]}const U7={draggable:` To pick up a draggable item, press the space bar. While dragging, use the arrow keys to move the item. Press space again to drop the item in its new position, or press escape to cancel. - `},U7={onDragStart(r){let{active:e}=r;return"Picked up draggable item "+e.id+"."},onDragOver(r){let{active:e,over:t}=r;return t?"Draggable item "+e.id+" was moved over droppable area "+t.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(r){let{active:e,over:t}=r;return t?"Draggable item "+e.id+" was dropped over droppable area "+t.id:"Draggable item "+e.id+" was dropped."},onDragCancel(r){let{active:e}=r;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function q7(r){let{announcements:e=U7,container:t,hiddenTextDescribedById:a,screenReaderInstructions:i=B7}=r;const{announce:o,announcement:d}=z7(),g=No("DndLiveRegion"),[h,f]=j.useState(!1);if(j.useEffect(()=>{f(!0)},[]),H7(j.useMemo(()=>({onDragStart(y){let{active:x}=y;o(e.onDragStart({active:x}))},onDragMove(y){let{active:x,over:S}=y;e.onDragMove&&o(e.onDragMove({active:x,over:S}))},onDragOver(y){let{active:x,over:S}=y;o(e.onDragOver({active:x,over:S}))},onDragEnd(y){let{active:x,over:S}=y;o(e.onDragEnd({active:x,over:S}))},onDragCancel(y){let{active:x,over:S}=y;o(e.onDragCancel({active:x,over:S}))}}),[o,e])),!h)return null;const p=Ke.createElement(Ke.Fragment,null,Ke.createElement($7,{id:a,value:i.draggable}),Ke.createElement(I7,{id:g,announcement:d}));return t?Os.createPortal(p,t):p}var cn;(function(r){r.DragStart="dragStart",r.DragMove="dragMove",r.DragEnd="dragEnd",r.DragCancel="dragCancel",r.DragOver="dragOver",r.RegisterDroppable="registerDroppable",r.SetDroppableDisabled="setDroppableDisabled",r.UnregisterDroppable="unregisterDroppable"})(cn||(cn={}));function wc(){}function iy(r,e){return j.useMemo(()=>({sensor:r,options:e??{}}),[r,e])}function G7(){for(var r=arguments.length,e=new Array(r),t=0;t[...e].filter(a=>a!=null),[...e])}const Ca=Object.freeze({x:0,y:0});function oy(r,e){return Math.sqrt(Math.pow(r.x-e.x,2)+Math.pow(r.y-e.y,2))}function ly(r,e){let{data:{value:t}}=r,{data:{value:a}}=e;return t-a}function F7(r,e){let{data:{value:t}}=r,{data:{value:a}}=e;return a-t}function cy(r){let{left:e,top:t,height:a,width:i}=r;return[{x:e,y:t},{x:e+i,y:t},{x:e,y:t+a},{x:e+i,y:t+a}]}function dy(r,e){if(!r||r.length===0)return null;const[t]=r;return t[e]}function uy(r,e,t){return e===void 0&&(e=r.left),t===void 0&&(t=r.top),{x:e+r.width*.5,y:t+r.height*.5}}const V7=r=>{let{collisionRect:e,droppableRects:t,droppableContainers:a}=r;const i=uy(e,e.left,e.top),o=[];for(const d of a){const{id:g}=d,h=t.get(g);if(h){const f=oy(uy(h),i);o.push({id:g,data:{droppableContainer:d,value:f}})}}return o.sort(ly)},K7=r=>{let{collisionRect:e,droppableRects:t,droppableContainers:a}=r;const i=cy(e),o=[];for(const d of a){const{id:g}=d,h=t.get(g);if(h){const f=cy(h),p=i.reduce((x,S,v)=>x+oy(f[v],S),0),y=Number((p/4).toFixed(4));o.push({id:g,data:{droppableContainer:d,value:y}})}}return o.sort(ly)};function W7(r,e){const t=Math.max(e.top,r.top),a=Math.max(e.left,r.left),i=Math.min(e.left+e.width,r.left+r.width),o=Math.min(e.top+e.height,r.top+r.height),d=i-a,g=o-t;if(a{let{collisionRect:e,droppableRects:t,droppableContainers:a}=r;const i=[];for(const o of a){const{id:d}=o,g=t.get(d);if(g){const h=W7(g,e);h>0&&i.push({id:d,data:{droppableContainer:o,value:h}})}}return i.sort(F7)};function J7(r,e,t){return{...r,scaleX:e&&t?e.width/t.width:1,scaleY:e&&t?e.height/t.height:1}}function gy(r,e){return r&&e?{x:r.left-e.left,y:r.top-e.top}:Ca}function X7(r){return function(t){for(var a=arguments.length,i=new Array(a>1?a-1:0),o=1;o({...d,top:d.top+r*g.y,bottom:d.bottom+r*g.y,left:d.left+r*g.x,right:d.right+r*g.x}),{...t})}}const Q7=X7(1);function Z7(r){if(r.startsWith("matrix3d(")){const e=r.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(r.startsWith("matrix(")){const e=r.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function eC(r,e,t){const a=Z7(e);if(!a)return r;const{scaleX:i,scaleY:o,x:d,y:g}=a,h=r.left-d-(1-i)*parseFloat(t),f=r.top-g-(1-o)*parseFloat(t.slice(t.indexOf(" ")+1)),p=i?r.width/i:r.width,y=o?r.height/o:r.height;return{width:p,height:y,top:f,right:h+p,bottom:f+y,left:h}}const tC={ignoreTransform:!1};function ui(r,e){e===void 0&&(e=tC);let t=r.getBoundingClientRect();if(e.ignoreTransform){const{transform:f,transformOrigin:p}=Ln(r).getComputedStyle(r);f&&(t=eC(t,f,p))}const{top:a,left:i,width:o,height:d,bottom:g,right:h}=t;return{top:a,left:i,width:o,height:d,bottom:g,right:h}}function hy(r){return ui(r,{ignoreTransform:!0})}function nC(r){const e=r.innerWidth,t=r.innerHeight;return{top:0,left:0,right:e,bottom:t,width:e,height:t}}function aC(r,e){return e===void 0&&(e=Ln(r).getComputedStyle(r)),e.position==="fixed"}function sC(r,e){e===void 0&&(e=Ln(r).getComputedStyle(r));const t=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const o=e[i];return typeof o=="string"?t.test(o):!1})}function Sc(r,e){const t=[];function a(i){if(e!=null&&t.length>=e||!i)return t;if(fg(i)&&i.scrollingElement!=null&&!t.includes(i.scrollingElement))return t.push(i.scrollingElement),t;if(!Co(i)||ny(i)||t.includes(i))return t;const o=Ln(r).getComputedStyle(i);return i!==r&&sC(i,o)&&t.push(i),aC(i,o)?t:a(i.parentNode)}return r?a(r):t}function fy(r){const[e]=Sc(r,1);return e??null}function vg(r){return!bc||!r?null:li(r)?r:hg(r)?fg(r)||r===ci(r).scrollingElement?window:Co(r)?r:null:null}function py(r){return li(r)?r.scrollX:r.scrollLeft}function my(r){return li(r)?r.scrollY:r.scrollTop}function wg(r){return{x:py(r),y:my(r)}}var pn;(function(r){r[r.Forward=1]="Forward",r[r.Backward=-1]="Backward"})(pn||(pn={}));function yy(r){return!bc||!r?!1:r===document.scrollingElement}function xy(r){const e={x:0,y:0},t=yy(r)?{height:window.innerHeight,width:window.innerWidth}:{height:r.clientHeight,width:r.clientWidth},a={x:r.scrollWidth-t.width,y:r.scrollHeight-t.height},i=r.scrollTop<=e.y,o=r.scrollLeft<=e.x,d=r.scrollTop>=a.y,g=r.scrollLeft>=a.x;return{isTop:i,isLeft:o,isBottom:d,isRight:g,maxScroll:a,minScroll:e}}const rC={x:.2,y:.2};function iC(r,e,t,a,i){let{top:o,left:d,right:g,bottom:h}=t;a===void 0&&(a=10),i===void 0&&(i=rC);const{isTop:f,isBottom:p,isLeft:y,isRight:x}=xy(r),S={x:0,y:0},v={x:0,y:0},w={height:e.height*i.y,width:e.width*i.x};return!f&&o<=e.top+w.height?(S.y=pn.Backward,v.y=a*Math.abs((e.top+w.height-o)/w.height)):!p&&h>=e.bottom-w.height&&(S.y=pn.Forward,v.y=a*Math.abs((e.bottom-w.height-h)/w.height)),!x&&g>=e.right-w.width?(S.x=pn.Forward,v.x=a*Math.abs((e.right-w.width-g)/w.width)):!y&&d<=e.left+w.width&&(S.x=pn.Backward,v.x=a*Math.abs((e.left+w.width-d)/w.width)),{direction:S,speed:v}}function oC(r){if(r===document.scrollingElement){const{innerWidth:o,innerHeight:d}=window;return{top:0,left:0,right:o,bottom:d,width:o,height:d}}const{top:e,left:t,right:a,bottom:i}=r.getBoundingClientRect();return{top:e,left:t,right:a,bottom:i,width:r.clientWidth,height:r.clientHeight}}function by(r){return r.reduce((e,t)=>di(e,wg(t)),Ca)}function lC(r){return r.reduce((e,t)=>e+py(t),0)}function cC(r){return r.reduce((e,t)=>e+my(t),0)}function dC(r,e){if(e===void 0&&(e=ui),!r)return;const{top:t,left:a,bottom:i,right:o}=e(r);fy(r)&&(i<=0||o<=0||t>=window.innerHeight||a>=window.innerWidth)&&r.scrollIntoView({block:"center",inline:"center"})}const uC=[["x",["left","right"],lC],["y",["top","bottom"],cC]];class Sg{constructor(e,t){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const a=Sc(t),i=by(a);this.rect={...e},this.width=e.width,this.height=e.height;for(const[o,d,g]of uC)for(const h of d)Object.defineProperty(this,h,{get:()=>{const f=g(a),p=i[o]-f;return this.rect[h]+p},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Ao{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(t=>{var a;return(a=this.target)==null?void 0:a.removeEventListener(...t)})},this.target=e}add(e,t,a){var i;(i=this.target)==null||i.addEventListener(e,t,a),this.listeners.push([e,t,a])}}function gC(r){const{EventTarget:e}=Ln(r);return r instanceof e?r:ci(r)}function Cg(r,e){const t=Math.abs(r.x),a=Math.abs(r.y);return typeof e=="number"?Math.sqrt(t**2+a**2)>e:"x"in e&&"y"in e?t>e.x&&a>e.y:"x"in e?t>e.x:"y"in e?a>e.y:!1}var ra;(function(r){r.Click="click",r.DragStart="dragstart",r.Keydown="keydown",r.ContextMenu="contextmenu",r.Resize="resize",r.SelectionChange="selectionchange",r.VisibilityChange="visibilitychange"})(ra||(ra={}));function vy(r){r.preventDefault()}function hC(r){r.stopPropagation()}var ht;(function(r){r.Space="Space",r.Down="ArrowDown",r.Right="ArrowRight",r.Left="ArrowLeft",r.Up="ArrowUp",r.Esc="Escape",r.Enter="Enter",r.Tab="Tab"})(ht||(ht={}));const wy={start:[ht.Space,ht.Enter],cancel:[ht.Esc],end:[ht.Space,ht.Enter,ht.Tab]},fC=(r,e)=>{let{currentCoordinates:t}=e;switch(r.code){case ht.Right:return{...t,x:t.x+25};case ht.Left:return{...t,x:t.x-25};case ht.Down:return{...t,y:t.y+25};case ht.Up:return{...t,y:t.y-25}}};class jg{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:t}}=e;this.props=e,this.listeners=new Ao(ci(t)),this.windowListeners=new Ao(Ln(t)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(ra.Resize,this.handleCancel),this.windowListeners.add(ra.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(ra.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:t}=this.props,a=e.node.current;a&&dC(a),t(Ca)}handleKeyDown(e){if(xg(e)){const{active:t,context:a,options:i}=this.props,{keyboardCodes:o=wy,coordinateGetter:d=fC,scrollBehavior:g="smooth"}=i,{code:h}=e;if(o.end.includes(h)){this.handleEnd(e);return}if(o.cancel.includes(h)){this.handleCancel(e);return}const{collisionRect:f}=a.current,p=f?{x:f.left,y:f.top}:Ca;this.referenceCoordinates||(this.referenceCoordinates=p);const y=d(e,{active:t,context:a.current,currentCoordinates:p});if(y){const x=Eo(y,p),S={x:0,y:0},{scrollableAncestors:v}=a.current;for(const w of v){const k=e.code,{isTop:A,isRight:O,isLeft:N,isBottom:D,maxScroll:$,minScroll:M}=xy(w),z=oC(w),K={x:Math.min(k===ht.Right?z.right-z.width/2:z.right,Math.max(k===ht.Right?z.left:z.left+z.width/2,y.x)),y:Math.min(k===ht.Down?z.bottom-z.height/2:z.bottom,Math.max(k===ht.Down?z.top:z.top+z.height/2,y.y))},pe=k===ht.Right&&!O||k===ht.Left&&!N,we=k===ht.Down&&!D||k===ht.Up&&!A;if(pe&&K.x!==y.x){const J=w.scrollLeft+x.x,be=k===ht.Right&&J<=$.x||k===ht.Left&&J>=M.x;if(be&&!x.y){w.scrollTo({left:J,behavior:g});return}be?S.x=w.scrollLeft-J:S.x=k===ht.Right?w.scrollLeft-$.x:w.scrollLeft-M.x,S.x&&w.scrollBy({left:-S.x,behavior:g});break}else if(we&&K.y!==y.y){const J=w.scrollTop+x.y,be=k===ht.Down&&J<=$.y||k===ht.Up&&J>=M.y;if(be&&!x.x){w.scrollTo({top:J,behavior:g});return}be?S.y=w.scrollTop-J:S.y=k===ht.Down?w.scrollTop-$.y:w.scrollTop-M.y,S.y&&w.scrollBy({top:-S.y,behavior:g});break}}this.handleMove(e,di(Eo(y,this.referenceCoordinates),S))}}}handleMove(e,t){const{onMove:a}=this.props;e.preventDefault(),a(t)}handleEnd(e){const{onEnd:t}=this.props;e.preventDefault(),this.detach(),t()}handleCancel(e){const{onCancel:t}=this.props;e.preventDefault(),this.detach(),t()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}jg.activators=[{eventName:"onKeyDown",handler:(r,e,t)=>{let{keyboardCodes:a=wy,onActivation:i}=e,{active:o}=t;const{code:d}=r.nativeEvent;if(a.start.includes(d)){const g=o.activatorNode.current;return g&&r.target!==g?!1:(r.preventDefault(),i?.({event:r.nativeEvent}),!0)}return!1}}];function Sy(r){return!!(r&&"distance"in r)}function Cy(r){return!!(r&&"delay"in r)}class kg{constructor(e,t,a){var i;a===void 0&&(a=gC(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=t;const{event:o}=e,{target:d}=o;this.props=e,this.events=t,this.document=ci(d),this.documentListeners=new Ao(this.document),this.listeners=new Ao(a),this.windowListeners=new Ao(Ln(d)),this.initialCoordinates=(i=bg(o))!=null?i:Ca,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:e,props:{options:{activationConstraint:t,bypassActivationConstraint:a}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(ra.Resize,this.handleCancel),this.windowListeners.add(ra.DragStart,vy),this.windowListeners.add(ra.VisibilityChange,this.handleCancel),this.windowListeners.add(ra.ContextMenu,vy),this.documentListeners.add(ra.Keydown,this.handleKeydown),t){if(a!=null&&a({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Cy(t)){this.timeoutId=setTimeout(this.handleStart,t.delay),this.handlePending(t);return}if(Sy(t)){this.handlePending(t);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,t){const{active:a,onPending:i}=this.props;i(a,e,this.initialCoordinates,t)}handleStart(){const{initialCoordinates:e}=this,{onStart:t}=this.props;e&&(this.activated=!0,this.documentListeners.add(ra.Click,hC,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(ra.SelectionChange,this.removeTextSelection),t(e))}handleMove(e){var t;const{activated:a,initialCoordinates:i,props:o}=this,{onMove:d,options:{activationConstraint:g}}=o;if(!i)return;const h=(t=bg(e))!=null?t:Ca,f=Eo(i,h);if(!a&&g){if(Sy(g)){if(g.tolerance!=null&&Cg(f,g.tolerance))return this.handleCancel();if(Cg(f,g.distance))return this.handleStart()}if(Cy(g)&&Cg(f,g.tolerance))return this.handleCancel();this.handlePending(g,f);return}e.cancelable&&e.preventDefault(),d(h)}handleEnd(){const{onAbort:e,onEnd:t}=this.props;this.detach(),this.activated||e(this.props.active),t()}handleCancel(){const{onAbort:e,onCancel:t}=this.props;this.detach(),this.activated||e(this.props.active),t()}handleKeydown(e){e.code===ht.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const pC={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Ng extends kg{constructor(e){const{event:t}=e,a=ci(t.target);super(e,pC,a)}}Ng.activators=[{eventName:"onPointerDown",handler:(r,e)=>{let{nativeEvent:t}=r,{onActivation:a}=e;return!t.isPrimary||t.button!==0?!1:(a?.({event:t}),!0)}}];const mC={move:{name:"mousemove"},end:{name:"mouseup"}};var Eg;(function(r){r[r.RightClick=2]="RightClick"})(Eg||(Eg={}));class yC extends kg{constructor(e){super(e,mC,ci(e.event.target))}}yC.activators=[{eventName:"onMouseDown",handler:(r,e)=>{let{nativeEvent:t}=r,{onActivation:a}=e;return t.button===Eg.RightClick?!1:(a?.({event:t}),!0)}}];const _g={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class xC extends kg{constructor(e){super(e,_g)}static setup(){return window.addEventListener(_g.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(_g.move.name,e)};function e(){}}}xC.activators=[{eventName:"onTouchStart",handler:(r,e)=>{let{nativeEvent:t}=r,{onActivation:a}=e;const{touches:i}=t;return i.length>1?!1:(a?.({event:t}),!0)}}];var To;(function(r){r[r.Pointer=0]="Pointer",r[r.DraggableRect=1]="DraggableRect"})(To||(To={}));var Cc;(function(r){r[r.TreeOrder=0]="TreeOrder",r[r.ReversedTreeOrder=1]="ReversedTreeOrder"})(Cc||(Cc={}));function bC(r){let{acceleration:e,activator:t=To.Pointer,canScroll:a,draggingRect:i,enabled:o,interval:d=5,order:g=Cc.TreeOrder,pointerCoordinates:h,scrollableAncestors:f,scrollableAncestorRects:p,delta:y,threshold:x}=r;const S=wC({delta:y,disabled:!o}),[v,w]=D7(),k=j.useRef({x:0,y:0}),A=j.useRef({x:0,y:0}),O=j.useMemo(()=>{switch(t){case To.Pointer:return h?{top:h.y,bottom:h.y,left:h.x,right:h.x}:null;case To.DraggableRect:return i}},[t,i,h]),N=j.useRef(null),D=j.useCallback(()=>{const M=N.current;if(!M)return;const z=k.current.x*A.current.x,K=k.current.y*A.current.y;M.scrollBy(z,K)},[]),$=j.useMemo(()=>g===Cc.TreeOrder?[...f].reverse():f,[g,f]);j.useEffect(()=>{if(!o||!f.length||!O){w();return}for(const M of $){if(a?.(M)===!1)continue;const z=f.indexOf(M),K=p[z];if(!K)continue;const{direction:pe,speed:we}=iC(M,K,O,e,x);for(const J of["x","y"])S[J][pe[J]]||(we[J]=0,pe[J]=0);if(we.x>0||we.y>0){w(),N.current=M,v(D,d),k.current=we,A.current=pe;return}}k.current={x:0,y:0},A.current={x:0,y:0},w()},[e,D,a,w,o,d,JSON.stringify(O),JSON.stringify(S),v,f,$,p,JSON.stringify(x)])}const vC={x:{[pn.Backward]:!1,[pn.Forward]:!1},y:{[pn.Backward]:!1,[pn.Forward]:!1}};function wC(r){let{delta:e,disabled:t}=r;const a=mg(e);return ko(i=>{if(t||!a||!i)return vC;const o={x:Math.sign(e.x-a.x),y:Math.sign(e.y-a.y)};return{x:{[pn.Backward]:i.x[pn.Backward]||o.x===-1,[pn.Forward]:i.x[pn.Forward]||o.x===1},y:{[pn.Backward]:i.y[pn.Backward]||o.y===-1,[pn.Forward]:i.y[pn.Forward]||o.y===1}}},[t,e,a])}function SC(r,e){const t=e!=null?r.get(e):void 0,a=t?t.node.current:null;return ko(i=>{var o;return e==null?null:(o=a??i)!=null?o:null},[a,e])}function CC(r,e){return j.useMemo(()=>r.reduce((t,a)=>{const{sensor:i}=a,o=i.activators.map(d=>({eventName:d.eventName,handler:e(d.handler,a)}));return[...t,...o]},[]),[r,e])}var Do;(function(r){r[r.Always=0]="Always",r[r.BeforeDragging=1]="BeforeDragging",r[r.WhileDragging=2]="WhileDragging"})(Do||(Do={}));var Ag;(function(r){r.Optimized="optimized"})(Ag||(Ag={}));const jy=new Map;function jC(r,e){let{dragging:t,dependencies:a,config:i}=e;const[o,d]=j.useState(null),{frequency:g,measure:h,strategy:f}=i,p=j.useRef(r),y=k(),x=jo(y),S=j.useCallback(function(A){A===void 0&&(A=[]),!x.current&&d(O=>O===null?A:O.concat(A.filter(N=>!O.includes(N))))},[x]),v=j.useRef(null),w=ko(A=>{if(y&&!t)return jy;if(!A||A===jy||p.current!==r||o!=null){const O=new Map;for(let N of r){if(!N)continue;if(o&&o.length>0&&!o.includes(N.id)&&N.rect.current){O.set(N.id,N.rect.current);continue}const D=N.node.current,$=D?new Sg(h(D),D):null;N.rect.current=$,$&&O.set(N.id,$)}return O}return A},[r,o,t,y,h]);return j.useEffect(()=>{p.current=r},[r]),j.useEffect(()=>{y||S()},[t,y]),j.useEffect(()=>{o&&o.length>0&&d(null)},[JSON.stringify(o)]),j.useEffect(()=>{y||typeof g!="number"||v.current!==null||(v.current=setTimeout(()=>{S(),v.current=null},g))},[g,y,S,...a]),{droppableRects:w,measureDroppableContainers:S,measuringScheduled:o!=null};function k(){switch(f){case Do.Always:return!1;case Do.BeforeDragging:return t;default:return!t}}}function ky(r,e){return ko(t=>r?t||(typeof e=="function"?e(r):r):null,[e,r])}function kC(r,e){return ky(r,e)}function NC(r){let{callback:e,disabled:t}=r;const a=pg(e),i=j.useMemo(()=>{if(t||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:o}=window;return new o(a)},[a,t]);return j.useEffect(()=>()=>i?.disconnect(),[i]),i}function jc(r){let{callback:e,disabled:t}=r;const a=pg(e),i=j.useMemo(()=>{if(t||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:o}=window;return new o(a)},[t]);return j.useEffect(()=>()=>i?.disconnect(),[i]),i}function EC(r){return new Sg(ui(r),r)}function Ny(r,e,t){e===void 0&&(e=EC);const[a,i]=j.useState(null);function o(){i(h=>{if(!r)return null;if(r.isConnected===!1){var f;return(f=h??t)!=null?f:null}const p=e(r);return JSON.stringify(h)===JSON.stringify(p)?h:p})}const d=NC({callback(h){if(r)for(const f of h){const{type:p,target:y}=f;if(p==="childList"&&y instanceof HTMLElement&&y.contains(r)){o();break}}}}),g=jc({callback:o});return Ba(()=>{o(),r?(g?.observe(r),d?.observe(document.body,{childList:!0,subtree:!0})):(g?.disconnect(),d?.disconnect())},[r]),a}function _C(r){const e=ky(r);return gy(r,e)}const Ey=[];function AC(r){const e=j.useRef(r),t=ko(a=>r?a&&a!==Ey&&r&&e.current&&r.parentNode===e.current.parentNode?a:Sc(r):Ey,[r]);return j.useEffect(()=>{e.current=r},[r]),t}function TC(r){const[e,t]=j.useState(null),a=j.useRef(r),i=j.useCallback(o=>{const d=vg(o.target);d&&t(g=>g?(g.set(d,wg(d)),new Map(g)):null)},[]);return j.useEffect(()=>{const o=a.current;if(r!==o){d(o);const g=r.map(h=>{const f=vg(h);return f?(f.addEventListener("scroll",i,{passive:!0}),[f,wg(f)]):null}).filter(h=>h!=null);t(g.length?new Map(g):null),a.current=r}return()=>{d(r),d(o)};function d(g){g.forEach(h=>{const f=vg(h);f?.removeEventListener("scroll",i)})}},[i,r]),j.useMemo(()=>r.length?e?Array.from(e.values()).reduce((o,d)=>di(o,d),Ca):by(r):Ca,[r,e])}function _y(r,e){e===void 0&&(e=[]);const t=j.useRef(null);return j.useEffect(()=>{t.current=null},e),j.useEffect(()=>{const a=r!==Ca;a&&!t.current&&(t.current=r),!a&&t.current&&(t.current=null)},[r]),t.current?Eo(r,t.current):Ca}function DC(r){j.useEffect(()=>{if(!bc)return;const e=r.map(t=>{let{sensor:a}=t;return a.setup==null?void 0:a.setup()});return()=>{for(const t of e)t?.()}},r.map(e=>{let{sensor:t}=e;return t}))}function RC(r,e){return j.useMemo(()=>r.reduce((t,a)=>{let{eventName:i,handler:o}=a;return t[i]=d=>{o(d,e)},t},{}),[r,e])}function Ay(r){return j.useMemo(()=>r?nC(r):null,[r])}const Ty=[];function OC(r,e){e===void 0&&(e=ui);const[t]=r,a=Ay(t?Ln(t):null),[i,o]=j.useState(Ty);function d(){o(()=>r.length?r.map(h=>yy(h)?a:new Sg(e(h),h)):Ty)}const g=jc({callback:d});return Ba(()=>{g?.disconnect(),d(),r.forEach(h=>g?.observe(h))},[r]),i}function LC(r){if(!r)return null;if(r.children.length>1)return r;const e=r.children[0];return Co(e)?e:r}function MC(r){let{measure:e}=r;const[t,a]=j.useState(null),i=j.useCallback(f=>{for(const{target:p}of f)if(Co(p)){a(y=>{const x=e(p);return y?{...y,width:x.width,height:x.height}:x});break}},[e]),o=jc({callback:i}),d=j.useCallback(f=>{const p=LC(f);o?.disconnect(),p&&o?.observe(p),a(p?e(p):null)},[e,o]),[g,h]=vc(d);return j.useMemo(()=>({nodeRef:g,rect:t,setRef:h}),[t,g,h])}const $C=[{sensor:Ng,options:{}},{sensor:jg,options:{}}],IC={current:{}},kc={draggable:{measure:hy},droppable:{measure:hy,strategy:Do.WhileDragging,frequency:Ag.Optimized},dragOverlay:{measure:ui}};class Ro extends Map{get(e){var t;return e!=null&&(t=super.get(e))!=null?t:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:t}=e;return!t})}getNodeFor(e){var t,a;return(t=(a=this.get(e))==null?void 0:a.node.current)!=null?t:void 0}}const zC={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Ro,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:wc},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:kc,measureDroppableContainers:wc,windowRect:null,measuringScheduled:!1},HC={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:wc,draggableNodes:new Map,over:null,measureDroppableContainers:wc},Nc=j.createContext(HC),Dy=j.createContext(zC);function PC(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Ro}}}function BC(r,e){switch(e.type){case cn.DragStart:return{...r,draggable:{...r.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case cn.DragMove:return r.draggable.active==null?r:{...r,draggable:{...r.draggable,translate:{x:e.coordinates.x-r.draggable.initialCoordinates.x,y:e.coordinates.y-r.draggable.initialCoordinates.y}}};case cn.DragEnd:case cn.DragCancel:return{...r,draggable:{...r.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case cn.RegisterDroppable:{const{element:t}=e,{id:a}=t,i=new Ro(r.droppable.containers);return i.set(a,t),{...r,droppable:{...r.droppable,containers:i}}}case cn.SetDroppableDisabled:{const{id:t,key:a,disabled:i}=e,o=r.droppable.containers.get(t);if(!o||a!==o.key)return r;const d=new Ro(r.droppable.containers);return d.set(t,{...o,disabled:i}),{...r,droppable:{...r.droppable,containers:d}}}case cn.UnregisterDroppable:{const{id:t,key:a}=e,i=r.droppable.containers.get(t);if(!i||a!==i.key)return r;const o=new Ro(r.droppable.containers);return o.delete(t),{...r,droppable:{...r.droppable,containers:o}}}default:return r}}function UC(r){let{disabled:e}=r;const{active:t,activatorEvent:a,draggableNodes:i}=j.useContext(Nc),o=mg(a),d=mg(t?.id);return j.useEffect(()=>{if(!e&&!a&&o&&d!=null){if(!xg(o)||document.activeElement===o.target)return;const g=i.get(d);if(!g)return;const{activatorNode:h,node:f}=g;if(!h.current&&!f.current)return;requestAnimationFrame(()=>{for(const p of[h.current,f.current]){if(!p)continue;const y=L7(p);if(y){y.focus();break}}})}},[a,e,i,d,o]),null}function qC(r,e){let{transform:t,...a}=e;return r!=null&&r.length?r.reduce((i,o)=>o({transform:i,...a}),t):t}function GC(r){return j.useMemo(()=>({draggable:{...kc.draggable,...r?.draggable},droppable:{...kc.droppable,...r?.droppable},dragOverlay:{...kc.dragOverlay,...r?.dragOverlay}}),[r?.draggable,r?.droppable,r?.dragOverlay])}function FC(r){let{activeNode:e,measure:t,initialRect:a,config:i=!0}=r;const o=j.useRef(!1),{x:d,y:g}=typeof i=="boolean"?{x:i,y:i}:i;Ba(()=>{if(!d&&!g||!e){o.current=!1;return}if(o.current||!a)return;const f=e?.node.current;if(!f||f.isConnected===!1)return;const p=t(f),y=gy(p,a);if(d||(y.x=0),g||(y.y=0),o.current=!0,Math.abs(y.x)>0||Math.abs(y.y)>0){const x=fy(f);x&&x.scrollBy({top:y.y,left:y.x})}},[e,d,g,a,t])}const Ry=j.createContext({...Ca,scaleX:1,scaleY:1});var Ls;(function(r){r[r.Uninitialized=0]="Uninitialized",r[r.Initializing=1]="Initializing",r[r.Initialized=2]="Initialized"})(Ls||(Ls={}));const VC=j.memo(function(e){var t,a,i,o;let{id:d,accessibility:g,autoScroll:h=!0,children:f,sensors:p=$C,collisionDetection:y=Y7,measuring:x,modifiers:S,...v}=e;const w=j.useReducer(BC,void 0,PC),[k,A]=w,[O,N]=P7(),[D,$]=j.useState(Ls.Uninitialized),M=D===Ls.Initialized,{draggable:{active:z,nodes:K,translate:pe},droppable:{containers:we}}=k,J=z!=null?K.get(z):null,be=j.useRef({initial:null,translated:null}),le=j.useMemo(()=>{var Ue;return z!=null?{id:z,data:(Ue=J?.data)!=null?Ue:IC,rect:be}:null},[z,J]),de=j.useRef(null),[je,W]=j.useState(null),[ge,ne]=j.useState(null),X=jo(v,Object.values(v)),ae=No("DndDescribedBy",d),R=j.useMemo(()=>we.getEnabled(),[we]),U=GC(x),{droppableRects:re,measureDroppableContainers:ye,measuringScheduled:oe}=jC(R,{dragging:M,dependencies:[pe.x,pe.y],config:U.droppable}),ke=SC(K,z),Oe=j.useMemo(()=>ge?bg(ge):null,[ge]),Te=Pe(),qe=kC(ke,U.draggable.measure);FC({activeNode:z!=null?K.get(z):null,config:Te.layoutShiftCompensation,initialRect:qe,measure:U.draggable.measure});const Ie=Ny(ke,U.draggable.measure,qe),Nt=Ny(ke?ke.parentElement:null),Tt=j.useRef({activatorEvent:null,active:null,activeNode:ke,collisionRect:null,collisions:null,droppableRects:re,draggableNodes:K,draggingNode:null,draggingNodeRect:null,droppableContainers:we,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Xt=we.getNodeFor((t=Tt.current.over)==null?void 0:t.id),Ot=MC({measure:U.dragOverlay.measure}),Qt=(a=Ot.nodeRef.current)!=null?a:ke,It=M?(i=Ot.rect)!=null?i:Ie:null,Tn=!!(Ot.nodeRef.current&&Ot.rect),Ce=_C(Tn?null:Ie),Ge=Ay(Qt?Ln(Qt):null),at=AC(M?Xt??ke:null),ft=OC(at),bt=qC(S,{transform:{x:pe.x-Ce.x,y:pe.y-Ce.y,scaleX:1,scaleY:1},activatorEvent:ge,active:le,activeNodeRect:Ie,containerNodeRect:Nt,draggingNodeRect:It,over:Tt.current.over,overlayNodeRect:Ot.rect,scrollableAncestors:at,scrollableAncestorRects:ft,windowRect:Ge}),Et=Oe?di(Oe,pe):null,pt=TC(at),tt=_y(pt),bn=_y(pt,[Ie]),wt=di(bt,tt),At=It?Q7(It,bt):null,qt=le&&At?y({active:le,collisionRect:At,droppableRects:re,droppableContainers:R,pointerCoordinates:Et}):null,Yn=dy(qt,"id"),[dn,Ta]=j.useState(null),ca=Tn?bt:di(bt,bn),V=J7(ca,(o=dn?.rect)!=null?o:null,Ie),ve=j.useRef(null),me=j.useCallback((Ue,Le)=>{let{sensor:Fe,options:We}=Le;if(de.current==null)return;const Je=K.get(de.current);if(!Je)return;const st=Ue.nativeEvent,Be=new Fe({active:de.current,activeNode:Je,event:st,options:We,context:Tt,onAbort($e){if(!K.get($e))return;const{onDragAbort:zt}=X.current,tn={id:$e};zt?.(tn),O({type:"onDragAbort",event:tn})},onPending($e,mt,zt,tn){if(!K.get($e))return;const{onDragPending:Jn}=X.current,Xn={id:$e,constraint:mt,initialCoordinates:zt,offset:tn};Jn?.(Xn),O({type:"onDragPending",event:Xn})},onStart($e){const mt=de.current;if(mt==null)return;const zt=K.get(mt);if(!zt)return;const{onDragStart:tn}=X.current,yn={activatorEvent:st,active:{id:mt,data:zt.data,rect:be}};Os.unstable_batchedUpdates(()=>{tn?.(yn),$(Ls.Initializing),A({type:cn.DragStart,initialCoordinates:$e,active:mt}),O({type:"onDragStart",event:yn}),W(ve.current),ne(st)})},onMove($e){A({type:cn.DragMove,coordinates:$e})},onEnd:De(cn.DragEnd),onCancel:De(cn.DragCancel)});ve.current=Be;function De($e){return async function(){const{active:zt,collisions:tn,over:yn,scrollAdjustedTranslate:Jn}=Tt.current;let Xn=null;if(zt&&Jn){const{cancelDrop:Ga}=X.current;Xn={activatorEvent:st,active:zt,collisions:tn,delta:Jn,over:yn},$e===cn.DragEnd&&typeof Ga=="function"&&await Promise.resolve(Ga(Xn))&&($e=cn.DragCancel)}de.current=null,Os.unstable_batchedUpdates(()=>{A({type:$e}),$(Ls.Uninitialized),Ta(null),W(null),ne(null),ve.current=null;const Ga=$e===cn.DragEnd?"onDragEnd":"onDragCancel";if(Xn){const In=X.current[Ga];In?.(Xn),O({type:Ga,event:Xn})}})}}},[K]),te=j.useCallback((Ue,Le)=>(Fe,We)=>{const Je=Fe.nativeEvent,st=K.get(We);if(de.current!==null||!st||Je.dndKit||Je.defaultPrevented)return;const Be={active:st};Ue(Fe,Le.options,Be)===!0&&(Je.dndKit={capturedBy:Le.sensor},de.current=We,me(Fe,Le))},[K,me]),_e=CC(p,te);DC(p),Ba(()=>{Ie&&D===Ls.Initializing&&$(Ls.Initialized)},[Ie,D]),j.useEffect(()=>{const{onDragMove:Ue}=X.current,{active:Le,activatorEvent:Fe,collisions:We,over:Je}=Tt.current;if(!Le||!Fe)return;const st={active:Le,activatorEvent:Fe,collisions:We,delta:{x:wt.x,y:wt.y},over:Je};Os.unstable_batchedUpdates(()=>{Ue?.(st),O({type:"onDragMove",event:st})})},[wt.x,wt.y]),j.useEffect(()=>{const{active:Ue,activatorEvent:Le,collisions:Fe,droppableContainers:We,scrollAdjustedTranslate:Je}=Tt.current;if(!Ue||de.current==null||!Le||!Je)return;const{onDragOver:st}=X.current,Be=We.get(Yn),De=Be&&Be.rect.current?{id:Be.id,rect:Be.rect.current,data:Be.data,disabled:Be.disabled}:null,$e={active:Ue,activatorEvent:Le,collisions:Fe,delta:{x:Je.x,y:Je.y},over:De};Os.unstable_batchedUpdates(()=>{Ta(De),st?.($e),O({type:"onDragOver",event:$e})})},[Yn]),Ba(()=>{Tt.current={activatorEvent:ge,active:le,activeNode:ke,collisionRect:At,collisions:qt,droppableRects:re,draggableNodes:K,draggingNode:Qt,draggingNodeRect:It,droppableContainers:we,over:dn,scrollableAncestors:at,scrollAdjustedTranslate:wt},be.current={initial:It,translated:At}},[le,ke,qt,At,K,Qt,It,re,we,dn,at,wt]),bC({...Te,delta:pe,draggingRect:At,pointerCoordinates:Et,scrollableAncestors:at,scrollableAncestorRects:ft});const Ae=j.useMemo(()=>({active:le,activeNode:ke,activeNodeRect:Ie,activatorEvent:ge,collisions:qt,containerNodeRect:Nt,dragOverlay:Ot,draggableNodes:K,droppableContainers:we,droppableRects:re,over:dn,measureDroppableContainers:ye,scrollableAncestors:at,scrollableAncestorRects:ft,measuringConfiguration:U,measuringScheduled:oe,windowRect:Ge}),[le,ke,Ie,ge,qt,Nt,Ot,K,we,re,dn,ye,at,ft,U,oe,Ge]),Re=j.useMemo(()=>({activatorEvent:ge,activators:_e,active:le,activeNodeRect:Ie,ariaDescribedById:{draggable:ae},dispatch:A,draggableNodes:K,over:dn,measureDroppableContainers:ye}),[ge,_e,le,Ie,A,ae,K,dn,ye]);return Ke.createElement(ry.Provider,{value:N},Ke.createElement(Nc.Provider,{value:Re},Ke.createElement(Dy.Provider,{value:Ae},Ke.createElement(Ry.Provider,{value:V},f)),Ke.createElement(UC,{disabled:g?.restoreFocus===!1})),Ke.createElement(q7,{...g,hiddenTextDescribedById:ae}));function Pe(){const Ue=je?.autoScrollEnabled===!1,Le=typeof h=="object"?h.enabled===!1:h===!1,Fe=M&&!Ue&&!Le;return typeof h=="object"?{...h,enabled:Fe}:{enabled:Fe}}}),KC=j.createContext(null),Oy="button",WC="Draggable";function YC(r){let{id:e,data:t,disabled:a=!1,attributes:i}=r;const o=No(WC),{activators:d,activatorEvent:g,active:h,activeNodeRect:f,ariaDescribedById:p,draggableNodes:y,over:x}=j.useContext(Nc),{role:S=Oy,roleDescription:v="draggable",tabIndex:w=0}=i??{},k=h?.id===e,A=j.useContext(k?Ry:KC),[O,N]=vc(),[D,$]=vc(),M=RC(d,e),z=jo(t);Ba(()=>(y.set(e,{id:e,key:o,node:O,activatorNode:D,data:z}),()=>{const pe=y.get(e);pe&&pe.key===o&&y.delete(e)}),[y,e]);const K=j.useMemo(()=>({role:S,tabIndex:w,"aria-disabled":a,"aria-pressed":k&&S===Oy?!0:void 0,"aria-roledescription":v,"aria-describedby":p.draggable}),[a,S,w,k,v,p.draggable]);return{active:h,activatorEvent:g,activeNodeRect:f,attributes:K,isDragging:k,listeners:a?void 0:M,node:O,over:x,setNodeRef:N,setActivatorNodeRef:$,transform:A}}function JC(){return j.useContext(Dy)}const XC="Droppable",QC={timeout:25};function ZC(r){let{data:e,disabled:t=!1,id:a,resizeObserverConfig:i}=r;const o=No(XC),{active:d,dispatch:g,over:h,measureDroppableContainers:f}=j.useContext(Nc),p=j.useRef({disabled:t}),y=j.useRef(!1),x=j.useRef(null),S=j.useRef(null),{disabled:v,updateMeasurementsFor:w,timeout:k}={...QC,...i},A=jo(w??a),O=j.useCallback(()=>{if(!y.current){y.current=!0;return}S.current!=null&&clearTimeout(S.current),S.current=setTimeout(()=>{f(Array.isArray(A.current)?A.current:[A.current]),S.current=null},k)},[k]),N=jc({callback:O,disabled:v||!d}),D=j.useCallback((K,pe)=>{N&&(pe&&(N.unobserve(pe),y.current=!1),K&&N.observe(K))},[N]),[$,M]=vc(D),z=jo(e);return j.useEffect(()=>{!N||!$.current||(N.disconnect(),y.current=!1,N.observe($.current))},[$,N]),j.useEffect(()=>(g({type:cn.RegisterDroppable,element:{id:a,key:o,disabled:t,node:$,rect:x,data:z}}),()=>g({type:cn.UnregisterDroppable,key:o,id:a})),[a]),j.useEffect(()=>{t!==p.current.disabled&&(g({type:cn.SetDroppableDisabled,id:a,key:o,disabled:t}),p.current.disabled=t)},[a,o,t,g]),{active:d,rect:x,isOver:h?.id===a,node:$,over:h,setNodeRef:M}}function Tg(r,e,t){const a=r.slice();return a.splice(t<0?a.length+t:t,0,a.splice(e,1)[0]),a}function ej(r,e){return r.reduce((t,a,i)=>{const o=e.get(a);return o&&(t[i]=o),t},Array(r.length))}function Ec(r){return r!==null&&r>=0}function tj(r,e){if(r===e)return!0;if(r.length!==e.length)return!1;for(let t=0;t{var e;let{rects:t,activeNodeRect:a,activeIndex:i,overIndex:o,index:d}=r;const g=(e=t[i])!=null?e:a;if(!g)return null;const h=sj(t,d,i);if(d===i){const f=t[o];return f?{x:ii&&d<=o?{x:-g.width-h,y:0,..._c}:d=o?{x:g.width+h,y:0,..._c}:{x:0,y:0,..._c}};function sj(r,e,t){const a=r[e],i=r[e-1],o=r[e+1];return!a||!i&&!o?0:t{let{rects:e,activeIndex:t,overIndex:a,index:i}=r;const o=Tg(e,a,t),d=e[i],g=o[i];return!g||!d?null:{x:g.left-d.left,y:g.top-d.top,scaleX:g.width/d.width,scaleY:g.height/d.height}},Ac={scaleX:1,scaleY:1},rj=r=>{var e;let{activeIndex:t,activeNodeRect:a,index:i,rects:o,overIndex:d}=r;const g=(e=o[t])!=null?e:a;if(!g)return null;if(i===t){const f=o[d];return f?{x:0,y:tt&&i<=d?{x:0,y:-g.height-h,...Ac}:i=d?{x:0,y:g.height+h,...Ac}:{x:0,y:0,...Ac}};function ij(r,e,t){const a=r[e],i=r[e-1],o=r[e+1];return a?ta.map(M=>typeof M=="object"&&"id"in M?M.id:M),[a]),v=d!=null,w=d?S.indexOf(d.id):-1,k=f?S.indexOf(f.id):-1,A=j.useRef(S),O=!tj(S,A.current),N=k!==-1&&w===-1||O,D=nj(o);Ba(()=>{O&&v&&p(S)},[O,S,v,p]),j.useEffect(()=>{A.current=S},[S]);const $=j.useMemo(()=>({activeIndex:w,containerId:y,disabled:D,disableTransforms:N,items:S,overIndex:k,useDragOverlay:x,sortedRects:ej(S,h),strategy:i}),[w,y,D.draggable,D.droppable,N,S,k,h,x,i]);return Ke.createElement(My.Provider,{value:$},e)}const lj=r=>{let{id:e,items:t,activeIndex:a,overIndex:i}=r;return Tg(t,a,i).indexOf(e)},cj=r=>{let{containerId:e,isSorting:t,wasDragging:a,index:i,items:o,newIndex:d,previousItems:g,previousContainerId:h,transition:f}=r;return!f||!a||g!==o&&i===d?!1:t?!0:d!==i&&e===h},dj={duration:200,easing:"ease"},$y="transform",uj=_o.Transition.toString({property:$y,duration:0,easing:"linear"}),gj={roleDescription:"sortable"};function hj(r){let{disabled:e,index:t,node:a,rect:i}=r;const[o,d]=j.useState(null),g=j.useRef(t);return Ba(()=>{if(!e&&t!==g.current&&a.current){const h=i.current;if(h){const f=ui(a.current,{ignoreTransform:!0}),p={x:h.left-f.left,y:h.top-f.top,scaleX:h.width/f.width,scaleY:h.height/f.height};(p.x||p.y)&&d(p)}}t!==g.current&&(g.current=t)},[e,t,a,i]),j.useEffect(()=>{o&&d(null)},[o]),o}function fj(r){let{animateLayoutChanges:e=cj,attributes:t,disabled:a,data:i,getNewIndex:o=lj,id:d,strategy:g,resizeObserverConfig:h,transition:f=dj}=r;const{items:p,containerId:y,activeIndex:x,disabled:S,disableTransforms:v,sortedRects:w,overIndex:k,useDragOverlay:A,strategy:O}=j.useContext(My),N=pj(a,S),D=p.indexOf(d),$=j.useMemo(()=>({sortable:{containerId:y,index:D,items:p},...i}),[y,i,D,p]),M=j.useMemo(()=>p.slice(p.indexOf(d)),[p,d]),{rect:z,node:K,isOver:pe,setNodeRef:we}=ZC({id:d,data:$,disabled:N.droppable,resizeObserverConfig:{updateMeasurementsFor:M,...h}}),{active:J,activatorEvent:be,activeNodeRect:le,attributes:de,setNodeRef:je,listeners:W,isDragging:ge,over:ne,setActivatorNodeRef:X,transform:ae}=YC({id:d,data:$,attributes:{...gj,...t},disabled:N.draggable}),R=T7(we,je),U=!!J,re=U&&!v&&Ec(x)&&Ec(k),ye=!A&&ge,oe=ye&&re?ae:null,Oe=re?oe??(g??O)({rects:w,activeNodeRect:le,activeIndex:x,overIndex:k,index:D}):null,Te=Ec(x)&&Ec(k)?o({id:d,items:p,activeIndex:x,overIndex:k}):D,qe=J?.id,Ie=j.useRef({activeId:qe,items:p,newIndex:Te,containerId:y}),Nt=p!==Ie.current.items,Tt=e({active:J,containerId:y,isDragging:ge,isSorting:U,id:d,index:D,items:p,newIndex:Ie.current.newIndex,previousItems:Ie.current.items,previousContainerId:Ie.current.containerId,transition:f,wasDragging:Ie.current.activeId!=null}),Xt=hj({disabled:!Tt,index:D,node:K,rect:z});return j.useEffect(()=>{U&&Ie.current.newIndex!==Te&&(Ie.current.newIndex=Te),y!==Ie.current.containerId&&(Ie.current.containerId=y),p!==Ie.current.items&&(Ie.current.items=p)},[U,Te,y,p]),j.useEffect(()=>{if(qe===Ie.current.activeId)return;if(qe!=null&&Ie.current.activeId==null){Ie.current.activeId=qe;return}const Qt=setTimeout(()=>{Ie.current.activeId=qe},50);return()=>clearTimeout(Qt)},[qe]),{active:J,activeIndex:x,attributes:de,data:$,rect:z,index:D,newIndex:Te,items:p,isOver:pe,isSorting:U,isDragging:ge,listeners:W,node:K,overIndex:k,over:ne,setNodeRef:R,setActivatorNodeRef:X,setDroppableNodeRef:we,setDraggableNodeRef:je,transform:Xt??Oe,transition:Ot()};function Ot(){if(Xt||Nt&&Ie.current.newIndex===D)return uj;if(!(ye&&!xg(be)||!f)&&(U||Tt))return _o.Transition.toString({...f,property:$y})}}function pj(r,e){var t,a;return typeof r=="boolean"?{draggable:r,droppable:!1}:{draggable:(t=r?.draggable)!=null?t:e.draggable,droppable:(a=r?.droppable)!=null?a:e.droppable}}function Tc(r){if(!r)return!1;const e=r.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}const mj=[ht.Down,ht.Right,ht.Up,ht.Left],yj=(r,e)=>{let{context:{active:t,collisionRect:a,droppableRects:i,droppableContainers:o,over:d,scrollableAncestors:g}}=e;if(mj.includes(r.code)){if(r.preventDefault(),!t||!a)return;const h=[];o.getEnabled().forEach(y=>{if(!y||y!=null&&y.disabled)return;const x=i.get(y.id);if(x)switch(r.code){case ht.Down:a.topx.top&&h.push(y);break;case ht.Left:a.left>x.left&&h.push(y);break;case ht.Right:a.left1&&(p=f[1].id),p!=null){const y=o.get(t.id),x=o.get(p),S=x?i.get(x.id):null,v=x?.node.current;if(v&&S&&y&&x){const k=Sc(v).some((M,z)=>g[z]!==M),A=Iy(y,x),O=xj(y,x),N=k||!A?{x:0,y:0}:{x:O?a.width-S.width:0,y:O?a.height-S.height:0},D={x:S.left,y:S.top};return N.x&&N.y?D:Eo(D,N)}}}};function Iy(r,e){return!Tc(r)||!Tc(e)?!1:r.data.current.sortable.containerId===e.data.current.sortable.containerId}function xj(r,e){return!Tc(r)||!Tc(e)||!Iy(r,e)?!1:r.data.current.sortable.index{const g=j.useId(),h=j.useRef({inProgress:!1,lastSortTime:0,lastActiveId:null}),f=G7(iy(Ng,{activationConstraint:{distance:5}}),iy(jg,{coordinateGetter:yj})),p=j.useCallback(S=>{h.current={inProgress:!0,lastSortTime:Date.now(),lastActiveId:S.active.id},o?.({activeId:S.active.id})},[o]),y=j.useCallback(S=>{const{active:v,over:w}=S,k=Date.now();if(!w||v.id===w.id){h.current.inProgress=!1;return}const{lastSortTime:A,lastActiveId:O,inProgress:N}=h.current;if(O===v.id&&k-A<500&&!N)return;h.current={inProgress:!1,lastSortTime:k,lastActiveId:v.id};const D=r.findIndex(M=>String(M[e])===String(v.id)),$=r.findIndex(M=>String(M[e])===String(w.id));if(D!==-1&&$!==-1&&D!==$){const M=Tg(r,D,$);i?.(M,{oldIndex:D,newIndex:$})}},[r,e,i]),x=r.map(S=>String(S[e]));return l.jsx(VC,{id:g,sensors:f,collisionDetection:V7,onDragStart:p,onDragEnd:y,children:l.jsx(oj,{items:x,strategy:bj[t],children:a})},d!==void 0?`${g}-v${d}`:g)},zy=j.createContext(null),wj=({value:r,children:e})=>l.jsx(zy.Provider,{value:r,children:e}),Sj=()=>j.useContext(zy),Cj=({id:r,handle:e,as:t="div",children:a})=>{const{attributes:i,listeners:o,setNodeRef:d,transform:g,transition:h,isDragging:f}=fj({id:r}),p={transform:_o.Transform.toString(g),transition:h,opacity:f?.5:1,position:"relative"};return l.jsx(t,{ref:d,style:p,...i,...e?{}:o,"data-sortable-item":!0,"data-sortable-id":String(r),"data-dragging":f,children:l.jsx(wj,{value:{listeners:o,handle:e,isDragging:f},children:a})})},vt=it("DynamicRenderer");function rs(){try{return window.G7Core?.devTools}catch{return}}function jj(r){const e=Object.keys(r);return e.length>0&&e.every(t=>/^\d+$/.test(t))}const ja=(r,e)=>{const t=["errors"],a={...r};for(const i of Object.keys(e)){const o=e[i],d=r[i];if(o===null){a[i]=null;continue}if(t.includes(i)){a[i]=o;continue}if(Array.isArray(o)){a[i]=o;continue}if(Array.isArray(d)&&o!==null&&typeof o=="object"&&!Array.isArray(o)&&jj(o)){const g=Object.keys(o).map(f=>parseInt(f,10));if((g.length>0?Math.max(...g):0)>=d.length+g.length+10)a[i]={...o};else{const f=[...d];for(const[p,y]of Object.entries(o)){const x=parseInt(p,10);x>=0&&x=f.length&&(f[x]=y)}a[i]=f}}else o!==null&&typeof o=="object"&&d!==null&&typeof d=="object"&&!Array.isArray(d)?a[i]=ja(d,o):a[i]=o}return a},Hy=(r,e)=>{const t={...r};for(const a of Object.keys(e)){if(!(a in t))continue;const i=e[a],o=t[a];if(i!==null&&typeof i=="object"&&!Array.isArray(i)&&o!==null&&typeof o=="object"&&!Array.isArray(o)){const d=Hy(o,i);Object.keys(d).length===0?delete t[a]:t[a]=d}else delete t[a]}return t},kj=r=>{const e={},t=r.split(";").filter(a=>a.trim());for(const a of t){const i=a.indexOf(":");if(i===-1)continue;const o=a.substring(0,i).trim(),d=a.substring(i+1).trim();if(o&&d){const g=o.replace(/-([a-z])/g,(h,f)=>f.toUpperCase());e[g]=d}}return e};class Nj extends j.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){vt.error(`컴포넌트 렌더링 에러 (ID: ${this.props.componentId}, Name: ${this.props.componentName}):`,e,t)}render(){return this.state.hasError?this.props.fallback?this.props.fallback:l.jsxs("div",{className:"p-4 my-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-red-800 dark:text-red-400",children:[l.jsx("div",{className:"font-semibold mb-1",children:"컴포넌트 로드 실패"}),l.jsxs("div",{className:"text-xs opacity-80",children:[this.props.componentName&&`[${this.props.componentName}] `,"데이터를 표시할 수 없습니다."]}),this.state.error&&l.jsxs("details",{className:"mt-2",children:[l.jsx("summary",{className:"cursor-pointer text-xs opacity-70 hover:opacity-100",children:"상세 정보"}),l.jsx("div",{className:"mt-1 p-2 bg-red-100 dark:bg-red-900/30 rounded text-xs font-mono whitespace-pre-wrap break-all",children:this.state.error.message})]})]}):this.props.children}}const Ua=j.memo(({componentDef:r,dataContext:e,translationContext:t,registry:a,bindingEngine:i,translationEngine:o,actionDispatcher:d,parentComponentContext:g,parentFormContextProp:h,parentDataContext:f,isRootRenderer:p=!1,isInsideIteration:y=!1,isEditMode:x=!1,onComponentSelect:S,onComponentHover:v,onDragStart:w,onDragEnd:k,componentPath:A,layoutKey:O})=>{const[N,D]=j.useState({loadingActions:{}});j.useLayoutEffect(()=>{g||(i.startRenderCycle(),window.__g7SetLocalOverrideKeys||(window.__g7ForcedLocalFields=void 0),window.__g7PendingLocalState=null)});const $=j.useRef(null);j.useLayoutEffect(()=>{if(!g&&e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:V,_merge:ve,...me}=e._localInit,te=`${JSON.stringify(me)}:${V||"no-force"}`;if($.current!==te){$.current=te;const _e=ve||"shallow",Ae=window.__g7PendingLocalState||{};_e==="replace"?window.__g7PendingLocalState={loadingActions:Ae.loadingActions||{},...me,hasChanges:!1}:_e==="deep"?window.__g7PendingLocalState=ja(Ae,{...me,hasChanges:!1}):window.__g7PendingLocalState={...Ae,...me,hasChanges:!1};const Re=window.__g7SetLocalOverrideKeys;Re&&typeof Re=="object"&&(_e==="replace"?window.__g7SetLocalOverrideKeys={...me,hasChanges:!1}:window.__g7SetLocalOverrideKeys=ja(Re,{...me,hasChanges:!1}))}}}),j.useLayoutEffect(()=>{if(!g){const V=window.__g7SetLocalOverrideKeys;if(V){D(_e=>Hy(_e,V));const ve=V,me=window.__g7ForcedLocalFields,te=window.__g7LastSetLocalSnapshot;queueMicrotask(()=>{window.__g7SetLocalOverrideKeys===ve&&(window.__g7SetLocalOverrideKeys=void 0),window.__g7ForcedLocalFields===me&&(window.__g7ForcedLocalFields=void 0),window.__g7LastSetLocalSnapshot===te&&(window.__g7LastSetLocalSnapshot=void 0)})}}},[e._local]);const M=j.useRef(O);j.useEffect(()=>{r._fromBase&&O&&M.current!==O&&(M.current=O,D({loadingActions:{}}))},[O,r._fromBase]);const z=j.useRef(""),K=j.useRef(!1),pe=j.useRef(null),we=j.useRef({}),J=j.useRef({}),be=j.useRef(f),le=A7(),de=g7(),je=de?.getParentDataContext()??f;j.useEffect(()=>{if(e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:V,...ve}=e._localInit,me=JSON.stringify(ve),te=V!==void 0,_e="__g7LocalInitTracking";window[_e]||(window[_e]={hash:"",timestamp:void 0});const Ae=window[_e],Re=`${me}:${V||"no-force"}`;if(Ae.hash!==Re){Ae.hash=Re,Ae.timestamp=V,z.current=me,te&&(K.current=!0);const{_merge:Le,...Fe}=ve,We=Le||"shallow";if(D(Je=>We==="replace"?{loadingActions:Je.loadingActions||{},...Fe,hasChanges:!1}:We==="deep"?ja(Je,{...Fe,hasChanges:!1}):{...Je,...Fe,hasChanges:!1}),e._globalSetState){const Je=e._global?._local||{};let st;We==="replace"?st={...Fe,hasChanges:!1}:We==="deep"?st=ja(Je,{...Fe,hasChanges:!1}):st={...Je,...Fe,hasChanges:!1},e._globalSetState({_local:st})}i.invalidateCacheByKeys(["_local"]),vt.log("_localInit applied (data changed):",Object.keys(ve))}pe.current=e._localInit}},[e._localInit,f,i]);const{isTransitioning:W}=Wm(),ge=v7(),ne=h??ge,{width:X}=Xm(),ae=Sj(),R=j.useMemo(()=>{let V=r;if(r.type==="iterator"&&r.data){const{data:te,itemName:_e,indexName:Ae,...Re}=r;V={...Re,iteration:{source:te,item_var:_e||"item",index_var:Ae}}}if(!V.responsive)return V;const ve=ei.getMatchingKey(V.responsive,X);if(!ve)return V;const me=V.responsive[ve];return{...V,props:{...V.props,...me.props},children:me.children??V.children,text:me.text??V.text,if:me.if??V.if,iteration:me.iteration??V.iteration}},[r,X]),U=j.useCallback(V=>{const ve=V?.__setStateId;if(D(me=>{const te=window.__g7PendingLocalState,Ae=window.__g7SetLocalOverrideKeys||te,Re=Ae?ja(me,Ae):me;if(typeof V=="function"){const We=V(Re);return ja(Re,We)}const{__mergeMode:Pe,__setStateId:Ue,...Le}=V;let Fe;if(Pe==="replace"?Fe=Le:Pe==="shallow"?Fe={...Re,...Le}:Fe=ja(Re,Le),Pe!==void 0){const We=window.__g7ForcedLocalFields;We&&(window.__g7ForcedLocalFields={...We,...Le})}return Fe}),ve){const me=rs();if(me?.isEnabled()){const te=R.id||"unknown",_e=R.name||"Unknown";setTimeout(()=>{me.trackComponentRender?.(te,_e,0,["_local"],[]),me.completeStateChange?.(ve)},0)}}},[R.id,R.name]),re=g?.state??N,ye=g?.setState??U,oe=j.useMemo(()=>{const V=e._localInit&&e._localInit!==pe.current;let ve;V&&e._local?ve=e._local:ve=e._local?ja(e._local,re):re;const me=window.__g7ForcedLocalFields;me&&(ve=ja(ve,me));const te={...e,_local:ve},_e=e._computedDefinitions;if(_e&&Object.keys(_e).length>0){const Ae=new _n,Re={...te,...le?{_isolated:le.state}:{}},Pe={},Ue=rs(),Le=Ue?.isEnabled()??!1;for(const[Fe,We]of Object.entries(_e)){const Je=Le?Date.now():0,st=Le?e._computed?.[Fe]:void 0;let Be;try{if(typeof We=="string")if(We.startsWith("{{")&&We.endsWith("}}")){const De=We.slice(2,-2).trim(),$e=Ae.evaluateExpression(De,Re,{skipCache:!0});Pe[Fe]=$e}else Pe[Fe]=We;else if(We&&typeof We=="object"&&"$switch"in We){const De=Ae.resolveSwitch(We,Re,{skipCache:!0});Pe[Fe]=De}}catch(De){vt.warn(`Failed to recalculate computed value: ${Fe}`,De),Pe[Fe]=e._computed?.[Fe],Be=De instanceof Error?De.message:String(De)}if(Le&&(Be||st!==Pe[Fe])){const $e=Date.now()-Je;Ue.trackComputedProperty?.(Fe,typeof We=="string"?We:JSON.stringify(We),[{type:"_local",path:"_local",value:te._local}],Pe[Fe],$e,R.id,Be),st!==Pe[Fe]&&Ue.trackComputedRecalc?.(Fe,"dependency-change",st,Pe[Fe],$e,{type:"_local",path:"_local"},R.id)}}te._computed=Pe}return le&&(te._isolated=le.state),je&&(te.$parent=je),r.extensionPointProps&&(te.extensionPointProps=i.resolveObject(r.extensionPointProps,te,y?{skipCache:!0}:void 0)),r.extensionPointCallbacks&&(te.extensionPointCallbacks=r.extensionPointCallbacks),te},[e,re,le?.state,je,de?.version,r.extensionPointProps,r.extensionPointCallbacks]);we.current=oe._local,J.current=oe._computed||{},be.current=je,j.useEffect(()=>{const V=rs();if(!V?.isEnabled())return;const ve=oe._local;ve&&V.updateLocalState(ve);const me=oe._computed;me&&V.updateComputedState(me),je&&V.updateParentContext?.(je);const te=R.id||`comp-${Date.now()}`,_e=R.name||"Unknown",Ae={global:Object.keys(e._global||{}),local:Object.keys(ve||{}),context:g?Object.keys(g.state||{}):[]},Re={type:g?"componentContext":"dynamicState",hasComponentContext:!!g,parentId:g?"parent":void 0};V.trackComponentStateSource?.(te,_e,Ae,Re),re&&Object.keys(re).length>0&&V.trackDynamicState?.(te,re);const Pe=!!(R.expandChildren||R.props?.expandChildren);V.trackContextFlow?.(te,_e,!!g,Pe,!0)},[oe._local,e,R.id,R.name,g,re,R.expandChildren,R.props?.expandChildren,je]);const ke=j.useMemo(()=>({state:{...oe._local},setState:ye,stateRef:we,computedRef:J,isolatedContext:le,parentDataContext:oe}),[oe._local,ye,N,le,oe]),Oe=j.useMemo(()=>{const V=ti({if:R.if,condition:R.condition,conditions:R.conditions},oe,i,R.id);if(R.if||R.condition!==void 0||R.conditions){const me=rs();me?.isEnabled()&&R.if&&me.trackIfCondition(R.id||`if-${Date.now()}`,R.if,V)}return V},[R.if,R.conditions,oe,i,R.id]),Te=j.useMemo(()=>{if(!R.slot)return null;const V=R.slot;if(V.startsWith("{{")&&V.endsWith("}}")){const ve=V.slice(2,-2).trim();try{const me={componentId:R.id,componentName:R.name,propName:"slot"},te=i.evaluateExpression(ve,oe,me);return vt.log(`[Slot] 표현식 평가: "${ve}" => "${te}" (컴포넌트: ${R.id})`),typeof te=="string"?te:null}catch(me){return vt.warn(`slot 표현식 평가 실패 (컴포넌트: ${R.id}):`,me),null}}return vt.log(`[Slot] 정적 슬롯 ID: "${V}" (컴포넌트: ${R.id})`),V},[R.slot,R.id,oe,i]),qe=j.useMemo(()=>!Te||!R.id?"":`${R.id}-${Te}-${JSON.stringify(R.slotOrder??0)}`,[Te,R.id,R.slotOrder]),Ie=j.useRef(null);j.useEffect(()=>{const V=window.__slotContextValue,ve=V?.isEnabled??!1;if(R.slot&&vt.log(`[Slot Registration] 컴포넌트: ${R.id}, isSlotEnabled: ${ve}, shouldRender: ${Oe}, resolvedSlotId: ${Te}`),!ve||!Oe){R.slot&&vt.log(`[Slot Registration] 등록 스킵 - isSlotEnabled: ${ve}, shouldRender: ${Oe}`),Ie.current&&R.id&&V&&(V.unregisterFromSlot(Ie.current,R.id),Ie.current=null);return}if(!Te||!R.id){R.slot&&vt.log(`[Slot Registration] 등록 스킵 - resolvedSlotId: ${Te}, id: ${R.id}`),Ie.current&&R.id&&V&&(V.unregisterFromSlot(Ie.current,R.id),Ie.current=null);return}Ie.current&&Ie.current!==Te&&V.unregisterFromSlot(Ie.current,R.id);const me={...R,slot:void 0,slotOrder:void 0};return V.registerToSlot(Te,R.id,{componentDef:me,dataContext:e,order:R.slotOrder??0,parentFormContext:h??null,getParentComponentContext:()=>ke,translationContext:t,registrationKey:qe}),Ie.current=Te,()=>{const te=window.__slotContextValue;Te&&R.id&&te&&te.unregisterFromSlot(Te,R.id)}},[Oe,Te,R,e,h,ke,t,qe]);const Nt=j.useCallback(V=>{if(typeof V=="string"){if(Fp(V))return Kp(V);if(Vp(V)){const ve=[],me=V.replace(new RegExp(`${ec}([^${co}]*)${co}`,"g"),(_e,Ae)=>(ve.push(Ae),`${Rs}${ve.length-1}${Rs}`));let te=me;return/\$t:[a-zA-Z0-9._-]+/.test(me)&&(te=o.resolveTranslations(me,t,oe)),te.replace(new RegExp(`${Rs}(\\d+)${Rs}`,"g"),(_e,Ae)=>ve[parseInt(Ae)])}if(V.startsWith("$t:defer:"))return V;if(/\$t:[a-zA-Z0-9._-]+/.test(V)){const ve=V.trim();return ve.startsWith("{")&&ve.endsWith("}")||ve.startsWith("[")&&ve.endsWith("]")?V:o.resolveTranslations(V,t,oe)}return V}if(Array.isArray(V))return V.map(ve=>Nt(ve));if(V&&typeof V=="object"){const ve={};for(const[me,te]of Object.entries(V))ve[me]=Nt(te);return ve}return V},[o,t,oe]),Tt=j.useCallback(V=>/[?:|&!+\-*/<>=()]/.test(V),[]),Xt=j.useCallback(V=>{if(!V.startsWith("{{")||!V.endsWith("}}"))return null;const ve=V.slice(2,-2);let me=null,te=0;for(let _e=0;_e0?ve[_e-1]:"")!=="\\"&&((Ae==='"'||Ae==="'")&&!me?me=Ae:Ae===me&&(me=null),!me&&(Ae==="{"&&te++,Ae==="}"&&te--,te<0)))return null}return te===0?ve.trim():null},[]),Ot=j.useMemo(()=>{let V={...R.props||{}};const ve=["cellChildren","expandChildren","expandContext","render"],te=a.getMetadata(R.name)?.skipBindingKeys||[],_e=[...new Set([...ve,...te])],Ae=y?{skipCache:!0}:void 0,Re=Be=>{if(Ae)return Ae;if(Be.startsWith("_computed")||Be.startsWith("$computed"))return{skipCache:!0}};for(const[Be,De]of Object.entries(V))if(!_e.includes(Be))if(typeof De=="string"){const $e=Xt(De);if($e!==null){let mt=!1,zt=$e;$e.startsWith(Ds)&&(mt=!0,zt=$e.slice(Ds.length));const tn={componentId:R.id,componentName:R.name,propName:Be};let yn;if(Tt(zt))try{yn=i.evaluateExpression(zt,oe,tn)}catch(Jn){vt.warn(`표현식 평가 실패 (컴포넌트: ${R.id}, prop: ${Be}):`,Jn),yn=void 0}else yn=i.resolve(zt,oe,Re(zt),tn);V[Be]=mt&&yn!=null?go(yn):yn}else{const mt={componentId:R.id,componentName:R.name,propName:Be};V[Be]=i.resolveBindings(De,oe,Ae,mt)}}else Array.isArray(De)?V[Be]=De.map($e=>typeof $e=="string"?i.resolveBindings($e,oe,Ae):typeof $e=="object"&&$e!==null?i.resolveObject($e,oe,Ae):$e):De&&typeof De=="object"&&(V[Be]=i.resolveObject(De,oe,Ae));for(const[Be,De]of Object.entries(V))V[Be]=Nt(De);if(typeof V.style=="string"&&(V.style=kj(V.style)),V=Ku(V,R.actions,oe,{componentContext:ke,actionDispatcher:d}),R.classMap){const Be=zw(R.classMap,oe,i,{skipCache:!0});if(Be){const De=V.className||"";V.className=De?`${De} ${Be}`:Be}}R.style&&(V.style=R.style),R.actions&&R.actions.length>0&&R.type==="composite"&&Object.assign(V,re),R.component_layout&&(V.__componentLayoutDefs=R.component_layout);const Pe=R.expandChildren||R.props?.expandChildren,Ue=R.props?.cellChildren,Le=R.children&&R.children.length>0,Fe=R.component_layout,We=R.slot,Je=R.props?.modalId,st=R.type==="composite";return(Pe||Ue||Le||Fe||We||Je||st)&&(V.__componentContext=ke),V},[R.props,R.actions,R.style,R.classMap,R.id,oe,t,i,o,ke,re,Nt,Tt,Xt,y]),Qt=j.useRef(null),It=j.useMemo(()=>Qt.current&&Qm(Qt.current,Ot)?Qt.current:(Qt.current=Ot,Ot),[Ot]),Tn=j.useMemo(()=>{const V=R.dataKey,ve=R.trackChanges,me=R.debounce;if(V){const te=V.startsWith("_global."),_e=te?V.slice(8):V,Ae=te?e._global:oe._local;return{dataKey:_e,trackChanges:ve??!1,debounce:me,setState:te?Pe=>{e._globalSetState?e._globalSetState(Pe):vt.warn("_global.formData 사용 시 _globalSetState가 필요합니다.")}:ye,state:Ae??{},_isGlobal:te}}if(ne.dataKey)return ne},[R.dataKey,R.trackChanges,R.debounce,R.id,ye,oe._local,e._global,e._globalSetState,ne]),Ce=j.useRef(new Set);j.useEffect(()=>{Ce.current.clear()},[e._global?._remountKeys]);const Ge=j.useCallback((V,ve)=>{const me=e._global?._remountKeys;return V&&me?.[V]&&!Ce.current.has(V)?(Ce.current.add(V),`${V}-remount-${me[V]}`):V||ve},[e._global?._remountKeys]),at=j.useMemo(()=>{if(R.text!==void 0){if(typeof R.text=="string"){const V=R.text;let ve=V;const me={componentId:R.id,componentName:R.name,propName:"text",skipCache:!0},te=Xt(V);if(te!==null)if(Gp(te))ve=i.resolveBindings(V,oe,{skipCache:!0},me);else if(Tt(te))try{ve=i.evaluateExpression(te,oe,me)}catch(_e){vt.warn(`text 표현식 평가 실패 (컴포넌트: ${R.id}):`,_e),ve=""}else ve=i.resolve(te,oe,{skipCache:!0},me);else V.includes("{{")&&(ve=i.resolveBindings(V,oe,{skipCache:!0},me));return ve=Nt(ve),ve??""}return R.text}return!R.children||R.children.length===0?null:R.children.map((V,ve)=>{if(typeof V=="string")return V;const me=A?`${A}.children.${ve}`:`${ve}`,te=V._fromBase?V.id||`child-${ve}`:Ge(V.id,`child-${ve}`),_e=!V._fromBase&&O?`${te}_${O}`:te;return l.jsx(Ua,{componentDef:V,dataContext:oe,translationContext:t,registry:a,bindingEngine:i,translationEngine:o,actionDispatcher:d,parentComponentContext:ke,parentFormContextProp:Tn,isInsideIteration:y,isEditMode:x,onComponentSelect:S,onComponentHover:v,componentPath:me,onDragStart:w,onDragEnd:k,layoutKey:O},_e)})},[R.text,R.children,R.id,e,oe,t,a,i,o,d,ke,Tn,Xt,Tt,Nt,Ge,y,x,S,v,A,w,k,O]),ft=j.useMemo(()=>{if(!R.iteration)return null;try{const V=Vu(R.iteration.source,oe,i);if(!Array.isArray(V))return vt.warn(`iteration source가 배열이 아닙니다 (컴포넌트: ${R.id}):`,V),null;const ve=rs();return ve?.isEnabled()&&ve.trackIteration(R.id||`iteration-${Date.now()}`,R.iteration.source,R.iteration.item_var,R.iteration.index_var,V.length),V.map((me,te)=>{const _e={...oe,[R.iteration.item_var]:me};R.iteration.index_var&&(_e[R.iteration.index_var]=te);const Ae=te===0||te===V.length-1;ve?.isEnabled()&&Ae&&ve.trackNestedContext?.({componentId:`${R.id||"unknown"}-iter-${te}`,componentType:"iteration",parentContext:{available:Object.keys(oe),values:{}},ownContext:{added:[R.iteration.item_var,...R.iteration.index_var?[R.iteration.index_var]:[]],values:{[R.iteration.item_var]:me,...R.iteration.index_var?{[R.iteration.index_var]:te}:{}}},depth:1});const Re={...R,iteration:void 0},Pe=A?`${A}.iteration.${te}`:`iteration.${te}`,Ue=`${Ge(R.id,"item")}-${te}`;return l.jsx(Ua,{componentDef:Re,dataContext:_e,translationContext:t,registry:a,bindingEngine:i,translationEngine:o,actionDispatcher:d,parentComponentContext:ke,parentFormContextProp:Tn,isInsideIteration:!0,isEditMode:x,onComponentSelect:S,onComponentHover:v,componentPath:Pe,onDragStart:w,onDragEnd:k,layoutKey:O},Ue)})}catch(V){return vt.error(`iteration 렌더링 실패 (컴포넌트: ${R.id}):`,V),null}},[R.iteration,R.children,R.id,e,oe,t,a,i,o,d,ke,Tn,Ge,x,S,v,A,w,k,O]),[bt,Et]=j.useState(0),pt=j.useMemo(()=>{if(!R.sortable||!R.itemTemplate)return null;const{sortable:V,itemTemplate:ve}=R;try{const me=Vu(V.source,oe,i);if(!Array.isArray(me))return vt.warn(`sortable source가 배열이 아닙니다 (컴포넌트: ${R.id}):`,me),null;if(me.length===0)return null;const te=V.itemKey||"id",_e=V.strategy||"verticalList",Ae=V.itemVar||"$item",Re=V.indexVar||"$index",Pe=V.handle,Ue=V.wrapperElement,Le=(Je,st)=>{const Be=R.actions?.filter(De=>De.event==="onSortEnd"||De.type==="onSortEnd");if(Et(De=>De+1),Be&&Be.length>0&&d){const De={...oe,$sortedItems:Je,$sortEvent:st};Be.forEach($e=>{try{const mt=d.createHandler($e,De,ke),zt=new Event("sortend");mt(zt)}catch(mt){vt.error(`onSortEnd action failed: ${$e.handler}`,mt)}})}},Fe=Je=>{const st=R.actions?.filter(Be=>Be.event==="onSortStart"||Be.type==="onSortStart");if(st&&st.length>0&&d){const Be={...oe,$activeId:Je.activeId};st.forEach(De=>{try{const $e=d.createHandler(De,Be,ke),mt=new Event("sortstart");$e(mt)}catch($e){vt.error(`onSortStart action failed: ${De.handler}`,$e)}})}},We=me.map((Je,st)=>{const Be=String(Je[te]),De={...oe,[Ae]:Je,[Re]:st},$e=A?`${A}.sortable.${st}`:`sortable.${st}`,mt=`${Ge(R.id,"sortable-item")}-v${bt}-${Be}`;return l.jsx(Cj,{id:Be,handle:Pe,...Ue?{as:Ue}:{},children:(Ue&&ve.children?ve.children:[ve]).map((zt,tn)=>l.jsx(Ua,{componentDef:zt,dataContext:De,translationContext:t,registry:a,bindingEngine:i,translationEngine:o,actionDispatcher:d,parentComponentContext:ke,parentFormContextProp:void 0,isInsideIteration:!0,isEditMode:x,onComponentSelect:S,onComponentHover:v,componentPath:$e,onDragStart:w,onDragEnd:k,layoutKey:O},`${mt}-child-${tn}`))},mt)});return l.jsx(vj,{items:me,itemKey:te,strategy:_e,onSortEnd:Le,onSortStart:Fe,sortVersion:bt,children:We})}catch(me){return vt.error(`sortable 렌더링 실패 (컴포넌트: ${R.id}):`,me),null}},[R.sortable,R.itemTemplate,R.actions,R.id,e,oe,t,a,i,o,d,ke,Ge,x,S,v,A,w,k,bt,O]),tt=j.useRef(!1);j.useEffect(()=>{if(tt.current)return;tt.current=!0;const V=rs();if(V?.isEnabled()&&V.trackMount(r.id,{name:r.name,type:r.type||"component",props:It}),r.lifecycle?.onMount&&r.lifecycle.onMount.length>0)for(const me of r.lifecycle.onMount)try{const te=d.createHandler(me,oe,ke),_e=new Event("mount");te(_e),vt.log(`Lifecycle onMount executed: ${me.handler} (Component: ${r.id})`)}catch(te){vt.error(`Lifecycle onMount failed: ${me.handler} (Component: ${r.id})`,te)}const ve=[];if(r.onComponentEvent&&r.onComponentEvent.length>0){const me=window.G7Core;if(me?.componentEvent?.on)for(const te of r.onComponentEvent){if(!te.event){vt.warn(`onComponentEvent: event name is required (Component: ${r.id})`);continue}const _e=async Re=>{try{const Pe={...oe,_eventData:Re},Le=await d.createHandler({handler:te.handler,params:te.params,onSuccess:te.onSuccess,onError:te.onError},Pe,ke)(new CustomEvent(te.event,{detail:Re}));return vt.log(`onComponentEvent "${te.event}" handled: ${te.handler} (Component: ${r.id})`,{eventData:Re,result:Le}),Le}catch(Pe){throw vt.error(`onComponentEvent "${te.event}" failed: ${te.handler} (Component: ${r.id})`,Pe),Pe}},Ae=me.componentEvent.on(te.event,_e);ve.push(Ae),vt.log(`onComponentEvent: Subscribed to "${te.event}" (Component: ${r.id})`)}else vt.warn(`onComponentEvent: G7Core.componentEvent is not available (Component: ${r.id})`)}return()=>{const me=rs();me?.isEnabled()&&me.trackUnmount(r.id);for(const te of ve)try{te()}catch(_e){vt.error(`onComponentEvent: Failed to unsubscribe (Component: ${r.id})`,_e)}if(ve.length>0&&vt.log(`onComponentEvent: Unsubscribed ${ve.length} event(s) (Component: ${r.id})`),r.lifecycle?.onUnmount&&r.lifecycle.onUnmount.length>0)for(const te of r.lifecycle.onUnmount)try{const _e=d.createHandler(te,oe,ke),Ae=new Event("unmount");_e(Ae),vt.log(`Lifecycle onUnmount executed: ${te.handler} (Component: ${r.id})`)}catch(_e){vt.error(`Lifecycle onUnmount failed: ${te.handler} (Component: ${r.id})`,_e)}}},[]);const bn=j.useMemo(()=>{const V=It.dataKey,ve=It.trackChanges,me=It.debounce;return V?{dataKey:V,trackChanges:ve??!1,debounce:me,setState:ye,state:re}:null},[It.dataKey,It.trackChanges,It.debounce,ye,re]);j.useEffect(()=>{const V=R.dataKey||It.dataKey;if(!V)return;const ve=rs();if(!ve?.isEnabled())return;const me=[],te=Ae=>{if(Ae)for(const Re of Ae){const Pe=Re?.props?.name;if(Pe&&me.push({name:Pe,type:Re.name||Re.type||"unknown"}),Re?.children&&te(Re.children),Re?.slots)for(const Ue of Object.values(Re.slots))Array.isArray(Ue)&&te(Ue)}};if(r.children&&te(r.children),r.slots)for(const Ae of Object.values(r.slots))Array.isArray(Ae)&&te(Ae);const _e=r.id||`form-${V}`;return ve.trackForm(_e,V,me),()=>{ve.untrackForm(_e)}},[R,It.dataKey,r.id,r.children]);const wt=j.useRef(null),At=j.useRef(void 0),qt=j.useMemo(()=>{const{dataKey:V,trackChanges:ve,debounce:me,...te}=It,_e=te.name;if(!_e||!ne.dataKey||!ne.setState)return te;if(te.autoBinding===!1){const{autoBinding:Be,...De}=te;return De}const Ae=`${ne.dataKey}.${_e}`,Re=w7(ne.state,Ae),Pe=Re!==void 0?Re:te.value,Le=a.getMetadata(r.name)?.bindingType,Fe=typeof Pe=="boolean"&&(Le==="checked"||Le==="checkable"&&["checkbox","radio"].includes(te?.type)),We=ne.debounce,Je=Be=>{const De=ne.state||{},$e=S7(De,Ae,Be);ne.trackChanges&&($e.hasChanges=!0),window.__g7PendingLocalState=$e,ne.setState($e)},st=(Be,De)=>{We&&We>0?(wt.current&&clearTimeout(wt.current),wt.current=setTimeout(()=>{Je(Be),wt.current=null,De&&(De(),window.__g7PendingLocalState=null)},We)):(Je(Be),De&&(De(),window.__g7PendingLocalState=null))};if(Fe)return{...te,checked:Pe,onChange:De=>{const $e=De.target.checked;Je($e),te.onChange&&te.onChange(De)}};{const Be=$e=>{const mt=$e?.target?.value!==void 0?$e.target.value:$e;We&&We>0&&(At.current=mt);const zt=$e?.target?{target:{value:mt,name:$e.target.name,type:$e.target.type,checked:$e.target.checked},currentTarget:$e.currentTarget?{value:mt,name:$e.currentTarget.name}:void 0}:$e;st(mt,()=>{te.onChange&&te.onChange(zt)})};let De;return At.current!==void 0?wt.current!==null?De=At.current:String(Pe??"")===String(At.current)?(At.current=void 0,De=Pe??""):De=At.current:De=Pe??"",{...te,value:De,onChange:Be}}},[It,ne,ne.state,ne.debounce]),Yn=j.useMemo(()=>{const V=rs();if(V?.isEnabled()&&V.trackRender(r.name),!Oe)return null;if(R.sortable&&R.itemTemplate)return pt;if(R.iteration)return ft;if(R.type==="extension_point"){const{layout:Pe,columns:Ue,gap:Le,className:Fe,...We}=R.props||{};let Je=Fe||"";return Pe==="grid"&&Ue?Je=`${Je} grid grid-cols-${Ue} gap-${Le||4}`.trim():Pe==="flex"&&(Je=`${Je} flex flex-col gap-${Le||4}`.trim()),l.jsx("div",{id:R.id,className:Je||void 0,...We,children:at})}const ve=a.getComponent(R.name);if(!ve)return vt.error(`컴포넌트를 찾을 수 없습니다: ${R.name} (ID: ${R.id})`,"componentDef:",JSON.stringify(R,null,2)),null;const me=e._global?._remountKeys,te={...qt,id:qt.id??R.id,...me&&Object.keys(me).length>0&&{__remountTrigger:JSON.stringify(me)}};if(ae?.listeners&&ae.handle&&qt["data-drag-handle"]!==void 0&&(Object.assign(te,ae.listeners),te.style={...te.style,cursor:ae.isDragging?"grabbing":"grab"}),x){const Pe=R.id||`auto_${R.name||R.type||"unknown"}_${Math.random().toString(36).substring(2,8)}`;te["data-editor-id"]=Pe,te["data-editor-name"]=R.name,te["data-editor-type"]=R.type,A&&(te["data-editor-path"]=A);const Ue=te.onClick;te.onClick=Le=>{S&&(Le.stopPropagation(),S(Pe,Le)),typeof Ue=="function"&&Ue(Le)},v&&(te.onMouseMove=Le=>{Le.stopPropagation(),v(Pe,Le)},te.onMouseLeave=Le=>{v(null,Le)}),te.draggable=!0,w&&(te.onDragStart=Le=>{Le.stopPropagation(),w(Pe,Le)}),k&&(te.onDragEnd=Le=>{k(Le)})}const Ae=R.type==="basic"||R.type==="layout"?(()=>{const{__componentContext:Pe,__componentLayoutDefs:Ue,...Le}=te;return Le})():te;let Re=l.jsx(ve,{...Ae,children:at});if(Tn&&(Re=l.jsx(b7,{value:Tn,children:Re})),R.isolatedState){const Pe=typeof R.isolatedState=="object"?R.isolatedState:{},Ue=e?._isolatedInit,Le=Ue?{...Pe,...Ue}:Pe;Re=l.jsx(_7,{initialState:Le,scopeId:R.isolatedScopeId,children:Re})}return Re},[Oe,R.iteration,R.sortable,R.itemTemplate,R.type,R.name,R.id,R.props,R.isolatedState,R.isolatedScopeId,a,qt,at,ft,pt,ae,bn,x,S,v,w,k,A,e._global?._remountKeys]),dn=j.useMemo(()=>{const V=R.blur_until_loaded;if(!V||e?._global?.__isPreview)return!1;if(typeof V=="string"){const te=Xt(V);if(te!==null)try{const _e={componentId:R.id,componentName:R.name,propName:"blur_until_loaded"};return!!i.evaluateExpression(te,oe,_e)}catch(_e){return vt.warn(`blur_until_loaded 표현식 평가 실패 (컴포넌트: ${R.id}):`,_e),!1}return!1}if(typeof V=="object"&&V!==null){if(!V.enabled)return!1;if(V.data_sources)return(Array.isArray(V.data_sources)?V.data_sources:[V.data_sources]).some(Re=>e[Re]===void 0);if(W)return!0;const te=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(Ae=>!te.includes(Ae)&&!Ae.startsWith("_")).some(Ae=>e[Ae]===void 0)}if(W)return!0;const ve=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(te=>!ve.includes(te)&&!te.startsWith("_")).some(te=>e[te]===void 0)},[R.blur_until_loaded,R.id,W,e,oe,i,Xt]);if(dn){const V=R.blur_until_loaded;if(typeof V=="object"&&V?.data_sources){const me=(Array.isArray(V.data_sources)?V.data_sources:[V.data_sources]).reduce((_e,Ae)=>(_e[Ae]=e[Ae]===void 0?"UNDEFINED":"LOADED",_e),{}),te=Object.keys(e).filter(_e=>!_e.startsWith("_"));vt.log(`[BLUR APPLIED] Component: ${R.id}, data_sources status:`,me,"Available keys:",te)}else vt.log(`[BLUR APPLIED] Component: ${R.id}, blur_until_loaded:`,V)}const Ta=window.__slotContextValue;return Te&&Ta?.isEnabled?null:l.jsx(Nj,{componentId:r.id,componentName:r.name,children:R.blur_until_loaded?l.jsx("div",{className:dn?"opacity-50 blur-sm transition-all duration-300 pointer-events-none":void 0,children:Yn}):Yn})});Ua.displayName="DynamicRenderer",typeof window<"u"&&(window.__DynamicRenderer=Ua);function Ej(r){const e={};try{const a=new URL(r,typeof window<"u"?window.location.origin:"http://localhost").searchParams,i=new Set;for(const o of a.keys()){if(i.has(o))continue;i.add(o);const d=a.getAll(o);d.length>1||o.endsWith("[]")?e[o]=d:e[o]=d[0]}}catch{}return e}function _j(r){try{return new URL(r,typeof window<"u"?window.location.origin:"http://localhost").pathname}catch{return r.split("?")[0]}}const Er=class Er{constructor(){H(this,"config",{enabled:!1,maxHistorySize:100,logLevel:"info",serverEndpoint:"/_boost/g7-debug/dump-state",autoCapture:!0});H(this,"stateHistory",[]);H(this,"snapshotIdCounter",0);H(this,"stateWatchers",new Map);H(this,"currentLocalState",{});H(this,"currentComputedState",{});H(this,"currentParentContext");H(this,"actionHistory",[]);H(this,"actionWatchers",new Set);H(this,"cacheStats",{hits:0,misses:0,entries:0});H(this,"cacheDecisions",[]);H(this,"cacheDecisionIdCounter",0);H(this,"maxCacheDecisions",200);H(this,"currentRenderCycleId",null);H(this,"isInActionExecution",!1);H(this,"isInIteration",!1);H(this,"mountedComponents",new Map);H(this,"eventListeners",new Map);H(this,"mountWatchers",new Set);H(this,"unmountWatchers",new Set);H(this,"renderCounts",new Map);H(this,"bindingEvalCount",0);H(this,"profilingData",[]);H(this,"isProfiling",!1);H(this,"profilingStartTime",0);H(this,"activeRequests",new Map);H(this,"requestHistory",[]);H(this,"pendingDataSources",new Set);H(this,"requestWatchers",new Set);H(this,"wsConnections",new Map);H(this,"wsMessageHistory",[]);H(this,"wsMessageWatchers",new Set);H(this,"ifConditions",new Map);H(this,"iterations",new Map);H(this,"conditionWatchers",new Set);H(this,"forms",new Map);H(this,"formWatchers",new Set);H(this,"expressionHistory",[]);H(this,"expressionWatchers",new Set);H(this,"expressionIdCounter",0);H(this,"dataSources",new Map);H(this,"dataPathTransforms",[]);H(this,"maxDataPathTransforms",100);H(this,"nestedContexts",[]);H(this,"nestedContextIdCounter",0);H(this,"maxNestedContexts",100);H(this,"formBindingIssues",[]);H(this,"formBindingValidations",[]);H(this,"formBindingIssueIdCounter",0);H(this,"maxFormBindingIssues",100);H(this,"computedProperties",new Map);H(this,"computedRecalcLogs",[]);H(this,"computedRecalcIdCounter",0);H(this,"maxComputedRecalcLogs",100);H(this,"handlers",new Map);H(this,"componentEventSubscriptions",new Map);H(this,"componentEventEmitHistory",[]);H(this,"componentEventIdCounter",0);H(this,"maxComponentEventHistory",100);H(this,"stateRenderingLogs",[]);H(this,"currentStateChangeContext",null);H(this,"stateRenderingIdCounter",0);H(this,"componentRenderCounts",new Map);H(this,"stateToComponentMap",new Map);H(this,"maxStateRenderingLogs",100);H(this,"componentStateSources",new Map);H(this,"contextFlowNodes",new Map);H(this,"dynamicStates",new Map);H(this,"styleIssues",[]);H(this,"componentStyles",new Map);H(this,"authEvents",[]);H(this,"authHeaderHistory",[]);H(this,"authEventIdCounter",0);H(this,"maxAuthEventHistory",50);H(this,"logHistory",[]);H(this,"logIdCounter",0);H(this,"maxLogHistory",500);H(this,"currentLayout",null);H(this,"layoutHistory",[]);H(this,"layoutIdCounter",0);H(this,"layoutStats",{totalLoads:0,cacheHits:0,apiLoads:0});H(this,"maxLayoutHistory",50);H(this,"executionDetails",new Map);H(this,"stateChangeHistory",[]);H(this,"dataSourceChangeHistory",[]);H(this,"changeAlerts",[]);H(this,"changeExpectations",new Map);H(this,"executionIdCounter",0);H(this,"stateChangeIdCounter",0);H(this,"alertIdCounter",0);H(this,"maxExecutionDetails",100);H(this,"maxStateChangeHistory",200);H(this,"maxChangeAlerts",100);H(this,"sequenceExecutions",[]);H(this,"sequenceExecutionStack",[]);H(this,"sequenceIdCounter",0);H(this,"maxSequenceExecutions",50);H(this,"staleClosureWarnings",[]);H(this,"staleClosureIdCounter",0);H(this,"maxStaleClosureWarnings",100);H(this,"stateCaptureRegistry",new Map);H(this,"modalStates",new Map);H(this,"modalStateIssues",[]);H(this,"modalStateRelations",[]);H(this,"modalStateChangeLogs",[]);H(this,"modalStateIssueIdCounter",0);H(this,"modalStateChangeLogIdCounter",0);H(this,"maxModalStateIssues",100);H(this,"maxModalStateChangeLogs",200);H(this,"namedActionDefinitions",{});H(this,"namedActionRefLogs",[]);H(this,"namedActionRefIdCounter",0);H(this,"maxNamedActionRefLogs",200);H(this,"debounceActionHistory",[]);H(this,"dataSourceUpdateHistory",[]);H(this,"debounceActionIdCounter",0);H(this,"dataSourceUpdateIdCounter",0)}static getInstance(){return Er.instance||(Er.instance=new Er),Er.instance}initialize(){if(this.config.enabled=this.checkDebugMode(),!this.config.enabled){console.log("[G7DevTools] 비활성화됨 (환경설정 > 고급 설정 > 디버그 모드를 켜세요)");return}console.log("[G7DevTools] 활성화됨"),this.setupGlobalErrorHandler()}checkDebugMode(){try{if(window.G7Config?.debug===!0)return!0;const a=window.G7Core?.state?.get?.();return a?.settings?.advanced?.debug_mode===!0||a?._global?.settings?.advanced?.debug_mode===!0}catch{return!1}}isEnabled(){return this.config.enabled}setupGlobalErrorHandler(){window.addEventListener("error",e=>{this.config.enabled&&this.logAction({id:this.generateId(),type:"globalError",startTime:Date.now(),status:"error",error:{name:"Error",message:e.message,stack:e.error?.stack}})}),window.addEventListener("unhandledrejection",e=>{this.config.enabled&&this.logAction({id:this.generateId(),type:"unhandledRejection",startTime:Date.now(),status:"error",error:{name:"UnhandledRejection",message:String(e.reason)}})})}captureStateSnapshot(e){if(!this.config.enabled)return;const t={id:++this.snapshotIdCounter,timestamp:Date.now(),source:e.source,prev:this.sanitizeObject(e.prev),next:this.sanitizeObject(e.next),diff:e.diff};this.stateHistory.push(t),this.stateHistory.length>this.config.maxHistorySize&&this.stateHistory.shift(),this.notifyStateWatchers(t)}getState(){try{const e=window.G7Core,t=e?.state?.get?.()||{},a={};if(e?._isolatedStates&&typeof e._isolatedStates=="object")for(const[i,o]of Object.entries(e._isolatedStates))a[i]=this.sanitizeObject(o);return{_global:t._global||t,_local:this.currentLocalState,_computed:this.currentComputedState,_isolated:Object.keys(a).length>0?a:void 0,$parent:this.currentParentContext}}catch{return{_global:{},_local:this.currentLocalState,_computed:this.currentComputedState}}}updateLocalState(e){this.config.enabled&&(this.currentLocalState=this.sanitizeObject(e))}updateComputedState(e){this.config.enabled&&(this.currentComputedState=this.sanitizeObject(e))}updateParentContext(e){this.config.enabled&&(this.currentParentContext=e?this.sanitizeObject(e):void 0)}getStateHistory(){return[...this.stateHistory]}watchState(e,t){return this.stateWatchers.has(e)||this.stateWatchers.set(e,new Set),this.stateWatchers.get(e).add(t),()=>{this.stateWatchers.get(e)?.delete(t)}}notifyStateWatchers(e){if(this.stateWatchers.get("*")?.forEach(t=>{try{t(e.next,e.prev,"*")}catch(a){console.error("[G7DevTools] State watcher error:",a)}}),e.diff)for(const t of e.diff.changed)this.stateWatchers.get(t.path)?.forEach(a=>{try{a(t.newValue,t.oldValue,t.path)}catch(i){console.error("[G7DevTools] State watcher error:",i)}})}diffSnapshots(e,t){const a=this.stateHistory.find(o=>o.id===e),i=this.stateHistory.find(o=>o.id===t);return!a||!i?null:this.calculateDiff(a.next,i.next)}calculateDiff(e,t,a=""){const i={added:[],removed:[],changed:[]},o=new Set(Object.keys(e)),d=new Set(Object.keys(t));for(const g of d){const h=a?`${a}.${g}`:g;o.has(g)?JSON.stringify(e[g])!==JSON.stringify(t[g])&&i.changed.push({path:h,oldValue:e[g],newValue:t[g]}):i.added.push(h)}for(const g of o){const h=a?`${a}.${g}`:g;d.has(g)||i.removed.push(h)}return i}logAction(e){if(!this.config.enabled)return;const t=this.actionHistory.findIndex(a=>a.id===e.id);t>=0?this.actionHistory[t]={...this.actionHistory[t],...e}:(this.actionHistory.push(e),this.actionHistory.length>this.config.maxHistorySize&&this.actionHistory.shift()),this.isProfiling&&this.profilingData.push({type:"action",action:e.type,timestamp:performance.now(),duration:e.duration}),this.notifyActionWatchers(e)}getActionHistory(){return[...this.actionHistory]}watchActions(e){return this.actionWatchers.add(e),()=>{this.actionWatchers.delete(e)}}notifyActionWatchers(e){this.actionWatchers.forEach(t=>{try{t(e)}catch(a){console.error("[G7DevTools] Action watcher error:",a)}})}getActionMetrics(){const e=this.actionHistory.filter(o=>o.status==="success"),t=this.actionHistory.filter(o=>o.status==="error"),a={};for(const o of this.actionHistory)a[o.type]=(a[o.type]||0)+1;const i=e.reduce((o,d)=>o+(d.duration||0),0);return{totalActions:this.actionHistory.length,successCount:e.length,errorCount:t.length,averageDuration:e.length>0?i/e.length:0,actionsByType:a}}recordCacheHit(){this.config.enabled&&this.cacheStats.hits++}recordCacheMiss(){this.config.enabled&&this.cacheStats.misses++}updateCacheEntries(e){this.config.enabled&&(this.cacheStats.entries=e)}getCacheStats(){const e=this.cacheStats.hits+this.cacheStats.misses;return{...this.cacheStats,hitRate:e>0?this.cacheStats.hits/e:0}}resetCacheStats(){this.cacheStats={hits:0,misses:0,entries:0}}trackCacheDecision(e){if(!this.config.enabled)return;const t={id:`cache-${++this.cacheDecisionIdCounter}`,timestamp:Date.now(),expression:e.expression,decision:e.decision,reason:e.reason,context:{isInIteration:this.isInIteration,isInAction:this.isInActionExecution,renderCycleId:this.currentRenderCycleId||void 0,componentId:e.componentId,skipCacheOption:e.skipCacheOption},cachedValue:e.cachedValue!==void 0?this.safeClone(e.cachedValue):void 0,freshValue:e.freshValue!==void 0?this.safeClone(e.freshValue):void 0,valueMatch:e.cachedValue!==void 0&&e.freshValue!==void 0?JSON.stringify(e.cachedValue)===JSON.stringify(e.freshValue):void 0,duration:e.duration};this.cacheDecisions.push(t),this.cacheDecisions.length>this.maxCacheDecisions&&this.cacheDecisions.shift(),e.decision==="cache_hit"?this.cacheStats.hits++:(e.decision==="cache_miss"||e.decision==="skip_cache")&&this.cacheStats.misses++}startRenderCycle(e){return this.currentRenderCycleId=`render-${Date.now()}-${e||"root"}`,this.currentRenderCycleId}endRenderCycle(){this.currentRenderCycleId=null}startActionContext(){this.isInActionExecution=!0}endActionContext(){this.isInActionExecution=!1}startIterationContext(){this.isInIteration=!0}endIterationContext(){this.isInIteration=!1}getCacheDecisionTrackingInfo(){const e=this.getCacheDecisionStats();return{decisions:[...this.cacheDecisions],stats:e,timestamp:Date.now()}}getCacheDecisionStats(){const e=this.cacheDecisions;let t=0,a=0,i=0,o=0;const d={},g={};for(const f of e)f.decision==="cache_hit"?t++:f.decision==="cache_miss"?a++:f.decision==="skip_cache"?i++:f.decision==="invalidate"&&o++,d[f.reason]=(d[f.reason]||0)+1,f.context.componentId&&(g[f.context.componentId]=(g[f.context.componentId]||0)+1);const h=t+a+i;return{totalDecisions:e.length,cacheHits:t,cacheMisses:a,skipCacheCount:i,invalidateCount:o,byReason:d,byComponent:g,avgHitRate:h>0?t/h:0}}getRecentCacheDecisions(e=20,t){let a=[...this.cacheDecisions];return t&&(a=a.filter(i=>i.decision===t)),a.slice(-e)}clearCacheDecisionData(){this.cacheDecisions=[],this.cacheDecisionIdCounter=0}summarizePropsForLifecycle(e){if(!e||typeof e!="object")return e;const t={},a=["children","ref","key"];for(const[i,o]of Object.entries(e))if(!a.includes(i))if(o==null)t[i]=o;else if(Array.isArray(o))t[i]=`[Array(${o.length})]`;else if(typeof o=="object"){const d=Object.keys(o);d.length<=3?t[i]=`{${d.join(", ")}}`:t[i]=`{${d.slice(0,3).join(", ")}, ... +${d.length-3}}`}else typeof o=="string"&&o.length>50?t[i]=o.substring(0,50)+"...":typeof o=="function"?t[i]="[Function]":t[i]=o;return t}trackMount(e,t){if(!this.config.enabled)return;const a=this.summarizePropsForLifecycle(t.props),i={...t,props:a,id:e,mountTime:Date.now()};this.mountedComponents.set(e,i),this.mountWatchers.forEach(o=>{try{o({componentId:e,componentName:t.name,timestamp:i.mountTime})}catch(d){console.error("[G7DevTools] Mount watcher error:",d)}})}trackUnmount(e){if(!this.config.enabled)return;const t=this.mountedComponents.get(e),a=this.eventListeners.get(e)||[];a.length>0&&console.warn(`[G7DevTools] 컴포넌트 ${e} 언마운트 시 ${a.length}개 리스너 미정리`),t&&this.unmountWatchers.forEach(i=>{try{i({componentId:e,componentName:t.name,timestamp:Date.now(),orphanedListeners:a.length})}catch(o){console.error("[G7DevTools] Unmount watcher error:",o)}}),this.mountedComponents.delete(e)}trackListener(e,t,a){if(!this.config.enabled)return;const i=this.eventListeners.get(e)||[];i.push({type:t,target:a,addedAt:Date.now()}),this.eventListeners.set(e,i)}removeListener(e,t){if(!this.config.enabled)return;const a=this.eventListeners.get(e)||[],i=a.findIndex(o=>o.type===t);i>=0&&a.splice(i,1)}getMountedComponents(){return Array.from(this.mountedComponents.values())}getOrphanedListeners(){const e=[];for(const[t,a]of this.eventListeners)this.mountedComponents.has(t)||e.push(...a.map(i=>({...i,componentId:t})));return e}watchMount(e){return this.mountWatchers.add(e),()=>{this.mountWatchers.delete(e)}}watchUnmount(e){return this.unmountWatchers.add(e),()=>{this.unmountWatchers.delete(e)}}trackRender(e){if(!this.config.enabled)return;const t=this.renderCounts.get(e)||0;this.renderCounts.set(e,t+1),this.isProfiling&&this.profilingData.push({type:"render",component:e,timestamp:performance.now()})}trackBindingEval(e){this.config.enabled&&(this.bindingEvalCount++,this.isProfiling&&e&&this.profilingData.push({type:"binding",expression:e,timestamp:performance.now()}))}getRenderCount(){return new Map(this.renderCounts)}getBindingEvalCount(){return this.bindingEvalCount}getMemoryWarnings(){const e=[];try{const i=this.getState(),o=JSON.stringify(i).length;o>1e6&&e.push({type:"large-state",message:`상태 크기가 ${(o/1024/1024).toFixed(2)}MB입니다`,suggestion:"불필요한 데이터 정리 필요",severity:o>5e6?"error":"warning"})}catch{}this.stateHistory.length>this.config.maxHistorySize*.8&&e.push({type:"large-history",message:`상태 이력이 ${this.stateHistory.length}개입니다`,suggestion:"maxHistory 설정 조정 필요",severity:"warning"});const t=this.getOrphanedListeners().length;t>0&&e.push({type:"orphaned-listeners",message:`${t}개의 정리되지 않은 이벤트 리스너`,suggestion:"useEffect cleanup 또는 removeEventListener 확인",severity:t>10?"error":"warning"});const a=Array.from(this.renderCounts.entries()).filter(([,i])=>i>50);return a.length>0&&e.push({type:"excessive-renders",message:`${a.length}개 컴포넌트가 50회 이상 렌더링`,suggestion:"React.memo, useMemo, useCallback 사용 고려",severity:"warning"}),e}startProfiling(){this.config.enabled&&(this.isProfiling=!0,this.profilingData=[],this.profilingStartTime=performance.now(),console.log("[G7DevTools] 프로파일링 시작"))}stopProfiling(){this.isProfiling=!1;const e=performance.now()-this.profilingStartTime,t=this.analyzeProfile(e);return console.log("[G7DevTools] 프로파일링 완료",t),t}analyzeProfile(e){const t=this.profilingData.filter(f=>f.type==="render"),a=this.profilingData.filter(f=>f.type==="binding"),i=this.profilingData.filter(f=>f.type==="action"),o={};for(const f of t)f.component&&(o[f.component]||(o[f.component]={count:0,durations:[]}),o[f.component].count++,f.duration&&o[f.component].durations.push(f.duration));const d=Object.entries(o).map(([f,p])=>({name:f,renderCount:p.count,avgDuration:p.durations.length>0?p.durations.reduce((y,x)=>y+x,0)/p.durations.length:0})).sort((f,p)=>p.renderCount-f.renderCount).slice(0,10),g={};for(const f of a)f.expression&&(g[f.expression]=(g[f.expression]||0)+1);const h=Object.entries(g).sort(([,f],[,p])=>p-f).slice(0,10).map(([f])=>f);return{duration:e,entries:this.profilingData,summary:{totalRenders:t.length,totalBindings:a.length,totalActions:i.length,slowestComponents:d,hotPaths:h}}}resetPerformanceStats(){this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[]}trackRequest(e,t,a){if(!this.config.enabled)return"";const i=this.generateId(),o=_j(e),d=Ej(e);return this.activeRequests.set(i,{id:i,url:o,fullUrl:e,queryParams:d,method:t,startTime:Date.now(),status:"pending",requestBody:a?.requestBody?this.sanitizeObject(a.requestBody):void 0,dataSourceId:a?.dataSourceId}),this.isProfiling&&this.profilingData.push({type:"network",timestamp:performance.now()}),i}completeRequest(e,t,a){if(!this.config.enabled)return;const i=this.activeRequests.get(e);if(!i)return;const o={...i,status:t>=200&&t<300?"success":"error",statusCode:t,duration:Date.now()-i.startTime,endTime:Date.now(),response:this.sanitizeObject(a)};this.requestHistory.push(o),this.activeRequests.delete(e),this.requestHistory.length>this.config.maxHistorySize&&this.requestHistory.shift(),this.notifyRequestWatchers(o)}failRequest(e,t){if(!this.config.enabled)return;const a=this.activeRequests.get(e);if(!a)return;const i={...a,status:"error",error:t,duration:Date.now()-a.startTime,endTime:Date.now()};this.requestHistory.push(i),this.activeRequests.delete(e),this.notifyRequestWatchers(i)}trackDataSource(e){this.config.enabled&&this.pendingDataSources.add(e)}completeDataSource(e){this.config.enabled&&this.pendingDataSources.delete(e)}getActiveRequests(){return Array.from(this.activeRequests.values())}getRequestHistory(){return[...this.requestHistory]}getPendingDataSources(){return Array.from(this.pendingDataSources)}watchRequest(e){return this.requestWatchers.add(e),()=>{this.requestWatchers.delete(e)}}notifyRequestWatchers(e){this.requestWatchers.forEach(t=>{try{t(e)}catch(a){console.error("[G7DevTools] Request watcher error:",a)}})}trackWebSocketConnection(e,t,a){this.config.enabled&&this.wsConnections.set(e,{id:e,url:t,state:a,connectedAt:a==="open"?Date.now():void 0})}trackWebSocketMessage(e,t,a,i){if(!this.config.enabled)return;const o={id:this.generateId(),connectionId:e,direction:t,type:a,payload:this.sanitizeObject(i),timestamp:Date.now(),sequence:this.wsMessageHistory.length};this.wsMessageHistory.push(o),this.wsMessageHistory.length>this.config.maxHistorySize&&this.wsMessageHistory.shift(),this.notifyWebSocketWatchers(o)}getWebSocketConnections(){return Array.from(this.wsConnections.values())}getWebSocketMessageHistory(){return[...this.wsMessageHistory]}getWebSocketConnectionState(){const e=Array.from(this.wsConnections.values());return e.some(t=>t.state==="open")?"connected":e.some(t=>t.state==="connecting")?"reconnecting":"disconnected"}watchWebSocketMessage(e){return this.wsMessageWatchers.add(e),()=>{this.wsMessageWatchers.delete(e)}}notifyWebSocketWatchers(e){this.wsMessageWatchers.forEach(t=>{try{t(e)}catch(a){console.error("[G7DevTools] WebSocket watcher error:",a)}})}trackIfCondition(e,t,a){if(!this.config.enabled)return;const i=this.ifConditions.get(e),o=i?.evaluatedValue;this.ifConditions.set(e,{id:e,expression:t,evaluatedValue:a,evaluationCount:(i?.evaluationCount||0)+1,lastEvaluated:Date.now()}),i&&o!==a&&this.notifyConditionWatchers({id:e,expression:t,oldValue:o,newValue:a,timestamp:Date.now()})}trackIteration(e,t){this.config.enabled&&this.iterations.set(e,{id:e,...t,lastRendered:Date.now()})}getIfConditions(){return Array.from(this.ifConditions.values())}getIterations(){return Array.from(this.iterations.values())}getScopeChain(e){const t=[],a=this.getState();return t.push({name:"_global",value:a._global,source:"global"}),t.push({name:"_local",value:a._local,source:"local"}),t.push({name:"_computed",value:a._computed,source:"computed"}),t}watchConditionChange(e){return this.conditionWatchers.add(e),()=>{this.conditionWatchers.delete(e)}}notifyConditionWatchers(e){this.conditionWatchers.forEach(t=>{try{t(e)}catch(a){console.error("[G7DevTools] Condition watcher error:",a)}})}trackForm(e,t,a){this.config.enabled&&this.forms.set(e,{id:e,dataKey:t,inputs:a,trackedAt:Date.now()})}trackFormChange(e,t,a){if(!this.config.enabled)return;const i={formId:e,inputName:t,value:a,timestamp:Date.now()};this.notifyFormWatchers(i)}untrackForm(e){this.forms.delete(e)}getForms(){return Array.from(this.forms.values())}getFormState(e){const t=this.getState();return this.getNestedValue(t,e)||{}}getBindingPath(e,t){return`${e}.${t}`}watchFormChange(e){return this.formWatchers.add(e),()=>{this.formWatchers.delete(e)}}notifyFormWatchers(e){this.formWatchers.forEach(t=>{try{t(e)}catch(a){console.error("[G7DevTools] Form watcher error:",a)}})}trackFormBindingIssue(e,t,a){if(!this.config.enabled)return;const i={id:`form-issue-${++this.formBindingIssueIdCounter}`,timestamp:Date.now(),type:e,severity:t,formId:a.formId,formDataKey:a.formDataKey,inputInfo:a.inputInfo,contextInfo:a.contextInfo,description:a.description,suggestion:a.suggestion,docLink:a.docLink};this.formBindingIssues.push(i),this.formBindingIssues.length>this.maxFormBindingIssues&&this.formBindingIssues.shift()}validateFormBinding(e,t,a,i){const o=a.map(h=>{const f=[];let p=!0;return h.name||(f.push("Input에 name 속성이 없습니다"),p=!1,this.trackFormBindingIssue("missing-input-name","error",{formId:e,formDataKey:t,inputInfo:{name:h.name,type:h.type},description:"Input에 name 속성이 없어 자동 바인딩이 동작하지 않습니다",suggestion:"Input에 name 속성을 추가하세요",docLink:"troubleshooting-components-form.md"})),t||(f.push("Form에 dataKey가 없습니다"),p=!1),{inputName:h.name||"(unnamed)",inputType:h.type,bindingPath:t&&h.name?`${t}.${h.name}`:"-",isValid:p,currentValue:h.value,issues:f}});if(t||this.trackFormBindingIssue("missing-datakey","error",{formId:e,description:"Form에 dataKey가 설정되지 않아 자동 바인딩이 동작하지 않습니다",suggestion:"Form 컴포넌트에 dataKey props를 설정하세요",docLink:"troubleshooting-components-form.md"}),i.isContextBroken){const h=i.breakReason?.includes("sortable")?"sortable-context-break":i.breakReason?.includes("modal")?"modal-context-isolation":"context-not-propagated";this.trackFormBindingIssue(h,"warning",{formId:e,formDataKey:t,contextInfo:{hasParentFormContext:i.hasParentContext,parentFormContextProp:i.parentContextProp,isInsideSortable:i.breakReason?.includes("sortable")||!1,isInsideModal:i.breakReason?.includes("modal")||!1,depth:0},description:i.breakReason||"Form 컨텍스트가 제대로 전파되지 않았습니다",suggestion:"parentFormContextProp={undefined}를 확인하거나 중첩 구조를 검토하세요",docLink:"troubleshooting-components-form.md"})}const d={formId:e,dataKey:t,timestamp:Date.now(),contextPropagation:i,inputBindings:o,isValid:o.every(h=>h.isValid)&&!!t&&!i.isContextBroken,issueCount:o.filter(h=>!h.isValid).length+(t?0:1)+(i.isContextBroken?1:0)},g=this.formBindingValidations.findIndex(h=>h.formId===e);return g>=0?this.formBindingValidations[g]=d:this.formBindingValidations.push(d),d}getFormBindingValidationTrackingInfo(){const e=this.getFormBindingValidationStats();return{issues:[...this.formBindingIssues],validations:[...this.formBindingValidations],stats:e,timestamp:Date.now()}}getFormBindingValidationStats(){const e={"missing-datakey":0,"missing-input-name":0,"context-not-propagated":0,"sortable-context-break":0,"modal-context-isolation":0,"duplicate-input-name":0,"value-type-mismatch":0,"binding-path-invalid":0},t={info:0,warning:0,error:0};for(const i of this.formBindingIssues)e[i.type]++,t[i.severity]++;const a=Object.entries(e).filter(([,i])=>i>0).sort((i,o)=>o[1]-i[1]).slice(0,5).map(([i,o])=>({type:i,count:o,description:this.getIssueTypeDescription(i)}));return{totalFormsValidated:this.formBindingValidations.length,validForms:this.formBindingValidations.filter(i=>i.isValid).length,formsWithIssues:this.formBindingValidations.filter(i=>!i.isValid).length,totalIssues:this.formBindingIssues.length,byIssueType:e,bySeverity:t,topIssues:a}}getIssueTypeDescription(e){return{"missing-datakey":"Form에 dataKey 누락","missing-input-name":"Input에 name 속성 누락","context-not-propagated":"Form 컨텍스트 전파 실패","sortable-context-break":"Sortable 컨테이너에서 컨텍스트 단절","modal-context-isolation":"모달에서 부모 Form 컨텍스트 격리","duplicate-input-name":"동일 Form 내 중복 Input name","value-type-mismatch":"값 타입과 Input 타입 불일치","binding-path-invalid":"바인딩 경로 유효하지 않음"}[e]||e}clearFormBindingIssues(){this.formBindingIssues=[],this.formBindingValidations=[],this.formBindingIssueIdCounter=0}trackComputedProperty(e,t,a,i,o,d,g){if(!this.config.enabled)return;const h=`computed-${e}-${d||"global"}`,f={id:h,name:e,expression:t,componentId:d,dependencies:a,currentValue:this.safeClone(i),lastComputedAt:Date.now(),computationTime:o,error:g};this.computedProperties.set(h,f)}trackComputedRecalc(e,t,a,i,o,d,g){if(!this.config.enabled)return;const h=`computed-${e}-${g||"global"}`,f=JSON.stringify(a)!==JSON.stringify(i),p={id:`recalc-${++this.computedRecalcIdCounter}`,computedId:h,computedName:e,timestamp:Date.now(),trigger:t,triggeredBy:d,previousValue:this.safeClone(a),newValue:this.safeClone(i),valueChanged:f,computationTime:o,cascadeCount:0};this.computedRecalcLogs.push(p),this.computedRecalcLogs.length>this.maxComputedRecalcLogs&&this.computedRecalcLogs.shift();const y=this.computedProperties.get(h);y&&(y.currentValue=this.safeClone(i),y.lastComputedAt=Date.now(),y.computationTime=o)}analyzeComputedDependencyChain(e,t){const a=new Set,i=[];let o=!1,d,g=0;const h=(p,y)=>{if(g=Math.max(g,y),a.has(p))return o=!0,d=[...i,p],{name:p,type:"computed",children:[],depth:y};a.add(p),i.push(p);const x=this.computedProperties.get(`computed-${p}-${t||"global"}`),S=[];if(x)for(const v of x.dependencies)v.type==="computed"?S.push(h(v.path,y+1)):S.push({name:v.path,type:v.type,children:[],depth:y+1});return i.pop(),a.delete(p),{name:p,type:"computed",children:S,depth:y}},f=h(e,0);return{root:e,tree:f,hasCycle:o,cyclePath:d,maxDepth:g}}getComputedDependencyTrackingInfo(){const e=Array.from(this.computedProperties.values()),t=this.getComputedDependencyStats(),a=[];for(const i of e){const o=this.analyzeComputedDependencyChain(i.name,i.componentId);a.push(o)}return{properties:e,recalcLogs:[...this.computedRecalcLogs],dependencyChains:a,stats:t,timestamp:Date.now()}}getComputedDependencyStats(){const e={"state-change":0,"datasource-update":0,"dependency-change":0,manual:0,initial:0},t={},a={};let i=0,o=0;for(const f of this.computedRecalcLogs)e[f.trigger]++,f.valueChanged||o++,t[f.computedName]=(t[f.computedName]||0)+1,a[f.computedName]||(a[f.computedName]=[]),a[f.computedName].push(f.computationTime),i+=f.computationTime;const d=Object.entries(t).sort((f,p)=>p[1]-f[1]).slice(0,5).map(([f,p])=>({name:f,count:p})),g=Object.entries(a).map(([f,p])=>({name:f,avgTime:p.reduce((y,x)=>y+x,0)/p.length})).sort((f,p)=>p.avgTime-f.avgTime).slice(0,5);let h=0;for(const f of this.computedProperties.values())this.analyzeComputedDependencyChain(f.name,f.componentId).hasCycle&&h++;return{totalComputed:this.computedProperties.size,totalRecalculations:this.computedRecalcLogs.length,unnecessaryRecalculations:o,avgComputationTime:this.computedRecalcLogs.length>0?i/this.computedRecalcLogs.length:0,topRecalculated:d,slowestComputed:g,cycleDetectionCount:h,byTrigger:e}}clearComputedTracking(){this.computedProperties.clear(),this.computedRecalcLogs=[],this.computedRecalcIdCounter=0}trackModalOpen(e){if(!this.config.enabled)return;const t={modalId:e.modalId,modalName:e.modalName,openedAt:Date.now(),closedAt:null,scopeType:e.scopeType||"isolated",parentModalId:e.parentModalId,componentId:e.componentId,initialState:e.initialState?{...e.initialState}:{},currentState:e.initialState?{...e.initialState}:{},stateChangeCount:0,isolatedStateKeys:e.isolatedStateKeys||[],sharedStateKeys:e.sharedStateKeys||[]};this.modalStates.set(e.modalId,t),this.validateModalDefinitionExists(e.modalId,e.modalName),e.parentModalId&&(this.modalStateRelations.find(i=>i.parentModalId===e.parentModalId&&i.childModalId===e.modalId)||this.modalStateRelations.push({parentModalId:e.parentModalId,childModalId:e.modalId,sharedKeys:e.sharedStateKeys||[],isolatedKeys:e.isolatedStateKeys||[],relationType:"parent-child"}))}trackModalClose(e,t){if(!this.config.enabled)return;const a=this.modalStates.get(e);a&&(a.closedAt=Date.now(),t&&(a.currentState={...t}),this.detectStateLeakage(a))}validateModalDefinitionExists(e,t){const a=this.currentLayout;if(!a?.layoutJson)return;const i=a.layoutJson.modals;if(!i){this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:t,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 현재 레이아웃에 modals 섹션이 없습니다. 레이아웃 경로: ${a.layoutPath}`,affectedStateKeys:[],expectedValue:`modals 섹션에 id="${e}" 정의 존재`,actualValue:"modals 섹션 없음"});return}const o=Array.isArray(i)?i:Object.values(i);o.some(g=>g?.id===e||g?.props?.id===e)||this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:t,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 렌더링된 레이아웃의 modals 섹션에 해당 ID의 정의가 없습니다. partial 로딩 실패, 레이아웃 병합 문제, extends 상속 누락 등을 확인하세요. 레이아웃 경로: ${a.layoutPath}`,affectedStateKeys:[],expectedValue:`modals 배열에 id="${e}" 항목 존재`,actualValue:`modals 배열에 ${o.length}개 모달 정의 (${o.map(g=>g?.id||"unknown").join(", ")})`})}trackModalStateChange(e){if(!this.config.enabled)return;const t=this.modalStates.get(e.modalId);if(!t)return;t.stateChangeCount++,t.currentState[e.stateKey]=e.newValue;const a=this.checkIsolationViolation(t,e.stateKey),i={id:`modal-change-${++this.modalStateChangeLogIdCounter}`,modalId:e.modalId,modalName:t.modalName,timestamp:Date.now(),stateKey:e.stateKey,previousValue:e.previousValue,newValue:e.newValue,changeSource:e.changeSource||"user-action",violatesIsolation:a};this.modalStateChangeLogs.push(i),this.modalStateChangeLogs.length>this.maxModalStateChangeLogs&&this.modalStateChangeLogs.shift(),a&&this.recordModalStateIssue({type:"isolation-violation",modalId:e.modalId,modalName:t.modalName,severity:"warning",description:`모달 '${t.modalName}'에서 격리된 상태 키 '${e.stateKey}'가 변경됨`,affectedStateKeys:[e.stateKey]})}detectStateLeakage(e){if(e.scopeType==="isolated")for(const t of e.isolatedStateKeys){const a=e.initialState[t],i=e.currentState[t];if(a!==i&&e.parentModalId){const o=this.modalStates.get(e.parentModalId);o&&o.currentState.hasOwnProperty(t)&&this.recordModalStateIssue({type:"state-leakage",modalId:e.modalId,modalName:e.modalName,severity:"error",description:`모달 닫힘 후 상태 '${t}'가 부모 모달로 유출될 수 있음`,affectedStateKeys:[t],leakedValue:i,expectedValue:a})}}}checkIsolationViolation(e,t){return e.scopeType==="isolated",!1}recordModalStateIssue(e){const t={id:`modal-issue-${++this.modalStateIssueIdCounter}`,type:e.type,modalId:e.modalId,modalName:e.modalName,timestamp:Date.now(),severity:e.severity,description:e.description,affectedStateKeys:e.affectedStateKeys,leakedValue:e.leakedValue,expectedValue:e.expectedValue,actualValue:e.actualValue,stackInfo:e.stackInfo};this.modalStateIssues.push(t),this.modalStateIssues.length>this.maxModalStateIssues&&this.modalStateIssues.shift()}getModalStateScopeTrackingInfo(){const e=Array.from(this.modalStates.values()),t=this.getModalStateScopeStats();return{modals:e,issues:[...this.modalStateIssues],relations:[...this.modalStateRelations],changeLogs:[...this.modalStateChangeLogs],stats:t,timestamp:Date.now()}}getModalStateScopeStats(){const e=Array.from(this.modalStates.values()),t={warning:0,error:0},a={"state-leakage":0,"isolation-violation":0,"parent-mutation":0,"orphaned-state":0,"scope-mismatch":0,"cleanup-failure":0,"missing-definition":0};for(const o of this.modalStateIssues)t[o.severity]++,a[o.type]++;const i={isolated:0,shared:0,inherited:0};for(const o of e)i[o.scopeType]++;return{totalModals:e.length,openModals:e.filter(o=>o.closedAt===null).length,nestedModals:e.filter(o=>o.parentModalId!==void 0).length,totalIssues:this.modalStateIssues.length,issuesBySeverity:t,issuesByType:a,byScope:i,leakageDetectionCount:a["state-leakage"],cleanupFailureCount:a["cleanup-failure"]}}clearModalStateScopeTracking(){this.modalStates.clear(),this.modalStateIssues=[],this.modalStateRelations=[],this.modalStateChangeLogs=[],this.modalStateIssueIdCounter=0,this.modalStateChangeLogIdCounter=0}setNamedActionDefinitions(e){this.config.enabled&&(this.namedActionDefinitions=e||{})}trackNamedActionRef(e){if(!this.config.enabled)return;const t={...e,id:`named_action_ref_${++this.namedActionRefIdCounter}`};this.namedActionRefLogs.push(t),this.namedActionRefLogs.length>this.maxNamedActionRefLogs&&(this.namedActionRefLogs=this.namedActionRefLogs.slice(-this.maxNamedActionRefLogs))}getNamedActionTrackingInfo(){const e={};for(const a of this.namedActionRefLogs)e[a.actionRefName]=(e[a.actionRefName]||0)+1;const t=Object.keys(this.namedActionDefinitions).filter(a=>!e[a]);return{definitions:this.namedActionDefinitions,refLogs:[...this.namedActionRefLogs],stats:{totalDefinitions:Object.keys(this.namedActionDefinitions).length,totalRefs:this.namedActionRefLogs.length,refCountByName:e,unusedDefinitions:t},timestamp:Date.now()}}clearNamedActionTracking(){this.namedActionDefinitions={},this.namedActionRefLogs=[],this.namedActionRefIdCounter=0}trackExpressionEval(e){if(!this.config.enabled)return;const t={...e,id:`expr-${++this.expressionIdCounter}`,timestamp:Date.now(),warning:this.detectExpressionWarning(e)};this.expressionHistory.push(t),this.expressionHistory.length>500&&this.expressionHistory.shift(),this.isProfiling&&this.profilingData.push({type:"binding",expression:e.expression,timestamp:performance.now(),duration:e.duration}),this.notifyExpressionWatchers(t)}detectExpressionWarning(e){const{expression:t,result:a,resultType:i,method:o,duration:d}=e;if(i==="undefined"&&!t.includes("??")&&!t.includes("||")&&/^[a-zA-Z_$][a-zA-Z0-9_$.]*$/.test(t.replace(/{{|}}/g,"").trim()))return{type:"undefined-result",message:"표현식 결과가 undefined입니다",suggestion:`데이터가 로드되었는지 확인하거나 fallback 값을 추가하세요: ${t} ?? ''`};if(i==="null")return{type:"null-result",message:"표현식 결과가 null입니다",suggestion:`nullish coalescing 연산자를 사용하세요: ${t} ?? ''`};if(o==="resolveBindings"&&i==="string"){const g=String(a);if(g.includes("[object Object]")||/^\[.*\]$/.test(g))return{type:"array-to-string",message:"배열/객체가 문자열로 변환되었습니다",suggestion:"evaluateExpression()을 사용하여 원본 타입을 유지하세요"}}if(o==="resolveBindings"&&i==="string"&&String(a).includes("[object Object]"))return{type:"object-to-string",message:"객체가 [object Object]로 변환되었습니다",suggestion:"evaluateExpression()을 사용하거나 특정 속성에 접근하세요"};if(i==="undefined"&&t.includes(".")&&!t.includes("?.")){const g=t.replace(/{{|}}/g,"").trim().split(".");if(g.length>=2)return{type:"missing-optional-chain",message:"Optional chaining(?.) 누락 가능성",suggestion:`안전한 접근을 위해 ?. 사용을 고려하세요: ${g.join("?.")}`}}if((t.includes("{{item.")||t.includes("{{index}}"))&&Array.from(this.iterations.values()).some(f=>f.itemVar!=="item"))return{type:"wrong-iteration-var",message:"'item'/'index' 대신 iteration에서 정의한 변수명을 사용해야 합니다",suggestion:"iteration의 item_var/index_var에 정의된 변수명을 확인하세요"};if(d&&d>10)return{type:"slow-evaluation",message:`표현식 평가에 ${d.toFixed(2)}ms 소요됨`,suggestion:"복잡한 표현식을 단순화하거나 computed 값으로 분리하세요"}}getExpressions(){return[...this.expressionHistory]}getExpressionWarnings(){return this.expressionHistory.filter(e=>e.warning!=null)}searchExpressions(e){const t=e.toLowerCase();return this.expressionHistory.filter(a=>a.expression.toLowerCase().includes(t)||a.componentName?.toLowerCase().includes(t)||a.propName?.toLowerCase().includes(t))}getExpressionStats(){const e=this.expressionHistory,t=new Set(e.map(h=>h.expression)),a=e.filter(h=>h.warning!=null),i=e.filter(h=>h.fromCache),o=e.filter(h=>h.duration!=null).map(h=>h.duration),d={};for(const h of e)d[h.resultType]=(d[h.resultType]||0)+1;const g={};for(const h of a)h.warning&&(g[h.warning.type]=(g[h.warning.type]||0)+1);return{totalEvaluations:e.length,uniqueExpressions:t.size,warningCount:a.length,cacheHitRate:e.length>0?i.length/e.length:0,averageDuration:o.length>0?o.reduce((h,f)=>h+f,0)/o.length:0,byType:d,byWarning:g}}clearExpressions(){this.expressionHistory=[],this.expressionIdCounter=0}watchExpressions(e){return this.expressionWatchers.add(e),()=>{this.expressionWatchers.delete(e)}}notifyExpressionWatchers(e){this.expressionWatchers.forEach(t=>{try{t(e)}catch(a){console.error("[G7DevTools] Expression watcher error:",a)}})}setLogLevel(e){this.config.logLevel=e}setMaxHistory(e){this.config.maxHistorySize=Math.max(10,Math.min(1e3,e))}setServerEndpoint(e){this.config.serverEndpoint=e}getConfig(){return{...this.config}}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}sanitizeObject(e,t=new WeakSet){if(e===null||typeof e!="object")return e;if(t.has(e))return"[Circular]";if(t.add(e),Array.isArray(e))return e.map(i=>this.sanitizeObject(i,t));const a={};for(const i of Object.keys(e))try{a[i]=this.sanitizeObject(e[i],t)}catch{a[i]="[Unable to serialize]"}return a}getNestedValue(e,t){if(!t)return e;const a=t.split(".");let i=e;for(const o of a){if(i==null)return;i=i[o]}return i}getLifecycleInfo(){return{mountedComponents:Array.from(this.mountedComponents.values()),orphanedListeners:this.getOrphanedListeners()}}getPerformanceInfo(){return{renderCounts:this.renderCounts,bindingEvalCount:this.bindingEvalCount,memoryWarnings:this.getMemoryWarnings()}}getNetworkInfo(){return{activeRequests:Array.from(this.activeRequests.values()),requestHistory:[...this.requestHistory],pendingDataSources:Array.from(this.pendingDataSources)}}getConditionalInfo(){return{ifConditions:Array.from(this.ifConditions.values()),iterations:Array.from(this.iterations.values())}}getFormInfo(){return Array.from(this.forms.values())}getWebSocketInfo(){return{connections:Array.from(this.wsConnections.values()),messageHistory:[...this.wsMessageHistory],connectionState:this.getWebSocketConnectionState()}}getStateAtTime(e){const t=[...this.stateHistory].reverse().find(a=>a.timestamp<=e);if(t)return{_global:t.next,_local:{}}}reset(){this.stateHistory=[],this.actionHistory=[],this.cacheStats={hits:0,misses:0,entries:0},this.cacheDecisions=[],this.cacheDecisionIdCounter=0,this.currentRenderCycleId=null,this.isInActionExecution=!1,this.isInIteration=!1,this.mountedComponents.clear(),this.eventListeners.clear(),this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[],this.activeRequests.clear(),this.requestHistory=[],this.pendingDataSources.clear(),this.wsConnections.clear(),this.wsMessageHistory=[],this.ifConditions.clear(),this.iterations.clear(),this.forms.clear(),this.expressionHistory=[],this.expressionIdCounter=0,this.dataSources.clear(),this.dataPathTransforms=[],this.nestedContexts=[],this.nestedContextIdCounter=0,this.formBindingIssues=[],this.formBindingValidations=[],this.formBindingIssueIdCounter=0,this.computedProperties.clear(),this.computedRecalcLogs=[],this.computedRecalcIdCounter=0,this.modalStates.clear(),this.modalStateIssues=[],this.modalStateRelations=[],this.modalStateChangeLogs=[],this.modalStateIssueIdCounter=0,this.modalStateChangeLogIdCounter=0,this.logHistory=[],this.logIdCounter=0}getExpressionInfo(){return{expressions:this.getExpressions(),stats:this.getExpressionStats()}}trackLog(e,t,a){if(!this.config.enabled)return;const i=a.map(d=>{if(typeof d=="string")return d;try{return JSON.stringify(d)}catch{return String(d)}}).join(" "),o={id:`log-${++this.logIdCounter}`,level:e,prefix:t,message:i,args:this.sanitizeObject(a),timestamp:Date.now(),stack:e==="error"?new Error().stack:void 0};this.logHistory.push(o),this.logHistory.length>this.maxLogHistory&&this.logHistory.shift()}trackAction(e){if(!this.config.enabled)return;const t={id:`debounce-action-${++this.debounceActionIdCounter}`,...e,timestamp:Date.now()};this.debounceActionHistory.push(t),this.debounceActionHistory.length>100&&this.debounceActionHistory.shift()}trackDataSourceUpdate(e){if(!this.config.enabled)return;const t={id:`ds-update-${++this.dataSourceUpdateIdCounter}`,...e};this.dataSourceUpdateHistory.push(t),this.dataSourceUpdateHistory.length>100&&this.dataSourceUpdateHistory.shift()}getDebounceActionHistory(e){let t=[...this.debounceActionHistory];return e?.handler&&(t=t.filter(a=>a.handler.includes(e.handler))),e?.status&&(t=t.filter(a=>a.status===e.status)),e?.limit&&(t=t.slice(-e.limit)),t}getDataSourceUpdateHistory(e){let t=[...this.dataSourceUpdateHistory];return e?.dataSourceId&&(t=t.filter(a=>a.dataSourceId===e.dataSourceId)),e?.updateType&&(t=t.filter(a=>a.updateType===e.updateType)),e?.limit&&(t=t.slice(-e.limit)),t}getLogs(e){let t=[...this.logHistory];if(e?.level){const a=Array.isArray(e.level)?e.level:[e.level];t=t.filter(i=>a.includes(i.level))}if(e?.prefix){const a=e.prefix.toLowerCase();t=t.filter(i=>i.prefix.toLowerCase().includes(a))}if(e?.search){const a=e.search.toLowerCase();t=t.filter(i=>i.message.toLowerCase().includes(a))}return e?.since&&(t=t.filter(a=>a.timestamp>=e.since)),e?.limit&&(t=t.slice(-e.limit)),t}getLogStats(){const t=Date.now()-6e4,a={log:0,warn:0,error:0,debug:0,info:0},i={};let o=0,d=0;for(const g of this.logHistory)a[g.level]++,i[g.prefix]=(i[g.prefix]||0)+1,g.timestamp>=t&&(g.level==="error"&&o++,g.level==="warn"&&d++);return{totalLogs:this.logHistory.length,byLevel:a,byPrefix:i,recentErrors:o,recentWarnings:d}}clearLogs(){this.logHistory=[],this.logIdCounter=0}getLogInfo(){return{entries:this.getLogs(),stats:this.getLogStats()}}trackDataSourceDefinition(e){this.config.enabled&&this.dataSources.set(e.id,{...e,status:"idle"})}trackDataSourceLoading(e){if(!this.config.enabled)return;const t=this.dataSources.get(e);t&&this.dataSources.set(e,{...t,status:"loading"})}trackDataSourceLoaded(e,t,a){if(!this.config.enabled)return;const i=this.dataSources.get(e);if(!i)return;let o,d,g=a;t&&(Array.isArray(t)?(o=t.length,d=t.length>0&&typeof t[0]=="object"?Object.keys(t[0]):void 0):typeof t=="object"&&(Array.isArray(t.data)?(g=g||"data",o=t.data.length,d=t.data.length>0&&typeof t.data[0]=="object"?Object.keys(t.data[0]):void 0):Array.isArray(t.items)?(g=g||"items",o=t.items.length,d=t.items.length>0&&typeof t.items[0]=="object"?Object.keys(t.items[0]):void 0):d=Object.keys(t))),this.dataSources.set(e,{...i,status:"loaded",dataPath:g,itemCount:o,keys:d,lastLoadedAt:Date.now(),error:void 0})}trackDataSourceError(e,t){if(!this.config.enabled)return;const a=this.dataSources.get(e);a&&this.dataSources.set(e,{...a,status:"error",error:t,lastLoadedAt:Date.now()})}untrackDataSource(e){this.dataSources.delete(e)}getDataSources(){return Array.from(this.dataSources.values())}getDataSource(e){return this.dataSources.get(e)}clearDataSources(){this.dataSources.clear()}trackDataPathTransform(e){if(!this.config.enabled)return;let t=this.dataPathTransforms.find(a=>a.dataSourceId===e.dataSourceId);t||(t={dataSourceId:e.dataSourceId,timestamp:Date.now(),transformSteps:[],warnings:[]},this.dataPathTransforms.push(t),this.dataPathTransforms.length>this.maxDataPathTransforms&&this.dataPathTransforms.shift()),t.transformSteps.push({step:e.step,inputPath:e.inputPath,inputValue:this.safeClone(e.inputValue),outputPath:e.outputPath,outputValue:this.safeClone(e.outputValue),config:e.config}),e.warning&&t.warnings.push(e.warning)}setDataPathFinalBinding(e,t){if(!this.config.enabled)return;const a=this.dataPathTransforms.find(i=>i.dataSourceId===e);a&&(a.finalBinding={expression:t.expression,resolvedPath:t.resolvedPath,value:this.safeClone(t.value)})}getDataPathTransformTrackingInfo(){const e=this.getDataPathTransformStats();return{transforms:[...this.dataPathTransforms],stats:e,timestamp:Date.now()}}getDataPathTransformStats(){const e=this.dataPathTransforms,t={};let a=0;const i={};for(const d of e){t[d.dataSourceId]=(t[d.dataSourceId]||0)+1,a+=d.warnings.length;for(const g of d.warnings)i[g]=(i[g]||0)+1}const o=Object.entries(i).map(([d,g])=>({warning:d,count:g})).sort((d,g)=>g.count-d.count).slice(0,10);return{totalTransforms:e.length,byDataSource:t,warningsCount:a,commonWarnings:o}}getDataPathTransformForDataSource(e){return this.dataPathTransforms.find(t=>t.dataSourceId===e)}clearDataPathTransforms(){this.dataPathTransforms=[]}trackNestedContext(e){if(!this.config.enabled)return"";const t=`nested-${++this.nestedContextIdCounter}`,a=[...new Set([...e.parentContext.available,...e.ownContext.added])],i={...e.parentContext.values,...e.ownContext.values},o={id:t,timestamp:Date.now(),componentId:e.componentId,componentType:e.componentType,parentContext:{available:e.parentContext.available,values:this.safeClone(e.parentContext.values)},ownContext:{added:e.ownContext.added,values:this.safeClone(e.ownContext.values)},mergedContext:{all:a,values:this.safeClone(i)},accessAttempts:[],depth:e.depth,parentId:e.parentId};return this.nestedContexts.push(o),this.nestedContexts.length>this.maxNestedContexts&&this.nestedContexts.shift(),t}trackNestedContextAccess(e,t){if(!this.config.enabled)return;const a=this.nestedContexts.find(i=>i.id===e);a&&a.accessAttempts.push({path:t.path,found:t.found,value:t.found?this.safeClone(t.value):void 0,error:t.error})}getNestedContextTrackingInfo(){const e=this.getNestedContextStats();return{contexts:[...this.nestedContexts],stats:e,timestamp:Date.now()}}getNestedContextStats(){const e=this.nestedContexts,t={expandChildren:0,cellChildren:0,iteration:0,modal:0,slot:0};let a=0,i=0;const o={};for(const g of e){t[g.componentType]++,g.depth>a&&(a=g.depth);for(const h of g.accessAttempts)h.found||(i++,o[h.path]=(o[h.path]||0)+1)}const d=Object.entries(o).map(([g,h])=>({path:g,count:h})).sort((g,h)=>h.count-g.count).slice(0,10);return{totalContexts:e.length,byType:t,maxDepth:a,failedAccessCount:i,commonFailedPaths:d}}getNestedContextForComponent(e){return this.nestedContexts.find(t=>t.componentId===e)}clearNestedContexts(){this.nestedContexts=[],this.nestedContextIdCounter=0}trackHandlerRegistration(e,t="custom",a,i){this.isEnabled&&this.handlers.set(e,{name:e,category:t,description:a,registeredAt:Date.now(),source:i})}trackHandlerUnregistration(e){this.isEnabled&&this.handlers.delete(e)}getHandlers(){return Array.from(this.handlers.values())}getHandler(e){return this.handlers.get(e)}getHandlersByCategory(e){return Array.from(this.handlers.values()).filter(t=>t.category===e)}clearHandlers(){this.handlers.clear()}trackEventSubscribe(e){if(!this.isEnabled)return;const t=this.componentEventSubscriptions.get(e),a=Date.now();t?(t.subscriberCount++,t.lastSubscribedAt=a):this.componentEventSubscriptions.set(e,{eventName:e,subscriberCount:1,firstSubscribedAt:a,lastSubscribedAt:a})}trackEventUnsubscribe(e){if(!this.isEnabled)return;const t=this.componentEventSubscriptions.get(e);t&&(t.subscriberCount--,t.subscriberCount<=0&&this.componentEventSubscriptions.delete(e))}trackEventEmit(e,t,a,i,o){if(!this.isEnabled)return;const d={id:`evt_${++this.componentEventIdCounter}`,eventName:e,data:this.sanitizeForLogging(t),timestamp:Date.now(),listenerCount:a,results:i?this.sanitizeForLogging(i):void 0,hasError:!!o,errorMessage:o?.message};this.componentEventEmitHistory.push(d),this.componentEventEmitHistory.length>this.maxComponentEventHistory&&(this.componentEventEmitHistory=this.componentEventEmitHistory.slice(-this.maxComponentEventHistory))}trackEventOff(e){this.isEnabled&&this.componentEventSubscriptions.delete(e)}trackEventClear(){this.isEnabled&&this.componentEventSubscriptions.clear()}getComponentEventInfo(){const e=Array.from(this.componentEventSubscriptions.values());return{subscriptions:e,emitHistory:[...this.componentEventEmitHistory],totalSubscribers:e.reduce((t,a)=>t+a.subscriberCount,0),totalEmits:this.componentEventEmitHistory.length}}getEventEmitHistory(){return[...this.componentEventEmitHistory]}getEventSubscriptions(){return Array.from(this.componentEventSubscriptions.values())}clearComponentEvents(){this.componentEventSubscriptions.clear(),this.componentEventEmitHistory=[],this.componentEventIdCounter=0}sanitizeForLogging(e){if(e==null||typeof e!="object")return e;try{return JSON.parse(JSON.stringify(e))}catch{return"[Circular or Non-serializable]"}}startStateChange(e,t,a,i){if(!this.config.enabled)return"";const o=`setState_${++this.stateRenderingIdCounter}`;this.currentStateChangeContext={setStateId:o,startTime:performance.now(),changedPath:e,trigger:i||{},renderedComponents:[]};const d={id:`sr_${this.stateRenderingIdCounter}`,setStateId:o,statePath:e,oldValue:this.sanitizeForLogging(t),newValue:this.sanitizeForLogging(a),timestamp:Date.now(),triggeredBy:i||{},renderedComponents:[],totalRenderDuration:0,affectedBindingsCount:0};return this.stateRenderingLogs.push(d),this.stateRenderingLogs.length>this.maxStateRenderingLogs&&this.stateRenderingLogs.shift(),o}trackComponentRender(e,t,a,i=[],o=[],d){if(!this.config.enabled)return;const g=this.componentRenderCounts.get(t)||0;this.componentRenderCounts.set(t,g+1);for(const h of i)this.stateToComponentMap.has(h)||this.stateToComponentMap.set(h,new Set),this.stateToComponentMap.get(h).add(t);if(this.currentStateChangeContext){const h={componentId:e,componentName:t,renderDuration:a,accessedStatePaths:i,evaluatedBindings:o,renderOrder:this.currentStateChangeContext.renderedComponents.length,parentId:d};this.currentStateChangeContext.renderedComponents.push(h)}this.trackRender(t)}completeStateChange(e){if(!this.config.enabled||!this.currentStateChangeContext||this.currentStateChangeContext.setStateId!==e)return;const t=this.currentStateChangeContext,i=performance.now()-t.startTime,o=this.stateRenderingLogs.findIndex(d=>d.setStateId===e);if(o>=0){const d=this.stateRenderingLogs[o];d.renderedComponents=t.renderedComponents,d.totalRenderDuration=i,d.affectedBindingsCount=t.renderedComponents.reduce((g,h)=>g+h.evaluatedBindings.length,0)}this.currentStateChangeContext=null}getCurrentStateChangeContext(){return this.currentStateChangeContext}getStateRenderingLogs(){return[...this.stateRenderingLogs]}getStateRenderingInfo(){const e=this.stateRenderingLogs,t=Object.fromEntries(this.componentRenderCounts),a={};for(const[i,o]of this.stateToComponentMap)a[i]=Array.from(o);return{logs:e,componentRenderCounts:t,stateToComponentMap:a,stats:this.calculateStateRenderingStats()}}calculateStateRenderingStats(){const e=this.stateRenderingLogs;if(e.length===0)return{totalStateChanges:0,totalRenders:0,avgRenderDuration:0,avgComponentsPerChange:0,topRenderedComponents:[],topInfluentialPaths:[]};const t=e.reduce((g,h)=>g+h.renderedComponents.length,0),a=e.reduce((g,h)=>g+h.totalRenderDuration,0)/e.length,i=t/e.length,o=Array.from(this.componentRenderCounts.entries()).sort((g,h)=>h[1]-g[1]).slice(0,5).map(([g,h])=>({name:g,count:h})),d=Array.from(this.stateToComponentMap.entries()).sort((g,h)=>h[1].size-g[1].size).slice(0,5).map(([g,h])=>({path:g,affectedComponents:h.size}));return{totalStateChanges:e.length,totalRenders:t,avgRenderDuration:a,avgComponentsPerChange:i,topRenderedComponents:o,topInfluentialPaths:d}}getComponentsAffectedByState(e){const t=this.stateToComponentMap.get(e);return t?Array.from(t):[]}getComponentRenderHistory(e){return this.stateRenderingLogs.filter(t=>t.renderedComponents.some(a=>a.componentName===e))}clearStateRenderingLogs(){this.stateRenderingLogs=[],this.componentRenderCounts.clear(),this.stateToComponentMap.clear(),this.currentStateChangeContext=null,this.stateRenderingIdCounter=0}trackComponentStateSource(e,t,a,i){this.config.enabled&&this.componentStateSources.set(e,{componentId:e,componentName:t,stateSource:a,stateProvider:i})}trackDynamicState(e,t){this.config.enabled&&this.dynamicStates.set(e,t)}trackContextFlow(e,t,a,i,o,d){if(!this.config.enabled)return;const g={component:t,componentId:e,contextReceived:a,passedToChildren:i,usedInRender:o};if(this.contextFlowNodes.set(e,g),d){const h=this.contextFlowNodes.get(d);h&&(h.children||(h.children=[]),h.children.push(g))}}getStateHierarchyInfo(e=!0){const t=this.buildStateHierarchyLayers(),a=this.detectStateConflicts(t),i=Array.from(this.componentStateSources.values());return{layers:e?t.map(d=>({...d,values:this.summarizeValues(d.values,2)})):t,conflicts:a,componentStateSources:i,timestamp:Date.now()}}summarizeValues(e,t,a=0){if(e==null)return e;if(typeof e!="object")return typeof e=="string"&&e.length>100?e.substring(0,100)+`... (${e.length}자)`:e;if(a>=t){if(Array.isArray(e))return`[Array(${e.length})]`;const d=Object.keys(e);return`{${d.slice(0,5).join(", ")}${d.length>5?`, ... +${d.length-5}`:""}}`}if(Array.isArray(e))return e.length<=3?e.map(d=>this.summarizeValues(d,t,a+1)):{__type:"array",__length:e.length,__preview:e.slice(0,3).map(d=>this.summarizeValues(d,t,a+1))};const i={},o=Object.keys(e);for(const d of o)i[d]=this.summarizeValues(e[d],t,a+1);return i}buildStateHierarchyLayers(){const e=[];try{const a=window.G7Core?.state?.get?.();if(!a)return e;a._local&&e.push({name:"Global _local",type:"global",path:"_local",values:a._local,priority:1}),a._global&&e.push({name:"Global _global",type:"global",path:"_global",values:a._global,priority:1});for(const[o,d]of this.dynamicStates)d&&Object.keys(d).length>0&&e.push({name:`DynamicState (${o})`,type:"dynamicState",componentId:o,values:d,priority:2});const i=this.computeEffectiveState(a._local||{});e.push({name:"Effective _local (merged)",type:"effective",values:i,priority:3})}catch(t){console.warn("[G7DevTools] 상태 계층 빌드 실패:",t)}return e}computeEffectiveState(e){const t={...e};for(const[,a]of this.dynamicStates)a._local&&Object.assign(t,a._local);return t}detectStateConflicts(e){const t=[],a=e.find(o=>o.type==="global"&&o.path==="_local");if(!a)return t;const i=e.filter(o=>o.type==="dynamicState");for(const o of i){const d=o.values._local||o.values;for(const[g,h]of Object.entries(d)){const f=a.values[g];if(JSON.stringify(f)!==JSON.stringify(h)){const p=[],y=[];for(const x of this.componentStateSources.values())x.stateSource.local.some(v=>v===`_local.${g}`||v===g)&&(x.stateProvider.type==="dynamicState"?p.push(x.componentName):x.stateProvider.type==="globalState"&&y.push(x.componentName));t.push({path:`_local.${g}`,globalValue:f,dynamicStateValue:h,effectiveValue:h,usedBy:p,notUsedBy:y,severity:y.length>0?"warning":"info",description:y.length>0?`${y.join(", ")}은(는) globalState._local을 읽어 dynamicState 값을 사용하지 못함`:"dynamicState 값이 globalState와 다르지만 모든 컴포넌트가 dynamicState를 사용"})}}}return t}getContextFlowInfo(){const e=[],t=new Set(this.contextFlowNodes.keys());for(const a of this.contextFlowNodes.values())if(a.children)for(const i of a.children)t.delete(i.componentId);for(const a of t){const i=this.contextFlowNodes.get(a);i&&e.push(i)}return{rootComponent:e.length>0?e[0].component:"Unknown",contextFlow:e,timestamp:Date.now()}}clearStateHierarchyData(){this.componentStateSources.clear(),this.contextFlowNodes.clear(),this.dynamicStates.clear()}trackComponentStyle(e,t,a,i){if(!this.config.enabled)return;const o=this.analyzeTailwindClasses(a),d={componentId:e,componentName:t,classes:a,computedStyles:i,tailwindAnalysis:o};this.componentStyles.set(e,d),this.detectStyleIssues(d)}analyzeTailwindClasses(e){const t=[],a=[],i=[],o=[],d=["sm:","md:","lg:","xl:","2xl:"],g=[/bg-\w+-\d+/,/text-\w+-\d+/,/border-\w+-\d+/];for(const h of e){o.push(h),h.startsWith("dark:")&&t.push(h);for(const f of d)if(h.startsWith(f)){a.push(h);break}for(const f of g)if(f.test(h)){i.push(h);break}}return{usedClasses:o,darkClasses:t,responsiveClasses:a,dynamicClasses:i}}detectStyleIssues(e){const{componentId:t,componentName:a,computedStyles:i,tailwindAnalysis:o}=e;(i.opacity==="0"||i.visibility==="hidden"||i.display==="none"||i.width==="0px"&&i.height==="0px")&&this.addStyleIssue({id:this.generateId(),type:"invisible-element",componentId:t,componentName:a,property:i.opacity==="0"?"opacity":i.visibility==="hidden"?"visibility":i.display==="none"?"display":"width/height",currentValue:i.opacity==="0"?"0":i.visibility==="hidden"?"hidden":i.display==="none"?"none":"0px",severity:"warning",description:"요소가 화면에 보이지 않습니다.",suggestion:"opacity, visibility, display, width/height 값을 확인하세요."});const d=o.usedClasses.filter(h=>h.startsWith("bg-")&&!h.startsWith("dark:")),g=o.darkClasses.filter(h=>h.includes("bg-"));d.length>0&&g.length===0&&this.addStyleIssue({id:this.generateId(),type:"dark-mode-missing",componentId:t,componentName:a,property:"background-color",currentValue:d.join(", "),expectedValue:"dark:bg-* 클래스 필요",severity:"info",description:"다크 모드 배경색 클래스가 누락되었습니다.",suggestion:`${d[0]}에 대응하는 dark: 클래스를 추가하세요.`}),o.dynamicClasses.length>0&&this.addStyleIssue({id:this.generateId(),type:"tailwind-purging",componentId:t,componentName:a,property:"class",currentValue:o.dynamicClasses.join(", "),severity:"info",description:"동적으로 생성된 Tailwind 클래스가 있습니다.",suggestion:"tailwind.config.js의 safelist에 추가하거나 전체 클래스명을 상수로 정의하세요."})}addStyleIssue(e){this.styleIssues.some(a=>a.componentId===e.componentId&&a.type===e.type&&a.property===e.property)||this.styleIssues.push(e)}getStyleValidationInfo(){const e=Array.from(this.componentStyles.values());return{issues:[...this.styleIssues],componentStyles:e,stats:{totalComponents:e.length,invisibleCount:this.styleIssues.filter(t=>t.type==="invisible-element").length,tailwindIssueCount:this.styleIssues.filter(t=>t.type==="tailwind-purging").length,darkModeIssueCount:this.styleIssues.filter(t=>t.type==="dark-mode-missing").length},timestamp:Date.now()}}clearStyleValidationData(){this.styleIssues=[],this.componentStyles.clear()}trackAuthEvent(e,t,a,i){if(!this.config.enabled)return;const o={id:`auth_${++this.authEventIdCounter}`,type:e,timestamp:Date.now(),success:t,error:a,details:i};this.authEvents.push(o),this.authEvents.length>this.maxAuthEventHistory&&(this.authEvents=this.authEvents.slice(-this.maxAuthEventHistory))}trackAuthHeader(e,t,a,i,o){if(!this.config.enabled)return;const d={url:e,hasAuthHeader:t,headerType:a,tokenValid:i??!1,responseStatus:o,timestamp:Date.now()};this.authHeaderHistory.push(d),this.authHeaderHistory.length>this.maxAuthEventHistory&&(this.authHeaderHistory=this.authHeaderHistory.slice(-this.maxAuthEventHistory)),o===401&&this.trackAuthEvent("api-unauthorized",!1,`401 Unauthorized: ${e}`,{url:e})}getAuthState(){try{const e=window.G7Core,t=e?.api;let a=e?.auth;!a&&e?.AuthManager?.getInstance&&(a=e.AuthManager.getInstance());const i=t?.getToken?.()||a?.getAccessToken?.()||localStorage.getItem("auth_token")||localStorage.getItem("access_token"),o=a?.getRefreshToken?.()||localStorage.getItem("refresh_token");let d="unknown",g=a?.getUser?.();if(g&&(d="AuthManager"),!g){const S=e?.state?.get?.();g=S?._global?.user||S?._global?.currentUser||S?.user||S?.currentUser,g&&(d="G7Core.state")}const h=a?.isAuthenticated?.()??!1;let f="memory";localStorage.getItem("auth_token")||localStorage.getItem("access_token")?f="localStorage":(sessionStorage.getItem("auth_token")||sessionStorage.getItem("access_token"))&&(f="sessionStorage");const p=!!i&&(!!g||h);let y;i&&typeof i=="string"&&i.length>20?y=`${i.substring(0,10)}...${i.substring(i.length-6)}`:i&&(y="***");const x=g?{id:g.id,email:g.email,name:g.name,roles:g.roles?.map(S=>typeof S=="string"?{name:S}:{id:S.id,name:S.name,guard_name:S.guard_name}),permissions:g.permissions?.map(S=>typeof S=="string"?{name:S}:{id:S.id,name:S.name,guard_name:S.guard_name}),avatar:g.avatar||g.profile_photo_url||g.profile_image,created_at:g.created_at,updated_at:g.updated_at,last_login_at:g.last_login_at,email_verified_at:g.email_verified_at,...g.phone&&{phone:g.phone},...g.nickname&&{nickname:g.nickname},...g.status&&{status:g.status},...g.locale&&{locale:g.locale}}:void 0;return{isAuthenticated:p,user:x,tokens:{hasAccessToken:!!i,hasRefreshToken:!!o,storage:f,accessTokenPreview:y},lastActivity:Date.now(),source:d}}catch{return{isAuthenticated:!1,tokens:{hasAccessToken:!1,hasRefreshToken:!1,storage:"memory"},source:"unknown"}}}getAuthDebugInfo(){const e=[...this.authEvents];return{state:this.getAuthState(),events:e,headerAnalysis:[...this.authHeaderHistory],stats:{loginAttempts:e.filter(t=>t.type==="login").length,successfulLogins:e.filter(t=>t.type==="login"&&t.success).length,failedLogins:e.filter(t=>t.type==="login"&&!t.success).length,tokenRefreshes:e.filter(t=>t.type==="token-refresh").length,unauthorizedResponses:e.filter(t=>t.type==="api-unauthorized").length},timestamp:Date.now()}}clearAuthData(){this.authEvents=[],this.authHeaderHistory=[],this.authEventIdCounter=0}trackLayoutLoad(e,t,a,i="api"){if(!this.config.enabled)return;const o=Date.now();this.currentLayout={layoutPath:e,templateId:t,layoutJson:this.sanitizeObject(a),loadedAt:o,version:a.version,layoutName:a.layout_name,source:i};const d={id:`layout-${++this.layoutIdCounter}`,layoutPath:e,templateId:t,loadedAt:o,source:i,version:a.version};this.layoutHistory.push(d),this.layoutHistory.length>this.maxLayoutHistory&&this.layoutHistory.shift(),this.layoutStats.totalLoads++,i==="cache"?this.layoutStats.cacheHits++:this.layoutStats.apiLoads++}getCurrentLayout(){return this.currentLayout}getLayoutHistory(){return[...this.layoutHistory]}getLayoutDebugInfo(){return{current:this.currentLayout,history:[...this.layoutHistory],stats:{...this.layoutStats}}}clearLayoutData(){this.currentLayout=null,this.layoutHistory=[],this.layoutIdCounter=0,this.layoutStats={totalLoads:0,cacheHits:0,apiLoads:0}}startHandlerExecution(e){if(!this.config.enabled)return"";const t=`exec_${++this.executionIdCounter}_${Date.now()}`,a={handlerName:e,executionId:t,startTime:Date.now(),stateChanges:[],dataSourceChanges:[],alerts:[]};if(this.executionDetails.set(t,a),this.executionDetails.size>this.maxExecutionDetails){const i=Array.from(this.executionDetails.keys());i.slice(0,i.length-this.maxExecutionDetails).forEach(d=>this.executionDetails.delete(d))}return t}endHandlerExecution(e,t,a,i){if(!this.config.enabled||!e)return;const o=this.executionDetails.get(e);if(!o)return;o.endTime=Date.now(),o.duration=o.endTime-o.startTime,o.exitReason=t,o.exitLocation=a,o.exitDescription=i;const d=this.changeExpectations.get(e);d&&(o.expectedChanges=d,this.checkExpectations(e,o,d),this.changeExpectations.delete(e)),t==="normal"&&o.stateChanges.length===0&&o.dataSourceChanges.length===0&&this.addChangeAlert(e,{type:"no-state-change",severity:"warning",message:`핸들러 "${o.handlerName}"이(가) 상태 변경 없이 완료됨`,description:"핸들러가 성공적으로 완료되었지만 상태나 데이터소스 변경이 없습니다. 의도한 동작인지 확인하세요.",handlerName:o.handlerName,suggestion:'핸들러 내부 조건문을 확인하거나 DevTools의 "변경감지" 탭에서 exitLocation을 확인하세요.',docLink:".claude/docs/frontend/troubleshooting-state.md"}),(t==="early-return-condition"||t==="early-return-validation")&&this.addChangeAlert(e,{type:"early-return-detected",severity:"info",message:`핸들러 "${o.handlerName}"이(가) early return으로 종료됨`,description:i||`종료 위치: ${a||"알 수 없음"}`,handlerName:o.handlerName,suggestion:t==="early-return-validation"?"검증 실패로 인한 early return입니다. 입력 데이터를 확인하세요.":"조건부 early return입니다. 조건문의 평가 결과를 확인하세요."})}recordExitReason(e,t,a,i){if(!this.config.enabled||!e)return;const o=this.executionDetails.get(e);o&&(o.exitReason=t,o.exitLocation=a,o.exitDescription=i)}recordStateChange(e,t,a,i,o){if(!this.config.enabled)return;const d={id:`sc_${++this.stateChangeIdCounter}`,path:t,changeType:a,oldValue:this.safeClone(i),newValue:this.safeClone(o),timestamp:Date.now(),comparison:this.compareValues(i,o),executionId:e};if(this.stateChangeHistory.push(d),e){const g=this.executionDetails.get(e);g&&g.stateChanges.push(d)}this.stateChangeHistory.length>this.maxStateChangeHistory&&this.stateChangeHistory.splice(0,this.stateChangeHistory.length-this.maxStateChangeHistory),d.comparison.isDeepEqual&&typeof i=="object"&&i!==null&&this.addChangeAlert(e||"",{type:"object-reference-same",severity:"warning",message:`상태 "${t}"가 변경되었으나 값이 동일함`,description:"객체 참조가 동일하거나 깊은 비교 결과 변경이 없습니다. 변경 감지가 실패할 수 있습니다.",handlerName:e&&this.executionDetails.get(e)?.handlerName||"unknown",statePath:t,suggestion:"불변성을 유지하여 새 객체를 생성하세요. 예: { ...oldObject, newField: value }",docLink:".claude/docs/frontend/troubleshooting-state.md#object-mutation"})}recordDataSourceChange(e,t,a,i,o){if(!this.config.enabled)return;const d={dataSourceId:t,changeType:a,timestamp:Date.now(),previousStatus:i,newStatus:o,executionId:e};if(this.dataSourceChangeHistory.push(d),e){const g=this.executionDetails.get(e);g&&g.dataSourceChanges.push(d)}this.dataSourceChangeHistory.length>this.maxStateChangeHistory&&this.dataSourceChangeHistory.splice(0,this.dataSourceChangeHistory.length-this.maxStateChangeHistory)}expectChange(e,t,a){if(!this.config.enabled||!e)return;const i=this.executionDetails.get(e);if(!i)return;const o={expectedStatePaths:t,expectedDataSources:a,setAt:Date.now(),source:i.handlerName};this.changeExpectations.set(e,o)}checkExpectations(e,t,a){const i=new Set(t.stateChanges.map(d=>d.path)),o=new Set(t.dataSourceChanges.map(d=>d.dataSourceId));for(const d of a.expectedStatePaths)i.has(d)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 상태 변경 "${d}"가 발생하지 않음`,description:`핸들러 "${t.handlerName}"이(가) "${d}" 변경을 예고했지만 실제로 변경되지 않았습니다.`,handlerName:t.handlerName,statePath:d,suggestion:"핸들러 내부 로직을 확인하세요. early return이나 조건부 분기로 인해 변경이 생략되었을 수 있습니다.",docLink:".claude/docs/frontend/troubleshooting-state.md"});for(const d of a.expectedDataSources)o.has(d)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 데이터소스 갱신 "${d}"가 발생하지 않음`,description:`핸들러 "${t.handlerName}"이(가) "${d}" 갱신을 예고했지만 실제로 갱신되지 않았습니다.`,handlerName:t.handlerName,dataSourceId:d,suggestion:"refetchDataSource 호출이 실행되었는지 확인하세요.",docLink:".claude/docs/frontend/data-sources.md"})}addChangeAlert(e,t){const a={...t,id:`alert_${++this.alertIdCounter}`,timestamp:Date.now()};if(this.changeAlerts.push(a),e){const i=this.executionDetails.get(e);i&&i.alerts.push(a)}this.changeAlerts.length>this.maxChangeAlerts&&this.changeAlerts.splice(0,this.changeAlerts.length-this.maxChangeAlerts)}compareValues(e,t){const a=this.getValueType(e),i=this.getValueType(t),o=a!==i;let d=!1,g;return!o&&(a==="object"||a==="array")?(d=this.deepEqual(e,t),!d&&a==="object"&&(g=this.getChangedKeys(e,t))):d=e===t,{typeChanged:o,oldType:a,newType:i,isDeepEqual:d,changedKeys:g}}getValueType(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}deepEqual(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e===null||t===null||typeof e!="object")return e===t;if(Array.isArray(e)!==Array.isArray(t))return!1;const a=Object.keys(e),i=Object.keys(t);if(a.length!==i.length)return!1;for(const o of a)if(!i.includes(o)||!this.deepEqual(e[o],t[o]))return!1;return!0}getChangedKeys(e,t){const a=[],i=new Set([...Object.keys(e),...Object.keys(t)]);for(const o of i)this.deepEqual(e[o],t[o])||a.push(o);return a}getChangeDetectionInfo(){const e=Array.from(this.executionDetails.values()),t={totalExecutions:e.length,executionsWithStateChange:e.filter(a=>a.stateChanges.length>0).length,executionsWithoutStateChange:e.filter(a=>a.stateChanges.length===0&&a.exitReason==="normal").length,earlyReturnCount:e.filter(a=>a.exitReason==="early-return-condition"||a.exitReason==="early-return-validation").length,alertCount:this.changeAlerts.length,alertsByType:this.getAlertsByType()};return{executionDetails:e,stateChangeHistory:[...this.stateChangeHistory],dataSourceChangeHistory:[...this.dataSourceChangeHistory],alerts:[...this.changeAlerts],stats:t,timestamp:Date.now()}}getAlertsByType(){const e={"no-state-change":0,"no-datasource-change":0,"expected-not-fulfilled":0,"object-reference-same":0,"early-return-detected":0,"async-timing-issue":0};for(const t of this.changeAlerts)e[t.type]++;return e}clearChangeDetectionData(){this.executionDetails.clear(),this.stateChangeHistory=[],this.dataSourceChangeHistory=[],this.changeAlerts=[],this.changeExpectations.clear(),this.executionIdCounter=0,this.stateChangeIdCounter=0,this.alertIdCounter=0}getRecentAlerts(e=10,t){let a=[...this.changeAlerts];return t&&(a=a.filter(i=>i.severity===t)),a.slice(-e)}getHandlerExecutions(e,t=10){return Array.from(this.executionDetails.values()).filter(i=>i.handlerName===e).slice(-t)}findExecutionInStack(e){return this.sequenceExecutionStack.find(t=>t.sequenceId===e)}startSequenceExecution(e){if(!this.config.enabled)return"";const t=`seq_${++this.sequenceIdCounter}_${Date.now()}`,a={sequenceId:t,startTime:Date.now(),totalDuration:0,trigger:e,actions:[],status:"running"};return this.sequenceExecutionStack.push(a),t}captureSequenceActionBefore(e,t,a,i,o){if(!this.config.enabled)return;const d=this.findExecutionInStack(e);if(!d)return;const g={index:t,handler:a,params:this.safeClone(i),stateBeforeAction:{_global:this.safeClone(o._global),_local:this.safeClone(o._local),_isolated:o._isolated?this.safeClone(o._isolated):void 0},stateAfterAction:{_global:{},_local:{}},duration:0,status:"success"};d.actions.push(g)}captureSequenceActionAfter(e,t,a,i,o,d){if(!this.config.enabled)return;const g=this.findExecutionInStack(e);if(!g)return;const h=g.actions.find(p=>p.index===t);if(!h)return;h.stateAfterAction={_global:this.safeClone(a._global),_local:this.safeClone(a._local),_isolated:a._isolated?this.safeClone(a._isolated):void 0},h.duration=i,h.result=this.safeClone(o),h.stateDiff={global:this.computeStateDiff(h.stateBeforeAction._global,h.stateAfterAction._global),local:this.computeStateDiff(h.stateBeforeAction._local,h.stateAfterAction._local)},h.stateBeforeAction._isolated&&h.stateAfterAction._isolated&&(h.stateDiff.isolated=this.computeStateDiff(h.stateBeforeAction._isolated,h.stateAfterAction._isolated));const f=window.__g7PendingLocalState;f&&(h.pendingState=this.safeClone(f)),d&&(h.status="error",h.error={name:d.name,message:d.message,stack:d.stack})}endSequenceExecution(e,t){if(!this.config.enabled)return;const a=this.sequenceExecutionStack.findIndex(o=>o.sequenceId===e);if(a===-1)return;const i=this.sequenceExecutionStack[a];if(i.endTime=Date.now(),i.totalDuration=i.endTime-i.startTime,t){i.status="error",i.error={name:t.name,message:t.message,stack:t.stack};const o=i.actions.find(d=>d.status==="error");o&&(i.failedAtIndex=o.index)}else i.status="success";this.sequenceExecutions.push(i),this.sequenceExecutions.length>this.maxSequenceExecutions&&this.sequenceExecutions.shift(),this.sequenceExecutionStack.splice(a,1)}computeStateDiff(e,t){const a=[],i=[],o=[],d=new Set(Object.keys(e)),g=new Set(Object.keys(t));for(const h of g)d.has(h)||a.push(h);for(const h of d)g.has(h)||i.push(h);for(const h of d)if(g.has(h)){const f=e[h],p=t[h];JSON.stringify(f)!==JSON.stringify(p)&&o.push({path:h,oldValue:f,newValue:p})}return{added:a,removed:i,changed:o}}getSequenceTrackingInfo(){const e=this.getSequenceStats(),t=this.sequenceExecutionStack.length>0?this.sequenceExecutionStack[this.sequenceExecutionStack.length-1]:void 0;return{executions:[...this.sequenceExecutions],currentExecution:t,stats:e}}getSequenceStats(){const e=this.sequenceExecutions,t=e.length,a=e.filter(f=>f.status==="success").length,i=e.filter(f=>f.status==="error").length,o=e.reduce((f,p)=>f+p.actions.length,0),d=t>0?e.reduce((f,p)=>f+p.totalDuration,0)/t:0,g={};for(const f of e)for(const p of f.actions)g[p.handler]=(g[p.handler]||0)+1;const h=Object.entries(g).sort(([,f],[,p])=>p-f).slice(0,5).map(([f,p])=>({handler:f,count:p}));return{totalExecutions:t,successCount:a,errorCount:i,totalActions:o,avgDuration:d,topHandlers:h}}clearSequenceData(){this.sequenceExecutions=[],this.sequenceExecutionStack=[],this.sequenceIdCounter=0}getSequenceExecution(e){const t=this.findExecutionInStack(e);return t||this.sequenceExecutions.find(a=>a.sequenceId===e)}getRecentSequences(e=10){return this.sequenceExecutions.slice(-e)}registerStateCaptureForHandler(e,t,a){if(!this.config.enabled)return;const i=new Map,o=Date.now();for(const d of t)i.set(d,{value:this.safeClone(a[d]),capturedAt:o});this.stateCaptureRegistry.set(e,i)}detectStaleClosure(e,t,a,i,o){if(!this.config.enabled)return[];const d=this.stateCaptureRegistry.get(e);if(!d)return[];const g=Date.now(),h=[];for(const[f,p]of d){const y=this.getValueByPath(a,f),x=g-p.capturedAt;if(!this.isDeepEqual(p.value,y)&&x>0){const S=this.createStaleClosureWarning(i,t,f,p.value,p.capturedAt,y,g,x,o);h.push(S),this.addStaleClosureWarning(S)}}return this.stateCaptureRegistry.delete(e),h}trackStaleClosureWarning(e){if(!this.config.enabled)return;const t=Date.now(),a=this.createStaleClosureWarning(e.type,e.location,e.capturedPath,e.capturedValue,e.capturedAt,e.currentValue,t,t-e.capturedAt,e.actionId,e.stackTrace);this.addStaleClosureWarning(a)}createStaleClosureWarning(e,t,a,i,o,d,g,h,f,p){const y=this.getStaleClosureSeverity(e,h),{description:x,suggestion:S,docLink:v}=this.getStaleClosureMessages(e,a,h);return{id:`stale_${++this.staleClosureIdCounter}_${Date.now()}`,timestamp:Date.now(),type:e,location:t,capturedState:{path:a,capturedValue:this.safeClone(i),capturedAt:o},currentState:{path:a,currentValue:this.safeClone(d),retrievedAt:g},timeDiff:h,severity:y,description:x,suggestion:S,docLink:v,actionId:f,stackTrace:p}}getStaleClosureSeverity(e,t){if(t>5e3)return"error";if(t>1e3)return"warning";switch(e){case"async-state-capture":case"sequence-state-mismatch":return"warning";case"callback-state-capture":case"timeout-state-capture":return"info";case"event-handler-stale":return"warning";default:return"info"}}getStaleClosureMessages(e,t,a){const i=a<1e3?`${a}ms`:`${(a/1e3).toFixed(1)}s`;switch(e){case"async-state-capture":return{description:`await 후 ${i} 경과 시점에 '${t}' 상태가 변경됨. 캡처된 상태 대신 최신 상태를 사용해야 함`,suggestion:"await 이후에는 G7Core.state.get()으로 최신 상태를 다시 조회하거나, useRef + getter 패턴을 사용하세요",docLink:"troubleshooting-state-closure.md"};case"callback-state-capture":return{description:`콜백에서 ${i} 전에 캡처된 '${t}' 상태를 사용 중. 최신 상태와 다름`,suggestion:"콜백에서 상태를 참조할 때는 stateRef.current 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};case"timeout-state-capture":return{description:`setTimeout/setInterval 콜백에서 '${t}' 상태가 ${i} 전 값 사용 중`,suggestion:"타이머 콜백 내에서는 G7Core.state.get()으로 최신 상태를 조회하세요",docLink:"troubleshooting-state-closure.md"};case"sequence-state-mismatch":return{description:`sequence 내 '${t}' 상태가 이전 액션 결과와 불일치. context.state 대신 캡처된 값 사용 의심`,suggestion:"sequence 내에서는 context.state 또는 $prev를 사용하여 최신 상태를 참조하세요",docLink:"troubleshooting-state-setstate.md"};case"event-handler-stale":return{description:`이벤트 핸들러에서 ${i} 전에 바인딩된 '${t}' 상태 사용 중`,suggestion:"이벤트 핸들러에서 상태를 참조할 때는 useRef 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};default:return{description:`'${t}' 상태에서 stale closure 감지됨 (${i} 경과)`,suggestion:"상태 참조 시 최신 값을 사용하는지 확인하세요"}}}addStaleClosureWarning(e){this.staleClosureWarnings.push(e),this.staleClosureWarnings.length>this.maxStaleClosureWarnings&&this.staleClosureWarnings.shift()}getValueByPath(e,t){const a=t.split(".");let i=e;for(const o of a){if(i==null)return;i=i[o]}return i}isDeepEqual(e,t){if(e===t)return!0;if(e===null||t===null)return e===t;if(typeof e!=typeof t)return!1;if(typeof e!="object")return e===t;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}getStaleClosureTrackingInfo(){const e=this.getStaleClosureStats();return{warnings:[...this.staleClosureWarnings],stats:e,timestamp:Date.now()}}getStaleClosureStats(){const e=this.staleClosureWarnings,t={"async-state-capture":0,"callback-state-capture":0,"timeout-state-capture":0,"sequence-state-mismatch":0,"event-handler-stale":0};for(const h of e)t[h.type]++;const a={info:0,warning:0,error:0};for(const h of e)a[h.severity]++;const i={};for(const h of e)i[h.location]=(i[h.location]||0)+1;const o=Object.entries(i).sort(([,h],[,f])=>f-h).slice(0,5).map(([h,f])=>({location:h,count:f})),d={};for(const h of e)d[h.capturedState.path]=(d[h.capturedState.path]||0)+1;const g=Object.entries(d).sort(([,h],[,f])=>f-h).slice(0,5).map(([h,f])=>({path:h,count:f}));return{totalWarnings:e.length,warningsByType:t,warningsBySeverity:a,topLocations:o,topAffectedPaths:g}}clearStaleClosureData(){this.staleClosureWarnings=[],this.staleClosureIdCounter=0,this.stateCaptureRegistry.clear()}getRecentStaleClosureWarnings(e=10,t){let a=[...this.staleClosureWarnings];return t&&(a=a.filter(i=>i.severity===t)),a.slice(-e)}safeClone(e){if(e==null||typeof e!="object")return e;try{return JSON.parse(JSON.stringify(e))}catch{if(Array.isArray(e))return e.map(a=>{try{return JSON.parse(JSON.stringify(a))}catch{return"[Unserializable]"}});const t={};for(const a of Object.keys(e))try{t[a]=JSON.parse(JSON.stringify(e[a]))}catch{t[a]="[Unserializable]"}return t}}};H(Er,"instance");let ka=Er;const Kn=it("LayoutLoader");class Ms extends Error{constructor(e,t,a){super(e),this.code=t,this.details=a,this.name="LayoutLoaderError"}}class Rg{constructor(e){H(this,"componentRegistry");H(this,"currentLayout",null);H(this,"layoutCache",new Map);H(this,"cacheVersion",0);this.componentRegistry=e}setCacheVersion(e){this.cacheVersion!==e&&(Kn.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.layoutCache.clear())}getCacheVersion(){return this.cacheVersion}async loadLayout(e,t){const a=`${e}:${t}`;if(this.layoutCache.has(a)){Kn.log("Loading layout from cache:",t);const o=await this.layoutCache.get(a),d=JSON.parse(JSON.stringify(o));return this.currentLayout=d,ka.getInstance().trackLayoutLoad(t,e,d,"cache"),d}const i=this.fetchLayout(e,t);return this.layoutCache.set(a,i),i}async fetchLayout(e,t,a=!1){try{let i;t.startsWith("__preview__/")?i=`/api/layouts/preview/${t.replace("__preview__/","")}.json`:i=`/api/layouts/${e}/${t}.json`;const o=this.cacheVersion>0?`${i}?v=${this.cacheVersion}`:i;Kn.log("Fetching layout from API:",o);const d=ns(),g=a?null:d.getToken(),h={Accept:"application/json"};g&&(h.Authorization=`Bearer ${g}`);const f=await fetch(o,{headers:h});let p;try{p=await f.json()}catch{p=null}if(!f.ok){if(f.status===401&&!a&&g)return Kn.log("Token invalid, removing and retrying without token"),d.removeToken(),this.fetchLayout(e,t,!0);const x=p?.message||p?.error;throw new Ms(`Failed to fetch layout: ${f.status} ${f.statusText}`,"FETCH_FAILED",{status:f.status,statusText:f.statusText,url:o,apiMessage:x})}const y=p.data||p;return this.validateLayoutData(y),this.currentLayout=y,ka.getInstance().trackLayoutLoad(t,e,y,"api"),Kn.log("Layout fetched and cached successfully:",y.layout_name),y}catch(i){const o=`${e}:${t}`;throw this.layoutCache.delete(o),i instanceof Ms?i:new Ms("Failed to load layout","LOAD_FAILED",{originalError:i})}}prefetchLayout(e,t){return this.loadLayout(e,t)}validateLayoutData(e){if(!e.version)throw new Ms("Layout data missing required field: version","VALIDATION_FAILED",{field:"version"});if(!e.layout_name)throw new Ms("Layout data missing required field: layout_name","VALIDATION_FAILED",{field:"layout_name"});if(!Array.isArray(e.components))throw new Ms('Layout data field "components" must be an array',"VALIDATION_FAILED",{field:"components",value:e.components});Kn.log("Layout data validation passed")}renderLayout(e,t){try{const a=t||this.currentLayout;if(!a)throw new Ms("No layout data to render","NO_LAYOUT_DATA");Kn.log("Rendering layout:",a.layout_name),e.innerHTML="",this.renderComponents(e,a.components),Kn.log("Layout rendered successfully")}catch(a){Kn.error("Render error:",a),this.renderErrorState(e,a)}}renderComponents(e,t){for(const a of t){const i=this.renderComponent(a);i&&e.appendChild(i)}}renderComponent(e){try{if(!this.componentRegistry.getComponent(e.type))return Kn.warn(`Component not found: ${e.type}`),this.createPlaceholderElement(e.type);const a=document.createElement("div");return a.setAttribute("data-component",e.type),e.props&&Object.entries(e.props).forEach(([i,o])=>{a.setAttribute(`data-prop-${i}`,JSON.stringify(o))}),e.children&&e.children.length>0?this.renderComponents(a,e.children):e.text&&(a.textContent=e.text),a}catch(t){return Kn.error(`Error rendering component ${e.type}:`,t),this.createErrorElement(e.type,t)}}createPlaceholderElement(e){const t=document.createElement("div");return t.className="component-placeholder",t.setAttribute("data-component-type",e),t.innerHTML=` + `},q7={onDragStart(r){let{active:e}=r;return"Picked up draggable item "+e.id+"."},onDragOver(r){let{active:e,over:t}=r;return t?"Draggable item "+e.id+" was moved over droppable area "+t.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(r){let{active:e,over:t}=r;return t?"Draggable item "+e.id+" was dropped over droppable area "+t.id:"Draggable item "+e.id+" was dropped."},onDragCancel(r){let{active:e}=r;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function G7(r){let{announcements:e=q7,container:t,hiddenTextDescribedById:a,screenReaderInstructions:i=U7}=r;const{announce:o,announcement:d}=H7(),g=No("DndLiveRegion"),[h,f]=j.useState(!1);if(j.useEffect(()=>{f(!0)},[]),P7(j.useMemo(()=>({onDragStart(y){let{active:x}=y;o(e.onDragStart({active:x}))},onDragMove(y){let{active:x,over:S}=y;e.onDragMove&&o(e.onDragMove({active:x,over:S}))},onDragOver(y){let{active:x,over:S}=y;o(e.onDragOver({active:x,over:S}))},onDragEnd(y){let{active:x,over:S}=y;o(e.onDragEnd({active:x,over:S}))},onDragCancel(y){let{active:x,over:S}=y;o(e.onDragCancel({active:x,over:S}))}}),[o,e])),!h)return null;const p=Ke.createElement(Ke.Fragment,null,Ke.createElement(I7,{id:a,value:i.draggable}),Ke.createElement(z7,{id:g,announcement:d}));return t?Os.createPortal(p,t):p}var cn;(function(r){r.DragStart="dragStart",r.DragMove="dragMove",r.DragEnd="dragEnd",r.DragCancel="dragCancel",r.DragOver="dragOver",r.RegisterDroppable="registerDroppable",r.SetDroppableDisabled="setDroppableDisabled",r.UnregisterDroppable="unregisterDroppable"})(cn||(cn={}));function Sc(){}function iy(r,e){return j.useMemo(()=>({sensor:r,options:e??{}}),[r,e])}function F7(){for(var r=arguments.length,e=new Array(r),t=0;t[...e].filter(a=>a!=null),[...e])}const Ca=Object.freeze({x:0,y:0});function oy(r,e){return Math.sqrt(Math.pow(r.x-e.x,2)+Math.pow(r.y-e.y,2))}function ly(r,e){let{data:{value:t}}=r,{data:{value:a}}=e;return t-a}function V7(r,e){let{data:{value:t}}=r,{data:{value:a}}=e;return a-t}function cy(r){let{left:e,top:t,height:a,width:i}=r;return[{x:e,y:t},{x:e+i,y:t},{x:e,y:t+a},{x:e+i,y:t+a}]}function dy(r,e){if(!r||r.length===0)return null;const[t]=r;return t[e]}function uy(r,e,t){return e===void 0&&(e=r.left),t===void 0&&(t=r.top),{x:e+r.width*.5,y:t+r.height*.5}}const K7=r=>{let{collisionRect:e,droppableRects:t,droppableContainers:a}=r;const i=uy(e,e.left,e.top),o=[];for(const d of a){const{id:g}=d,h=t.get(g);if(h){const f=oy(uy(h),i);o.push({id:g,data:{droppableContainer:d,value:f}})}}return o.sort(ly)},W7=r=>{let{collisionRect:e,droppableRects:t,droppableContainers:a}=r;const i=cy(e),o=[];for(const d of a){const{id:g}=d,h=t.get(g);if(h){const f=cy(h),p=i.reduce((x,S,v)=>x+oy(f[v],S),0),y=Number((p/4).toFixed(4));o.push({id:g,data:{droppableContainer:d,value:y}})}}return o.sort(ly)};function Y7(r,e){const t=Math.max(e.top,r.top),a=Math.max(e.left,r.left),i=Math.min(e.left+e.width,r.left+r.width),o=Math.min(e.top+e.height,r.top+r.height),d=i-a,g=o-t;if(a{let{collisionRect:e,droppableRects:t,droppableContainers:a}=r;const i=[];for(const o of a){const{id:d}=o,g=t.get(d);if(g){const h=Y7(g,e);h>0&&i.push({id:d,data:{droppableContainer:o,value:h}})}}return i.sort(V7)};function X7(r,e,t){return{...r,scaleX:e&&t?e.width/t.width:1,scaleY:e&&t?e.height/t.height:1}}function gy(r,e){return r&&e?{x:r.left-e.left,y:r.top-e.top}:Ca}function Q7(r){return function(t){for(var a=arguments.length,i=new Array(a>1?a-1:0),o=1;o({...d,top:d.top+r*g.y,bottom:d.bottom+r*g.y,left:d.left+r*g.x,right:d.right+r*g.x}),{...t})}}const Z7=Q7(1);function eC(r){if(r.startsWith("matrix3d(")){const e=r.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(r.startsWith("matrix(")){const e=r.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function tC(r,e,t){const a=eC(e);if(!a)return r;const{scaleX:i,scaleY:o,x:d,y:g}=a,h=r.left-d-(1-i)*parseFloat(t),f=r.top-g-(1-o)*parseFloat(t.slice(t.indexOf(" ")+1)),p=i?r.width/i:r.width,y=o?r.height/o:r.height;return{width:p,height:y,top:f,right:h+p,bottom:f+y,left:h}}const nC={ignoreTransform:!1};function ui(r,e){e===void 0&&(e=nC);let t=r.getBoundingClientRect();if(e.ignoreTransform){const{transform:f,transformOrigin:p}=Ln(r).getComputedStyle(r);f&&(t=tC(t,f,p))}const{top:a,left:i,width:o,height:d,bottom:g,right:h}=t;return{top:a,left:i,width:o,height:d,bottom:g,right:h}}function hy(r){return ui(r,{ignoreTransform:!0})}function aC(r){const e=r.innerWidth,t=r.innerHeight;return{top:0,left:0,right:e,bottom:t,width:e,height:t}}function sC(r,e){return e===void 0&&(e=Ln(r).getComputedStyle(r)),e.position==="fixed"}function rC(r,e){e===void 0&&(e=Ln(r).getComputedStyle(r));const t=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const o=e[i];return typeof o=="string"?t.test(o):!1})}function Cc(r,e){const t=[];function a(i){if(e!=null&&t.length>=e||!i)return t;if(fg(i)&&i.scrollingElement!=null&&!t.includes(i.scrollingElement))return t.push(i.scrollingElement),t;if(!Co(i)||ny(i)||t.includes(i))return t;const o=Ln(r).getComputedStyle(i);return i!==r&&rC(i,o)&&t.push(i),sC(i,o)?t:a(i.parentNode)}return r?a(r):t}function fy(r){const[e]=Cc(r,1);return e??null}function vg(r){return!vc||!r?null:li(r)?r:hg(r)?fg(r)||r===ci(r).scrollingElement?window:Co(r)?r:null:null}function py(r){return li(r)?r.scrollX:r.scrollLeft}function my(r){return li(r)?r.scrollY:r.scrollTop}function wg(r){return{x:py(r),y:my(r)}}var pn;(function(r){r[r.Forward=1]="Forward",r[r.Backward=-1]="Backward"})(pn||(pn={}));function yy(r){return!vc||!r?!1:r===document.scrollingElement}function xy(r){const e={x:0,y:0},t=yy(r)?{height:window.innerHeight,width:window.innerWidth}:{height:r.clientHeight,width:r.clientWidth},a={x:r.scrollWidth-t.width,y:r.scrollHeight-t.height},i=r.scrollTop<=e.y,o=r.scrollLeft<=e.x,d=r.scrollTop>=a.y,g=r.scrollLeft>=a.x;return{isTop:i,isLeft:o,isBottom:d,isRight:g,maxScroll:a,minScroll:e}}const iC={x:.2,y:.2};function oC(r,e,t,a,i){let{top:o,left:d,right:g,bottom:h}=t;a===void 0&&(a=10),i===void 0&&(i=iC);const{isTop:f,isBottom:p,isLeft:y,isRight:x}=xy(r),S={x:0,y:0},v={x:0,y:0},w={height:e.height*i.y,width:e.width*i.x};return!f&&o<=e.top+w.height?(S.y=pn.Backward,v.y=a*Math.abs((e.top+w.height-o)/w.height)):!p&&h>=e.bottom-w.height&&(S.y=pn.Forward,v.y=a*Math.abs((e.bottom-w.height-h)/w.height)),!x&&g>=e.right-w.width?(S.x=pn.Forward,v.x=a*Math.abs((e.right-w.width-g)/w.width)):!y&&d<=e.left+w.width&&(S.x=pn.Backward,v.x=a*Math.abs((e.left+w.width-d)/w.width)),{direction:S,speed:v}}function lC(r){if(r===document.scrollingElement){const{innerWidth:o,innerHeight:d}=window;return{top:0,left:0,right:o,bottom:d,width:o,height:d}}const{top:e,left:t,right:a,bottom:i}=r.getBoundingClientRect();return{top:e,left:t,right:a,bottom:i,width:r.clientWidth,height:r.clientHeight}}function by(r){return r.reduce((e,t)=>di(e,wg(t)),Ca)}function cC(r){return r.reduce((e,t)=>e+py(t),0)}function dC(r){return r.reduce((e,t)=>e+my(t),0)}function uC(r,e){if(e===void 0&&(e=ui),!r)return;const{top:t,left:a,bottom:i,right:o}=e(r);fy(r)&&(i<=0||o<=0||t>=window.innerHeight||a>=window.innerWidth)&&r.scrollIntoView({block:"center",inline:"center"})}const gC=[["x",["left","right"],cC],["y",["top","bottom"],dC]];class Sg{constructor(e,t){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const a=Cc(t),i=by(a);this.rect={...e},this.width=e.width,this.height=e.height;for(const[o,d,g]of gC)for(const h of d)Object.defineProperty(this,h,{get:()=>{const f=g(a),p=i[o]-f;return this.rect[h]+p},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Ao{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(t=>{var a;return(a=this.target)==null?void 0:a.removeEventListener(...t)})},this.target=e}add(e,t,a){var i;(i=this.target)==null||i.addEventListener(e,t,a),this.listeners.push([e,t,a])}}function hC(r){const{EventTarget:e}=Ln(r);return r instanceof e?r:ci(r)}function Cg(r,e){const t=Math.abs(r.x),a=Math.abs(r.y);return typeof e=="number"?Math.sqrt(t**2+a**2)>e:"x"in e&&"y"in e?t>e.x&&a>e.y:"x"in e?t>e.x:"y"in e?a>e.y:!1}var ra;(function(r){r.Click="click",r.DragStart="dragstart",r.Keydown="keydown",r.ContextMenu="contextmenu",r.Resize="resize",r.SelectionChange="selectionchange",r.VisibilityChange="visibilitychange"})(ra||(ra={}));function vy(r){r.preventDefault()}function fC(r){r.stopPropagation()}var ft;(function(r){r.Space="Space",r.Down="ArrowDown",r.Right="ArrowRight",r.Left="ArrowLeft",r.Up="ArrowUp",r.Esc="Escape",r.Enter="Enter",r.Tab="Tab"})(ft||(ft={}));const wy={start:[ft.Space,ft.Enter],cancel:[ft.Esc],end:[ft.Space,ft.Enter,ft.Tab]},pC=(r,e)=>{let{currentCoordinates:t}=e;switch(r.code){case ft.Right:return{...t,x:t.x+25};case ft.Left:return{...t,x:t.x-25};case ft.Down:return{...t,y:t.y+25};case ft.Up:return{...t,y:t.y-25}}};class jg{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:t}}=e;this.props=e,this.listeners=new Ao(ci(t)),this.windowListeners=new Ao(Ln(t)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(ra.Resize,this.handleCancel),this.windowListeners.add(ra.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(ra.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:t}=this.props,a=e.node.current;a&&uC(a),t(Ca)}handleKeyDown(e){if(xg(e)){const{active:t,context:a,options:i}=this.props,{keyboardCodes:o=wy,coordinateGetter:d=pC,scrollBehavior:g="smooth"}=i,{code:h}=e;if(o.end.includes(h)){this.handleEnd(e);return}if(o.cancel.includes(h)){this.handleCancel(e);return}const{collisionRect:f}=a.current,p=f?{x:f.left,y:f.top}:Ca;this.referenceCoordinates||(this.referenceCoordinates=p);const y=d(e,{active:t,context:a.current,currentCoordinates:p});if(y){const x=Eo(y,p),S={x:0,y:0},{scrollableAncestors:v}=a.current;for(const w of v){const k=e.code,{isTop:A,isRight:O,isLeft:N,isBottom:D,maxScroll:$,minScroll:M}=xy(w),z=lC(w),K={x:Math.min(k===ft.Right?z.right-z.width/2:z.right,Math.max(k===ft.Right?z.left:z.left+z.width/2,y.x)),y:Math.min(k===ft.Down?z.bottom-z.height/2:z.bottom,Math.max(k===ft.Down?z.top:z.top+z.height/2,y.y))},ye=k===ft.Right&&!O||k===ft.Left&&!N,we=k===ft.Down&&!D||k===ft.Up&&!A;if(ye&&K.x!==y.x){const J=w.scrollLeft+x.x,ve=k===ft.Right&&J<=$.x||k===ft.Left&&J>=M.x;if(ve&&!x.y){w.scrollTo({left:J,behavior:g});return}ve?S.x=w.scrollLeft-J:S.x=k===ft.Right?w.scrollLeft-$.x:w.scrollLeft-M.x,S.x&&w.scrollBy({left:-S.x,behavior:g});break}else if(we&&K.y!==y.y){const J=w.scrollTop+x.y,ve=k===ft.Down&&J<=$.y||k===ft.Up&&J>=M.y;if(ve&&!x.x){w.scrollTo({top:J,behavior:g});return}ve?S.y=w.scrollTop-J:S.y=k===ft.Down?w.scrollTop-$.y:w.scrollTop-M.y,S.y&&w.scrollBy({top:-S.y,behavior:g});break}}this.handleMove(e,di(Eo(y,this.referenceCoordinates),S))}}}handleMove(e,t){const{onMove:a}=this.props;e.preventDefault(),a(t)}handleEnd(e){const{onEnd:t}=this.props;e.preventDefault(),this.detach(),t()}handleCancel(e){const{onCancel:t}=this.props;e.preventDefault(),this.detach(),t()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}jg.activators=[{eventName:"onKeyDown",handler:(r,e,t)=>{let{keyboardCodes:a=wy,onActivation:i}=e,{active:o}=t;const{code:d}=r.nativeEvent;if(a.start.includes(d)){const g=o.activatorNode.current;return g&&r.target!==g?!1:(r.preventDefault(),i?.({event:r.nativeEvent}),!0)}return!1}}];function Sy(r){return!!(r&&"distance"in r)}function Cy(r){return!!(r&&"delay"in r)}class kg{constructor(e,t,a){var i;a===void 0&&(a=hC(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=t;const{event:o}=e,{target:d}=o;this.props=e,this.events=t,this.document=ci(d),this.documentListeners=new Ao(this.document),this.listeners=new Ao(a),this.windowListeners=new Ao(Ln(d)),this.initialCoordinates=(i=bg(o))!=null?i:Ca,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:e,props:{options:{activationConstraint:t,bypassActivationConstraint:a}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(ra.Resize,this.handleCancel),this.windowListeners.add(ra.DragStart,vy),this.windowListeners.add(ra.VisibilityChange,this.handleCancel),this.windowListeners.add(ra.ContextMenu,vy),this.documentListeners.add(ra.Keydown,this.handleKeydown),t){if(a!=null&&a({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Cy(t)){this.timeoutId=setTimeout(this.handleStart,t.delay),this.handlePending(t);return}if(Sy(t)){this.handlePending(t);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,t){const{active:a,onPending:i}=this.props;i(a,e,this.initialCoordinates,t)}handleStart(){const{initialCoordinates:e}=this,{onStart:t}=this.props;e&&(this.activated=!0,this.documentListeners.add(ra.Click,fC,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(ra.SelectionChange,this.removeTextSelection),t(e))}handleMove(e){var t;const{activated:a,initialCoordinates:i,props:o}=this,{onMove:d,options:{activationConstraint:g}}=o;if(!i)return;const h=(t=bg(e))!=null?t:Ca,f=Eo(i,h);if(!a&&g){if(Sy(g)){if(g.tolerance!=null&&Cg(f,g.tolerance))return this.handleCancel();if(Cg(f,g.distance))return this.handleStart()}if(Cy(g)&&Cg(f,g.tolerance))return this.handleCancel();this.handlePending(g,f);return}e.cancelable&&e.preventDefault(),d(h)}handleEnd(){const{onAbort:e,onEnd:t}=this.props;this.detach(),this.activated||e(this.props.active),t()}handleCancel(){const{onAbort:e,onCancel:t}=this.props;this.detach(),this.activated||e(this.props.active),t()}handleKeydown(e){e.code===ft.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const mC={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Ng extends kg{constructor(e){const{event:t}=e,a=ci(t.target);super(e,mC,a)}}Ng.activators=[{eventName:"onPointerDown",handler:(r,e)=>{let{nativeEvent:t}=r,{onActivation:a}=e;return!t.isPrimary||t.button!==0?!1:(a?.({event:t}),!0)}}];const yC={move:{name:"mousemove"},end:{name:"mouseup"}};var Eg;(function(r){r[r.RightClick=2]="RightClick"})(Eg||(Eg={}));class xC extends kg{constructor(e){super(e,yC,ci(e.event.target))}}xC.activators=[{eventName:"onMouseDown",handler:(r,e)=>{let{nativeEvent:t}=r,{onActivation:a}=e;return t.button===Eg.RightClick?!1:(a?.({event:t}),!0)}}];const _g={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class bC extends kg{constructor(e){super(e,_g)}static setup(){return window.addEventListener(_g.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(_g.move.name,e)};function e(){}}}bC.activators=[{eventName:"onTouchStart",handler:(r,e)=>{let{nativeEvent:t}=r,{onActivation:a}=e;const{touches:i}=t;return i.length>1?!1:(a?.({event:t}),!0)}}];var To;(function(r){r[r.Pointer=0]="Pointer",r[r.DraggableRect=1]="DraggableRect"})(To||(To={}));var jc;(function(r){r[r.TreeOrder=0]="TreeOrder",r[r.ReversedTreeOrder=1]="ReversedTreeOrder"})(jc||(jc={}));function vC(r){let{acceleration:e,activator:t=To.Pointer,canScroll:a,draggingRect:i,enabled:o,interval:d=5,order:g=jc.TreeOrder,pointerCoordinates:h,scrollableAncestors:f,scrollableAncestorRects:p,delta:y,threshold:x}=r;const S=SC({delta:y,disabled:!o}),[v,w]=R7(),k=j.useRef({x:0,y:0}),A=j.useRef({x:0,y:0}),O=j.useMemo(()=>{switch(t){case To.Pointer:return h?{top:h.y,bottom:h.y,left:h.x,right:h.x}:null;case To.DraggableRect:return i}},[t,i,h]),N=j.useRef(null),D=j.useCallback(()=>{const M=N.current;if(!M)return;const z=k.current.x*A.current.x,K=k.current.y*A.current.y;M.scrollBy(z,K)},[]),$=j.useMemo(()=>g===jc.TreeOrder?[...f].reverse():f,[g,f]);j.useEffect(()=>{if(!o||!f.length||!O){w();return}for(const M of $){if(a?.(M)===!1)continue;const z=f.indexOf(M),K=p[z];if(!K)continue;const{direction:ye,speed:we}=oC(M,K,O,e,x);for(const J of["x","y"])S[J][ye[J]]||(we[J]=0,ye[J]=0);if(we.x>0||we.y>0){w(),N.current=M,v(D,d),k.current=we,A.current=ye;return}}k.current={x:0,y:0},A.current={x:0,y:0},w()},[e,D,a,w,o,d,JSON.stringify(O),JSON.stringify(S),v,f,$,p,JSON.stringify(x)])}const wC={x:{[pn.Backward]:!1,[pn.Forward]:!1},y:{[pn.Backward]:!1,[pn.Forward]:!1}};function SC(r){let{delta:e,disabled:t}=r;const a=mg(e);return ko(i=>{if(t||!a||!i)return wC;const o={x:Math.sign(e.x-a.x),y:Math.sign(e.y-a.y)};return{x:{[pn.Backward]:i.x[pn.Backward]||o.x===-1,[pn.Forward]:i.x[pn.Forward]||o.x===1},y:{[pn.Backward]:i.y[pn.Backward]||o.y===-1,[pn.Forward]:i.y[pn.Forward]||o.y===1}}},[t,e,a])}function CC(r,e){const t=e!=null?r.get(e):void 0,a=t?t.node.current:null;return ko(i=>{var o;return e==null?null:(o=a??i)!=null?o:null},[a,e])}function jC(r,e){return j.useMemo(()=>r.reduce((t,a)=>{const{sensor:i}=a,o=i.activators.map(d=>({eventName:d.eventName,handler:e(d.handler,a)}));return[...t,...o]},[]),[r,e])}var Do;(function(r){r[r.Always=0]="Always",r[r.BeforeDragging=1]="BeforeDragging",r[r.WhileDragging=2]="WhileDragging"})(Do||(Do={}));var Ag;(function(r){r.Optimized="optimized"})(Ag||(Ag={}));const jy=new Map;function kC(r,e){let{dragging:t,dependencies:a,config:i}=e;const[o,d]=j.useState(null),{frequency:g,measure:h,strategy:f}=i,p=j.useRef(r),y=k(),x=jo(y),S=j.useCallback(function(A){A===void 0&&(A=[]),!x.current&&d(O=>O===null?A:O.concat(A.filter(N=>!O.includes(N))))},[x]),v=j.useRef(null),w=ko(A=>{if(y&&!t)return jy;if(!A||A===jy||p.current!==r||o!=null){const O=new Map;for(let N of r){if(!N)continue;if(o&&o.length>0&&!o.includes(N.id)&&N.rect.current){O.set(N.id,N.rect.current);continue}const D=N.node.current,$=D?new Sg(h(D),D):null;N.rect.current=$,$&&O.set(N.id,$)}return O}return A},[r,o,t,y,h]);return j.useEffect(()=>{p.current=r},[r]),j.useEffect(()=>{y||S()},[t,y]),j.useEffect(()=>{o&&o.length>0&&d(null)},[JSON.stringify(o)]),j.useEffect(()=>{y||typeof g!="number"||v.current!==null||(v.current=setTimeout(()=>{S(),v.current=null},g))},[g,y,S,...a]),{droppableRects:w,measureDroppableContainers:S,measuringScheduled:o!=null};function k(){switch(f){case Do.Always:return!1;case Do.BeforeDragging:return t;default:return!t}}}function ky(r,e){return ko(t=>r?t||(typeof e=="function"?e(r):r):null,[e,r])}function NC(r,e){return ky(r,e)}function EC(r){let{callback:e,disabled:t}=r;const a=pg(e),i=j.useMemo(()=>{if(t||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:o}=window;return new o(a)},[a,t]);return j.useEffect(()=>()=>i?.disconnect(),[i]),i}function kc(r){let{callback:e,disabled:t}=r;const a=pg(e),i=j.useMemo(()=>{if(t||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:o}=window;return new o(a)},[t]);return j.useEffect(()=>()=>i?.disconnect(),[i]),i}function _C(r){return new Sg(ui(r),r)}function Ny(r,e,t){e===void 0&&(e=_C);const[a,i]=j.useState(null);function o(){i(h=>{if(!r)return null;if(r.isConnected===!1){var f;return(f=h??t)!=null?f:null}const p=e(r);return JSON.stringify(h)===JSON.stringify(p)?h:p})}const d=EC({callback(h){if(r)for(const f of h){const{type:p,target:y}=f;if(p==="childList"&&y instanceof HTMLElement&&y.contains(r)){o();break}}}}),g=kc({callback:o});return Ba(()=>{o(),r?(g?.observe(r),d?.observe(document.body,{childList:!0,subtree:!0})):(g?.disconnect(),d?.disconnect())},[r]),a}function AC(r){const e=ky(r);return gy(r,e)}const Ey=[];function TC(r){const e=j.useRef(r),t=ko(a=>r?a&&a!==Ey&&r&&e.current&&r.parentNode===e.current.parentNode?a:Cc(r):Ey,[r]);return j.useEffect(()=>{e.current=r},[r]),t}function DC(r){const[e,t]=j.useState(null),a=j.useRef(r),i=j.useCallback(o=>{const d=vg(o.target);d&&t(g=>g?(g.set(d,wg(d)),new Map(g)):null)},[]);return j.useEffect(()=>{const o=a.current;if(r!==o){d(o);const g=r.map(h=>{const f=vg(h);return f?(f.addEventListener("scroll",i,{passive:!0}),[f,wg(f)]):null}).filter(h=>h!=null);t(g.length?new Map(g):null),a.current=r}return()=>{d(r),d(o)};function d(g){g.forEach(h=>{const f=vg(h);f?.removeEventListener("scroll",i)})}},[i,r]),j.useMemo(()=>r.length?e?Array.from(e.values()).reduce((o,d)=>di(o,d),Ca):by(r):Ca,[r,e])}function _y(r,e){e===void 0&&(e=[]);const t=j.useRef(null);return j.useEffect(()=>{t.current=null},e),j.useEffect(()=>{const a=r!==Ca;a&&!t.current&&(t.current=r),!a&&t.current&&(t.current=null)},[r]),t.current?Eo(r,t.current):Ca}function RC(r){j.useEffect(()=>{if(!vc)return;const e=r.map(t=>{let{sensor:a}=t;return a.setup==null?void 0:a.setup()});return()=>{for(const t of e)t?.()}},r.map(e=>{let{sensor:t}=e;return t}))}function OC(r,e){return j.useMemo(()=>r.reduce((t,a)=>{let{eventName:i,handler:o}=a;return t[i]=d=>{o(d,e)},t},{}),[r,e])}function Ay(r){return j.useMemo(()=>r?aC(r):null,[r])}const Ty=[];function LC(r,e){e===void 0&&(e=ui);const[t]=r,a=Ay(t?Ln(t):null),[i,o]=j.useState(Ty);function d(){o(()=>r.length?r.map(h=>yy(h)?a:new Sg(e(h),h)):Ty)}const g=kc({callback:d});return Ba(()=>{g?.disconnect(),d(),r.forEach(h=>g?.observe(h))},[r]),i}function MC(r){if(!r)return null;if(r.children.length>1)return r;const e=r.children[0];return Co(e)?e:r}function $C(r){let{measure:e}=r;const[t,a]=j.useState(null),i=j.useCallback(f=>{for(const{target:p}of f)if(Co(p)){a(y=>{const x=e(p);return y?{...y,width:x.width,height:x.height}:x});break}},[e]),o=kc({callback:i}),d=j.useCallback(f=>{const p=MC(f);o?.disconnect(),p&&o?.observe(p),a(p?e(p):null)},[e,o]),[g,h]=wc(d);return j.useMemo(()=>({nodeRef:g,rect:t,setRef:h}),[t,g,h])}const IC=[{sensor:Ng,options:{}},{sensor:jg,options:{}}],zC={current:{}},Nc={draggable:{measure:hy},droppable:{measure:hy,strategy:Do.WhileDragging,frequency:Ag.Optimized},dragOverlay:{measure:ui}};class Ro extends Map{get(e){var t;return e!=null&&(t=super.get(e))!=null?t:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:t}=e;return!t})}getNodeFor(e){var t,a;return(t=(a=this.get(e))==null?void 0:a.node.current)!=null?t:void 0}}const HC={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Ro,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Sc},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Nc,measureDroppableContainers:Sc,windowRect:null,measuringScheduled:!1},PC={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Sc,draggableNodes:new Map,over:null,measureDroppableContainers:Sc},Ec=j.createContext(PC),Dy=j.createContext(HC);function BC(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Ro}}}function UC(r,e){switch(e.type){case cn.DragStart:return{...r,draggable:{...r.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case cn.DragMove:return r.draggable.active==null?r:{...r,draggable:{...r.draggable,translate:{x:e.coordinates.x-r.draggable.initialCoordinates.x,y:e.coordinates.y-r.draggable.initialCoordinates.y}}};case cn.DragEnd:case cn.DragCancel:return{...r,draggable:{...r.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case cn.RegisterDroppable:{const{element:t}=e,{id:a}=t,i=new Ro(r.droppable.containers);return i.set(a,t),{...r,droppable:{...r.droppable,containers:i}}}case cn.SetDroppableDisabled:{const{id:t,key:a,disabled:i}=e,o=r.droppable.containers.get(t);if(!o||a!==o.key)return r;const d=new Ro(r.droppable.containers);return d.set(t,{...o,disabled:i}),{...r,droppable:{...r.droppable,containers:d}}}case cn.UnregisterDroppable:{const{id:t,key:a}=e,i=r.droppable.containers.get(t);if(!i||a!==i.key)return r;const o=new Ro(r.droppable.containers);return o.delete(t),{...r,droppable:{...r.droppable,containers:o}}}default:return r}}function qC(r){let{disabled:e}=r;const{active:t,activatorEvent:a,draggableNodes:i}=j.useContext(Ec),o=mg(a),d=mg(t?.id);return j.useEffect(()=>{if(!e&&!a&&o&&d!=null){if(!xg(o)||document.activeElement===o.target)return;const g=i.get(d);if(!g)return;const{activatorNode:h,node:f}=g;if(!h.current&&!f.current)return;requestAnimationFrame(()=>{for(const p of[h.current,f.current]){if(!p)continue;const y=M7(p);if(y){y.focus();break}}})}},[a,e,i,d,o]),null}function GC(r,e){let{transform:t,...a}=e;return r!=null&&r.length?r.reduce((i,o)=>o({transform:i,...a}),t):t}function FC(r){return j.useMemo(()=>({draggable:{...Nc.draggable,...r?.draggable},droppable:{...Nc.droppable,...r?.droppable},dragOverlay:{...Nc.dragOverlay,...r?.dragOverlay}}),[r?.draggable,r?.droppable,r?.dragOverlay])}function VC(r){let{activeNode:e,measure:t,initialRect:a,config:i=!0}=r;const o=j.useRef(!1),{x:d,y:g}=typeof i=="boolean"?{x:i,y:i}:i;Ba(()=>{if(!d&&!g||!e){o.current=!1;return}if(o.current||!a)return;const f=e?.node.current;if(!f||f.isConnected===!1)return;const p=t(f),y=gy(p,a);if(d||(y.x=0),g||(y.y=0),o.current=!0,Math.abs(y.x)>0||Math.abs(y.y)>0){const x=fy(f);x&&x.scrollBy({top:y.y,left:y.x})}},[e,d,g,a,t])}const Ry=j.createContext({...Ca,scaleX:1,scaleY:1});var Ls;(function(r){r[r.Uninitialized=0]="Uninitialized",r[r.Initializing=1]="Initializing",r[r.Initialized=2]="Initialized"})(Ls||(Ls={}));const KC=j.memo(function(e){var t,a,i,o;let{id:d,accessibility:g,autoScroll:h=!0,children:f,sensors:p=IC,collisionDetection:y=J7,measuring:x,modifiers:S,...v}=e;const w=j.useReducer(UC,void 0,BC),[k,A]=w,[O,N]=B7(),[D,$]=j.useState(Ls.Uninitialized),M=D===Ls.Initialized,{draggable:{active:z,nodes:K,translate:ye},droppable:{containers:we}}=k,J=z!=null?K.get(z):null,ve=j.useRef({initial:null,translated:null}),le=j.useMemo(()=>{var Ue;return z!=null?{id:z,data:(Ue=J?.data)!=null?Ue:zC,rect:ve}:null},[z,J]),de=j.useRef(null),[je,W]=j.useState(null),[he,ee]=j.useState(null),X=jo(v,Object.values(v)),ae=No("DndDescribedBy",d),R=j.useMemo(()=>we.getEnabled(),[we]),U=FC(x),{droppableRects:re,measureDroppableContainers:xe,measuringScheduled:oe}=kC(R,{dragging:M,dependencies:[ye.x,ye.y],config:U.droppable}),ke=CC(K,z),Oe=j.useMemo(()=>he?bg(he):null,[he]),Te=Be(),qe=NC(ke,U.draggable.measure);VC({activeNode:z!=null?K.get(z):null,config:Te.layoutShiftCompensation,initialRect:qe,measure:U.draggable.measure});const Ie=Ny(ke,U.draggable.measure,qe),Nt=Ny(ke?ke.parentElement:null),Rt=j.useRef({activatorEvent:null,active:null,activeNode:ke,collisionRect:null,collisions:null,droppableRects:re,draggableNodes:K,draggingNode:null,draggingNodeRect:null,droppableContainers:we,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Xt=we.getNodeFor((t=Rt.current.over)==null?void 0:t.id),Mt=$C({measure:U.dragOverlay.measure}),Qt=(a=Mt.nodeRef.current)!=null?a:ke,Et=M?(i=Mt.rect)!=null?i:Ie:null,Tn=!!(Mt.nodeRef.current&&Mt.rect),Ce=AC(Tn?null:Ie),Ge=Ay(Qt?Ln(Qt):null),at=TC(M?Xt??ke:null),pt=LC(at),bt=GC(S,{transform:{x:ye.x-Ce.x,y:ye.y-Ce.y,scaleX:1,scaleY:1},activatorEvent:he,active:le,activeNodeRect:Ie,containerNodeRect:Nt,draggingNodeRect:Et,over:Rt.current.over,overlayNodeRect:Mt.rect,scrollableAncestors:at,scrollableAncestorRects:pt,windowRect:Ge}),_t=Oe?di(Oe,ye):null,mt=DC(at),tt=_y(mt),bn=_y(mt,[Ie]),wt=di(bt,tt),Tt=Et?Z7(Et,bt):null,qt=le&&Tt?y({active:le,collisionRect:Tt,droppableRects:re,droppableContainers:R,pointerCoordinates:_t}):null,Yn=dy(qt,"id"),[dn,Ta]=j.useState(null),ca=Tn?bt:di(bt,bn),V=X7(ca,(o=dn?.rect)!=null?o:null,Ie),me=j.useRef(null),ue=j.useCallback((Ue,Le)=>{let{sensor:Fe,options:We}=Le;if(de.current==null)return;const Je=K.get(de.current);if(!Je)return;const st=Ue.nativeEvent,He=new Fe({active:de.current,activeNode:Je,event:st,options:We,context:Rt,onAbort($e){if(!K.get($e))return;const{onDragAbort:Dt}=X.current,tn={id:$e};Dt?.(tn),O({type:"onDragAbort",event:tn})},onPending($e,lt,Dt,tn){if(!K.get($e))return;const{onDragPending:Jn}=X.current,Xn={id:$e,constraint:lt,initialCoordinates:Dt,offset:tn};Jn?.(Xn),O({type:"onDragPending",event:Xn})},onStart($e){const lt=de.current;if(lt==null)return;const Dt=K.get(lt);if(!Dt)return;const{onDragStart:tn}=X.current,yn={activatorEvent:st,active:{id:lt,data:Dt.data,rect:ve}};Os.unstable_batchedUpdates(()=>{tn?.(yn),$(Ls.Initializing),A({type:cn.DragStart,initialCoordinates:$e,active:lt}),O({type:"onDragStart",event:yn}),W(me.current),ee(st)})},onMove($e){A({type:cn.DragMove,coordinates:$e})},onEnd:De(cn.DragEnd),onCancel:De(cn.DragCancel)});me.current=He;function De($e){return async function(){const{active:Dt,collisions:tn,over:yn,scrollAdjustedTranslate:Jn}=Rt.current;let Xn=null;if(Dt&&Jn){const{cancelDrop:Ga}=X.current;Xn={activatorEvent:st,active:Dt,collisions:tn,delta:Jn,over:yn},$e===cn.DragEnd&&typeof Ga=="function"&&await Promise.resolve(Ga(Xn))&&($e=cn.DragCancel)}de.current=null,Os.unstable_batchedUpdates(()=>{A({type:$e}),$(Ls.Uninitialized),Ta(null),W(null),ee(null),me.current=null;const Ga=$e===cn.DragEnd?"onDragEnd":"onDragCancel";if(Xn){const In=X.current[Ga];In?.(Xn),O({type:Ga,event:Xn})}})}}},[K]),ne=j.useCallback((Ue,Le)=>(Fe,We)=>{const Je=Fe.nativeEvent,st=K.get(We);if(de.current!==null||!st||Je.dndKit||Je.defaultPrevented)return;const He={active:st};Ue(Fe,Le.options,He)===!0&&(Je.dndKit={capturedBy:Le.sensor},de.current=We,ue(Fe,Le))},[K,ue]),_e=jC(p,ne);RC(p),Ba(()=>{Ie&&D===Ls.Initializing&&$(Ls.Initialized)},[Ie,D]),j.useEffect(()=>{const{onDragMove:Ue}=X.current,{active:Le,activatorEvent:Fe,collisions:We,over:Je}=Rt.current;if(!Le||!Fe)return;const st={active:Le,activatorEvent:Fe,collisions:We,delta:{x:wt.x,y:wt.y},over:Je};Os.unstable_batchedUpdates(()=>{Ue?.(st),O({type:"onDragMove",event:st})})},[wt.x,wt.y]),j.useEffect(()=>{const{active:Ue,activatorEvent:Le,collisions:Fe,droppableContainers:We,scrollAdjustedTranslate:Je}=Rt.current;if(!Ue||de.current==null||!Le||!Je)return;const{onDragOver:st}=X.current,He=We.get(Yn),De=He&&He.rect.current?{id:He.id,rect:He.rect.current,data:He.data,disabled:He.disabled}:null,$e={active:Ue,activatorEvent:Le,collisions:Fe,delta:{x:Je.x,y:Je.y},over:De};Os.unstable_batchedUpdates(()=>{Ta(De),st?.($e),O({type:"onDragOver",event:$e})})},[Yn]),Ba(()=>{Rt.current={activatorEvent:he,active:le,activeNode:ke,collisionRect:Tt,collisions:qt,droppableRects:re,draggableNodes:K,draggingNode:Qt,draggingNodeRect:Et,droppableContainers:we,over:dn,scrollableAncestors:at,scrollAdjustedTranslate:wt},ve.current={initial:Et,translated:Tt}},[le,ke,qt,Tt,K,Qt,Et,re,we,dn,at,wt]),vC({...Te,delta:ye,draggingRect:Tt,pointerCoordinates:_t,scrollableAncestors:at,scrollableAncestorRects:pt});const Ae=j.useMemo(()=>({active:le,activeNode:ke,activeNodeRect:Ie,activatorEvent:he,collisions:qt,containerNodeRect:Nt,dragOverlay:Mt,draggableNodes:K,droppableContainers:we,droppableRects:re,over:dn,measureDroppableContainers:xe,scrollableAncestors:at,scrollableAncestorRects:pt,measuringConfiguration:U,measuringScheduled:oe,windowRect:Ge}),[le,ke,Ie,he,qt,Nt,Mt,K,we,re,dn,xe,at,pt,U,oe,Ge]),Re=j.useMemo(()=>({activatorEvent:he,activators:_e,active:le,activeNodeRect:Ie,ariaDescribedById:{draggable:ae},dispatch:A,draggableNodes:K,over:dn,measureDroppableContainers:xe}),[he,_e,le,Ie,A,ae,K,dn,xe]);return Ke.createElement(ry.Provider,{value:N},Ke.createElement(Ec.Provider,{value:Re},Ke.createElement(Dy.Provider,{value:Ae},Ke.createElement(Ry.Provider,{value:V},f)),Ke.createElement(qC,{disabled:g?.restoreFocus===!1})),Ke.createElement(G7,{...g,hiddenTextDescribedById:ae}));function Be(){const Ue=je?.autoScrollEnabled===!1,Le=typeof h=="object"?h.enabled===!1:h===!1,Fe=M&&!Ue&&!Le;return typeof h=="object"?{...h,enabled:Fe}:{enabled:Fe}}}),WC=j.createContext(null),Oy="button",YC="Draggable";function JC(r){let{id:e,data:t,disabled:a=!1,attributes:i}=r;const o=No(YC),{activators:d,activatorEvent:g,active:h,activeNodeRect:f,ariaDescribedById:p,draggableNodes:y,over:x}=j.useContext(Ec),{role:S=Oy,roleDescription:v="draggable",tabIndex:w=0}=i??{},k=h?.id===e,A=j.useContext(k?Ry:WC),[O,N]=wc(),[D,$]=wc(),M=OC(d,e),z=jo(t);Ba(()=>(y.set(e,{id:e,key:o,node:O,activatorNode:D,data:z}),()=>{const ye=y.get(e);ye&&ye.key===o&&y.delete(e)}),[y,e]);const K=j.useMemo(()=>({role:S,tabIndex:w,"aria-disabled":a,"aria-pressed":k&&S===Oy?!0:void 0,"aria-roledescription":v,"aria-describedby":p.draggable}),[a,S,w,k,v,p.draggable]);return{active:h,activatorEvent:g,activeNodeRect:f,attributes:K,isDragging:k,listeners:a?void 0:M,node:O,over:x,setNodeRef:N,setActivatorNodeRef:$,transform:A}}function XC(){return j.useContext(Dy)}const QC="Droppable",ZC={timeout:25};function ej(r){let{data:e,disabled:t=!1,id:a,resizeObserverConfig:i}=r;const o=No(QC),{active:d,dispatch:g,over:h,measureDroppableContainers:f}=j.useContext(Ec),p=j.useRef({disabled:t}),y=j.useRef(!1),x=j.useRef(null),S=j.useRef(null),{disabled:v,updateMeasurementsFor:w,timeout:k}={...ZC,...i},A=jo(w??a),O=j.useCallback(()=>{if(!y.current){y.current=!0;return}S.current!=null&&clearTimeout(S.current),S.current=setTimeout(()=>{f(Array.isArray(A.current)?A.current:[A.current]),S.current=null},k)},[k]),N=kc({callback:O,disabled:v||!d}),D=j.useCallback((K,ye)=>{N&&(ye&&(N.unobserve(ye),y.current=!1),K&&N.observe(K))},[N]),[$,M]=wc(D),z=jo(e);return j.useEffect(()=>{!N||!$.current||(N.disconnect(),y.current=!1,N.observe($.current))},[$,N]),j.useEffect(()=>(g({type:cn.RegisterDroppable,element:{id:a,key:o,disabled:t,node:$,rect:x,data:z}}),()=>g({type:cn.UnregisterDroppable,key:o,id:a})),[a]),j.useEffect(()=>{t!==p.current.disabled&&(g({type:cn.SetDroppableDisabled,id:a,key:o,disabled:t}),p.current.disabled=t)},[a,o,t,g]),{active:d,rect:x,isOver:h?.id===a,node:$,over:h,setNodeRef:M}}function Tg(r,e,t){const a=r.slice();return a.splice(t<0?a.length+t:t,0,a.splice(e,1)[0]),a}function tj(r,e){return r.reduce((t,a,i)=>{const o=e.get(a);return o&&(t[i]=o),t},Array(r.length))}function _c(r){return r!==null&&r>=0}function nj(r,e){if(r===e)return!0;if(r.length!==e.length)return!1;for(let t=0;t{var e;let{rects:t,activeNodeRect:a,activeIndex:i,overIndex:o,index:d}=r;const g=(e=t[i])!=null?e:a;if(!g)return null;const h=rj(t,d,i);if(d===i){const f=t[o];return f?{x:ii&&d<=o?{x:-g.width-h,y:0,...Ac}:d=o?{x:g.width+h,y:0,...Ac}:{x:0,y:0,...Ac}};function rj(r,e,t){const a=r[e],i=r[e-1],o=r[e+1];return!a||!i&&!o?0:t{let{rects:e,activeIndex:t,overIndex:a,index:i}=r;const o=Tg(e,a,t),d=e[i],g=o[i];return!g||!d?null:{x:g.left-d.left,y:g.top-d.top,scaleX:g.width/d.width,scaleY:g.height/d.height}},Tc={scaleX:1,scaleY:1},ij=r=>{var e;let{activeIndex:t,activeNodeRect:a,index:i,rects:o,overIndex:d}=r;const g=(e=o[t])!=null?e:a;if(!g)return null;if(i===t){const f=o[d];return f?{x:0,y:tt&&i<=d?{x:0,y:-g.height-h,...Tc}:i=d?{x:0,y:g.height+h,...Tc}:{x:0,y:0,...Tc}};function oj(r,e,t){const a=r[e],i=r[e-1],o=r[e+1];return a?ta.map(M=>typeof M=="object"&&"id"in M?M.id:M),[a]),v=d!=null,w=d?S.indexOf(d.id):-1,k=f?S.indexOf(f.id):-1,A=j.useRef(S),O=!nj(S,A.current),N=k!==-1&&w===-1||O,D=aj(o);Ba(()=>{O&&v&&p(S)},[O,S,v,p]),j.useEffect(()=>{A.current=S},[S]);const $=j.useMemo(()=>({activeIndex:w,containerId:y,disabled:D,disableTransforms:N,items:S,overIndex:k,useDragOverlay:x,sortedRects:tj(S,h),strategy:i}),[w,y,D.draggable,D.droppable,N,S,k,h,x,i]);return Ke.createElement(My.Provider,{value:$},e)}const cj=r=>{let{id:e,items:t,activeIndex:a,overIndex:i}=r;return Tg(t,a,i).indexOf(e)},dj=r=>{let{containerId:e,isSorting:t,wasDragging:a,index:i,items:o,newIndex:d,previousItems:g,previousContainerId:h,transition:f}=r;return!f||!a||g!==o&&i===d?!1:t?!0:d!==i&&e===h},uj={duration:200,easing:"ease"},$y="transform",gj=_o.Transition.toString({property:$y,duration:0,easing:"linear"}),hj={roleDescription:"sortable"};function fj(r){let{disabled:e,index:t,node:a,rect:i}=r;const[o,d]=j.useState(null),g=j.useRef(t);return Ba(()=>{if(!e&&t!==g.current&&a.current){const h=i.current;if(h){const f=ui(a.current,{ignoreTransform:!0}),p={x:h.left-f.left,y:h.top-f.top,scaleX:h.width/f.width,scaleY:h.height/f.height};(p.x||p.y)&&d(p)}}t!==g.current&&(g.current=t)},[e,t,a,i]),j.useEffect(()=>{o&&d(null)},[o]),o}function pj(r){let{animateLayoutChanges:e=dj,attributes:t,disabled:a,data:i,getNewIndex:o=cj,id:d,strategy:g,resizeObserverConfig:h,transition:f=uj}=r;const{items:p,containerId:y,activeIndex:x,disabled:S,disableTransforms:v,sortedRects:w,overIndex:k,useDragOverlay:A,strategy:O}=j.useContext(My),N=mj(a,S),D=p.indexOf(d),$=j.useMemo(()=>({sortable:{containerId:y,index:D,items:p},...i}),[y,i,D,p]),M=j.useMemo(()=>p.slice(p.indexOf(d)),[p,d]),{rect:z,node:K,isOver:ye,setNodeRef:we}=ej({id:d,data:$,disabled:N.droppable,resizeObserverConfig:{updateMeasurementsFor:M,...h}}),{active:J,activatorEvent:ve,activeNodeRect:le,attributes:de,setNodeRef:je,listeners:W,isDragging:he,over:ee,setActivatorNodeRef:X,transform:ae}=JC({id:d,data:$,attributes:{...hj,...t},disabled:N.draggable}),R=D7(we,je),U=!!J,re=U&&!v&&_c(x)&&_c(k),xe=!A&&he,oe=xe&&re?ae:null,Oe=re?oe??(g??O)({rects:w,activeNodeRect:le,activeIndex:x,overIndex:k,index:D}):null,Te=_c(x)&&_c(k)?o({id:d,items:p,activeIndex:x,overIndex:k}):D,qe=J?.id,Ie=j.useRef({activeId:qe,items:p,newIndex:Te,containerId:y}),Nt=p!==Ie.current.items,Rt=e({active:J,containerId:y,isDragging:he,isSorting:U,id:d,index:D,items:p,newIndex:Ie.current.newIndex,previousItems:Ie.current.items,previousContainerId:Ie.current.containerId,transition:f,wasDragging:Ie.current.activeId!=null}),Xt=fj({disabled:!Rt,index:D,node:K,rect:z});return j.useEffect(()=>{U&&Ie.current.newIndex!==Te&&(Ie.current.newIndex=Te),y!==Ie.current.containerId&&(Ie.current.containerId=y),p!==Ie.current.items&&(Ie.current.items=p)},[U,Te,y,p]),j.useEffect(()=>{if(qe===Ie.current.activeId)return;if(qe!=null&&Ie.current.activeId==null){Ie.current.activeId=qe;return}const Qt=setTimeout(()=>{Ie.current.activeId=qe},50);return()=>clearTimeout(Qt)},[qe]),{active:J,activeIndex:x,attributes:de,data:$,rect:z,index:D,newIndex:Te,items:p,isOver:ye,isSorting:U,isDragging:he,listeners:W,node:K,overIndex:k,over:ee,setNodeRef:R,setActivatorNodeRef:X,setDroppableNodeRef:we,setDraggableNodeRef:je,transform:Xt??Oe,transition:Mt()};function Mt(){if(Xt||Nt&&Ie.current.newIndex===D)return gj;if(!(xe&&!xg(ve)||!f)&&(U||Rt))return _o.Transition.toString({...f,property:$y})}}function mj(r,e){var t,a;return typeof r=="boolean"?{draggable:r,droppable:!1}:{draggable:(t=r?.draggable)!=null?t:e.draggable,droppable:(a=r?.droppable)!=null?a:e.droppable}}function Dc(r){if(!r)return!1;const e=r.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}const yj=[ft.Down,ft.Right,ft.Up,ft.Left],xj=(r,e)=>{let{context:{active:t,collisionRect:a,droppableRects:i,droppableContainers:o,over:d,scrollableAncestors:g}}=e;if(yj.includes(r.code)){if(r.preventDefault(),!t||!a)return;const h=[];o.getEnabled().forEach(y=>{if(!y||y!=null&&y.disabled)return;const x=i.get(y.id);if(x)switch(r.code){case ft.Down:a.topx.top&&h.push(y);break;case ft.Left:a.left>x.left&&h.push(y);break;case ft.Right:a.left1&&(p=f[1].id),p!=null){const y=o.get(t.id),x=o.get(p),S=x?i.get(x.id):null,v=x?.node.current;if(v&&S&&y&&x){const k=Cc(v).some((M,z)=>g[z]!==M),A=Iy(y,x),O=bj(y,x),N=k||!A?{x:0,y:0}:{x:O?a.width-S.width:0,y:O?a.height-S.height:0},D={x:S.left,y:S.top};return N.x&&N.y?D:Eo(D,N)}}}};function Iy(r,e){return!Dc(r)||!Dc(e)?!1:r.data.current.sortable.containerId===e.data.current.sortable.containerId}function bj(r,e){return!Dc(r)||!Dc(e)||!Iy(r,e)?!1:r.data.current.sortable.index{const g=j.useId(),h=j.useRef({inProgress:!1,lastSortTime:0,lastActiveId:null}),f=F7(iy(Ng,{activationConstraint:{distance:5}}),iy(jg,{coordinateGetter:xj})),p=j.useCallback(S=>{h.current={inProgress:!0,lastSortTime:Date.now(),lastActiveId:S.active.id},o?.({activeId:S.active.id})},[o]),y=j.useCallback(S=>{const{active:v,over:w}=S,k=Date.now();if(!w||v.id===w.id){h.current.inProgress=!1;return}const{lastSortTime:A,lastActiveId:O,inProgress:N}=h.current;if(O===v.id&&k-A<500&&!N)return;h.current={inProgress:!1,lastSortTime:k,lastActiveId:v.id};const D=r.findIndex(M=>String(M[e])===String(v.id)),$=r.findIndex(M=>String(M[e])===String(w.id));if(D!==-1&&$!==-1&&D!==$){const M=Tg(r,D,$);i?.(M,{oldIndex:D,newIndex:$})}},[r,e,i]),x=r.map(S=>String(S[e]));return l.jsx(KC,{id:g,sensors:f,collisionDetection:K7,onDragStart:p,onDragEnd:y,children:l.jsx(lj,{items:x,strategy:vj[t],children:a})},d!==void 0?`${g}-v${d}`:g)},zy=j.createContext(null),Sj=({value:r,children:e})=>l.jsx(zy.Provider,{value:r,children:e}),Cj=()=>j.useContext(zy),jj=({id:r,handle:e,as:t="div",children:a})=>{const{attributes:i,listeners:o,setNodeRef:d,transform:g,transition:h,isDragging:f}=pj({id:r}),p={transform:_o.Transform.toString(g),transition:h,opacity:f?.5:1,position:"relative"};return l.jsx(t,{ref:d,style:p,...i,...e?{}:o,"data-sortable-item":!0,"data-sortable-id":String(r),"data-dragging":f,children:l.jsx(Sj,{value:{listeners:o,handle:e,isDragging:f},children:a})})},vt=it("DynamicRenderer");function rs(){try{return window.G7Core?.devTools}catch{return}}function kj(r){const e=Object.keys(r);return e.length>0&&e.every(t=>/^\d+$/.test(t))}const ja=(r,e)=>{const t=["errors"],a={...r};for(const i of Object.keys(e)){const o=e[i],d=r[i];if(o===null){a[i]=null;continue}if(t.includes(i)){a[i]=o;continue}if(Array.isArray(o)){a[i]=o;continue}if(Array.isArray(d)&&o!==null&&typeof o=="object"&&!Array.isArray(o)&&kj(o)){const g=Object.keys(o).map(f=>parseInt(f,10));if((g.length>0?Math.max(...g):0)>=d.length+g.length+10)a[i]={...o};else{const f=[...d];for(const[p,y]of Object.entries(o)){const x=parseInt(p,10);x>=0&&x=f.length&&(f[x]=y)}a[i]=f}}else o!==null&&typeof o=="object"&&d!==null&&typeof d=="object"&&!Array.isArray(d)?a[i]=ja(d,o):a[i]=o}return a},Hy=(r,e)=>{const t={...r};for(const a of Object.keys(e)){if(!(a in t))continue;const i=e[a],o=t[a];if(i!==null&&typeof i=="object"&&!Array.isArray(i)&&o!==null&&typeof o=="object"&&!Array.isArray(o)){const d=Hy(o,i);Object.keys(d).length===0?delete t[a]:t[a]=d}else delete t[a]}return t},Nj=r=>{const e={},t=r.split(";").filter(a=>a.trim());for(const a of t){const i=a.indexOf(":");if(i===-1)continue;const o=a.substring(0,i).trim(),d=a.substring(i+1).trim();if(o&&d){const g=o.replace(/-([a-z])/g,(h,f)=>f.toUpperCase());e[g]=d}}return e};class Ej extends j.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){vt.error(`컴포넌트 렌더링 에러 (ID: ${this.props.componentId}, Name: ${this.props.componentName}):`,e,t)}render(){return this.state.hasError?this.props.fallback?this.props.fallback:l.jsxs("div",{className:"p-4 my-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-red-800 dark:text-red-400",children:[l.jsx("div",{className:"font-semibold mb-1",children:"컴포넌트 로드 실패"}),l.jsxs("div",{className:"text-xs opacity-80",children:[this.props.componentName&&`[${this.props.componentName}] `,"데이터를 표시할 수 없습니다."]}),this.state.error&&l.jsxs("details",{className:"mt-2",children:[l.jsx("summary",{className:"cursor-pointer text-xs opacity-70 hover:opacity-100",children:"상세 정보"}),l.jsx("div",{className:"mt-1 p-2 bg-red-100 dark:bg-red-900/30 rounded text-xs font-mono whitespace-pre-wrap break-all",children:this.state.error.message})]})]}):this.props.children}}const Ua=j.memo(({componentDef:r,dataContext:e,translationContext:t,registry:a,bindingEngine:i,translationEngine:o,actionDispatcher:d,parentComponentContext:g,parentFormContextProp:h,parentDataContext:f,isRootRenderer:p=!1,isInsideIteration:y=!1,isEditMode:x=!1,onComponentSelect:S,onComponentHover:v,onDragStart:w,onDragEnd:k,componentPath:A,layoutKey:O})=>{const[N,D]=j.useState({loadingActions:{}});j.useLayoutEffect(()=>{g||(i.startRenderCycle(),window.__g7SetLocalOverrideKeys||(window.__g7ForcedLocalFields=void 0),window.__g7PendingLocalState=null)});const $=j.useRef(null);j.useLayoutEffect(()=>{if(!g&&e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:V,_merge:me,...ue}=e._localInit,ne=`${JSON.stringify(ue)}:${V||"no-force"}`;if($.current!==ne){$.current=ne;const _e=me||"shallow",Ae=window.__g7PendingLocalState||{};_e==="replace"?window.__g7PendingLocalState={loadingActions:Ae.loadingActions||{},...ue,hasChanges:!1}:_e==="deep"?window.__g7PendingLocalState=ja(Ae,{...ue,hasChanges:!1}):window.__g7PendingLocalState={...Ae,...ue,hasChanges:!1};const Re=window.__g7SetLocalOverrideKeys;Re&&typeof Re=="object"&&(_e==="replace"?window.__g7SetLocalOverrideKeys={...ue,hasChanges:!1}:window.__g7SetLocalOverrideKeys=ja(Re,{...ue,hasChanges:!1}))}}}),j.useLayoutEffect(()=>{if(!g){const V=window.__g7SetLocalOverrideKeys;if(V){D(_e=>Hy(_e,V));const me=V,ue=window.__g7ForcedLocalFields,ne=window.__g7LastSetLocalSnapshot;queueMicrotask(()=>{window.__g7SetLocalOverrideKeys===me&&(window.__g7SetLocalOverrideKeys=void 0),window.__g7ForcedLocalFields===ue&&(window.__g7ForcedLocalFields=void 0),window.__g7LastSetLocalSnapshot===ne&&(window.__g7LastSetLocalSnapshot=void 0)})}}},[e._local]);const M=j.useRef(O);j.useEffect(()=>{r._fromBase&&O&&M.current!==O&&(M.current=O,D({loadingActions:{}}))},[O,r._fromBase]);const z=j.useRef(""),K=j.useRef(!1),ye=j.useRef(null),we=j.useRef({}),J=j.useRef({}),ve=j.useRef(f),le=T7(),de=h7(),je=de?.getParentDataContext()??f;j.useEffect(()=>{if(e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:V,...me}=e._localInit,ue=JSON.stringify(me),ne=V!==void 0,_e="__g7LocalInitTracking";window[_e]||(window[_e]={hash:"",timestamp:void 0});const Ae=window[_e],Re=`${ue}:${V||"no-force"}`;if(Ae.hash!==Re){Ae.hash=Re,Ae.timestamp=V,z.current=ue,ne&&(K.current=!0);const{_merge:Le,...Fe}=me,We=Le||"shallow";if(D(Je=>We==="replace"?{loadingActions:Je.loadingActions||{},...Fe,hasChanges:!1}:We==="deep"?ja(Je,{...Fe,hasChanges:!1}):{...Je,...Fe,hasChanges:!1}),e._globalSetState){const Je=e._global?._local||{};let st;We==="replace"?st={...Fe,hasChanges:!1}:We==="deep"?st=ja(Je,{...Fe,hasChanges:!1}):st={...Je,...Fe,hasChanges:!1},e._globalSetState({_local:st})}i.invalidateCacheByKeys(["_local"]),vt.log("_localInit applied (data changed):",Object.keys(me))}ye.current=e._localInit}},[e._localInit,f,i]);const{isTransitioning:W}=Wm(),he=w7(),ee=h??he,{width:X}=Xm(),ae=Cj(),R=j.useMemo(()=>{let V=r;if(r.type==="iterator"&&r.data){const{data:ne,itemName:_e,indexName:Ae,...Re}=r;V={...Re,iteration:{source:ne,item_var:_e||"item",index_var:Ae}}}if(!V.responsive)return V;const me=ei.getMatchingKey(V.responsive,X);if(!me)return V;const ue=V.responsive[me];return{...V,props:{...V.props,...ue.props},children:ue.children??V.children,text:ue.text??V.text,if:ue.if??V.if,iteration:ue.iteration??V.iteration}},[r,X]),U=j.useCallback(V=>{const me=V?.__setStateId;if(D(ue=>{const ne=window.__g7PendingLocalState,Ae=window.__g7SetLocalOverrideKeys||ne,Re=Ae?ja(ue,Ae):ue;if(typeof V=="function"){const We=V(Re);return ja(Re,We)}const{__mergeMode:Be,__setStateId:Ue,...Le}=V;let Fe;if(Be==="replace"?Fe=Le:Be==="shallow"?Fe={...Re,...Le}:Fe=ja(Re,Le),Be!==void 0){const We=window.__g7ForcedLocalFields;We&&(window.__g7ForcedLocalFields={...We,...Le})}return Fe}),me){const ue=rs();if(ue?.isEnabled()){const ne=R.id||"unknown",_e=R.name||"Unknown";setTimeout(()=>{ue.trackComponentRender?.(ne,_e,0,["_local"],[]),ue.completeStateChange?.(me)},0)}}},[R.id,R.name]),re=g?.state??N,xe=g?.setState??U,oe=j.useMemo(()=>{const V=e._localInit&&e._localInit!==ye.current;let me;V&&e._local?me=e._local:me=e._local?ja(e._local,re):re;const ue=window.__g7ForcedLocalFields;ue&&(me=ja(me,ue));const ne={...e,_local:me},_e=e._computedDefinitions;if(_e&&Object.keys(_e).length>0){const Ae=new _n,Re={...ne,...le?{_isolated:le.state}:{}},Be={},Ue=rs(),Le=Ue?.isEnabled()??!1;for(const[Fe,We]of Object.entries(_e)){const Je=Le?Date.now():0,st=Le?e._computed?.[Fe]:void 0;let He;try{if(typeof We=="string")if(We.startsWith("{{")&&We.endsWith("}}")){const De=We.slice(2,-2).trim(),$e=Ae.evaluateExpression(De,Re,{skipCache:!0});Be[Fe]=$e}else Be[Fe]=We;else if(We&&typeof We=="object"&&"$switch"in We){const De=Ae.resolveSwitch(We,Re,{skipCache:!0});Be[Fe]=De}}catch(De){vt.warn(`Failed to recalculate computed value: ${Fe}`,De),Be[Fe]=e._computed?.[Fe],He=De instanceof Error?De.message:String(De)}if(Le&&(He||st!==Be[Fe])){const $e=Date.now()-Je;Ue.trackComputedProperty?.(Fe,typeof We=="string"?We:JSON.stringify(We),[{type:"_local",path:"_local",value:ne._local}],Be[Fe],$e,R.id,He),st!==Be[Fe]&&Ue.trackComputedRecalc?.(Fe,"dependency-change",st,Be[Fe],$e,{type:"_local",path:"_local"},R.id)}}ne._computed=Be}return le&&(ne._isolated=le.state),je&&(ne.$parent=je),r.extensionPointProps&&(ne.extensionPointProps=i.resolveObject(r.extensionPointProps,ne,y?{skipCache:!0}:void 0)),r.extensionPointCallbacks&&(ne.extensionPointCallbacks=r.extensionPointCallbacks),ne},[e,re,le?.state,je,de?.version,r.extensionPointProps,r.extensionPointCallbacks]);we.current=oe._local,J.current=oe._computed||{},ve.current=je,j.useEffect(()=>{const V=rs();if(!V?.isEnabled())return;const me=oe._local;me&&V.updateLocalState(me);const ue=oe._computed;ue&&V.updateComputedState(ue),je&&V.updateParentContext?.(je);const ne=R.id||`comp-${Date.now()}`,_e=R.name||"Unknown",Ae={global:Object.keys(e._global||{}),local:Object.keys(me||{}),context:g?Object.keys(g.state||{}):[]},Re={type:g?"componentContext":"dynamicState",hasComponentContext:!!g,parentId:g?"parent":void 0};V.trackComponentStateSource?.(ne,_e,Ae,Re),re&&Object.keys(re).length>0&&V.trackDynamicState?.(ne,re);const Be=!!(R.expandChildren||R.props?.expandChildren);V.trackContextFlow?.(ne,_e,!!g,Be,!0)},[oe._local,e,R.id,R.name,g,re,R.expandChildren,R.props?.expandChildren,je]);const ke=j.useMemo(()=>({state:{...oe._local},setState:xe,stateRef:we,computedRef:J,isolatedContext:le,parentDataContext:oe}),[oe._local,xe,N,le,oe]),Oe=j.useMemo(()=>{const V=ti({if:R.if,condition:R.condition,conditions:R.conditions},oe,i,R.id);if(R.if||R.condition!==void 0||R.conditions){const ue=rs();ue?.isEnabled()&&R.if&&ue.trackIfCondition(R.id||`if-${Date.now()}`,R.if,V)}return V},[R.if,R.conditions,oe,i,R.id]),Te=j.useMemo(()=>{if(!R.slot)return null;const V=R.slot;if(V.startsWith("{{")&&V.endsWith("}}")){const me=V.slice(2,-2).trim();try{const ue={componentId:R.id,componentName:R.name,propName:"slot"},ne=i.evaluateExpression(me,oe,ue);return vt.log(`[Slot] 표현식 평가: "${me}" => "${ne}" (컴포넌트: ${R.id})`),typeof ne=="string"?ne:null}catch(ue){return vt.warn(`slot 표현식 평가 실패 (컴포넌트: ${R.id}):`,ue),null}}return vt.log(`[Slot] 정적 슬롯 ID: "${V}" (컴포넌트: ${R.id})`),V},[R.slot,R.id,oe,i]),qe=j.useMemo(()=>!Te||!R.id?"":`${R.id}-${Te}-${JSON.stringify(R.slotOrder??0)}`,[Te,R.id,R.slotOrder]),Ie=j.useRef(null);j.useEffect(()=>{const V=window.__slotContextValue,me=V?.isEnabled??!1;if(R.slot&&vt.log(`[Slot Registration] 컴포넌트: ${R.id}, isSlotEnabled: ${me}, shouldRender: ${Oe}, resolvedSlotId: ${Te}`),!me||!Oe){R.slot&&vt.log(`[Slot Registration] 등록 스킵 - isSlotEnabled: ${me}, shouldRender: ${Oe}`),Ie.current&&R.id&&V&&(V.unregisterFromSlot(Ie.current,R.id),Ie.current=null);return}if(!Te||!R.id){R.slot&&vt.log(`[Slot Registration] 등록 스킵 - resolvedSlotId: ${Te}, id: ${R.id}`),Ie.current&&R.id&&V&&(V.unregisterFromSlot(Ie.current,R.id),Ie.current=null);return}Ie.current&&Ie.current!==Te&&V.unregisterFromSlot(Ie.current,R.id);const ue={...R,slot:void 0,slotOrder:void 0};return V.registerToSlot(Te,R.id,{componentDef:ue,dataContext:e,order:R.slotOrder??0,parentFormContext:h??null,getParentComponentContext:()=>ke,translationContext:t,registrationKey:qe}),Ie.current=Te,()=>{const ne=window.__slotContextValue;Te&&R.id&&ne&&ne.unregisterFromSlot(Te,R.id)}},[Oe,Te,R,e,h,ke,t,qe]);const Nt=j.useCallback(V=>{if(typeof V=="string"){if(Fp(V))return Kp(V);if(Vp(V)){const me=[],ue=V.replace(new RegExp(`${tc}([^${co}]*)${co}`,"g"),(_e,Ae)=>(me.push(Ae),`${Rs}${me.length-1}${Rs}`));let ne=ue;return/\$t:[a-zA-Z0-9._-]+/.test(ue)&&(ne=o.resolveTranslations(ue,t,oe)),ne.replace(new RegExp(`${Rs}(\\d+)${Rs}`,"g"),(_e,Ae)=>me[parseInt(Ae)])}if(V.startsWith("$t:defer:"))return V;if(/\$t:[a-zA-Z0-9._-]+/.test(V)){const me=V.trim();return me.startsWith("{")&&me.endsWith("}")||me.startsWith("[")&&me.endsWith("]")?V:o.resolveTranslations(V,t,oe)}return V}if(Array.isArray(V))return V.map(me=>Nt(me));if(V&&typeof V=="object"){const me={};for(const[ue,ne]of Object.entries(V))me[ue]=Nt(ne);return me}return V},[o,t,oe]),Rt=j.useCallback(V=>/[?:|&!+\-*/<>=()]/.test(V),[]),Xt=j.useCallback(V=>{if(!V.startsWith("{{")||!V.endsWith("}}"))return null;const me=V.slice(2,-2);let ue=null,ne=0;for(let _e=0;_e0?me[_e-1]:"")!=="\\"&&((Ae==='"'||Ae==="'")&&!ue?ue=Ae:Ae===ue&&(ue=null),!ue&&(Ae==="{"&&ne++,Ae==="}"&&ne--,ne<0)))return null}return ne===0?me.trim():null},[]),Mt=j.useMemo(()=>{let V={...R.props||{}};const me=["cellChildren","expandChildren","expandContext","render"],ne=a.getMetadata(R.name)?.skipBindingKeys||[],_e=[...new Set([...me,...ne])],Ae=y?{skipCache:!0}:void 0,Re=He=>{if(Ae)return Ae;if(He.startsWith("_computed")||He.startsWith("$computed"))return{skipCache:!0}};for(const[He,De]of Object.entries(V))if(!_e.includes(He))if(typeof De=="string"){const $e=Xt(De);if($e!==null){let lt=!1,Dt=$e;$e.startsWith(Ds)&&(lt=!0,Dt=$e.slice(Ds.length));const tn={componentId:R.id,componentName:R.name,propName:He};let yn;if(Rt(Dt))try{yn=i.evaluateExpression(Dt,oe,tn)}catch(Jn){vt.warn(`표현식 평가 실패 (컴포넌트: ${R.id}, prop: ${He}):`,Jn),yn=void 0}else yn=i.resolve(Dt,oe,Re(Dt),tn);V[He]=lt&&yn!=null?go(yn):yn}else{const lt={componentId:R.id,componentName:R.name,propName:He};V[He]=i.resolveBindings(De,oe,Ae,lt)}}else Array.isArray(De)?V[He]=De.map($e=>typeof $e=="string"?i.resolveBindings($e,oe,Ae):typeof $e=="object"&&$e!==null?i.resolveObject($e,oe,Ae):$e):De&&typeof De=="object"&&(V[He]=i.resolveObject(De,oe,Ae));for(const[He,De]of Object.entries(V))V[He]=Nt(De);if(typeof V.style=="string"&&(V.style=Nj(V.style)),V=Ku(V,R.actions,oe,{componentContext:ke,actionDispatcher:d}),R.classMap){const He=Hw(R.classMap,oe,i,{skipCache:!0});if(He){const De=V.className||"";V.className=De?`${De} ${He}`:He}}R.style&&(V.style=R.style),R.actions&&R.actions.length>0&&R.type==="composite"&&Object.assign(V,re),R.component_layout&&(V.__componentLayoutDefs=R.component_layout);const Be=R.expandChildren||R.props?.expandChildren,Ue=R.props?.cellChildren,Le=R.children&&R.children.length>0,Fe=R.component_layout,We=R.slot,Je=R.props?.modalId,st=R.type==="composite";return(Be||Ue||Le||Fe||We||Je||st)&&(V.__componentContext=ke),V},[R.props,R.actions,R.style,R.classMap,R.id,oe,t,i,o,ke,re,Nt,Rt,Xt,y]),Qt=j.useRef(null),Et=j.useMemo(()=>Qt.current&&Qm(Qt.current,Mt)?Qt.current:(Qt.current=Mt,Mt),[Mt]),Tn=j.useMemo(()=>{const V=R.dataKey,me=R.trackChanges,ue=R.debounce;if(V){const ne=V.startsWith("_global."),_e=ne?V.slice(8):V,Ae=ne?e._global:oe._local;return{dataKey:_e,trackChanges:me??!1,debounce:ue,setState:ne?Be=>{e._globalSetState?e._globalSetState(Be):vt.warn("_global.formData 사용 시 _globalSetState가 필요합니다.")}:xe,state:Ae??{},_isGlobal:ne}}if(ee.dataKey)return ee},[R.dataKey,R.trackChanges,R.debounce,R.id,xe,oe._local,e._global,e._globalSetState,ee]),Ce=j.useRef(new Set);j.useEffect(()=>{Ce.current.clear()},[e._global?._remountKeys]);const Ge=j.useCallback((V,me)=>{const ue=e._global?._remountKeys;return V&&ue?.[V]&&!Ce.current.has(V)?(Ce.current.add(V),`${V}-remount-${ue[V]}`):V||me},[e._global?._remountKeys]),at=j.useMemo(()=>{if(R.text!==void 0){if(typeof R.text=="string"){const V=R.text;let me=V;const ue={componentId:R.id,componentName:R.name,propName:"text",skipCache:!0},ne=Xt(V);if(ne!==null)if(Gp(ne))me=i.resolveBindings(V,oe,{skipCache:!0},ue);else if(Rt(ne))try{me=i.evaluateExpression(ne,oe,ue)}catch(_e){vt.warn(`text 표현식 평가 실패 (컴포넌트: ${R.id}):`,_e),me=""}else me=i.resolve(ne,oe,{skipCache:!0},ue);else V.includes("{{")&&(me=i.resolveBindings(V,oe,{skipCache:!0},ue));return me=Nt(me),me??""}return R.text}return!R.children||R.children.length===0?null:R.children.map((V,me)=>{if(typeof V=="string")return V;const ue=A?`${A}.children.${me}`:`${me}`,ne=V._fromBase?V.id||`child-${me}`:Ge(V.id,`child-${me}`),_e=!V._fromBase&&O?`${ne}_${O}`:ne;return l.jsx(Ua,{componentDef:V,dataContext:oe,translationContext:t,registry:a,bindingEngine:i,translationEngine:o,actionDispatcher:d,parentComponentContext:ke,parentFormContextProp:Tn,isInsideIteration:y,isEditMode:x,onComponentSelect:S,onComponentHover:v,componentPath:ue,onDragStart:w,onDragEnd:k,layoutKey:O},_e)})},[R.text,R.children,R.id,e,oe,t,a,i,o,d,ke,Tn,Xt,Rt,Nt,Ge,y,x,S,v,A,w,k,O]),pt=j.useMemo(()=>{if(!R.iteration)return null;try{const V=Vu(R.iteration.source,oe,i);if(!Array.isArray(V))return vt.warn(`iteration source가 배열이 아닙니다 (컴포넌트: ${R.id}):`,V),null;const me=rs();return me?.isEnabled()&&me.trackIteration(R.id||`iteration-${Date.now()}`,R.iteration.source,R.iteration.item_var,R.iteration.index_var,V.length),V.map((ue,ne)=>{const _e={...oe,[R.iteration.item_var]:ue};R.iteration.index_var&&(_e[R.iteration.index_var]=ne);const Ae=ne===0||ne===V.length-1;me?.isEnabled()&&Ae&&me.trackNestedContext?.({componentId:`${R.id||"unknown"}-iter-${ne}`,componentType:"iteration",parentContext:{available:Object.keys(oe),values:{}},ownContext:{added:[R.iteration.item_var,...R.iteration.index_var?[R.iteration.index_var]:[]],values:{[R.iteration.item_var]:ue,...R.iteration.index_var?{[R.iteration.index_var]:ne}:{}}},depth:1});const Re={...R,iteration:void 0},Be=A?`${A}.iteration.${ne}`:`iteration.${ne}`,Ue=`${Ge(R.id,"item")}-${ne}`;return l.jsx(Ua,{componentDef:Re,dataContext:_e,translationContext:t,registry:a,bindingEngine:i,translationEngine:o,actionDispatcher:d,parentComponentContext:ke,parentFormContextProp:Tn,isInsideIteration:!0,isEditMode:x,onComponentSelect:S,onComponentHover:v,componentPath:Be,onDragStart:w,onDragEnd:k,layoutKey:O},Ue)})}catch(V){return vt.error(`iteration 렌더링 실패 (컴포넌트: ${R.id}):`,V),null}},[R.iteration,R.children,R.id,e,oe,t,a,i,o,d,ke,Tn,Ge,x,S,v,A,w,k,O]),[bt,_t]=j.useState(0),mt=j.useMemo(()=>{if(!R.sortable||!R.itemTemplate)return null;const{sortable:V,itemTemplate:me}=R;try{const ue=Vu(V.source,oe,i);if(!Array.isArray(ue))return vt.warn(`sortable source가 배열이 아닙니다 (컴포넌트: ${R.id}):`,ue),null;if(ue.length===0)return null;const ne=V.itemKey||"id",_e=V.strategy||"verticalList",Ae=V.itemVar||"$item",Re=V.indexVar||"$index",Be=V.handle,Ue=V.wrapperElement,Le=(Je,st)=>{const He=R.actions?.filter(De=>De.event==="onSortEnd"||De.type==="onSortEnd");if(_t(De=>De+1),He&&He.length>0&&d){const De={...oe,$sortedItems:Je,$sortEvent:st};He.forEach($e=>{try{const lt=d.createHandler($e,De,ke),Dt=new Event("sortend");lt(Dt)}catch(lt){vt.error(`onSortEnd action failed: ${$e.handler}`,lt)}})}},Fe=Je=>{const st=R.actions?.filter(He=>He.event==="onSortStart"||He.type==="onSortStart");if(st&&st.length>0&&d){const He={...oe,$activeId:Je.activeId};st.forEach(De=>{try{const $e=d.createHandler(De,He,ke),lt=new Event("sortstart");$e(lt)}catch($e){vt.error(`onSortStart action failed: ${De.handler}`,$e)}})}},We=ue.map((Je,st)=>{const He=String(Je[ne]),De={...oe,[Ae]:Je,[Re]:st},$e=A?`${A}.sortable.${st}`:`sortable.${st}`,lt=`${Ge(R.id,"sortable-item")}-v${bt}-${He}`;return l.jsx(jj,{id:He,handle:Be,...Ue?{as:Ue}:{},children:(Ue&&me.children?me.children:[me]).map((Dt,tn)=>l.jsx(Ua,{componentDef:Dt,dataContext:De,translationContext:t,registry:a,bindingEngine:i,translationEngine:o,actionDispatcher:d,parentComponentContext:ke,parentFormContextProp:void 0,isInsideIteration:!0,isEditMode:x,onComponentSelect:S,onComponentHover:v,componentPath:$e,onDragStart:w,onDragEnd:k,layoutKey:O},`${lt}-child-${tn}`))},lt)});return l.jsx(wj,{items:ue,itemKey:ne,strategy:_e,onSortEnd:Le,onSortStart:Fe,sortVersion:bt,children:We})}catch(ue){return vt.error(`sortable 렌더링 실패 (컴포넌트: ${R.id}):`,ue),null}},[R.sortable,R.itemTemplate,R.actions,R.id,e,oe,t,a,i,o,d,ke,Ge,x,S,v,A,w,k,bt,O]),tt=j.useRef(!1);j.useEffect(()=>{if(tt.current)return;tt.current=!0;const V=rs();if(V?.isEnabled()&&V.trackMount(r.id,{name:r.name,type:r.type||"component",props:Et}),r.lifecycle?.onMount&&r.lifecycle.onMount.length>0)for(const ue of r.lifecycle.onMount)try{const ne=d.createHandler(ue,oe,ke),_e=new Event("mount");ne(_e),vt.log(`Lifecycle onMount executed: ${ue.handler} (Component: ${r.id})`)}catch(ne){vt.error(`Lifecycle onMount failed: ${ue.handler} (Component: ${r.id})`,ne)}const me=[];if(r.onComponentEvent&&r.onComponentEvent.length>0){const ue=window.G7Core;if(ue?.componentEvent?.on)for(const ne of r.onComponentEvent){if(!ne.event){vt.warn(`onComponentEvent: event name is required (Component: ${r.id})`);continue}const _e=async Re=>{try{const Be={...oe,_eventData:Re},Le=await d.createHandler({handler:ne.handler,params:ne.params,onSuccess:ne.onSuccess,onError:ne.onError},Be,ke)(new CustomEvent(ne.event,{detail:Re}));return vt.log(`onComponentEvent "${ne.event}" handled: ${ne.handler} (Component: ${r.id})`,{eventData:Re,result:Le}),Le}catch(Be){throw vt.error(`onComponentEvent "${ne.event}" failed: ${ne.handler} (Component: ${r.id})`,Be),Be}},Ae=ue.componentEvent.on(ne.event,_e);me.push(Ae),vt.log(`onComponentEvent: Subscribed to "${ne.event}" (Component: ${r.id})`)}else vt.warn(`onComponentEvent: G7Core.componentEvent is not available (Component: ${r.id})`)}return()=>{const ue=rs();ue?.isEnabled()&&ue.trackUnmount(r.id);for(const ne of me)try{ne()}catch(_e){vt.error(`onComponentEvent: Failed to unsubscribe (Component: ${r.id})`,_e)}if(me.length>0&&vt.log(`onComponentEvent: Unsubscribed ${me.length} event(s) (Component: ${r.id})`),r.lifecycle?.onUnmount&&r.lifecycle.onUnmount.length>0)for(const ne of r.lifecycle.onUnmount)try{const _e=d.createHandler(ne,oe,ke),Ae=new Event("unmount");_e(Ae),vt.log(`Lifecycle onUnmount executed: ${ne.handler} (Component: ${r.id})`)}catch(_e){vt.error(`Lifecycle onUnmount failed: ${ne.handler} (Component: ${r.id})`,_e)}}},[]);const bn=j.useMemo(()=>{const V=Et.dataKey,me=Et.trackChanges,ue=Et.debounce;return V?{dataKey:V,trackChanges:me??!1,debounce:ue,setState:xe,state:re}:null},[Et.dataKey,Et.trackChanges,Et.debounce,xe,re]);j.useEffect(()=>{const V=R.dataKey||Et.dataKey;if(!V)return;const me=rs();if(!me?.isEnabled())return;const ue=[],ne=Ae=>{if(Ae)for(const Re of Ae){const Be=Re?.props?.name;if(Be&&ue.push({name:Be,type:Re.name||Re.type||"unknown"}),Re?.children&&ne(Re.children),Re?.slots)for(const Ue of Object.values(Re.slots))Array.isArray(Ue)&&ne(Ue)}};if(r.children&&ne(r.children),r.slots)for(const Ae of Object.values(r.slots))Array.isArray(Ae)&&ne(Ae);const _e=r.id||`form-${V}`;return me.trackForm(_e,V,ue),()=>{me.untrackForm(_e)}},[R,Et.dataKey,r.id,r.children]);const wt=j.useRef(null),Tt=j.useRef(void 0);j.useEffect(()=>{const V=Et?.name;if(!V||!ee.dataKey||!ee.setState||Et?.autoBinding===!1)return;const me=`${ee.dataKey}.${V}`,ue=window.__g7AutoBindingPaths??new Map;return window.__g7AutoBindingPaths=ue,ue.set(me,(ue.get(me)??0)+1),()=>{const ne=ue.get(me)??0;ne<=1?ue.delete(me):ue.set(me,ne-1)}},[Et?.name,Et?.autoBinding,ee.dataKey,ee.setState]);const qt=j.useMemo(()=>{const{dataKey:V,trackChanges:me,debounce:ue,...ne}=Et,_e=ne.name;if(!_e||!ee.dataKey||!ee.setState)return ne;if(ne.autoBinding===!1){const{autoBinding:He,...De}=ne;return De}const Ae=`${ee.dataKey}.${_e}`,Re=S7(ee.state,Ae),Be=Re!==void 0?Re:ne.value,Le=a.getMetadata(r.name)?.bindingType,Fe=typeof Be=="boolean"&&(Le==="checked"||Le==="checkable"&&["checkbox","radio"].includes(ne?.type)),We=ee.debounce,Je=He=>{const De=ee.state||{},$e=C7(De,Ae,He);if(ee.trackChanges&&($e.hasChanges=!0),window.__g7PendingLocalState=$e,ee.setState($e),ee._isGlobal)return;const lt=window.G7Core,Dt={[Ae]:He};ee.trackChanges&&(Dt.hasChanges=!0),lt?.state?.setLocal?.(Dt,{render:!1})},st=(He,De)=>{We&&We>0?(wt.current&&clearTimeout(wt.current),wt.current=setTimeout(()=>{Je(He),wt.current=null,De&&(De(),window.__g7PendingLocalState=null)},We)):(Je(He),De&&(De(),window.__g7PendingLocalState=null))};if(Fe)return{...ne,checked:Be,onChange:De=>{const $e=De.target.checked;Je($e),ne.onChange&&ne.onChange(De)}};{const He=$e=>{const lt=$e?.target?.value!==void 0?$e.target.value:$e;We&&We>0&&(Tt.current=lt);const Dt=$e?.target?{target:{value:lt,name:$e.target.name,type:$e.target.type,checked:$e.target.checked},currentTarget:$e.currentTarget?{value:lt,name:$e.currentTarget.name}:void 0}:$e;st(lt,()=>{ne.onChange&&ne.onChange(Dt)})};let De;return Tt.current!==void 0?wt.current!==null?De=Tt.current:String(Be??"")===String(Tt.current)?(Tt.current=void 0,De=Be??""):De=Tt.current:De=Be??"",{...ne,value:De,onChange:He}}},[Et,ee,ee.state,ee.debounce]),Yn=j.useMemo(()=>{const V=rs();if(V?.isEnabled()&&V.trackRender(r.name),!Oe)return null;if(R.sortable&&R.itemTemplate)return mt;if(R.iteration)return pt;if(R.type==="extension_point"){const{layout:Be,columns:Ue,gap:Le,className:Fe,...We}=R.props||{};let Je=Fe||"";return Be==="grid"&&Ue?Je=`${Je} grid grid-cols-${Ue} gap-${Le||4}`.trim():Be==="flex"&&(Je=`${Je} flex flex-col gap-${Le||4}`.trim()),l.jsx("div",{id:R.id,className:Je||void 0,...We,children:at})}const me=a.getComponent(R.name);if(!me)return vt.error(`컴포넌트를 찾을 수 없습니다: ${R.name} (ID: ${R.id})`,"componentDef:",JSON.stringify(R,null,2)),null;const ue=e._global?._remountKeys,ne={...qt,id:qt.id??R.id,...ue&&Object.keys(ue).length>0&&{__remountTrigger:JSON.stringify(ue)}};if(ae?.listeners&&ae.handle&&qt["data-drag-handle"]!==void 0&&(Object.assign(ne,ae.listeners),ne.style={...ne.style,cursor:ae.isDragging?"grabbing":"grab"}),x){const Be=R.id||`auto_${R.name||R.type||"unknown"}_${Math.random().toString(36).substring(2,8)}`;ne["data-editor-id"]=Be,ne["data-editor-name"]=R.name,ne["data-editor-type"]=R.type,A&&(ne["data-editor-path"]=A);const Ue=ne.onClick;ne.onClick=Le=>{S&&(Le.stopPropagation(),S(Be,Le)),typeof Ue=="function"&&Ue(Le)},v&&(ne.onMouseMove=Le=>{Le.stopPropagation(),v(Be,Le)},ne.onMouseLeave=Le=>{v(null,Le)}),ne.draggable=!0,w&&(ne.onDragStart=Le=>{Le.stopPropagation(),w(Be,Le)}),k&&(ne.onDragEnd=Le=>{k(Le)})}const Ae=R.type==="basic"||R.type==="layout"?(()=>{const{__componentContext:Be,__componentLayoutDefs:Ue,...Le}=ne;return Le})():ne;let Re=l.jsx(me,{...Ae,children:at});if(Tn&&(Re=l.jsx(v7,{value:Tn,children:Re})),R.isolatedState){const Be=typeof R.isolatedState=="object"?R.isolatedState:{},Ue=e?._isolatedInit,Le=Ue?{...Be,...Ue}:Be;Re=l.jsx(A7,{initialState:Le,scopeId:R.isolatedScopeId,children:Re})}return Re},[Oe,R.iteration,R.sortable,R.itemTemplate,R.type,R.name,R.id,R.props,R.isolatedState,R.isolatedScopeId,a,qt,at,pt,mt,ae,bn,x,S,v,w,k,A,e._global?._remountKeys]),dn=j.useMemo(()=>{const V=R.blur_until_loaded;if(!V||e?._global?.__isPreview)return!1;if(typeof V=="string"){const ne=Xt(V);if(ne!==null)try{const _e={componentId:R.id,componentName:R.name,propName:"blur_until_loaded"};return!!i.evaluateExpression(ne,oe,_e)}catch(_e){return vt.warn(`blur_until_loaded 표현식 평가 실패 (컴포넌트: ${R.id}):`,_e),!1}return!1}if(typeof V=="object"&&V!==null){if(!V.enabled)return!1;if(V.data_sources)return(Array.isArray(V.data_sources)?V.data_sources:[V.data_sources]).some(Re=>e[Re]===void 0);if(W)return!0;const ne=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(Ae=>!ne.includes(Ae)&&!Ae.startsWith("_")).some(Ae=>e[Ae]===void 0)}if(W)return!0;const me=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(ne=>!me.includes(ne)&&!ne.startsWith("_")).some(ne=>e[ne]===void 0)},[R.blur_until_loaded,R.id,W,e,oe,i,Xt]);if(dn){const V=R.blur_until_loaded;if(typeof V=="object"&&V?.data_sources){const ue=(Array.isArray(V.data_sources)?V.data_sources:[V.data_sources]).reduce((_e,Ae)=>(_e[Ae]=e[Ae]===void 0?"UNDEFINED":"LOADED",_e),{}),ne=Object.keys(e).filter(_e=>!_e.startsWith("_"));vt.log(`[BLUR APPLIED] Component: ${R.id}, data_sources status:`,ue,"Available keys:",ne)}else vt.log(`[BLUR APPLIED] Component: ${R.id}, blur_until_loaded:`,V)}const Ta=window.__slotContextValue;return Te&&Ta?.isEnabled?null:l.jsx(Ej,{componentId:r.id,componentName:r.name,children:R.blur_until_loaded?l.jsx("div",{className:dn?"opacity-50 blur-sm transition-all duration-300 pointer-events-none":void 0,children:Yn}):Yn})});Ua.displayName="DynamicRenderer",typeof window<"u"&&(window.__DynamicRenderer=Ua);function _j(r){const e={};try{const a=new URL(r,typeof window<"u"?window.location.origin:"http://localhost").searchParams,i=new Set;for(const o of a.keys()){if(i.has(o))continue;i.add(o);const d=a.getAll(o);d.length>1||o.endsWith("[]")?e[o]=d:e[o]=d[0]}}catch{}return e}function Aj(r){try{return new URL(r,typeof window<"u"?window.location.origin:"http://localhost").pathname}catch{return r.split("?")[0]}}const Er=class Er{constructor(){H(this,"config",{enabled:!1,maxHistorySize:100,logLevel:"info",serverEndpoint:"/_boost/g7-debug/dump-state",autoCapture:!0});H(this,"stateHistory",[]);H(this,"snapshotIdCounter",0);H(this,"stateWatchers",new Map);H(this,"currentLocalState",{});H(this,"currentComputedState",{});H(this,"currentParentContext");H(this,"actionHistory",[]);H(this,"actionWatchers",new Set);H(this,"cacheStats",{hits:0,misses:0,entries:0});H(this,"cacheDecisions",[]);H(this,"cacheDecisionIdCounter",0);H(this,"maxCacheDecisions",200);H(this,"currentRenderCycleId",null);H(this,"isInActionExecution",!1);H(this,"isInIteration",!1);H(this,"mountedComponents",new Map);H(this,"eventListeners",new Map);H(this,"mountWatchers",new Set);H(this,"unmountWatchers",new Set);H(this,"renderCounts",new Map);H(this,"bindingEvalCount",0);H(this,"profilingData",[]);H(this,"isProfiling",!1);H(this,"profilingStartTime",0);H(this,"activeRequests",new Map);H(this,"requestHistory",[]);H(this,"pendingDataSources",new Set);H(this,"requestWatchers",new Set);H(this,"wsConnections",new Map);H(this,"wsMessageHistory",[]);H(this,"wsMessageWatchers",new Set);H(this,"ifConditions",new Map);H(this,"iterations",new Map);H(this,"conditionWatchers",new Set);H(this,"forms",new Map);H(this,"formWatchers",new Set);H(this,"expressionHistory",[]);H(this,"expressionWatchers",new Set);H(this,"expressionIdCounter",0);H(this,"dataSources",new Map);H(this,"dataPathTransforms",[]);H(this,"maxDataPathTransforms",100);H(this,"nestedContexts",[]);H(this,"nestedContextIdCounter",0);H(this,"maxNestedContexts",100);H(this,"formBindingIssues",[]);H(this,"formBindingValidations",[]);H(this,"formBindingIssueIdCounter",0);H(this,"maxFormBindingIssues",100);H(this,"computedProperties",new Map);H(this,"computedRecalcLogs",[]);H(this,"computedRecalcIdCounter",0);H(this,"maxComputedRecalcLogs",100);H(this,"handlers",new Map);H(this,"componentEventSubscriptions",new Map);H(this,"componentEventEmitHistory",[]);H(this,"componentEventIdCounter",0);H(this,"maxComponentEventHistory",100);H(this,"stateRenderingLogs",[]);H(this,"currentStateChangeContext",null);H(this,"stateRenderingIdCounter",0);H(this,"componentRenderCounts",new Map);H(this,"stateToComponentMap",new Map);H(this,"maxStateRenderingLogs",100);H(this,"componentStateSources",new Map);H(this,"contextFlowNodes",new Map);H(this,"dynamicStates",new Map);H(this,"styleIssues",[]);H(this,"componentStyles",new Map);H(this,"authEvents",[]);H(this,"authHeaderHistory",[]);H(this,"authEventIdCounter",0);H(this,"maxAuthEventHistory",50);H(this,"logHistory",[]);H(this,"logIdCounter",0);H(this,"maxLogHistory",500);H(this,"currentLayout",null);H(this,"layoutHistory",[]);H(this,"layoutIdCounter",0);H(this,"layoutStats",{totalLoads:0,cacheHits:0,apiLoads:0});H(this,"maxLayoutHistory",50);H(this,"executionDetails",new Map);H(this,"stateChangeHistory",[]);H(this,"dataSourceChangeHistory",[]);H(this,"changeAlerts",[]);H(this,"changeExpectations",new Map);H(this,"executionIdCounter",0);H(this,"stateChangeIdCounter",0);H(this,"alertIdCounter",0);H(this,"maxExecutionDetails",100);H(this,"maxStateChangeHistory",200);H(this,"maxChangeAlerts",100);H(this,"sequenceExecutions",[]);H(this,"sequenceExecutionStack",[]);H(this,"sequenceIdCounter",0);H(this,"maxSequenceExecutions",50);H(this,"staleClosureWarnings",[]);H(this,"staleClosureIdCounter",0);H(this,"maxStaleClosureWarnings",100);H(this,"stateCaptureRegistry",new Map);H(this,"modalStates",new Map);H(this,"modalStateIssues",[]);H(this,"modalStateRelations",[]);H(this,"modalStateChangeLogs",[]);H(this,"modalStateIssueIdCounter",0);H(this,"modalStateChangeLogIdCounter",0);H(this,"maxModalStateIssues",100);H(this,"maxModalStateChangeLogs",200);H(this,"namedActionDefinitions",{});H(this,"namedActionRefLogs",[]);H(this,"namedActionRefIdCounter",0);H(this,"maxNamedActionRefLogs",200);H(this,"debounceActionHistory",[]);H(this,"dataSourceUpdateHistory",[]);H(this,"debounceActionIdCounter",0);H(this,"dataSourceUpdateIdCounter",0)}static getInstance(){return Er.instance||(Er.instance=new Er),Er.instance}initialize(){if(this.config.enabled=this.checkDebugMode(),!this.config.enabled){console.log("[G7DevTools] 비활성화됨 (환경설정 > 고급 설정 > 디버그 모드를 켜세요)");return}console.log("[G7DevTools] 활성화됨"),this.setupGlobalErrorHandler()}checkDebugMode(){try{if(window.G7Config?.debug===!0)return!0;const a=window.G7Core?.state?.get?.();return a?.settings?.advanced?.debug_mode===!0||a?._global?.settings?.advanced?.debug_mode===!0}catch{return!1}}isEnabled(){return this.config.enabled}setupGlobalErrorHandler(){window.addEventListener("error",e=>{this.config.enabled&&this.logAction({id:this.generateId(),type:"globalError",startTime:Date.now(),status:"error",error:{name:"Error",message:e.message,stack:e.error?.stack}})}),window.addEventListener("unhandledrejection",e=>{this.config.enabled&&this.logAction({id:this.generateId(),type:"unhandledRejection",startTime:Date.now(),status:"error",error:{name:"UnhandledRejection",message:String(e.reason)}})})}captureStateSnapshot(e){if(!this.config.enabled)return;const t={id:++this.snapshotIdCounter,timestamp:Date.now(),source:e.source,prev:this.sanitizeObject(e.prev),next:this.sanitizeObject(e.next),diff:e.diff};this.stateHistory.push(t),this.stateHistory.length>this.config.maxHistorySize&&this.stateHistory.shift(),this.notifyStateWatchers(t)}getState(){try{const e=window.G7Core,t=e?.state?.get?.()||{},a={};if(e?._isolatedStates&&typeof e._isolatedStates=="object")for(const[i,o]of Object.entries(e._isolatedStates))a[i]=this.sanitizeObject(o);return{_global:t._global||t,_local:this.currentLocalState,_computed:this.currentComputedState,_isolated:Object.keys(a).length>0?a:void 0,$parent:this.currentParentContext}}catch{return{_global:{},_local:this.currentLocalState,_computed:this.currentComputedState}}}updateLocalState(e){this.config.enabled&&(this.currentLocalState=this.sanitizeObject(e))}updateComputedState(e){this.config.enabled&&(this.currentComputedState=this.sanitizeObject(e))}updateParentContext(e){this.config.enabled&&(this.currentParentContext=e?this.sanitizeObject(e):void 0)}getStateHistory(){return[...this.stateHistory]}getDualStorageMismatch(){const e=this.currentLocalState||{};let t={};try{t=(window.G7Core?.state?.get?.()||{})._local||{}}catch{t={}}const a=this.findMismatchedLeafPaths(e,t);return{hasMismatch:a.length>0,mismatchedPaths:a,storageA:e,storageB:t}}findMismatchedLeafPaths(e,t,a=""){const i=[],o=new Set([...Object.keys(e||{}),...Object.keys(t||{})]);for(const d of o){const g=a?`${a}.${d}`:d,h=e?.[d],f=t?.[d],p=h&&typeof h=="object"&&!Array.isArray(h),y=f&&typeof f=="object"&&!Array.isArray(f);if(p&&y)i.push(...this.findMismatchedLeafPaths(h,f,g));else{const x=h===void 0?"__undefined__":JSON.stringify(h),S=f===void 0?"__undefined__":JSON.stringify(f);x!==S&&i.push(g)}}return i}watchState(e,t){return this.stateWatchers.has(e)||this.stateWatchers.set(e,new Set),this.stateWatchers.get(e).add(t),()=>{this.stateWatchers.get(e)?.delete(t)}}notifyStateWatchers(e){if(this.stateWatchers.get("*")?.forEach(t=>{try{t(e.next,e.prev,"*")}catch(a){console.error("[G7DevTools] State watcher error:",a)}}),e.diff)for(const t of e.diff.changed)this.stateWatchers.get(t.path)?.forEach(a=>{try{a(t.newValue,t.oldValue,t.path)}catch(i){console.error("[G7DevTools] State watcher error:",i)}})}diffSnapshots(e,t){const a=this.stateHistory.find(o=>o.id===e),i=this.stateHistory.find(o=>o.id===t);return!a||!i?null:this.calculateDiff(a.next,i.next)}calculateDiff(e,t,a=""){const i={added:[],removed:[],changed:[]},o=new Set(Object.keys(e)),d=new Set(Object.keys(t));for(const g of d){const h=a?`${a}.${g}`:g;o.has(g)?JSON.stringify(e[g])!==JSON.stringify(t[g])&&i.changed.push({path:h,oldValue:e[g],newValue:t[g]}):i.added.push(h)}for(const g of o){const h=a?`${a}.${g}`:g;d.has(g)||i.removed.push(h)}return i}logAction(e){if(!this.config.enabled)return;const t=this.actionHistory.findIndex(a=>a.id===e.id);t>=0?this.actionHistory[t]={...this.actionHistory[t],...e}:(this.actionHistory.push(e),this.actionHistory.length>this.config.maxHistorySize&&this.actionHistory.shift()),this.isProfiling&&this.profilingData.push({type:"action",action:e.type,timestamp:performance.now(),duration:e.duration}),this.notifyActionWatchers(e)}getActionHistory(){return[...this.actionHistory]}watchActions(e){return this.actionWatchers.add(e),()=>{this.actionWatchers.delete(e)}}notifyActionWatchers(e){this.actionWatchers.forEach(t=>{try{t(e)}catch(a){console.error("[G7DevTools] Action watcher error:",a)}})}getActionMetrics(){const e=this.actionHistory.filter(o=>o.status==="success"),t=this.actionHistory.filter(o=>o.status==="error"),a={};for(const o of this.actionHistory)a[o.type]=(a[o.type]||0)+1;const i=e.reduce((o,d)=>o+(d.duration||0),0);return{totalActions:this.actionHistory.length,successCount:e.length,errorCount:t.length,averageDuration:e.length>0?i/e.length:0,actionsByType:a}}recordCacheHit(){this.config.enabled&&this.cacheStats.hits++}recordCacheMiss(){this.config.enabled&&this.cacheStats.misses++}updateCacheEntries(e){this.config.enabled&&(this.cacheStats.entries=e)}getCacheStats(){const e=this.cacheStats.hits+this.cacheStats.misses;return{...this.cacheStats,hitRate:e>0?this.cacheStats.hits/e:0}}resetCacheStats(){this.cacheStats={hits:0,misses:0,entries:0}}trackCacheDecision(e){if(!this.config.enabled)return;const t={id:`cache-${++this.cacheDecisionIdCounter}`,timestamp:Date.now(),expression:e.expression,decision:e.decision,reason:e.reason,context:{isInIteration:this.isInIteration,isInAction:this.isInActionExecution,renderCycleId:this.currentRenderCycleId||void 0,componentId:e.componentId,skipCacheOption:e.skipCacheOption},cachedValue:e.cachedValue!==void 0?this.safeClone(e.cachedValue):void 0,freshValue:e.freshValue!==void 0?this.safeClone(e.freshValue):void 0,valueMatch:e.cachedValue!==void 0&&e.freshValue!==void 0?JSON.stringify(e.cachedValue)===JSON.stringify(e.freshValue):void 0,duration:e.duration};this.cacheDecisions.push(t),this.cacheDecisions.length>this.maxCacheDecisions&&this.cacheDecisions.shift(),e.decision==="cache_hit"?this.cacheStats.hits++:(e.decision==="cache_miss"||e.decision==="skip_cache")&&this.cacheStats.misses++}startRenderCycle(e){return this.currentRenderCycleId=`render-${Date.now()}-${e||"root"}`,this.currentRenderCycleId}endRenderCycle(){this.currentRenderCycleId=null}startActionContext(){this.isInActionExecution=!0}endActionContext(){this.isInActionExecution=!1}startIterationContext(){this.isInIteration=!0}endIterationContext(){this.isInIteration=!1}getCacheDecisionTrackingInfo(){const e=this.getCacheDecisionStats();return{decisions:[...this.cacheDecisions],stats:e,timestamp:Date.now()}}getCacheDecisionStats(){const e=this.cacheDecisions;let t=0,a=0,i=0,o=0;const d={},g={};for(const f of e)f.decision==="cache_hit"?t++:f.decision==="cache_miss"?a++:f.decision==="skip_cache"?i++:f.decision==="invalidate"&&o++,d[f.reason]=(d[f.reason]||0)+1,f.context.componentId&&(g[f.context.componentId]=(g[f.context.componentId]||0)+1);const h=t+a+i;return{totalDecisions:e.length,cacheHits:t,cacheMisses:a,skipCacheCount:i,invalidateCount:o,byReason:d,byComponent:g,avgHitRate:h>0?t/h:0}}getRecentCacheDecisions(e=20,t){let a=[...this.cacheDecisions];return t&&(a=a.filter(i=>i.decision===t)),a.slice(-e)}clearCacheDecisionData(){this.cacheDecisions=[],this.cacheDecisionIdCounter=0}summarizePropsForLifecycle(e){if(!e||typeof e!="object")return e;const t={},a=["children","ref","key"];for(const[i,o]of Object.entries(e))if(!a.includes(i))if(o==null)t[i]=o;else if(Array.isArray(o))t[i]=`[Array(${o.length})]`;else if(typeof o=="object"){const d=Object.keys(o);d.length<=3?t[i]=`{${d.join(", ")}}`:t[i]=`{${d.slice(0,3).join(", ")}, ... +${d.length-3}}`}else typeof o=="string"&&o.length>50?t[i]=o.substring(0,50)+"...":typeof o=="function"?t[i]="[Function]":t[i]=o;return t}trackMount(e,t){if(!this.config.enabled)return;const a=this.summarizePropsForLifecycle(t.props),i={...t,props:a,id:e,mountTime:Date.now()};this.mountedComponents.set(e,i),this.mountWatchers.forEach(o=>{try{o({componentId:e,componentName:t.name,timestamp:i.mountTime})}catch(d){console.error("[G7DevTools] Mount watcher error:",d)}})}trackUnmount(e){if(!this.config.enabled)return;const t=this.mountedComponents.get(e),a=this.eventListeners.get(e)||[];a.length>0&&console.warn(`[G7DevTools] 컴포넌트 ${e} 언마운트 시 ${a.length}개 리스너 미정리`),t&&this.unmountWatchers.forEach(i=>{try{i({componentId:e,componentName:t.name,timestamp:Date.now(),orphanedListeners:a.length})}catch(o){console.error("[G7DevTools] Unmount watcher error:",o)}}),this.mountedComponents.delete(e)}trackListener(e,t,a){if(!this.config.enabled)return;const i=this.eventListeners.get(e)||[];i.push({type:t,target:a,addedAt:Date.now()}),this.eventListeners.set(e,i)}removeListener(e,t){if(!this.config.enabled)return;const a=this.eventListeners.get(e)||[],i=a.findIndex(o=>o.type===t);i>=0&&a.splice(i,1)}getMountedComponents(){return Array.from(this.mountedComponents.values())}getOrphanedListeners(){const e=[];for(const[t,a]of this.eventListeners)this.mountedComponents.has(t)||e.push(...a.map(i=>({...i,componentId:t})));return e}watchMount(e){return this.mountWatchers.add(e),()=>{this.mountWatchers.delete(e)}}watchUnmount(e){return this.unmountWatchers.add(e),()=>{this.unmountWatchers.delete(e)}}trackRender(e){if(!this.config.enabled)return;const t=this.renderCounts.get(e)||0;this.renderCounts.set(e,t+1),this.isProfiling&&this.profilingData.push({type:"render",component:e,timestamp:performance.now()})}trackBindingEval(e){this.config.enabled&&(this.bindingEvalCount++,this.isProfiling&&e&&this.profilingData.push({type:"binding",expression:e,timestamp:performance.now()}))}getRenderCount(){return new Map(this.renderCounts)}getBindingEvalCount(){return this.bindingEvalCount}getMemoryWarnings(){const e=[];try{const i=this.getState(),o=JSON.stringify(i).length;o>1e6&&e.push({type:"large-state",message:`상태 크기가 ${(o/1024/1024).toFixed(2)}MB입니다`,suggestion:"불필요한 데이터 정리 필요",severity:o>5e6?"error":"warning"})}catch{}this.stateHistory.length>this.config.maxHistorySize*.8&&e.push({type:"large-history",message:`상태 이력이 ${this.stateHistory.length}개입니다`,suggestion:"maxHistory 설정 조정 필요",severity:"warning"});const t=this.getOrphanedListeners().length;t>0&&e.push({type:"orphaned-listeners",message:`${t}개의 정리되지 않은 이벤트 리스너`,suggestion:"useEffect cleanup 또는 removeEventListener 확인",severity:t>10?"error":"warning"});const a=Array.from(this.renderCounts.entries()).filter(([,i])=>i>50);return a.length>0&&e.push({type:"excessive-renders",message:`${a.length}개 컴포넌트가 50회 이상 렌더링`,suggestion:"React.memo, useMemo, useCallback 사용 고려",severity:"warning"}),e}startProfiling(){this.config.enabled&&(this.isProfiling=!0,this.profilingData=[],this.profilingStartTime=performance.now(),console.log("[G7DevTools] 프로파일링 시작"))}stopProfiling(){this.isProfiling=!1;const e=performance.now()-this.profilingStartTime,t=this.analyzeProfile(e);return console.log("[G7DevTools] 프로파일링 완료",t),t}analyzeProfile(e){const t=this.profilingData.filter(f=>f.type==="render"),a=this.profilingData.filter(f=>f.type==="binding"),i=this.profilingData.filter(f=>f.type==="action"),o={};for(const f of t)f.component&&(o[f.component]||(o[f.component]={count:0,durations:[]}),o[f.component].count++,f.duration&&o[f.component].durations.push(f.duration));const d=Object.entries(o).map(([f,p])=>({name:f,renderCount:p.count,avgDuration:p.durations.length>0?p.durations.reduce((y,x)=>y+x,0)/p.durations.length:0})).sort((f,p)=>p.renderCount-f.renderCount).slice(0,10),g={};for(const f of a)f.expression&&(g[f.expression]=(g[f.expression]||0)+1);const h=Object.entries(g).sort(([,f],[,p])=>p-f).slice(0,10).map(([f])=>f);return{duration:e,entries:this.profilingData,summary:{totalRenders:t.length,totalBindings:a.length,totalActions:i.length,slowestComponents:d,hotPaths:h}}}resetPerformanceStats(){this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[]}trackRequest(e,t,a){if(!this.config.enabled)return"";const i=this.generateId(),o=Aj(e),d=_j(e);return this.activeRequests.set(i,{id:i,url:o,fullUrl:e,queryParams:d,method:t,startTime:Date.now(),status:"pending",requestBody:a?.requestBody?this.sanitizeObject(a.requestBody):void 0,dataSourceId:a?.dataSourceId}),this.isProfiling&&this.profilingData.push({type:"network",timestamp:performance.now()}),i}completeRequest(e,t,a){if(!this.config.enabled)return;const i=this.activeRequests.get(e);if(!i)return;const o={...i,status:t>=200&&t<300?"success":"error",statusCode:t,duration:Date.now()-i.startTime,endTime:Date.now(),response:this.sanitizeObject(a)};this.requestHistory.push(o),this.activeRequests.delete(e),this.requestHistory.length>this.config.maxHistorySize&&this.requestHistory.shift(),this.notifyRequestWatchers(o)}failRequest(e,t){if(!this.config.enabled)return;const a=this.activeRequests.get(e);if(!a)return;const i={...a,status:"error",error:t,duration:Date.now()-a.startTime,endTime:Date.now()};this.requestHistory.push(i),this.activeRequests.delete(e),this.notifyRequestWatchers(i)}trackDataSource(e){this.config.enabled&&this.pendingDataSources.add(e)}completeDataSource(e){this.config.enabled&&this.pendingDataSources.delete(e)}getActiveRequests(){return Array.from(this.activeRequests.values())}getRequestHistory(){return[...this.requestHistory]}getPendingDataSources(){return Array.from(this.pendingDataSources)}watchRequest(e){return this.requestWatchers.add(e),()=>{this.requestWatchers.delete(e)}}notifyRequestWatchers(e){this.requestWatchers.forEach(t=>{try{t(e)}catch(a){console.error("[G7DevTools] Request watcher error:",a)}})}trackWebSocketConnection(e,t,a){this.config.enabled&&this.wsConnections.set(e,{id:e,url:t,state:a,connectedAt:a==="open"?Date.now():void 0})}trackWebSocketMessage(e,t,a,i){if(!this.config.enabled)return;const o={id:this.generateId(),connectionId:e,direction:t,type:a,payload:this.sanitizeObject(i),timestamp:Date.now(),sequence:this.wsMessageHistory.length};this.wsMessageHistory.push(o),this.wsMessageHistory.length>this.config.maxHistorySize&&this.wsMessageHistory.shift(),this.notifyWebSocketWatchers(o)}getWebSocketConnections(){return Array.from(this.wsConnections.values())}getWebSocketMessageHistory(){return[...this.wsMessageHistory]}getWebSocketConnectionState(){const e=Array.from(this.wsConnections.values());return e.some(t=>t.state==="open")?"connected":e.some(t=>t.state==="connecting")?"reconnecting":"disconnected"}watchWebSocketMessage(e){return this.wsMessageWatchers.add(e),()=>{this.wsMessageWatchers.delete(e)}}notifyWebSocketWatchers(e){this.wsMessageWatchers.forEach(t=>{try{t(e)}catch(a){console.error("[G7DevTools] WebSocket watcher error:",a)}})}trackIfCondition(e,t,a){if(!this.config.enabled)return;const i=this.ifConditions.get(e),o=i?.evaluatedValue;this.ifConditions.set(e,{id:e,expression:t,evaluatedValue:a,evaluationCount:(i?.evaluationCount||0)+1,lastEvaluated:Date.now()}),i&&o!==a&&this.notifyConditionWatchers({id:e,expression:t,oldValue:o,newValue:a,timestamp:Date.now()})}trackIteration(e,t){this.config.enabled&&this.iterations.set(e,{id:e,...t,lastRendered:Date.now()})}getIfConditions(){return Array.from(this.ifConditions.values())}getIterations(){return Array.from(this.iterations.values())}getScopeChain(e){const t=[],a=this.getState();return t.push({name:"_global",value:a._global,source:"global"}),t.push({name:"_local",value:a._local,source:"local"}),t.push({name:"_computed",value:a._computed,source:"computed"}),t}watchConditionChange(e){return this.conditionWatchers.add(e),()=>{this.conditionWatchers.delete(e)}}notifyConditionWatchers(e){this.conditionWatchers.forEach(t=>{try{t(e)}catch(a){console.error("[G7DevTools] Condition watcher error:",a)}})}trackForm(e,t,a){this.config.enabled&&this.forms.set(e,{id:e,dataKey:t,inputs:a,trackedAt:Date.now()})}trackFormChange(e,t,a){if(!this.config.enabled)return;const i={formId:e,inputName:t,value:a,timestamp:Date.now()};this.notifyFormWatchers(i)}untrackForm(e){this.forms.delete(e)}getForms(){return Array.from(this.forms.values())}getFormState(e){const t=this.getState();return this.getNestedValue(t,e)||{}}getBindingPath(e,t){return`${e}.${t}`}watchFormChange(e){return this.formWatchers.add(e),()=>{this.formWatchers.delete(e)}}notifyFormWatchers(e){this.formWatchers.forEach(t=>{try{t(e)}catch(a){console.error("[G7DevTools] Form watcher error:",a)}})}trackFormBindingIssue(e,t,a){if(!this.config.enabled)return;const i={id:`form-issue-${++this.formBindingIssueIdCounter}`,timestamp:Date.now(),type:e,severity:t,formId:a.formId,formDataKey:a.formDataKey,inputInfo:a.inputInfo,contextInfo:a.contextInfo,description:a.description,suggestion:a.suggestion,docLink:a.docLink};this.formBindingIssues.push(i),this.formBindingIssues.length>this.maxFormBindingIssues&&this.formBindingIssues.shift()}validateFormBinding(e,t,a,i){const o=a.map(h=>{const f=[];let p=!0;return h.name||(f.push("Input에 name 속성이 없습니다"),p=!1,this.trackFormBindingIssue("missing-input-name","error",{formId:e,formDataKey:t,inputInfo:{name:h.name,type:h.type},description:"Input에 name 속성이 없어 자동 바인딩이 동작하지 않습니다",suggestion:"Input에 name 속성을 추가하세요",docLink:"troubleshooting-components-form.md"})),t||(f.push("Form에 dataKey가 없습니다"),p=!1),{inputName:h.name||"(unnamed)",inputType:h.type,bindingPath:t&&h.name?`${t}.${h.name}`:"-",isValid:p,currentValue:h.value,issues:f}});if(t||this.trackFormBindingIssue("missing-datakey","error",{formId:e,description:"Form에 dataKey가 설정되지 않아 자동 바인딩이 동작하지 않습니다",suggestion:"Form 컴포넌트에 dataKey props를 설정하세요",docLink:"troubleshooting-components-form.md"}),i.isContextBroken){const h=i.breakReason?.includes("sortable")?"sortable-context-break":i.breakReason?.includes("modal")?"modal-context-isolation":"context-not-propagated";this.trackFormBindingIssue(h,"warning",{formId:e,formDataKey:t,contextInfo:{hasParentFormContext:i.hasParentContext,parentFormContextProp:i.parentContextProp,isInsideSortable:i.breakReason?.includes("sortable")||!1,isInsideModal:i.breakReason?.includes("modal")||!1,depth:0},description:i.breakReason||"Form 컨텍스트가 제대로 전파되지 않았습니다",suggestion:"parentFormContextProp={undefined}를 확인하거나 중첩 구조를 검토하세요",docLink:"troubleshooting-components-form.md"})}const d={formId:e,dataKey:t,timestamp:Date.now(),contextPropagation:i,inputBindings:o,isValid:o.every(h=>h.isValid)&&!!t&&!i.isContextBroken,issueCount:o.filter(h=>!h.isValid).length+(t?0:1)+(i.isContextBroken?1:0)},g=this.formBindingValidations.findIndex(h=>h.formId===e);return g>=0?this.formBindingValidations[g]=d:this.formBindingValidations.push(d),d}getFormBindingValidationTrackingInfo(){const e=this.getFormBindingValidationStats();return{issues:[...this.formBindingIssues],validations:[...this.formBindingValidations],stats:e,timestamp:Date.now()}}getFormBindingValidationStats(){const e={"missing-datakey":0,"missing-input-name":0,"context-not-propagated":0,"sortable-context-break":0,"modal-context-isolation":0,"duplicate-input-name":0,"value-type-mismatch":0,"binding-path-invalid":0},t={info:0,warning:0,error:0};for(const i of this.formBindingIssues)e[i.type]++,t[i.severity]++;const a=Object.entries(e).filter(([,i])=>i>0).sort((i,o)=>o[1]-i[1]).slice(0,5).map(([i,o])=>({type:i,count:o,description:this.getIssueTypeDescription(i)}));return{totalFormsValidated:this.formBindingValidations.length,validForms:this.formBindingValidations.filter(i=>i.isValid).length,formsWithIssues:this.formBindingValidations.filter(i=>!i.isValid).length,totalIssues:this.formBindingIssues.length,byIssueType:e,bySeverity:t,topIssues:a}}getIssueTypeDescription(e){return{"missing-datakey":"Form에 dataKey 누락","missing-input-name":"Input에 name 속성 누락","context-not-propagated":"Form 컨텍스트 전파 실패","sortable-context-break":"Sortable 컨테이너에서 컨텍스트 단절","modal-context-isolation":"모달에서 부모 Form 컨텍스트 격리","duplicate-input-name":"동일 Form 내 중복 Input name","value-type-mismatch":"값 타입과 Input 타입 불일치","binding-path-invalid":"바인딩 경로 유효하지 않음"}[e]||e}clearFormBindingIssues(){this.formBindingIssues=[],this.formBindingValidations=[],this.formBindingIssueIdCounter=0}trackComputedProperty(e,t,a,i,o,d,g){if(!this.config.enabled)return;const h=`computed-${e}-${d||"global"}`,f={id:h,name:e,expression:t,componentId:d,dependencies:a,currentValue:this.safeClone(i),lastComputedAt:Date.now(),computationTime:o,error:g};this.computedProperties.set(h,f)}trackComputedRecalc(e,t,a,i,o,d,g){if(!this.config.enabled)return;const h=`computed-${e}-${g||"global"}`,f=JSON.stringify(a)!==JSON.stringify(i),p={id:`recalc-${++this.computedRecalcIdCounter}`,computedId:h,computedName:e,timestamp:Date.now(),trigger:t,triggeredBy:d,previousValue:this.safeClone(a),newValue:this.safeClone(i),valueChanged:f,computationTime:o,cascadeCount:0};this.computedRecalcLogs.push(p),this.computedRecalcLogs.length>this.maxComputedRecalcLogs&&this.computedRecalcLogs.shift();const y=this.computedProperties.get(h);y&&(y.currentValue=this.safeClone(i),y.lastComputedAt=Date.now(),y.computationTime=o)}analyzeComputedDependencyChain(e,t){const a=new Set,i=[];let o=!1,d,g=0;const h=(p,y)=>{if(g=Math.max(g,y),a.has(p))return o=!0,d=[...i,p],{name:p,type:"computed",children:[],depth:y};a.add(p),i.push(p);const x=this.computedProperties.get(`computed-${p}-${t||"global"}`),S=[];if(x)for(const v of x.dependencies)v.type==="computed"?S.push(h(v.path,y+1)):S.push({name:v.path,type:v.type,children:[],depth:y+1});return i.pop(),a.delete(p),{name:p,type:"computed",children:S,depth:y}},f=h(e,0);return{root:e,tree:f,hasCycle:o,cyclePath:d,maxDepth:g}}getComputedDependencyTrackingInfo(){const e=Array.from(this.computedProperties.values()),t=this.getComputedDependencyStats(),a=[];for(const i of e){const o=this.analyzeComputedDependencyChain(i.name,i.componentId);a.push(o)}return{properties:e,recalcLogs:[...this.computedRecalcLogs],dependencyChains:a,stats:t,timestamp:Date.now()}}getComputedDependencyStats(){const e={"state-change":0,"datasource-update":0,"dependency-change":0,manual:0,initial:0},t={},a={};let i=0,o=0;for(const f of this.computedRecalcLogs)e[f.trigger]++,f.valueChanged||o++,t[f.computedName]=(t[f.computedName]||0)+1,a[f.computedName]||(a[f.computedName]=[]),a[f.computedName].push(f.computationTime),i+=f.computationTime;const d=Object.entries(t).sort((f,p)=>p[1]-f[1]).slice(0,5).map(([f,p])=>({name:f,count:p})),g=Object.entries(a).map(([f,p])=>({name:f,avgTime:p.reduce((y,x)=>y+x,0)/p.length})).sort((f,p)=>p.avgTime-f.avgTime).slice(0,5);let h=0;for(const f of this.computedProperties.values())this.analyzeComputedDependencyChain(f.name,f.componentId).hasCycle&&h++;return{totalComputed:this.computedProperties.size,totalRecalculations:this.computedRecalcLogs.length,unnecessaryRecalculations:o,avgComputationTime:this.computedRecalcLogs.length>0?i/this.computedRecalcLogs.length:0,topRecalculated:d,slowestComputed:g,cycleDetectionCount:h,byTrigger:e}}clearComputedTracking(){this.computedProperties.clear(),this.computedRecalcLogs=[],this.computedRecalcIdCounter=0}trackModalOpen(e){if(!this.config.enabled)return;const t={modalId:e.modalId,modalName:e.modalName,openedAt:Date.now(),closedAt:null,scopeType:e.scopeType||"isolated",parentModalId:e.parentModalId,componentId:e.componentId,initialState:e.initialState?{...e.initialState}:{},currentState:e.initialState?{...e.initialState}:{},stateChangeCount:0,isolatedStateKeys:e.isolatedStateKeys||[],sharedStateKeys:e.sharedStateKeys||[]};this.modalStates.set(e.modalId,t),this.validateModalDefinitionExists(e.modalId,e.modalName),e.parentModalId&&(this.modalStateRelations.find(i=>i.parentModalId===e.parentModalId&&i.childModalId===e.modalId)||this.modalStateRelations.push({parentModalId:e.parentModalId,childModalId:e.modalId,sharedKeys:e.sharedStateKeys||[],isolatedKeys:e.isolatedStateKeys||[],relationType:"parent-child"}))}trackModalClose(e,t){if(!this.config.enabled)return;const a=this.modalStates.get(e);a&&(a.closedAt=Date.now(),t&&(a.currentState={...t}),this.detectStateLeakage(a))}validateModalDefinitionExists(e,t){const a=this.currentLayout;if(!a?.layoutJson)return;const i=a.layoutJson.modals;if(!i){this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:t,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 현재 레이아웃에 modals 섹션이 없습니다. 레이아웃 경로: ${a.layoutPath}`,affectedStateKeys:[],expectedValue:`modals 섹션에 id="${e}" 정의 존재`,actualValue:"modals 섹션 없음"});return}const o=Array.isArray(i)?i:Object.values(i);o.some(g=>g?.id===e||g?.props?.id===e)||this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:t,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 렌더링된 레이아웃의 modals 섹션에 해당 ID의 정의가 없습니다. partial 로딩 실패, 레이아웃 병합 문제, extends 상속 누락 등을 확인하세요. 레이아웃 경로: ${a.layoutPath}`,affectedStateKeys:[],expectedValue:`modals 배열에 id="${e}" 항목 존재`,actualValue:`modals 배열에 ${o.length}개 모달 정의 (${o.map(g=>g?.id||"unknown").join(", ")})`})}trackModalStateChange(e){if(!this.config.enabled)return;const t=this.modalStates.get(e.modalId);if(!t)return;t.stateChangeCount++,t.currentState[e.stateKey]=e.newValue;const a=this.checkIsolationViolation(t,e.stateKey),i={id:`modal-change-${++this.modalStateChangeLogIdCounter}`,modalId:e.modalId,modalName:t.modalName,timestamp:Date.now(),stateKey:e.stateKey,previousValue:e.previousValue,newValue:e.newValue,changeSource:e.changeSource||"user-action",violatesIsolation:a};this.modalStateChangeLogs.push(i),this.modalStateChangeLogs.length>this.maxModalStateChangeLogs&&this.modalStateChangeLogs.shift(),a&&this.recordModalStateIssue({type:"isolation-violation",modalId:e.modalId,modalName:t.modalName,severity:"warning",description:`모달 '${t.modalName}'에서 격리된 상태 키 '${e.stateKey}'가 변경됨`,affectedStateKeys:[e.stateKey]})}detectStateLeakage(e){if(e.scopeType==="isolated")for(const t of e.isolatedStateKeys){const a=e.initialState[t],i=e.currentState[t];if(a!==i&&e.parentModalId){const o=this.modalStates.get(e.parentModalId);o&&o.currentState.hasOwnProperty(t)&&this.recordModalStateIssue({type:"state-leakage",modalId:e.modalId,modalName:e.modalName,severity:"error",description:`모달 닫힘 후 상태 '${t}'가 부모 모달로 유출될 수 있음`,affectedStateKeys:[t],leakedValue:i,expectedValue:a})}}}checkIsolationViolation(e,t){return e.scopeType==="isolated",!1}recordModalStateIssue(e){const t={id:`modal-issue-${++this.modalStateIssueIdCounter}`,type:e.type,modalId:e.modalId,modalName:e.modalName,timestamp:Date.now(),severity:e.severity,description:e.description,affectedStateKeys:e.affectedStateKeys,leakedValue:e.leakedValue,expectedValue:e.expectedValue,actualValue:e.actualValue,stackInfo:e.stackInfo};this.modalStateIssues.push(t),this.modalStateIssues.length>this.maxModalStateIssues&&this.modalStateIssues.shift()}getModalStateScopeTrackingInfo(){const e=Array.from(this.modalStates.values()),t=this.getModalStateScopeStats();return{modals:e,issues:[...this.modalStateIssues],relations:[...this.modalStateRelations],changeLogs:[...this.modalStateChangeLogs],stats:t,timestamp:Date.now()}}getModalStateScopeStats(){const e=Array.from(this.modalStates.values()),t={warning:0,error:0},a={"state-leakage":0,"isolation-violation":0,"parent-mutation":0,"orphaned-state":0,"scope-mismatch":0,"cleanup-failure":0,"missing-definition":0};for(const o of this.modalStateIssues)t[o.severity]++,a[o.type]++;const i={isolated:0,shared:0,inherited:0};for(const o of e)i[o.scopeType]++;return{totalModals:e.length,openModals:e.filter(o=>o.closedAt===null).length,nestedModals:e.filter(o=>o.parentModalId!==void 0).length,totalIssues:this.modalStateIssues.length,issuesBySeverity:t,issuesByType:a,byScope:i,leakageDetectionCount:a["state-leakage"],cleanupFailureCount:a["cleanup-failure"]}}clearModalStateScopeTracking(){this.modalStates.clear(),this.modalStateIssues=[],this.modalStateRelations=[],this.modalStateChangeLogs=[],this.modalStateIssueIdCounter=0,this.modalStateChangeLogIdCounter=0}setNamedActionDefinitions(e){this.config.enabled&&(this.namedActionDefinitions=e||{})}trackNamedActionRef(e){if(!this.config.enabled)return;const t={...e,id:`named_action_ref_${++this.namedActionRefIdCounter}`};this.namedActionRefLogs.push(t),this.namedActionRefLogs.length>this.maxNamedActionRefLogs&&(this.namedActionRefLogs=this.namedActionRefLogs.slice(-this.maxNamedActionRefLogs))}getNamedActionTrackingInfo(){const e={};for(const a of this.namedActionRefLogs)e[a.actionRefName]=(e[a.actionRefName]||0)+1;const t=Object.keys(this.namedActionDefinitions).filter(a=>!e[a]);return{definitions:this.namedActionDefinitions,refLogs:[...this.namedActionRefLogs],stats:{totalDefinitions:Object.keys(this.namedActionDefinitions).length,totalRefs:this.namedActionRefLogs.length,refCountByName:e,unusedDefinitions:t},timestamp:Date.now()}}clearNamedActionTracking(){this.namedActionDefinitions={},this.namedActionRefLogs=[],this.namedActionRefIdCounter=0}trackExpressionEval(e){if(!this.config.enabled)return;const t={...e,id:`expr-${++this.expressionIdCounter}`,timestamp:Date.now(),warning:this.detectExpressionWarning(e)};this.expressionHistory.push(t),this.expressionHistory.length>500&&this.expressionHistory.shift(),this.isProfiling&&this.profilingData.push({type:"binding",expression:e.expression,timestamp:performance.now(),duration:e.duration}),this.notifyExpressionWatchers(t)}detectExpressionWarning(e){const{expression:t,result:a,resultType:i,method:o,duration:d}=e;if(i==="undefined"&&!t.includes("??")&&!t.includes("||")&&/^[a-zA-Z_$][a-zA-Z0-9_$.]*$/.test(t.replace(/{{|}}/g,"").trim()))return{type:"undefined-result",message:"표현식 결과가 undefined입니다",suggestion:`데이터가 로드되었는지 확인하거나 fallback 값을 추가하세요: ${t} ?? ''`};if(i==="null")return{type:"null-result",message:"표현식 결과가 null입니다",suggestion:`nullish coalescing 연산자를 사용하세요: ${t} ?? ''`};if(o==="resolveBindings"&&i==="string"){const g=String(a);if(g.includes("[object Object]")||/^\[.*\]$/.test(g))return{type:"array-to-string",message:"배열/객체가 문자열로 변환되었습니다",suggestion:"evaluateExpression()을 사용하여 원본 타입을 유지하세요"}}if(o==="resolveBindings"&&i==="string"&&String(a).includes("[object Object]"))return{type:"object-to-string",message:"객체가 [object Object]로 변환되었습니다",suggestion:"evaluateExpression()을 사용하거나 특정 속성에 접근하세요"};if(i==="undefined"&&t.includes(".")&&!t.includes("?.")){const g=t.replace(/{{|}}/g,"").trim().split(".");if(g.length>=2)return{type:"missing-optional-chain",message:"Optional chaining(?.) 누락 가능성",suggestion:`안전한 접근을 위해 ?. 사용을 고려하세요: ${g.join("?.")}`}}if((t.includes("{{item.")||t.includes("{{index}}"))&&Array.from(this.iterations.values()).some(f=>f.itemVar!=="item"))return{type:"wrong-iteration-var",message:"'item'/'index' 대신 iteration에서 정의한 변수명을 사용해야 합니다",suggestion:"iteration의 item_var/index_var에 정의된 변수명을 확인하세요"};if(d&&d>10)return{type:"slow-evaluation",message:`표현식 평가에 ${d.toFixed(2)}ms 소요됨`,suggestion:"복잡한 표현식을 단순화하거나 computed 값으로 분리하세요"}}getExpressions(){return[...this.expressionHistory]}getExpressionWarnings(){return this.expressionHistory.filter(e=>e.warning!=null)}searchExpressions(e){const t=e.toLowerCase();return this.expressionHistory.filter(a=>a.expression.toLowerCase().includes(t)||a.componentName?.toLowerCase().includes(t)||a.propName?.toLowerCase().includes(t))}getExpressionStats(){const e=this.expressionHistory,t=new Set(e.map(h=>h.expression)),a=e.filter(h=>h.warning!=null),i=e.filter(h=>h.fromCache),o=e.filter(h=>h.duration!=null).map(h=>h.duration),d={};for(const h of e)d[h.resultType]=(d[h.resultType]||0)+1;const g={};for(const h of a)h.warning&&(g[h.warning.type]=(g[h.warning.type]||0)+1);return{totalEvaluations:e.length,uniqueExpressions:t.size,warningCount:a.length,cacheHitRate:e.length>0?i.length/e.length:0,averageDuration:o.length>0?o.reduce((h,f)=>h+f,0)/o.length:0,byType:d,byWarning:g}}clearExpressions(){this.expressionHistory=[],this.expressionIdCounter=0}watchExpressions(e){return this.expressionWatchers.add(e),()=>{this.expressionWatchers.delete(e)}}notifyExpressionWatchers(e){this.expressionWatchers.forEach(t=>{try{t(e)}catch(a){console.error("[G7DevTools] Expression watcher error:",a)}})}setLogLevel(e){this.config.logLevel=e}setMaxHistory(e){this.config.maxHistorySize=Math.max(10,Math.min(1e3,e))}setServerEndpoint(e){this.config.serverEndpoint=e}getConfig(){return{...this.config}}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}sanitizeObject(e,t=new WeakSet){if(e===null||typeof e!="object")return e;if(t.has(e))return"[Circular]";if(t.add(e),Array.isArray(e))return e.map(i=>this.sanitizeObject(i,t));const a={};for(const i of Object.keys(e))try{a[i]=this.sanitizeObject(e[i],t)}catch{a[i]="[Unable to serialize]"}return a}getNestedValue(e,t){if(!t)return e;const a=t.split(".");let i=e;for(const o of a){if(i==null)return;i=i[o]}return i}getLifecycleInfo(){return{mountedComponents:Array.from(this.mountedComponents.values()),orphanedListeners:this.getOrphanedListeners()}}getPerformanceInfo(){return{renderCounts:this.renderCounts,bindingEvalCount:this.bindingEvalCount,memoryWarnings:this.getMemoryWarnings()}}getNetworkInfo(){return{activeRequests:Array.from(this.activeRequests.values()),requestHistory:[...this.requestHistory],pendingDataSources:Array.from(this.pendingDataSources)}}getConditionalInfo(){return{ifConditions:Array.from(this.ifConditions.values()),iterations:Array.from(this.iterations.values())}}getFormInfo(){return Array.from(this.forms.values())}getWebSocketInfo(){return{connections:Array.from(this.wsConnections.values()),messageHistory:[...this.wsMessageHistory],connectionState:this.getWebSocketConnectionState()}}getStateAtTime(e){const t=[...this.stateHistory].reverse().find(a=>a.timestamp<=e);if(t)return{_global:t.next,_local:{}}}reset(){this.stateHistory=[],this.actionHistory=[],this.cacheStats={hits:0,misses:0,entries:0},this.cacheDecisions=[],this.cacheDecisionIdCounter=0,this.currentRenderCycleId=null,this.isInActionExecution=!1,this.isInIteration=!1,this.mountedComponents.clear(),this.eventListeners.clear(),this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[],this.activeRequests.clear(),this.requestHistory=[],this.pendingDataSources.clear(),this.wsConnections.clear(),this.wsMessageHistory=[],this.ifConditions.clear(),this.iterations.clear(),this.forms.clear(),this.expressionHistory=[],this.expressionIdCounter=0,this.dataSources.clear(),this.dataPathTransforms=[],this.nestedContexts=[],this.nestedContextIdCounter=0,this.formBindingIssues=[],this.formBindingValidations=[],this.formBindingIssueIdCounter=0,this.computedProperties.clear(),this.computedRecalcLogs=[],this.computedRecalcIdCounter=0,this.modalStates.clear(),this.modalStateIssues=[],this.modalStateRelations=[],this.modalStateChangeLogs=[],this.modalStateIssueIdCounter=0,this.modalStateChangeLogIdCounter=0,this.logHistory=[],this.logIdCounter=0}getExpressionInfo(){return{expressions:this.getExpressions(),stats:this.getExpressionStats()}}trackLog(e,t,a){if(!this.config.enabled)return;const i=a.map(d=>{if(typeof d=="string")return d;try{return JSON.stringify(d)}catch{return String(d)}}).join(" "),o={id:`log-${++this.logIdCounter}`,level:e,prefix:t,message:i,args:this.sanitizeObject(a),timestamp:Date.now(),stack:e==="error"?new Error().stack:void 0};this.logHistory.push(o),this.logHistory.length>this.maxLogHistory&&this.logHistory.shift()}trackAction(e){if(!this.config.enabled)return;const t={id:`debounce-action-${++this.debounceActionIdCounter}`,...e,timestamp:Date.now()};this.debounceActionHistory.push(t),this.debounceActionHistory.length>100&&this.debounceActionHistory.shift()}trackDataSourceUpdate(e){if(!this.config.enabled)return;const t={id:`ds-update-${++this.dataSourceUpdateIdCounter}`,...e};this.dataSourceUpdateHistory.push(t),this.dataSourceUpdateHistory.length>100&&this.dataSourceUpdateHistory.shift()}getDebounceActionHistory(e){let t=[...this.debounceActionHistory];return e?.handler&&(t=t.filter(a=>a.handler.includes(e.handler))),e?.status&&(t=t.filter(a=>a.status===e.status)),e?.limit&&(t=t.slice(-e.limit)),t}getDataSourceUpdateHistory(e){let t=[...this.dataSourceUpdateHistory];return e?.dataSourceId&&(t=t.filter(a=>a.dataSourceId===e.dataSourceId)),e?.updateType&&(t=t.filter(a=>a.updateType===e.updateType)),e?.limit&&(t=t.slice(-e.limit)),t}getLogs(e){let t=[...this.logHistory];if(e?.level){const a=Array.isArray(e.level)?e.level:[e.level];t=t.filter(i=>a.includes(i.level))}if(e?.prefix){const a=e.prefix.toLowerCase();t=t.filter(i=>i.prefix.toLowerCase().includes(a))}if(e?.search){const a=e.search.toLowerCase();t=t.filter(i=>i.message.toLowerCase().includes(a))}return e?.since&&(t=t.filter(a=>a.timestamp>=e.since)),e?.limit&&(t=t.slice(-e.limit)),t}getLogStats(){const t=Date.now()-6e4,a={log:0,warn:0,error:0,debug:0,info:0},i={};let o=0,d=0;for(const g of this.logHistory)a[g.level]++,i[g.prefix]=(i[g.prefix]||0)+1,g.timestamp>=t&&(g.level==="error"&&o++,g.level==="warn"&&d++);return{totalLogs:this.logHistory.length,byLevel:a,byPrefix:i,recentErrors:o,recentWarnings:d}}clearLogs(){this.logHistory=[],this.logIdCounter=0}getLogInfo(){return{entries:this.getLogs(),stats:this.getLogStats()}}trackDataSourceDefinition(e){this.config.enabled&&this.dataSources.set(e.id,{...e,status:"idle"})}trackDataSourceLoading(e){if(!this.config.enabled)return;const t=this.dataSources.get(e);t&&this.dataSources.set(e,{...t,status:"loading"})}trackDataSourceLoaded(e,t,a){if(!this.config.enabled)return;const i=this.dataSources.get(e);if(!i)return;let o,d,g=a;t&&(Array.isArray(t)?(o=t.length,d=t.length>0&&typeof t[0]=="object"?Object.keys(t[0]):void 0):typeof t=="object"&&(Array.isArray(t.data)?(g=g||"data",o=t.data.length,d=t.data.length>0&&typeof t.data[0]=="object"?Object.keys(t.data[0]):void 0):Array.isArray(t.items)?(g=g||"items",o=t.items.length,d=t.items.length>0&&typeof t.items[0]=="object"?Object.keys(t.items[0]):void 0):d=Object.keys(t))),this.dataSources.set(e,{...i,status:"loaded",dataPath:g,itemCount:o,keys:d,lastLoadedAt:Date.now(),error:void 0})}trackDataSourceError(e,t){if(!this.config.enabled)return;const a=this.dataSources.get(e);a&&this.dataSources.set(e,{...a,status:"error",error:t,lastLoadedAt:Date.now()})}untrackDataSource(e){this.dataSources.delete(e)}getDataSources(){return Array.from(this.dataSources.values())}getDataSource(e){return this.dataSources.get(e)}clearDataSources(){this.dataSources.clear()}trackDataPathTransform(e){if(!this.config.enabled)return;let t=this.dataPathTransforms.find(a=>a.dataSourceId===e.dataSourceId);t||(t={dataSourceId:e.dataSourceId,timestamp:Date.now(),transformSteps:[],warnings:[]},this.dataPathTransforms.push(t),this.dataPathTransforms.length>this.maxDataPathTransforms&&this.dataPathTransforms.shift()),t.transformSteps.push({step:e.step,inputPath:e.inputPath,inputValue:this.safeClone(e.inputValue),outputPath:e.outputPath,outputValue:this.safeClone(e.outputValue),config:e.config}),e.warning&&t.warnings.push(e.warning)}setDataPathFinalBinding(e,t){if(!this.config.enabled)return;const a=this.dataPathTransforms.find(i=>i.dataSourceId===e);a&&(a.finalBinding={expression:t.expression,resolvedPath:t.resolvedPath,value:this.safeClone(t.value)})}getDataPathTransformTrackingInfo(){const e=this.getDataPathTransformStats();return{transforms:[...this.dataPathTransforms],stats:e,timestamp:Date.now()}}getDataPathTransformStats(){const e=this.dataPathTransforms,t={};let a=0;const i={};for(const d of e){t[d.dataSourceId]=(t[d.dataSourceId]||0)+1,a+=d.warnings.length;for(const g of d.warnings)i[g]=(i[g]||0)+1}const o=Object.entries(i).map(([d,g])=>({warning:d,count:g})).sort((d,g)=>g.count-d.count).slice(0,10);return{totalTransforms:e.length,byDataSource:t,warningsCount:a,commonWarnings:o}}getDataPathTransformForDataSource(e){return this.dataPathTransforms.find(t=>t.dataSourceId===e)}clearDataPathTransforms(){this.dataPathTransforms=[]}trackNestedContext(e){if(!this.config.enabled)return"";const t=`nested-${++this.nestedContextIdCounter}`,a=[...new Set([...e.parentContext.available,...e.ownContext.added])],i={...e.parentContext.values,...e.ownContext.values},o={id:t,timestamp:Date.now(),componentId:e.componentId,componentType:e.componentType,parentContext:{available:e.parentContext.available,values:this.safeClone(e.parentContext.values)},ownContext:{added:e.ownContext.added,values:this.safeClone(e.ownContext.values)},mergedContext:{all:a,values:this.safeClone(i)},accessAttempts:[],depth:e.depth,parentId:e.parentId};return this.nestedContexts.push(o),this.nestedContexts.length>this.maxNestedContexts&&this.nestedContexts.shift(),t}trackNestedContextAccess(e,t){if(!this.config.enabled)return;const a=this.nestedContexts.find(i=>i.id===e);a&&a.accessAttempts.push({path:t.path,found:t.found,value:t.found?this.safeClone(t.value):void 0,error:t.error})}getNestedContextTrackingInfo(){const e=this.getNestedContextStats();return{contexts:[...this.nestedContexts],stats:e,timestamp:Date.now()}}getNestedContextStats(){const e=this.nestedContexts,t={expandChildren:0,cellChildren:0,iteration:0,modal:0,slot:0};let a=0,i=0;const o={};for(const g of e){t[g.componentType]++,g.depth>a&&(a=g.depth);for(const h of g.accessAttempts)h.found||(i++,o[h.path]=(o[h.path]||0)+1)}const d=Object.entries(o).map(([g,h])=>({path:g,count:h})).sort((g,h)=>h.count-g.count).slice(0,10);return{totalContexts:e.length,byType:t,maxDepth:a,failedAccessCount:i,commonFailedPaths:d}}getNestedContextForComponent(e){return this.nestedContexts.find(t=>t.componentId===e)}clearNestedContexts(){this.nestedContexts=[],this.nestedContextIdCounter=0}trackHandlerRegistration(e,t="custom",a,i){this.isEnabled&&this.handlers.set(e,{name:e,category:t,description:a,registeredAt:Date.now(),source:i})}trackHandlerUnregistration(e){this.isEnabled&&this.handlers.delete(e)}getHandlers(){return Array.from(this.handlers.values())}getHandler(e){return this.handlers.get(e)}getHandlersByCategory(e){return Array.from(this.handlers.values()).filter(t=>t.category===e)}clearHandlers(){this.handlers.clear()}trackEventSubscribe(e){if(!this.isEnabled)return;const t=this.componentEventSubscriptions.get(e),a=Date.now();t?(t.subscriberCount++,t.lastSubscribedAt=a):this.componentEventSubscriptions.set(e,{eventName:e,subscriberCount:1,firstSubscribedAt:a,lastSubscribedAt:a})}trackEventUnsubscribe(e){if(!this.isEnabled)return;const t=this.componentEventSubscriptions.get(e);t&&(t.subscriberCount--,t.subscriberCount<=0&&this.componentEventSubscriptions.delete(e))}trackEventEmit(e,t,a,i,o){if(!this.isEnabled)return;const d={id:`evt_${++this.componentEventIdCounter}`,eventName:e,data:this.sanitizeForLogging(t),timestamp:Date.now(),listenerCount:a,results:i?this.sanitizeForLogging(i):void 0,hasError:!!o,errorMessage:o?.message};this.componentEventEmitHistory.push(d),this.componentEventEmitHistory.length>this.maxComponentEventHistory&&(this.componentEventEmitHistory=this.componentEventEmitHistory.slice(-this.maxComponentEventHistory))}trackEventOff(e){this.isEnabled&&this.componentEventSubscriptions.delete(e)}trackEventClear(){this.isEnabled&&this.componentEventSubscriptions.clear()}getComponentEventInfo(){const e=Array.from(this.componentEventSubscriptions.values());return{subscriptions:e,emitHistory:[...this.componentEventEmitHistory],totalSubscribers:e.reduce((t,a)=>t+a.subscriberCount,0),totalEmits:this.componentEventEmitHistory.length}}getEventEmitHistory(){return[...this.componentEventEmitHistory]}getEventSubscriptions(){return Array.from(this.componentEventSubscriptions.values())}clearComponentEvents(){this.componentEventSubscriptions.clear(),this.componentEventEmitHistory=[],this.componentEventIdCounter=0}sanitizeForLogging(e){if(e==null||typeof e!="object")return e;try{return JSON.parse(JSON.stringify(e))}catch{return"[Circular or Non-serializable]"}}startStateChange(e,t,a,i){if(!this.config.enabled)return"";const o=`setState_${++this.stateRenderingIdCounter}`;this.currentStateChangeContext={setStateId:o,startTime:performance.now(),changedPath:e,trigger:i||{},renderedComponents:[]};const d={id:`sr_${this.stateRenderingIdCounter}`,setStateId:o,statePath:e,oldValue:this.sanitizeForLogging(t),newValue:this.sanitizeForLogging(a),timestamp:Date.now(),triggeredBy:i||{},renderedComponents:[],totalRenderDuration:0,affectedBindingsCount:0};return this.stateRenderingLogs.push(d),this.stateRenderingLogs.length>this.maxStateRenderingLogs&&this.stateRenderingLogs.shift(),o}trackComponentRender(e,t,a,i=[],o=[],d){if(!this.config.enabled)return;const g=this.componentRenderCounts.get(t)||0;this.componentRenderCounts.set(t,g+1);for(const h of i)this.stateToComponentMap.has(h)||this.stateToComponentMap.set(h,new Set),this.stateToComponentMap.get(h).add(t);if(this.currentStateChangeContext){const h={componentId:e,componentName:t,renderDuration:a,accessedStatePaths:i,evaluatedBindings:o,renderOrder:this.currentStateChangeContext.renderedComponents.length,parentId:d};this.currentStateChangeContext.renderedComponents.push(h)}this.trackRender(t)}completeStateChange(e){if(!this.config.enabled||!this.currentStateChangeContext||this.currentStateChangeContext.setStateId!==e)return;const t=this.currentStateChangeContext,i=performance.now()-t.startTime,o=this.stateRenderingLogs.findIndex(d=>d.setStateId===e);if(o>=0){const d=this.stateRenderingLogs[o];d.renderedComponents=t.renderedComponents,d.totalRenderDuration=i,d.affectedBindingsCount=t.renderedComponents.reduce((g,h)=>g+h.evaluatedBindings.length,0)}this.currentStateChangeContext=null}getCurrentStateChangeContext(){return this.currentStateChangeContext}getStateRenderingLogs(){return[...this.stateRenderingLogs]}getStateRenderingInfo(){const e=this.stateRenderingLogs,t=Object.fromEntries(this.componentRenderCounts),a={};for(const[i,o]of this.stateToComponentMap)a[i]=Array.from(o);return{logs:e,componentRenderCounts:t,stateToComponentMap:a,stats:this.calculateStateRenderingStats()}}calculateStateRenderingStats(){const e=this.stateRenderingLogs;if(e.length===0)return{totalStateChanges:0,totalRenders:0,avgRenderDuration:0,avgComponentsPerChange:0,topRenderedComponents:[],topInfluentialPaths:[]};const t=e.reduce((g,h)=>g+h.renderedComponents.length,0),a=e.reduce((g,h)=>g+h.totalRenderDuration,0)/e.length,i=t/e.length,o=Array.from(this.componentRenderCounts.entries()).sort((g,h)=>h[1]-g[1]).slice(0,5).map(([g,h])=>({name:g,count:h})),d=Array.from(this.stateToComponentMap.entries()).sort((g,h)=>h[1].size-g[1].size).slice(0,5).map(([g,h])=>({path:g,affectedComponents:h.size}));return{totalStateChanges:e.length,totalRenders:t,avgRenderDuration:a,avgComponentsPerChange:i,topRenderedComponents:o,topInfluentialPaths:d}}getComponentsAffectedByState(e){const t=this.stateToComponentMap.get(e);return t?Array.from(t):[]}getComponentRenderHistory(e){return this.stateRenderingLogs.filter(t=>t.renderedComponents.some(a=>a.componentName===e))}clearStateRenderingLogs(){this.stateRenderingLogs=[],this.componentRenderCounts.clear(),this.stateToComponentMap.clear(),this.currentStateChangeContext=null,this.stateRenderingIdCounter=0}trackComponentStateSource(e,t,a,i){this.config.enabled&&this.componentStateSources.set(e,{componentId:e,componentName:t,stateSource:a,stateProvider:i})}trackDynamicState(e,t){this.config.enabled&&this.dynamicStates.set(e,t)}trackContextFlow(e,t,a,i,o,d){if(!this.config.enabled)return;const g={component:t,componentId:e,contextReceived:a,passedToChildren:i,usedInRender:o};if(this.contextFlowNodes.set(e,g),d){const h=this.contextFlowNodes.get(d);h&&(h.children||(h.children=[]),h.children.push(g))}}getStateHierarchyInfo(e=!0){const t=this.buildStateHierarchyLayers(),a=this.detectStateConflicts(t),i=Array.from(this.componentStateSources.values());return{layers:e?t.map(d=>({...d,values:this.summarizeValues(d.values,2)})):t,conflicts:a,componentStateSources:i,timestamp:Date.now()}}summarizeValues(e,t,a=0){if(e==null)return e;if(typeof e!="object")return typeof e=="string"&&e.length>100?e.substring(0,100)+`... (${e.length}자)`:e;if(a>=t){if(Array.isArray(e))return`[Array(${e.length})]`;const d=Object.keys(e);return`{${d.slice(0,5).join(", ")}${d.length>5?`, ... +${d.length-5}`:""}}`}if(Array.isArray(e))return e.length<=3?e.map(d=>this.summarizeValues(d,t,a+1)):{__type:"array",__length:e.length,__preview:e.slice(0,3).map(d=>this.summarizeValues(d,t,a+1))};const i={},o=Object.keys(e);for(const d of o)i[d]=this.summarizeValues(e[d],t,a+1);return i}buildStateHierarchyLayers(){const e=[];try{const a=window.G7Core?.state?.get?.();if(!a)return e;a._local&&e.push({name:"Global _local",type:"global",path:"_local",values:a._local,priority:1}),a._global&&e.push({name:"Global _global",type:"global",path:"_global",values:a._global,priority:1});for(const[o,d]of this.dynamicStates)d&&Object.keys(d).length>0&&e.push({name:`DynamicState (${o})`,type:"dynamicState",componentId:o,values:d,priority:2});const i=this.computeEffectiveState(a._local||{});e.push({name:"Effective _local (merged)",type:"effective",values:i,priority:3})}catch(t){console.warn("[G7DevTools] 상태 계층 빌드 실패:",t)}return e}computeEffectiveState(e){const t={...e};for(const[,a]of this.dynamicStates)a._local&&Object.assign(t,a._local);return t}detectStateConflicts(e){const t=[],a=e.find(o=>o.type==="global"&&o.path==="_local");if(!a)return t;const i=e.filter(o=>o.type==="dynamicState");for(const o of i){const d=o.values._local||o.values;for(const[g,h]of Object.entries(d)){const f=a.values[g];if(JSON.stringify(f)!==JSON.stringify(h)){const p=[],y=[];for(const x of this.componentStateSources.values())x.stateSource.local.some(v=>v===`_local.${g}`||v===g)&&(x.stateProvider.type==="dynamicState"?p.push(x.componentName):x.stateProvider.type==="globalState"&&y.push(x.componentName));t.push({path:`_local.${g}`,globalValue:f,dynamicStateValue:h,effectiveValue:h,usedBy:p,notUsedBy:y,severity:y.length>0?"warning":"info",description:y.length>0?`${y.join(", ")}은(는) globalState._local을 읽어 dynamicState 값을 사용하지 못함`:"dynamicState 값이 globalState와 다르지만 모든 컴포넌트가 dynamicState를 사용"})}}}return t}getContextFlowInfo(){const e=[],t=new Set(this.contextFlowNodes.keys());for(const a of this.contextFlowNodes.values())if(a.children)for(const i of a.children)t.delete(i.componentId);for(const a of t){const i=this.contextFlowNodes.get(a);i&&e.push(i)}return{rootComponent:e.length>0?e[0].component:"Unknown",contextFlow:e,timestamp:Date.now()}}clearStateHierarchyData(){this.componentStateSources.clear(),this.contextFlowNodes.clear(),this.dynamicStates.clear()}trackComponentStyle(e,t,a,i){if(!this.config.enabled)return;const o=this.analyzeTailwindClasses(a),d={componentId:e,componentName:t,classes:a,computedStyles:i,tailwindAnalysis:o};this.componentStyles.set(e,d),this.detectStyleIssues(d)}analyzeTailwindClasses(e){const t=[],a=[],i=[],o=[],d=["sm:","md:","lg:","xl:","2xl:"],g=[/bg-\w+-\d+/,/text-\w+-\d+/,/border-\w+-\d+/];for(const h of e){o.push(h),h.startsWith("dark:")&&t.push(h);for(const f of d)if(h.startsWith(f)){a.push(h);break}for(const f of g)if(f.test(h)){i.push(h);break}}return{usedClasses:o,darkClasses:t,responsiveClasses:a,dynamicClasses:i}}detectStyleIssues(e){const{componentId:t,componentName:a,computedStyles:i,tailwindAnalysis:o}=e;(i.opacity==="0"||i.visibility==="hidden"||i.display==="none"||i.width==="0px"&&i.height==="0px")&&this.addStyleIssue({id:this.generateId(),type:"invisible-element",componentId:t,componentName:a,property:i.opacity==="0"?"opacity":i.visibility==="hidden"?"visibility":i.display==="none"?"display":"width/height",currentValue:i.opacity==="0"?"0":i.visibility==="hidden"?"hidden":i.display==="none"?"none":"0px",severity:"warning",description:"요소가 화면에 보이지 않습니다.",suggestion:"opacity, visibility, display, width/height 값을 확인하세요."});const d=o.usedClasses.filter(h=>h.startsWith("bg-")&&!h.startsWith("dark:")),g=o.darkClasses.filter(h=>h.includes("bg-"));d.length>0&&g.length===0&&this.addStyleIssue({id:this.generateId(),type:"dark-mode-missing",componentId:t,componentName:a,property:"background-color",currentValue:d.join(", "),expectedValue:"dark:bg-* 클래스 필요",severity:"info",description:"다크 모드 배경색 클래스가 누락되었습니다.",suggestion:`${d[0]}에 대응하는 dark: 클래스를 추가하세요.`}),o.dynamicClasses.length>0&&this.addStyleIssue({id:this.generateId(),type:"tailwind-purging",componentId:t,componentName:a,property:"class",currentValue:o.dynamicClasses.join(", "),severity:"info",description:"동적으로 생성된 Tailwind 클래스가 있습니다.",suggestion:"tailwind.config.js의 safelist에 추가하거나 전체 클래스명을 상수로 정의하세요."})}addStyleIssue(e){this.styleIssues.some(a=>a.componentId===e.componentId&&a.type===e.type&&a.property===e.property)||this.styleIssues.push(e)}getStyleValidationInfo(){const e=Array.from(this.componentStyles.values());return{issues:[...this.styleIssues],componentStyles:e,stats:{totalComponents:e.length,invisibleCount:this.styleIssues.filter(t=>t.type==="invisible-element").length,tailwindIssueCount:this.styleIssues.filter(t=>t.type==="tailwind-purging").length,darkModeIssueCount:this.styleIssues.filter(t=>t.type==="dark-mode-missing").length},timestamp:Date.now()}}clearStyleValidationData(){this.styleIssues=[],this.componentStyles.clear()}trackAuthEvent(e,t,a,i){if(!this.config.enabled)return;const o={id:`auth_${++this.authEventIdCounter}`,type:e,timestamp:Date.now(),success:t,error:a,details:i};this.authEvents.push(o),this.authEvents.length>this.maxAuthEventHistory&&(this.authEvents=this.authEvents.slice(-this.maxAuthEventHistory))}trackAuthHeader(e,t,a,i,o){if(!this.config.enabled)return;const d={url:e,hasAuthHeader:t,headerType:a,tokenValid:i??!1,responseStatus:o,timestamp:Date.now()};this.authHeaderHistory.push(d),this.authHeaderHistory.length>this.maxAuthEventHistory&&(this.authHeaderHistory=this.authHeaderHistory.slice(-this.maxAuthEventHistory)),o===401&&this.trackAuthEvent("api-unauthorized",!1,`401 Unauthorized: ${e}`,{url:e})}getAuthState(){try{const e=window.G7Core,t=e?.api;let a=e?.auth;!a&&e?.AuthManager?.getInstance&&(a=e.AuthManager.getInstance());const i=t?.getToken?.()||a?.getAccessToken?.()||localStorage.getItem("auth_token")||localStorage.getItem("access_token"),o=a?.getRefreshToken?.()||localStorage.getItem("refresh_token");let d="unknown",g=a?.getUser?.();if(g&&(d="AuthManager"),!g){const S=e?.state?.get?.();g=S?._global?.user||S?._global?.currentUser||S?.user||S?.currentUser,g&&(d="G7Core.state")}const h=a?.isAuthenticated?.()??!1;let f="memory";localStorage.getItem("auth_token")||localStorage.getItem("access_token")?f="localStorage":(sessionStorage.getItem("auth_token")||sessionStorage.getItem("access_token"))&&(f="sessionStorage");const p=!!i&&(!!g||h);let y;i&&typeof i=="string"&&i.length>20?y=`${i.substring(0,10)}...${i.substring(i.length-6)}`:i&&(y="***");const x=g?{id:g.id,email:g.email,name:g.name,roles:g.roles?.map(S=>typeof S=="string"?{name:S}:{id:S.id,name:S.name,guard_name:S.guard_name}),permissions:g.permissions?.map(S=>typeof S=="string"?{name:S}:{id:S.id,name:S.name,guard_name:S.guard_name}),avatar:g.avatar||g.profile_photo_url||g.profile_image,created_at:g.created_at,updated_at:g.updated_at,last_login_at:g.last_login_at,email_verified_at:g.email_verified_at,...g.phone&&{phone:g.phone},...g.nickname&&{nickname:g.nickname},...g.status&&{status:g.status},...g.locale&&{locale:g.locale}}:void 0;return{isAuthenticated:p,user:x,tokens:{hasAccessToken:!!i,hasRefreshToken:!!o,storage:f,accessTokenPreview:y},lastActivity:Date.now(),source:d}}catch{return{isAuthenticated:!1,tokens:{hasAccessToken:!1,hasRefreshToken:!1,storage:"memory"},source:"unknown"}}}getAuthDebugInfo(){const e=[...this.authEvents];return{state:this.getAuthState(),events:e,headerAnalysis:[...this.authHeaderHistory],stats:{loginAttempts:e.filter(t=>t.type==="login").length,successfulLogins:e.filter(t=>t.type==="login"&&t.success).length,failedLogins:e.filter(t=>t.type==="login"&&!t.success).length,tokenRefreshes:e.filter(t=>t.type==="token-refresh").length,unauthorizedResponses:e.filter(t=>t.type==="api-unauthorized").length},timestamp:Date.now()}}clearAuthData(){this.authEvents=[],this.authHeaderHistory=[],this.authEventIdCounter=0}trackLayoutLoad(e,t,a,i="api"){if(!this.config.enabled)return;const o=Date.now();this.currentLayout={layoutPath:e,templateId:t,layoutJson:this.sanitizeObject(a),loadedAt:o,version:a.version,layoutName:a.layout_name,source:i};const d={id:`layout-${++this.layoutIdCounter}`,layoutPath:e,templateId:t,loadedAt:o,source:i,version:a.version};this.layoutHistory.push(d),this.layoutHistory.length>this.maxLayoutHistory&&this.layoutHistory.shift(),this.layoutStats.totalLoads++,i==="cache"?this.layoutStats.cacheHits++:this.layoutStats.apiLoads++}getCurrentLayout(){return this.currentLayout}getLayoutHistory(){return[...this.layoutHistory]}getLayoutDebugInfo(){return{current:this.currentLayout,history:[...this.layoutHistory],stats:{...this.layoutStats}}}clearLayoutData(){this.currentLayout=null,this.layoutHistory=[],this.layoutIdCounter=0,this.layoutStats={totalLoads:0,cacheHits:0,apiLoads:0}}startHandlerExecution(e){if(!this.config.enabled)return"";const t=`exec_${++this.executionIdCounter}_${Date.now()}`,a={handlerName:e,executionId:t,startTime:Date.now(),stateChanges:[],dataSourceChanges:[],alerts:[]};if(this.executionDetails.set(t,a),this.executionDetails.size>this.maxExecutionDetails){const i=Array.from(this.executionDetails.keys());i.slice(0,i.length-this.maxExecutionDetails).forEach(d=>this.executionDetails.delete(d))}return t}endHandlerExecution(e,t,a,i){if(!this.config.enabled||!e)return;const o=this.executionDetails.get(e);if(!o)return;o.endTime=Date.now(),o.duration=o.endTime-o.startTime,o.exitReason=t,o.exitLocation=a,o.exitDescription=i;const d=this.changeExpectations.get(e);d&&(o.expectedChanges=d,this.checkExpectations(e,o,d),this.changeExpectations.delete(e)),t==="normal"&&o.stateChanges.length===0&&o.dataSourceChanges.length===0&&this.addChangeAlert(e,{type:"no-state-change",severity:"warning",message:`핸들러 "${o.handlerName}"이(가) 상태 변경 없이 완료됨`,description:"핸들러가 성공적으로 완료되었지만 상태나 데이터소스 변경이 없습니다. 의도한 동작인지 확인하세요.",handlerName:o.handlerName,suggestion:'핸들러 내부 조건문을 확인하거나 DevTools의 "변경감지" 탭에서 exitLocation을 확인하세요.',docLink:".claude/docs/frontend/troubleshooting-state.md"}),(t==="early-return-condition"||t==="early-return-validation")&&this.addChangeAlert(e,{type:"early-return-detected",severity:"info",message:`핸들러 "${o.handlerName}"이(가) early return으로 종료됨`,description:i||`종료 위치: ${a||"알 수 없음"}`,handlerName:o.handlerName,suggestion:t==="early-return-validation"?"검증 실패로 인한 early return입니다. 입력 데이터를 확인하세요.":"조건부 early return입니다. 조건문의 평가 결과를 확인하세요."})}recordExitReason(e,t,a,i){if(!this.config.enabled||!e)return;const o=this.executionDetails.get(e);o&&(o.exitReason=t,o.exitLocation=a,o.exitDescription=i)}recordStateChange(e,t,a,i,o){if(!this.config.enabled)return;const d={id:`sc_${++this.stateChangeIdCounter}`,path:t,changeType:a,oldValue:this.safeClone(i),newValue:this.safeClone(o),timestamp:Date.now(),comparison:this.compareValues(i,o),executionId:e};if(this.stateChangeHistory.push(d),e){const g=this.executionDetails.get(e);g&&g.stateChanges.push(d)}this.stateChangeHistory.length>this.maxStateChangeHistory&&this.stateChangeHistory.splice(0,this.stateChangeHistory.length-this.maxStateChangeHistory),d.comparison.isDeepEqual&&typeof i=="object"&&i!==null&&this.addChangeAlert(e||"",{type:"object-reference-same",severity:"warning",message:`상태 "${t}"가 변경되었으나 값이 동일함`,description:"객체 참조가 동일하거나 깊은 비교 결과 변경이 없습니다. 변경 감지가 실패할 수 있습니다.",handlerName:e&&this.executionDetails.get(e)?.handlerName||"unknown",statePath:t,suggestion:"불변성을 유지하여 새 객체를 생성하세요. 예: { ...oldObject, newField: value }",docLink:".claude/docs/frontend/troubleshooting-state.md#object-mutation"})}recordDataSourceChange(e,t,a,i,o){if(!this.config.enabled)return;const d={dataSourceId:t,changeType:a,timestamp:Date.now(),previousStatus:i,newStatus:o,executionId:e};if(this.dataSourceChangeHistory.push(d),e){const g=this.executionDetails.get(e);g&&g.dataSourceChanges.push(d)}this.dataSourceChangeHistory.length>this.maxStateChangeHistory&&this.dataSourceChangeHistory.splice(0,this.dataSourceChangeHistory.length-this.maxStateChangeHistory)}expectChange(e,t,a){if(!this.config.enabled||!e)return;const i=this.executionDetails.get(e);if(!i)return;const o={expectedStatePaths:t,expectedDataSources:a,setAt:Date.now(),source:i.handlerName};this.changeExpectations.set(e,o)}checkExpectations(e,t,a){const i=new Set(t.stateChanges.map(d=>d.path)),o=new Set(t.dataSourceChanges.map(d=>d.dataSourceId));for(const d of a.expectedStatePaths)i.has(d)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 상태 변경 "${d}"가 발생하지 않음`,description:`핸들러 "${t.handlerName}"이(가) "${d}" 변경을 예고했지만 실제로 변경되지 않았습니다.`,handlerName:t.handlerName,statePath:d,suggestion:"핸들러 내부 로직을 확인하세요. early return이나 조건부 분기로 인해 변경이 생략되었을 수 있습니다.",docLink:".claude/docs/frontend/troubleshooting-state.md"});for(const d of a.expectedDataSources)o.has(d)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 데이터소스 갱신 "${d}"가 발생하지 않음`,description:`핸들러 "${t.handlerName}"이(가) "${d}" 갱신을 예고했지만 실제로 갱신되지 않았습니다.`,handlerName:t.handlerName,dataSourceId:d,suggestion:"refetchDataSource 호출이 실행되었는지 확인하세요.",docLink:".claude/docs/frontend/data-sources.md"})}addChangeAlert(e,t){const a={...t,id:`alert_${++this.alertIdCounter}`,timestamp:Date.now()};if(this.changeAlerts.push(a),e){const i=this.executionDetails.get(e);i&&i.alerts.push(a)}this.changeAlerts.length>this.maxChangeAlerts&&this.changeAlerts.splice(0,this.changeAlerts.length-this.maxChangeAlerts)}compareValues(e,t){const a=this.getValueType(e),i=this.getValueType(t),o=a!==i;let d=!1,g;return!o&&(a==="object"||a==="array")?(d=this.deepEqual(e,t),!d&&a==="object"&&(g=this.getChangedKeys(e,t))):d=e===t,{typeChanged:o,oldType:a,newType:i,isDeepEqual:d,changedKeys:g}}getValueType(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}deepEqual(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e===null||t===null||typeof e!="object")return e===t;if(Array.isArray(e)!==Array.isArray(t))return!1;const a=Object.keys(e),i=Object.keys(t);if(a.length!==i.length)return!1;for(const o of a)if(!i.includes(o)||!this.deepEqual(e[o],t[o]))return!1;return!0}getChangedKeys(e,t){const a=[],i=new Set([...Object.keys(e),...Object.keys(t)]);for(const o of i)this.deepEqual(e[o],t[o])||a.push(o);return a}getChangeDetectionInfo(){const e=Array.from(this.executionDetails.values()),t={totalExecutions:e.length,executionsWithStateChange:e.filter(a=>a.stateChanges.length>0).length,executionsWithoutStateChange:e.filter(a=>a.stateChanges.length===0&&a.exitReason==="normal").length,earlyReturnCount:e.filter(a=>a.exitReason==="early-return-condition"||a.exitReason==="early-return-validation").length,alertCount:this.changeAlerts.length,alertsByType:this.getAlertsByType()};return{executionDetails:e,stateChangeHistory:[...this.stateChangeHistory],dataSourceChangeHistory:[...this.dataSourceChangeHistory],alerts:[...this.changeAlerts],stats:t,timestamp:Date.now()}}getAlertsByType(){const e={"no-state-change":0,"no-datasource-change":0,"expected-not-fulfilled":0,"object-reference-same":0,"early-return-detected":0,"async-timing-issue":0};for(const t of this.changeAlerts)e[t.type]++;return e}clearChangeDetectionData(){this.executionDetails.clear(),this.stateChangeHistory=[],this.dataSourceChangeHistory=[],this.changeAlerts=[],this.changeExpectations.clear(),this.executionIdCounter=0,this.stateChangeIdCounter=0,this.alertIdCounter=0}getRecentAlerts(e=10,t){let a=[...this.changeAlerts];return t&&(a=a.filter(i=>i.severity===t)),a.slice(-e)}getHandlerExecutions(e,t=10){return Array.from(this.executionDetails.values()).filter(i=>i.handlerName===e).slice(-t)}findExecutionInStack(e){return this.sequenceExecutionStack.find(t=>t.sequenceId===e)}startSequenceExecution(e){if(!this.config.enabled)return"";const t=`seq_${++this.sequenceIdCounter}_${Date.now()}`,a={sequenceId:t,startTime:Date.now(),totalDuration:0,trigger:e,actions:[],status:"running"};return this.sequenceExecutionStack.push(a),t}captureSequenceActionBefore(e,t,a,i,o){if(!this.config.enabled)return;const d=this.findExecutionInStack(e);if(!d)return;const g={index:t,handler:a,params:this.safeClone(i),stateBeforeAction:{_global:this.safeClone(o._global),_local:this.safeClone(o._local),_isolated:o._isolated?this.safeClone(o._isolated):void 0},stateAfterAction:{_global:{},_local:{}},duration:0,status:"success"};d.actions.push(g)}captureSequenceActionAfter(e,t,a,i,o,d){if(!this.config.enabled)return;const g=this.findExecutionInStack(e);if(!g)return;const h=g.actions.find(p=>p.index===t);if(!h)return;h.stateAfterAction={_global:this.safeClone(a._global),_local:this.safeClone(a._local),_isolated:a._isolated?this.safeClone(a._isolated):void 0},h.duration=i,h.result=this.safeClone(o),h.stateDiff={global:this.computeStateDiff(h.stateBeforeAction._global,h.stateAfterAction._global),local:this.computeStateDiff(h.stateBeforeAction._local,h.stateAfterAction._local)},h.stateBeforeAction._isolated&&h.stateAfterAction._isolated&&(h.stateDiff.isolated=this.computeStateDiff(h.stateBeforeAction._isolated,h.stateAfterAction._isolated));const f=window.__g7PendingLocalState;f&&(h.pendingState=this.safeClone(f)),d&&(h.status="error",h.error={name:d.name,message:d.message,stack:d.stack})}endSequenceExecution(e,t){if(!this.config.enabled)return;const a=this.sequenceExecutionStack.findIndex(o=>o.sequenceId===e);if(a===-1)return;const i=this.sequenceExecutionStack[a];if(i.endTime=Date.now(),i.totalDuration=i.endTime-i.startTime,t){i.status="error",i.error={name:t.name,message:t.message,stack:t.stack};const o=i.actions.find(d=>d.status==="error");o&&(i.failedAtIndex=o.index)}else i.status="success";this.sequenceExecutions.push(i),this.sequenceExecutions.length>this.maxSequenceExecutions&&this.sequenceExecutions.shift(),this.sequenceExecutionStack.splice(a,1)}computeStateDiff(e,t){const a=[],i=[],o=[],d=new Set(Object.keys(e)),g=new Set(Object.keys(t));for(const h of g)d.has(h)||a.push(h);for(const h of d)g.has(h)||i.push(h);for(const h of d)if(g.has(h)){const f=e[h],p=t[h];JSON.stringify(f)!==JSON.stringify(p)&&o.push({path:h,oldValue:f,newValue:p})}return{added:a,removed:i,changed:o}}getSequenceTrackingInfo(){const e=this.getSequenceStats(),t=this.sequenceExecutionStack.length>0?this.sequenceExecutionStack[this.sequenceExecutionStack.length-1]:void 0;return{executions:[...this.sequenceExecutions],currentExecution:t,stats:e}}getSequenceStats(){const e=this.sequenceExecutions,t=e.length,a=e.filter(f=>f.status==="success").length,i=e.filter(f=>f.status==="error").length,o=e.reduce((f,p)=>f+p.actions.length,0),d=t>0?e.reduce((f,p)=>f+p.totalDuration,0)/t:0,g={};for(const f of e)for(const p of f.actions)g[p.handler]=(g[p.handler]||0)+1;const h=Object.entries(g).sort(([,f],[,p])=>p-f).slice(0,5).map(([f,p])=>({handler:f,count:p}));return{totalExecutions:t,successCount:a,errorCount:i,totalActions:o,avgDuration:d,topHandlers:h}}clearSequenceData(){this.sequenceExecutions=[],this.sequenceExecutionStack=[],this.sequenceIdCounter=0}getSequenceExecution(e){const t=this.findExecutionInStack(e);return t||this.sequenceExecutions.find(a=>a.sequenceId===e)}getRecentSequences(e=10){return this.sequenceExecutions.slice(-e)}registerStateCaptureForHandler(e,t,a){if(!this.config.enabled)return;const i=new Map,o=Date.now();for(const d of t)i.set(d,{value:this.safeClone(a[d]),capturedAt:o});this.stateCaptureRegistry.set(e,i)}detectStaleClosure(e,t,a,i,o){if(!this.config.enabled)return[];const d=this.stateCaptureRegistry.get(e);if(!d)return[];const g=Date.now(),h=[];for(const[f,p]of d){const y=this.getValueByPath(a,f),x=g-p.capturedAt;if(!this.isDeepEqual(p.value,y)&&x>0){const S=this.createStaleClosureWarning(i,t,f,p.value,p.capturedAt,y,g,x,o);h.push(S),this.addStaleClosureWarning(S)}}return this.stateCaptureRegistry.delete(e),h}trackStaleClosureWarning(e){if(!this.config.enabled)return;const t=Date.now(),a=this.createStaleClosureWarning(e.type,e.location,e.capturedPath,e.capturedValue,e.capturedAt,e.currentValue,t,t-e.capturedAt,e.actionId,e.stackTrace);this.addStaleClosureWarning(a)}createStaleClosureWarning(e,t,a,i,o,d,g,h,f,p){const y=this.getStaleClosureSeverity(e,h),{description:x,suggestion:S,docLink:v}=this.getStaleClosureMessages(e,a,h);return{id:`stale_${++this.staleClosureIdCounter}_${Date.now()}`,timestamp:Date.now(),type:e,location:t,capturedState:{path:a,capturedValue:this.safeClone(i),capturedAt:o},currentState:{path:a,currentValue:this.safeClone(d),retrievedAt:g},timeDiff:h,severity:y,description:x,suggestion:S,docLink:v,actionId:f,stackTrace:p}}getStaleClosureSeverity(e,t){if(t>5e3)return"error";if(t>1e3)return"warning";switch(e){case"async-state-capture":case"sequence-state-mismatch":return"warning";case"callback-state-capture":case"timeout-state-capture":return"info";case"event-handler-stale":return"warning";default:return"info"}}getStaleClosureMessages(e,t,a){const i=a<1e3?`${a}ms`:`${(a/1e3).toFixed(1)}s`;switch(e){case"async-state-capture":return{description:`await 후 ${i} 경과 시점에 '${t}' 상태가 변경됨. 캡처된 상태 대신 최신 상태를 사용해야 함`,suggestion:"await 이후에는 G7Core.state.get()으로 최신 상태를 다시 조회하거나, useRef + getter 패턴을 사용하세요",docLink:"troubleshooting-state-closure.md"};case"callback-state-capture":return{description:`콜백에서 ${i} 전에 캡처된 '${t}' 상태를 사용 중. 최신 상태와 다름`,suggestion:"콜백에서 상태를 참조할 때는 stateRef.current 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};case"timeout-state-capture":return{description:`setTimeout/setInterval 콜백에서 '${t}' 상태가 ${i} 전 값 사용 중`,suggestion:"타이머 콜백 내에서는 G7Core.state.get()으로 최신 상태를 조회하세요",docLink:"troubleshooting-state-closure.md"};case"sequence-state-mismatch":return{description:`sequence 내 '${t}' 상태가 이전 액션 결과와 불일치. context.state 대신 캡처된 값 사용 의심`,suggestion:"sequence 내에서는 context.state 또는 $prev를 사용하여 최신 상태를 참조하세요",docLink:"troubleshooting-state-setstate.md"};case"event-handler-stale":return{description:`이벤트 핸들러에서 ${i} 전에 바인딩된 '${t}' 상태 사용 중`,suggestion:"이벤트 핸들러에서 상태를 참조할 때는 useRef 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};default:return{description:`'${t}' 상태에서 stale closure 감지됨 (${i} 경과)`,suggestion:"상태 참조 시 최신 값을 사용하는지 확인하세요"}}}addStaleClosureWarning(e){this.staleClosureWarnings.push(e),this.staleClosureWarnings.length>this.maxStaleClosureWarnings&&this.staleClosureWarnings.shift()}getValueByPath(e,t){const a=t.split(".");let i=e;for(const o of a){if(i==null)return;i=i[o]}return i}isDeepEqual(e,t){if(e===t)return!0;if(e===null||t===null)return e===t;if(typeof e!=typeof t)return!1;if(typeof e!="object")return e===t;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}getStaleClosureTrackingInfo(){const e=this.getStaleClosureStats();return{warnings:[...this.staleClosureWarnings],stats:e,timestamp:Date.now()}}getStaleClosureStats(){const e=this.staleClosureWarnings,t={"async-state-capture":0,"callback-state-capture":0,"timeout-state-capture":0,"sequence-state-mismatch":0,"event-handler-stale":0};for(const h of e)t[h.type]++;const a={info:0,warning:0,error:0};for(const h of e)a[h.severity]++;const i={};for(const h of e)i[h.location]=(i[h.location]||0)+1;const o=Object.entries(i).sort(([,h],[,f])=>f-h).slice(0,5).map(([h,f])=>({location:h,count:f})),d={};for(const h of e)d[h.capturedState.path]=(d[h.capturedState.path]||0)+1;const g=Object.entries(d).sort(([,h],[,f])=>f-h).slice(0,5).map(([h,f])=>({path:h,count:f}));return{totalWarnings:e.length,warningsByType:t,warningsBySeverity:a,topLocations:o,topAffectedPaths:g}}clearStaleClosureData(){this.staleClosureWarnings=[],this.staleClosureIdCounter=0,this.stateCaptureRegistry.clear()}getRecentStaleClosureWarnings(e=10,t){let a=[...this.staleClosureWarnings];return t&&(a=a.filter(i=>i.severity===t)),a.slice(-e)}safeClone(e){if(e==null||typeof e!="object")return e;try{return JSON.parse(JSON.stringify(e))}catch{if(Array.isArray(e))return e.map(a=>{try{return JSON.parse(JSON.stringify(a))}catch{return"[Unserializable]"}});const t={};for(const a of Object.keys(e))try{t[a]=JSON.parse(JSON.stringify(e[a]))}catch{t[a]="[Unserializable]"}return t}}};H(Er,"instance");let ka=Er;const Kn=it("LayoutLoader");class Ms extends Error{constructor(e,t,a){super(e),this.code=t,this.details=a,this.name="LayoutLoaderError"}}class Rg{constructor(e){H(this,"componentRegistry");H(this,"currentLayout",null);H(this,"layoutCache",new Map);H(this,"cacheVersion",0);this.componentRegistry=e}setCacheVersion(e){this.cacheVersion!==e&&(Kn.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.layoutCache.clear())}getCacheVersion(){return this.cacheVersion}async loadLayout(e,t){const a=`${e}:${t}`;if(this.layoutCache.has(a)){Kn.log("Loading layout from cache:",t);const o=await this.layoutCache.get(a),d=JSON.parse(JSON.stringify(o));return this.currentLayout=d,ka.getInstance().trackLayoutLoad(t,e,d,"cache"),d}const i=this.fetchLayout(e,t);return this.layoutCache.set(a,i),i}async fetchLayout(e,t,a=!1){try{let i;t.startsWith("__preview__/")?i=`/api/layouts/preview/${t.replace("__preview__/","")}.json`:i=`/api/layouts/${e}/${t}.json`;const o=this.cacheVersion>0?`${i}?v=${this.cacheVersion}`:i;Kn.log("Fetching layout from API:",o);const d=ns(),g=a?null:d.getToken(),h={Accept:"application/json"};g&&(h.Authorization=`Bearer ${g}`);const f=await fetch(o,{headers:h});let p;try{p=await f.json()}catch{p=null}if(!f.ok){if(f.status===401&&!a&&g)return Kn.log("Token invalid, removing and retrying without token"),d.removeToken(),this.fetchLayout(e,t,!0);const x=p?.message||p?.error;throw new Ms(`Failed to fetch layout: ${f.status} ${f.statusText}`,"FETCH_FAILED",{status:f.status,statusText:f.statusText,url:o,apiMessage:x})}const y=p.data||p;return this.validateLayoutData(y),this.currentLayout=y,ka.getInstance().trackLayoutLoad(t,e,y,"api"),Kn.log("Layout fetched and cached successfully:",y.layout_name),y}catch(i){const o=`${e}:${t}`;throw this.layoutCache.delete(o),i instanceof Ms?i:new Ms("Failed to load layout","LOAD_FAILED",{originalError:i})}}prefetchLayout(e,t){return this.loadLayout(e,t)}validateLayoutData(e){if(!e.version)throw new Ms("Layout data missing required field: version","VALIDATION_FAILED",{field:"version"});if(!e.layout_name)throw new Ms("Layout data missing required field: layout_name","VALIDATION_FAILED",{field:"layout_name"});if(!Array.isArray(e.components))throw new Ms('Layout data field "components" must be an array',"VALIDATION_FAILED",{field:"components",value:e.components});Kn.log("Layout data validation passed")}renderLayout(e,t){try{const a=t||this.currentLayout;if(!a)throw new Ms("No layout data to render","NO_LAYOUT_DATA");Kn.log("Rendering layout:",a.layout_name),e.innerHTML="",this.renderComponents(e,a.components),Kn.log("Layout rendered successfully")}catch(a){Kn.error("Render error:",a),this.renderErrorState(e,a)}}renderComponents(e,t){for(const a of t){const i=this.renderComponent(a);i&&e.appendChild(i)}}renderComponent(e){try{if(!this.componentRegistry.getComponent(e.type))return Kn.warn(`Component not found: ${e.type}`),this.createPlaceholderElement(e.type);const a=document.createElement("div");return a.setAttribute("data-component",e.type),e.props&&Object.entries(e.props).forEach(([i,o])=>{a.setAttribute(`data-prop-${i}`,JSON.stringify(o))}),e.children&&e.children.length>0?this.renderComponents(a,e.children):e.text&&(a.textContent=e.text),a}catch(t){return Kn.error(`Error rendering component ${e.type}:`,t),this.createErrorElement(e.type,t)}}createPlaceholderElement(e){const t=document.createElement("div");return t.className="component-placeholder",t.setAttribute("data-component-type",e),t.innerHTML=`

Component not found: ${e}

@@ -139,14 +139,14 @@ Error generating stack: `+u.message+` " >페이지 새로고침 - `,Kn.error("Error state rendered:",i,a)}getCurrentLayout(){return this.currentLayout}clear(){this.currentLayout=null,this.layoutCache.clear(),Kn.log("Layout data and cache cleared")}}const Aj=it("TranslationContext"),Py=j.createContext(null),Dc=({children:r,translationEngine:e,translationContext:t})=>{const a=j.useMemo(()=>(o,d)=>{if(d){const g="|"+Object.entries(d).map(([h,f])=>`${h}=${f}`).join("|");return e.translate(o,t,g)}return e.translate(o,t)},[e,t]),i=j.useMemo(()=>({translationEngine:e,translationContext:t,t:a}),[e,t,a]);return l.jsx(Py.Provider,{value:i,children:r})},Tj=()=>{const r=j.useContext(Py);return r||(Aj.warn("TranslationProvider 외부에서 호출되었습니다. 키를 그대로 반환합니다."),{t:e=>e,translationEngine:null,translationContext:null})},$s=it("SlotContext"),Dj={registerToSlot:()=>{$s.warn("SlotContext not available: registerToSlot called outside SlotProvider")},unregisterFromSlot:()=>{$s.warn("SlotContext not available: unregisterFromSlot called outside SlotProvider")},getSlotComponents:()=>[],subscribeToSlot:()=>()=>{},clearAllSlots:()=>{},isEnabled:!1},Rj=j.createContext(Dj),Og=({children:r})=>{const e=j.useRef(new Map),t=j.useRef(new Map),a=j.useCallback(p=>{const y=t.current.get(p);y&&y.forEach(x=>{try{x()}catch(S){$s.error(`Slot subscriber error (slotId: ${p}):`,S)}})},[]),i=j.useCallback((p,y,x)=>{if(!p||!y){$s.warn("registerToSlot: slotId and componentId are required");return}e.current.has(p)||e.current.set(p,new Map);const S=e.current.get(p),v=S.get(y);v&&v.registrationKey===x.registrationKey||(S.set(y,x),$s.log(`Component registered to slot: ${y} -> ${p} (order: ${x.order})`),a(p))},[a]),o=j.useCallback((p,y)=>{const x=e.current.get(p);x&&x.has(y)&&(x.delete(y),$s.log(`Component unregistered from slot: ${y} <- ${p}`),x.size===0&&e.current.delete(p),a(p))},[a]),d=j.useCallback(p=>{const y=e.current.get(p);return y?Array.from(y.values()).sort((x,S)=>x.order-S.order):[]},[]),g=j.useCallback((p,y)=>{t.current.has(p)||t.current.set(p,new Set);const x=t.current.get(p);return x.add(y),()=>{x.delete(y),x.size===0&&t.current.delete(p)}},[]),h=j.useCallback(()=>{e.current.forEach((p,y)=>{a(y)}),e.current.clear(),t.current.clear(),$s.log("All slots cleared")},[a]),f=j.useMemo(()=>({registerToSlot:i,unregisterFromSlot:o,getSlotComponents:d,subscribeToSlot:g,clearAllSlots:h,isEnabled:!0}),[i,o,d,g,h]);return j.useLayoutEffect(()=>{typeof window<"u"&&(window.__slotContextValue=f,$s.log("SlotContext exposed to window.__slotContextValue"))},[f]),l.jsx(Rj.Provider,{value:f,children:r})};class Lg{constructor(){this.notificationCreatedEvent=".Illuminate\\Notifications\\Events\\BroadcastNotificationCreated"}listenForWhisper(e,t){return this.listen(".client-"+e,t)}notification(e){return this.listen(this.notificationCreatedEvent,e)}stopListeningForNotification(e){return this.stopListening(this.notificationCreatedEvent,e)}stopListeningForWhisper(e,t){return this.stopListening(".client-"+e,t)}}class By{constructor(e){this.namespace=e}format(e){return[".","\\"].includes(e.charAt(0))?e.substring(1):(this.namespace&&(e=this.namespace+"."+e),e.replace(/\./g,"\\"))}setNamespace(e){this.namespace=e}}function Oj(r){try{new r}catch(e){if(e instanceof Error&&e.message.includes("is not a constructor"))return!1}return!0}class Mg extends Lg{constructor(e,t,a){super(),this.name=t,this.pusher=e,this.options=a,this.eventFormatter=new By(this.options.namespace),this.subscribe()}subscribe(){this.subscription=this.pusher.subscribe(this.name)}unsubscribe(){this.pusher.unsubscribe(this.name)}listen(e,t){return this.on(this.eventFormatter.format(e),t),this}listenToAll(e){return this.subscription.bind_global((t,a)=>{if(t.startsWith("pusher:"))return;let i=String(this.options.namespace??"").replace(/\./g,"\\"),o=t.startsWith(i)?t.substring(i.length+1):"."+t;e(o,a)}),this}stopListening(e,t){return t?this.subscription.unbind(this.eventFormatter.format(e),t):this.subscription.unbind(this.eventFormatter.format(e)),this}stopListeningToAll(e){return e?this.subscription.unbind_global(e):this.subscription.unbind_global(),this}subscribed(e){return this.on("pusher:subscription_succeeded",()=>{e()}),this}error(e){return this.on("pusher:subscription_error",t=>{e(t)}),this}on(e,t){return this.subscription.bind(e,t),this}}class Uy extends Mg{whisper(e,t){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,t),this}}class Lj extends Mg{whisper(e,t){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,t),this}}class Mj extends Uy{here(e){return this.on("pusher:subscription_succeeded",t=>{e(Object.keys(t.members).map(a=>t.members[a]))}),this}joining(e){return this.on("pusher:member_added",t=>{e(t.info)}),this}whisper(e,t){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,t),this}leaving(e){return this.on("pusher:member_removed",t=>{e(t.info)}),this}}class qy extends Lg{constructor(e,t,a){super(),this.events={},this.listeners={},this.name=t,this.socket=e,this.options=a,this.eventFormatter=new By(this.options.namespace),this.subscribe()}subscribe(){this.socket.emit("subscribe",{channel:this.name,auth:this.options.auth||{}})}unsubscribe(){this.unbind(),this.socket.emit("unsubscribe",{channel:this.name,auth:this.options.auth||{}})}listen(e,t){return this.on(this.eventFormatter.format(e),t),this}stopListening(e,t){return this.unbindEvent(this.eventFormatter.format(e),t),this}subscribed(e){return this.on("connect",t=>{e(t)}),this}error(e){return this}on(e,t){return this.listeners[e]=this.listeners[e]||[],this.events[e]||(this.events[e]=(a,i)=>{this.name===a&&this.listeners[e]&&this.listeners[e].forEach(o=>o(i))},this.socket.on(e,this.events[e])),this.listeners[e].push(t),this}unbind(){Object.keys(this.events).forEach(e=>{this.unbindEvent(e)})}unbindEvent(e,t){this.listeners[e]=this.listeners[e]||[],t&&(this.listeners[e]=this.listeners[e].filter(a=>a!==t)),(!t||this.listeners[e].length===0)&&(this.events[e]&&(this.socket.removeListener(e,this.events[e]),delete this.events[e]),delete this.listeners[e])}}class Gy extends qy{whisper(e,t){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:t}),this}}class $j extends Gy{here(e){return this.on("presence:subscribed",t=>{e(t.map(a=>a.user_info))}),this}joining(e){return this.on("presence:joining",t=>e(t.user_info)),this}whisper(e,t){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:t}),this}leaving(e){return this.on("presence:leaving",t=>e(t.user_info)),this}}class Rc extends Lg{subscribe(){}unsubscribe(){}listen(e,t){return this}listenToAll(e){return this}stopListening(e,t){return this}subscribed(e){return this}error(e){return this}on(e,t){return this}}class Fy extends Rc{whisper(e,t){return this}}class Ij extends Rc{whisper(e,t){return this}}class zj extends Fy{here(e){return this}joining(e){return this}whisper(e,t){return this}leaving(e){return this}}const Vy=class mw{constructor(e){this.setOptions(e),this.connect()}setOptions(e){this.options={...mw._defaultOptions,...e,broadcaster:e.broadcaster};let t=this.csrfToken();t&&(this.options.auth.headers["X-CSRF-TOKEN"]=t,this.options.userAuthentication.headers["X-CSRF-TOKEN"]=t),t=this.options.bearerToken,t&&(this.options.auth.headers.Authorization="Bearer "+t,this.options.userAuthentication.headers.Authorization="Bearer "+t)}csrfToken(){var e,t;return typeof window<"u"&&(e=window.Laravel)!=null&&e.csrfToken?window.Laravel.csrfToken:this.options.csrfToken?this.options.csrfToken:typeof document<"u"&&typeof document.querySelector=="function"?((t=document.querySelector('meta[name="csrf-token"]'))==null?void 0:t.getAttribute("content"))??null:null}};Vy._defaultOptions={auth:{headers:{}},authEndpoint:"/broadcasting/auth",userAuthentication:{endpoint:"/broadcasting/user-auth",headers:{}},csrfToken:null,bearerToken:null,host:null,key:null,namespace:"App.Events"};let $g=Vy;class Oc extends $g{constructor(){super(...arguments),this.channels={}}connect(){if(typeof this.options.client<"u")this.pusher=this.options.client;else if(this.options.Pusher)this.pusher=new this.options.Pusher(this.options.key,this.options);else if(typeof window<"u"&&typeof window.Pusher<"u")this.pusher=new window.Pusher(this.options.key,this.options);else throw new Error("Pusher client not found. Should be globally available or passed via options.client")}signin(){this.pusher.signin()}listen(e,t,a){return this.channel(e).listen(t,a)}channel(e){return this.channels[e]||(this.channels[e]=new Mg(this.pusher,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new Uy(this.pusher,"private-"+e,this.options)),this.channels["private-"+e]}encryptedPrivateChannel(e){return this.channels["private-encrypted-"+e]||(this.channels["private-encrypted-"+e]=new Lj(this.pusher,"private-encrypted-"+e,this.options)),this.channels["private-encrypted-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new Mj(this.pusher,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"private-encrypted-"+e,"presence-"+e].forEach(t=>{this.leaveChannel(t)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.pusher.connection.socket_id}disconnect(){this.pusher.disconnect()}}class Hj extends $g{constructor(){super(...arguments),this.channels={}}connect(){let e=this.getSocketIO();this.socket=e(this.options.host??void 0,this.options),this.socket.io.on("reconnect",()=>{Object.values(this.channels).forEach(t=>{t.subscribe()})})}getSocketIO(){if(typeof this.options.client<"u")return this.options.client;if(typeof window<"u"&&typeof window.io<"u")return window.io;throw new Error("Socket.io client not found. Should be globally available or passed via options.client")}listen(e,t,a){return this.channel(e).listen(t,a)}channel(e){return this.channels[e]||(this.channels[e]=new qy(this.socket,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new Gy(this.socket,"private-"+e,this.options)),this.channels["private-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new $j(this.socket,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"presence-"+e].forEach(t=>{this.leaveChannel(t)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.socket.id}disconnect(){this.socket.disconnect()}}class Ky extends $g{constructor(){super(...arguments),this.channels={}}connect(){}listen(e,t,a){return new Rc}channel(e){return new Rc}privateChannel(e){return new Fy}encryptedPrivateChannel(e){return new Ij}presenceChannel(e){return new zj}leave(e){}leaveChannel(e){}socketId(){return"fake-socket-id"}disconnect(){}}class Pj{constructor(e){this.options=e,this.connect(),this.options.withoutInterceptors||this.registerInterceptors()}channel(e){return this.connector.channel(e)}connect(){if(this.options.broadcaster==="reverb")this.connector=new Oc({...this.options,cluster:""});else if(this.options.broadcaster==="pusher")this.connector=new Oc(this.options);else if(this.options.broadcaster==="ably")this.connector=new Oc({...this.options,cluster:"",broadcaster:"pusher"});else if(this.options.broadcaster==="socket.io")this.connector=new Hj(this.options);else if(this.options.broadcaster==="null")this.connector=new Ky(this.options);else if(typeof this.options.broadcaster=="function"&&Oj(this.options.broadcaster))this.connector=new this.options.broadcaster(this.options);else throw new Error(`Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} is not supported.`)}disconnect(){this.connector.disconnect()}join(e){return this.connector.presenceChannel(e)}leave(e){this.connector.leave(e)}leaveChannel(e){this.connector.leaveChannel(e)}leaveAllChannels(){for(const e in this.connector.channels)this.leaveChannel(e)}listen(e,t,a){return this.connector.listen(e,t,a)}private(e){return this.connector.privateChannel(e)}encryptedPrivate(e){if(this.connectorSupportsEncryptedPrivateChannels(this.connector))return this.connector.encryptedPrivateChannel(e);throw new Error(`Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} does not support encrypted private channels.`)}connectorSupportsEncryptedPrivateChannels(e){return e instanceof Oc||e instanceof Ky}socketId(){return this.connector.socketId()}registerInterceptors(){typeof Vue<"u"&&Vue!=null&&Vue.http&&this.registerVueRequestInterceptor(),typeof axios=="function"&&this.registerAxiosRequestInterceptor(),typeof jQuery=="function"&&this.registerjQueryAjaxSetup(),typeof Turbo=="object"&&this.registerTurboRequestInterceptor()}registerVueRequestInterceptor(){Vue.http.interceptors.push((e,t)=>{this.socketId()&&e.headers.set("X-Socket-ID",this.socketId()),t()})}registerAxiosRequestInterceptor(){axios.interceptors.request.use(e=>(this.socketId()&&(e.headers["X-Socket-Id"]=this.socketId()),e))}registerjQueryAjaxSetup(){typeof jQuery.ajax<"u"&&jQuery.ajaxPrefilter((e,t,a)=>{this.socketId()&&a.setRequestHeader("X-Socket-Id",this.socketId())})}registerTurboRequestInterceptor(){document.addEventListener("turbo:before-fetch-request",e=>{e.detail.fetchOptions.headers["X-Socket-Id"]=this.socketId()})}}var Ig={exports:{}};/*! + `,Kn.error("Error state rendered:",i,a)}getCurrentLayout(){return this.currentLayout}clear(){this.currentLayout=null,this.layoutCache.clear(),Kn.log("Layout data and cache cleared")}}const Tj=it("TranslationContext"),Py=j.createContext(null),Rc=({children:r,translationEngine:e,translationContext:t})=>{const a=j.useMemo(()=>(o,d)=>{if(d){const g="|"+Object.entries(d).map(([h,f])=>`${h}=${f}`).join("|");return e.translate(o,t,g)}return e.translate(o,t)},[e,t]),i=j.useMemo(()=>({translationEngine:e,translationContext:t,t:a}),[e,t,a]);return l.jsx(Py.Provider,{value:i,children:r})},Dj=()=>{const r=j.useContext(Py);return r||(Tj.warn("TranslationProvider 외부에서 호출되었습니다. 키를 그대로 반환합니다."),{t:e=>e,translationEngine:null,translationContext:null})},$s=it("SlotContext"),Rj={registerToSlot:()=>{$s.warn("SlotContext not available: registerToSlot called outside SlotProvider")},unregisterFromSlot:()=>{$s.warn("SlotContext not available: unregisterFromSlot called outside SlotProvider")},getSlotComponents:()=>[],subscribeToSlot:()=>()=>{},clearAllSlots:()=>{},isEnabled:!1},Oj=j.createContext(Rj),Og=({children:r})=>{const e=j.useRef(new Map),t=j.useRef(new Map),a=j.useCallback(p=>{const y=t.current.get(p);y&&y.forEach(x=>{try{x()}catch(S){$s.error(`Slot subscriber error (slotId: ${p}):`,S)}})},[]),i=j.useCallback((p,y,x)=>{if(!p||!y){$s.warn("registerToSlot: slotId and componentId are required");return}e.current.has(p)||e.current.set(p,new Map);const S=e.current.get(p),v=S.get(y);v&&v.registrationKey===x.registrationKey||(S.set(y,x),$s.log(`Component registered to slot: ${y} -> ${p} (order: ${x.order})`),a(p))},[a]),o=j.useCallback((p,y)=>{const x=e.current.get(p);x&&x.has(y)&&(x.delete(y),$s.log(`Component unregistered from slot: ${y} <- ${p}`),x.size===0&&e.current.delete(p),a(p))},[a]),d=j.useCallback(p=>{const y=e.current.get(p);return y?Array.from(y.values()).sort((x,S)=>x.order-S.order):[]},[]),g=j.useCallback((p,y)=>{t.current.has(p)||t.current.set(p,new Set);const x=t.current.get(p);return x.add(y),()=>{x.delete(y),x.size===0&&t.current.delete(p)}},[]),h=j.useCallback(()=>{e.current.forEach((p,y)=>{a(y)}),e.current.clear(),t.current.clear(),$s.log("All slots cleared")},[a]),f=j.useMemo(()=>({registerToSlot:i,unregisterFromSlot:o,getSlotComponents:d,subscribeToSlot:g,clearAllSlots:h,isEnabled:!0}),[i,o,d,g,h]);return j.useLayoutEffect(()=>{typeof window<"u"&&(window.__slotContextValue=f,$s.log("SlotContext exposed to window.__slotContextValue"))},[f]),l.jsx(Oj.Provider,{value:f,children:r})};class Lg{constructor(){this.notificationCreatedEvent=".Illuminate\\Notifications\\Events\\BroadcastNotificationCreated"}listenForWhisper(e,t){return this.listen(".client-"+e,t)}notification(e){return this.listen(this.notificationCreatedEvent,e)}stopListeningForNotification(e){return this.stopListening(this.notificationCreatedEvent,e)}stopListeningForWhisper(e,t){return this.stopListening(".client-"+e,t)}}class By{constructor(e){this.namespace=e}format(e){return[".","\\"].includes(e.charAt(0))?e.substring(1):(this.namespace&&(e=this.namespace+"."+e),e.replace(/\./g,"\\"))}setNamespace(e){this.namespace=e}}function Lj(r){try{new r}catch(e){if(e instanceof Error&&e.message.includes("is not a constructor"))return!1}return!0}class Mg extends Lg{constructor(e,t,a){super(),this.name=t,this.pusher=e,this.options=a,this.eventFormatter=new By(this.options.namespace),this.subscribe()}subscribe(){this.subscription=this.pusher.subscribe(this.name)}unsubscribe(){this.pusher.unsubscribe(this.name)}listen(e,t){return this.on(this.eventFormatter.format(e),t),this}listenToAll(e){return this.subscription.bind_global((t,a)=>{if(t.startsWith("pusher:"))return;let i=String(this.options.namespace??"").replace(/\./g,"\\"),o=t.startsWith(i)?t.substring(i.length+1):"."+t;e(o,a)}),this}stopListening(e,t){return t?this.subscription.unbind(this.eventFormatter.format(e),t):this.subscription.unbind(this.eventFormatter.format(e)),this}stopListeningToAll(e){return e?this.subscription.unbind_global(e):this.subscription.unbind_global(),this}subscribed(e){return this.on("pusher:subscription_succeeded",()=>{e()}),this}error(e){return this.on("pusher:subscription_error",t=>{e(t)}),this}on(e,t){return this.subscription.bind(e,t),this}}class Uy extends Mg{whisper(e,t){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,t),this}}class Mj extends Mg{whisper(e,t){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,t),this}}class $j extends Uy{here(e){return this.on("pusher:subscription_succeeded",t=>{e(Object.keys(t.members).map(a=>t.members[a]))}),this}joining(e){return this.on("pusher:member_added",t=>{e(t.info)}),this}whisper(e,t){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,t),this}leaving(e){return this.on("pusher:member_removed",t=>{e(t.info)}),this}}class qy extends Lg{constructor(e,t,a){super(),this.events={},this.listeners={},this.name=t,this.socket=e,this.options=a,this.eventFormatter=new By(this.options.namespace),this.subscribe()}subscribe(){this.socket.emit("subscribe",{channel:this.name,auth:this.options.auth||{}})}unsubscribe(){this.unbind(),this.socket.emit("unsubscribe",{channel:this.name,auth:this.options.auth||{}})}listen(e,t){return this.on(this.eventFormatter.format(e),t),this}stopListening(e,t){return this.unbindEvent(this.eventFormatter.format(e),t),this}subscribed(e){return this.on("connect",t=>{e(t)}),this}error(e){return this}on(e,t){return this.listeners[e]=this.listeners[e]||[],this.events[e]||(this.events[e]=(a,i)=>{this.name===a&&this.listeners[e]&&this.listeners[e].forEach(o=>o(i))},this.socket.on(e,this.events[e])),this.listeners[e].push(t),this}unbind(){Object.keys(this.events).forEach(e=>{this.unbindEvent(e)})}unbindEvent(e,t){this.listeners[e]=this.listeners[e]||[],t&&(this.listeners[e]=this.listeners[e].filter(a=>a!==t)),(!t||this.listeners[e].length===0)&&(this.events[e]&&(this.socket.removeListener(e,this.events[e]),delete this.events[e]),delete this.listeners[e])}}class Gy extends qy{whisper(e,t){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:t}),this}}class Ij extends Gy{here(e){return this.on("presence:subscribed",t=>{e(t.map(a=>a.user_info))}),this}joining(e){return this.on("presence:joining",t=>e(t.user_info)),this}whisper(e,t){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:t}),this}leaving(e){return this.on("presence:leaving",t=>e(t.user_info)),this}}class Oc extends Lg{subscribe(){}unsubscribe(){}listen(e,t){return this}listenToAll(e){return this}stopListening(e,t){return this}subscribed(e){return this}error(e){return this}on(e,t){return this}}class Fy extends Oc{whisper(e,t){return this}}class zj extends Oc{whisper(e,t){return this}}class Hj extends Fy{here(e){return this}joining(e){return this}whisper(e,t){return this}leaving(e){return this}}const Vy=class yw{constructor(e){this.setOptions(e),this.connect()}setOptions(e){this.options={...yw._defaultOptions,...e,broadcaster:e.broadcaster};let t=this.csrfToken();t&&(this.options.auth.headers["X-CSRF-TOKEN"]=t,this.options.userAuthentication.headers["X-CSRF-TOKEN"]=t),t=this.options.bearerToken,t&&(this.options.auth.headers.Authorization="Bearer "+t,this.options.userAuthentication.headers.Authorization="Bearer "+t)}csrfToken(){var e,t;return typeof window<"u"&&(e=window.Laravel)!=null&&e.csrfToken?window.Laravel.csrfToken:this.options.csrfToken?this.options.csrfToken:typeof document<"u"&&typeof document.querySelector=="function"?((t=document.querySelector('meta[name="csrf-token"]'))==null?void 0:t.getAttribute("content"))??null:null}};Vy._defaultOptions={auth:{headers:{}},authEndpoint:"/broadcasting/auth",userAuthentication:{endpoint:"/broadcasting/user-auth",headers:{}},csrfToken:null,bearerToken:null,host:null,key:null,namespace:"App.Events"};let $g=Vy;class Lc extends $g{constructor(){super(...arguments),this.channels={}}connect(){if(typeof this.options.client<"u")this.pusher=this.options.client;else if(this.options.Pusher)this.pusher=new this.options.Pusher(this.options.key,this.options);else if(typeof window<"u"&&typeof window.Pusher<"u")this.pusher=new window.Pusher(this.options.key,this.options);else throw new Error("Pusher client not found. Should be globally available or passed via options.client")}signin(){this.pusher.signin()}listen(e,t,a){return this.channel(e).listen(t,a)}channel(e){return this.channels[e]||(this.channels[e]=new Mg(this.pusher,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new Uy(this.pusher,"private-"+e,this.options)),this.channels["private-"+e]}encryptedPrivateChannel(e){return this.channels["private-encrypted-"+e]||(this.channels["private-encrypted-"+e]=new Mj(this.pusher,"private-encrypted-"+e,this.options)),this.channels["private-encrypted-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new $j(this.pusher,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"private-encrypted-"+e,"presence-"+e].forEach(t=>{this.leaveChannel(t)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.pusher.connection.socket_id}disconnect(){this.pusher.disconnect()}}class Pj extends $g{constructor(){super(...arguments),this.channels={}}connect(){let e=this.getSocketIO();this.socket=e(this.options.host??void 0,this.options),this.socket.io.on("reconnect",()=>{Object.values(this.channels).forEach(t=>{t.subscribe()})})}getSocketIO(){if(typeof this.options.client<"u")return this.options.client;if(typeof window<"u"&&typeof window.io<"u")return window.io;throw new Error("Socket.io client not found. Should be globally available or passed via options.client")}listen(e,t,a){return this.channel(e).listen(t,a)}channel(e){return this.channels[e]||(this.channels[e]=new qy(this.socket,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new Gy(this.socket,"private-"+e,this.options)),this.channels["private-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new Ij(this.socket,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"presence-"+e].forEach(t=>{this.leaveChannel(t)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.socket.id}disconnect(){this.socket.disconnect()}}class Ky extends $g{constructor(){super(...arguments),this.channels={}}connect(){}listen(e,t,a){return new Oc}channel(e){return new Oc}privateChannel(e){return new Fy}encryptedPrivateChannel(e){return new zj}presenceChannel(e){return new Hj}leave(e){}leaveChannel(e){}socketId(){return"fake-socket-id"}disconnect(){}}class Bj{constructor(e){this.options=e,this.connect(),this.options.withoutInterceptors||this.registerInterceptors()}channel(e){return this.connector.channel(e)}connect(){if(this.options.broadcaster==="reverb")this.connector=new Lc({...this.options,cluster:""});else if(this.options.broadcaster==="pusher")this.connector=new Lc(this.options);else if(this.options.broadcaster==="ably")this.connector=new Lc({...this.options,cluster:"",broadcaster:"pusher"});else if(this.options.broadcaster==="socket.io")this.connector=new Pj(this.options);else if(this.options.broadcaster==="null")this.connector=new Ky(this.options);else if(typeof this.options.broadcaster=="function"&&Lj(this.options.broadcaster))this.connector=new this.options.broadcaster(this.options);else throw new Error(`Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} is not supported.`)}disconnect(){this.connector.disconnect()}join(e){return this.connector.presenceChannel(e)}leave(e){this.connector.leave(e)}leaveChannel(e){this.connector.leaveChannel(e)}leaveAllChannels(){for(const e in this.connector.channels)this.leaveChannel(e)}listen(e,t,a){return this.connector.listen(e,t,a)}private(e){return this.connector.privateChannel(e)}encryptedPrivate(e){if(this.connectorSupportsEncryptedPrivateChannels(this.connector))return this.connector.encryptedPrivateChannel(e);throw new Error(`Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} does not support encrypted private channels.`)}connectorSupportsEncryptedPrivateChannels(e){return e instanceof Lc||e instanceof Ky}socketId(){return this.connector.socketId()}registerInterceptors(){typeof Vue<"u"&&Vue!=null&&Vue.http&&this.registerVueRequestInterceptor(),typeof axios=="function"&&this.registerAxiosRequestInterceptor(),typeof jQuery=="function"&&this.registerjQueryAjaxSetup(),typeof Turbo=="object"&&this.registerTurboRequestInterceptor()}registerVueRequestInterceptor(){Vue.http.interceptors.push((e,t)=>{this.socketId()&&e.headers.set("X-Socket-ID",this.socketId()),t()})}registerAxiosRequestInterceptor(){axios.interceptors.request.use(e=>(this.socketId()&&(e.headers["X-Socket-Id"]=this.socketId()),e))}registerjQueryAjaxSetup(){typeof jQuery.ajax<"u"&&jQuery.ajaxPrefilter((e,t,a)=>{this.socketId()&&a.setRequestHeader("X-Socket-Id",this.socketId())})}registerTurboRequestInterceptor(){document.addEventListener("turbo:before-fetch-request",e=>{e.detail.fetchOptions.headers["X-Socket-Id"]=this.socketId()})}}var Ig={exports:{}};/*! * Pusher JavaScript Library v8.4.0 * https://pusher.com/ * * Copyright 2020, Pusher * Released under the MIT licence. - */var Wy;function Bj(){return Wy||(Wy=1,(function(r,e){(function(a,i){r.exports=i()})(window,function(){return(function(t){var a={};function i(o){if(a[o])return a[o].exports;var d=a[o]={i:o,l:!1,exports:{}};return t[o].call(d.exports,d,d.exports,i),d.l=!0,d.exports}return i.m=t,i.c=a,i.d=function(o,d,g){i.o(o,d)||Object.defineProperty(o,d,{enumerable:!0,get:g})},i.r=function(o){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(o,"__esModule",{value:!0})},i.t=function(o,d){if(d&1&&(o=i(o)),d&8||d&4&&typeof o=="object"&&o&&o.__esModule)return o;var g=Object.create(null);if(i.r(g),Object.defineProperty(g,"default",{enumerable:!0,value:o}),d&2&&typeof o!="string")for(var h in o)i.d(g,h,function(f){return o[f]}.bind(null,h));return g},i.n=function(o){var d=o&&o.__esModule?function(){return o.default}:function(){return o};return i.d(d,"a",d),d},i.o=function(o,d){return Object.prototype.hasOwnProperty.call(o,d)},i.p="",i(i.s=2)})([(function(t,a,i){var o=this&&this.__extends||(function(){var w=function(k,A){return w=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(O,N){O.__proto__=N}||function(O,N){for(var D in N)N.hasOwnProperty(D)&&(O[D]=N[D])},w(k,A)};return function(k,A){w(k,A);function O(){this.constructor=k}k.prototype=A===null?Object.create(A):(O.prototype=A.prototype,new O)}})();Object.defineProperty(a,"__esModule",{value:!0});var d=256,g=(function(){function w(k){k===void 0&&(k="="),this._paddingCharacter=k}return w.prototype.encodedLength=function(k){return this._paddingCharacter?(k+2)/3*4|0:(k*8+5)/6|0},w.prototype.encode=function(k){for(var A="",O=0;O>>18&63),A+=this._encodeByte(N>>>12&63),A+=this._encodeByte(N>>>6&63),A+=this._encodeByte(N>>>0&63)}var D=k.length-O;if(D>0){var N=k[O]<<16|(D===2?k[O+1]<<8:0);A+=this._encodeByte(N>>>18&63),A+=this._encodeByte(N>>>12&63),D===2?A+=this._encodeByte(N>>>6&63):A+=this._paddingCharacter||"",A+=this._paddingCharacter||""}return A},w.prototype.maxDecodedLength=function(k){return this._paddingCharacter?k/4*3|0:(k*6+7)/8|0},w.prototype.decodedLength=function(k){return this.maxDecodedLength(k.length-this._getPaddingLength(k))},w.prototype.decode=function(k){if(k.length===0)return new Uint8Array(0);for(var A=this._getPaddingLength(k),O=k.length-A,N=new Uint8Array(this.maxDecodedLength(O)),D=0,$=0,M=0,z=0,K=0,pe=0,we=0;$>>4,N[D++]=K<<4|pe>>>2,N[D++]=pe<<6|we,M|=z&d,M|=K&d,M|=pe&d,M|=we&d;if($>>4,M|=z&d,M|=K&d),$>>2,M|=pe&d),$>>8&6,A+=51-k>>>8&-75,A+=61-k>>>8&-15,A+=62-k>>>8&3,String.fromCharCode(A)},w.prototype._decodeChar=function(k){var A=d;return A+=(42-k&k-44)>>>8&-d+k-43+62,A+=(46-k&k-48)>>>8&-d+k-47+63,A+=(47-k&k-58)>>>8&-d+k-48+52,A+=(64-k&k-91)>>>8&-d+k-65+0,A+=(96-k&k-123)>>>8&-d+k-97+26,A},w.prototype._getPaddingLength=function(k){var A=0;if(this._paddingCharacter){for(var O=k.length-1;O>=0&&k[O]===this._paddingCharacter;O--)A++;if(k.length<4||A>2)throw new Error("Base64Coder: incorrect padding")}return A},w})();a.Coder=g;var h=new g;function f(w){return h.encode(w)}a.encode=f;function p(w){return h.decode(w)}a.decode=p;var y=(function(w){o(k,w);function k(){return w!==null&&w.apply(this,arguments)||this}return k.prototype._encodeByte=function(A){var O=A;return O+=65,O+=25-A>>>8&6,O+=51-A>>>8&-75,O+=61-A>>>8&-13,O+=62-A>>>8&49,String.fromCharCode(O)},k.prototype._decodeChar=function(A){var O=d;return O+=(44-A&A-46)>>>8&-d+A-45+62,O+=(94-A&A-96)>>>8&-d+A-95+63,O+=(47-A&A-58)>>>8&-d+A-48+52,O+=(64-A&A-91)>>>8&-d+A-65+0,O+=(96-A&A-123)>>>8&-d+A-97+26,O},k})(g);a.URLSafeCoder=y;var x=new y;function S(w){return x.encode(w)}a.encodeURLSafe=S;function v(w){return x.decode(w)}a.decodeURLSafe=v,a.encodedLength=function(w){return h.encodedLength(w)},a.maxDecodedLength=function(w){return h.maxDecodedLength(w)},a.decodedLength=function(w){return h.decodedLength(w)}}),(function(t,a,i){Object.defineProperty(a,"__esModule",{value:!0});var o="utf8: invalid string",d="utf8: invalid source encoding";function g(p){for(var y=new Uint8Array(h(p)),x=0,S=0;S>6,y[x++]=128|v&63):v<55296?(y[x++]=224|v>>12,y[x++]=128|v>>6&63,y[x++]=128|v&63):(S++,v=(v&1023)<<10,v|=p.charCodeAt(S)&1023,v+=65536,y[x++]=240|v>>18,y[x++]=128|v>>12&63,y[x++]=128|v>>6&63,y[x++]=128|v&63)}return y}a.encode=g;function h(p){for(var y=0,x=0;x=p.length-1)throw new Error(o);x++,y+=4}else throw new Error(o)}return y}a.encodedLength=h;function f(p){for(var y=[],x=0;x=p.length)throw new Error(d);var w=p[++x];if((w&192)!==128)throw new Error(d);S=(S&31)<<6|w&63,v=128}else if(S<240){if(x>=p.length-1)throw new Error(d);var w=p[++x],k=p[++x];if((w&192)!==128||(k&192)!==128)throw new Error(d);S=(S&15)<<12|(w&63)<<6|k&63,v=2048}else if(S<248){if(x>=p.length-2)throw new Error(d);var w=p[++x],k=p[++x],A=p[++x];if((w&192)!==128||(k&192)!==128||(A&192)!==128)throw new Error(d);S=(S&15)<<18|(w&63)<<12|(k&63)<<6|A&63,v=65536}else throw new Error(d);if(S=55296&&S<=57343)throw new Error(d);if(S>=65536){if(S>1114111)throw new Error(d);S-=65536,y.push(String.fromCharCode(55296|S>>10)),S=56320|S&1023}}y.push(String.fromCharCode(S))}return y.join("")}a.decode=f}),(function(t,a,i){t.exports=i(3).default}),(function(t,a,i){i.r(a);class o{constructor(C,_){this.lastId=0,this.prefix=C,this.name=_}create(C){this.lastId++;var _=this.lastId,I=this.prefix+_,P=this.name+"["+_+"]",he=!1,Ne=function(){he||(C.apply(null,arguments),he=!0)};return this[_]=Ne,{number:_,id:I,name:P,callback:Ne}}remove(C){delete this[C.number]}}var d=new o("_pusher_script_","Pusher.ScriptReceivers"),g={VERSION:"8.4.0",PROTOCOL:7,wsPort:80,wssPort:443,wsPath:"",httpHost:"sockjs.pusher.com",httpPort:80,httpsPort:443,httpPath:"/pusher",stats_host:"stats.pusher.com",authEndpoint:"/pusher/auth",authTransport:"ajax",activityTimeout:12e4,pongTimeout:3e4,unavailableTimeout:1e4,userAuthentication:{endpoint:"/pusher/user-auth",transport:"ajax"},channelAuthorization:{endpoint:"/pusher/auth",transport:"ajax"},cdn_http:"http://js.pusher.com",cdn_https:"https://js.pusher.com",dependency_suffix:""},h=g;class f{constructor(C){this.options=C,this.receivers=C.receivers||d,this.loading={}}load(C,_,I){var P=this;if(P.loading[C]&&P.loading[C].length>0)P.loading[C].push(I);else{P.loading[C]=[I];var he=Xe.createScriptRequest(P.getPath(C,_)),Ne=P.receivers.create(function(ze){if(P.receivers.remove(Ne),P.loading[C]){var Qe=P.loading[C];delete P.loading[C];for(var dt=function(Kt){Kt||he.cleanup()},yt=0;yt>>6)+be(128|C&63):be(224|C>>>12&15)+be(128|C>>>6&63)+be(128|C&63)},je=function(T){return T.replace(/[^\x00-\x7F]/g,de)},W=function(T){var C=[0,2,1][T.length%3],_=T.charCodeAt(0)<<16|(T.length>1?T.charCodeAt(1):0)<<8|(T.length>2?T.charCodeAt(2):0),I=[le.charAt(_>>>18),le.charAt(_>>>12&63),C>=2?"=":le.charAt(_>>>6&63),C>=1?"=":le.charAt(_&63)];return I.join("")},ge=window.btoa||function(T){return T.replace(/[\s\S]{1,3}/g,W)};class ne{constructor(C,_,I,P){this.clear=_,this.timer=C(()=>{this.timer&&(this.timer=P(this.timer))},I)}isRunning(){return this.timer!==null}ensureAborted(){this.timer&&(this.clear(this.timer),this.timer=null)}}var X=ne;function ae(T){window.clearTimeout(T)}function R(T){window.clearInterval(T)}class U extends X{constructor(C,_){super(setTimeout,ae,C,function(I){return _(),null})}}class re extends X{constructor(C,_){super(setInterval,R,C,function(I){return _(),I})}}var ye={now(){return Date.now?Date.now():new Date().valueOf()},defer(T){return new U(0,T)},method(T,...C){var _=Array.prototype.slice.call(arguments,1);return function(I){return I[T].apply(I,_.concat(arguments))}}},oe=ye;function ke(T,...C){for(var _=0;_{window.console&&window.console.log&&window.console.log(C)}}debug(...C){this.log(this.globalLog,C)}warn(...C){this.log(this.globalLogWarn,C)}error(...C){this.log(this.globalLogError,C)}globalLogWarn(C){window.console&&window.console.warn?window.console.warn(C):this.globalLog(C)}globalLogError(C){window.console&&window.console.error?window.console.error(C):this.globalLogWarn(C)}log(C,..._){var I=Oe.apply(this,arguments);dl.log?dl.log(I):dl.logToConsole&&C.bind(this)(I)}}var tt=new pt,bn=function(T,C,_,I,P){(_.headers!==void 0||_.headersProvider!=null)&&tt.warn(`To send headers with the ${I.toString()} request, you must use AJAX, rather than JSONP.`);var he=T.nextAuthCallbackID.toString();T.nextAuthCallbackID++;var Ne=T.getDocument(),ze=Ne.createElement("script");T.auth_callbacks[he]=function(yt){P(null,yt)};var Qe="Pusher.auth_callbacks['"+he+"']";ze.src=_.endpoint+"?callback="+encodeURIComponent(Qe)+"&"+C;var dt=Ne.getElementsByTagName("head")[0]||Ne.documentElement;dt.insertBefore(ze,dt.firstChild)},wt=bn;class At{constructor(C){this.src=C}send(C){var _=this,I="Error loading "+_.src;_.script=document.createElement("script"),_.script.id=C.id,_.script.src=_.src,_.script.type="text/javascript",_.script.charset="UTF-8",_.script.addEventListener?(_.script.onerror=function(){C.callback(I)},_.script.onload=function(){C.callback(null)}):_.script.onreadystatechange=function(){(_.script.readyState==="loaded"||_.script.readyState==="complete")&&C.callback(null)},_.script.async===void 0&&document.attachEvent&&/opera/i.test(navigator.userAgent)?(_.errorScript=document.createElement("script"),_.errorScript.id=C.id+"_error",_.errorScript.text=C.name+"('"+I+"');",_.script.async=_.errorScript.async=!1):_.script.async=!0;var P=document.getElementsByTagName("head")[0];P.insertBefore(_.script,P.firstChild),_.errorScript&&P.insertBefore(_.errorScript,_.script.nextSibling)}cleanup(){this.script&&(this.script.onload=this.script.onerror=null,this.script.onreadystatechange=null),this.script&&this.script.parentNode&&this.script.parentNode.removeChild(this.script),this.errorScript&&this.errorScript.parentNode&&this.errorScript.parentNode.removeChild(this.errorScript),this.script=null,this.errorScript=null}}class qt{constructor(C,_){this.url=C,this.data=_}send(C){if(!this.request){var _=ft(this.data),I=this.url+"/"+C.number+"?"+_;this.request=Xe.createScriptRequest(I),this.request.send(C)}}cleanup(){this.request&&this.request.cleanup()}}var Yn=function(T,C){return function(_,I){var P="http"+(C?"s":"")+"://",he=P+(T.host||T.options.host)+T.options.path,Ne=Xe.createJSONPRequest(he,_),ze=Xe.ScriptReceivers.create(function(Qe,dt){d.remove(ze),Ne.cleanup(),dt&&dt.host&&(T.host=dt.host),I&&I(Qe,dt)});Ne.send(ze)}},dn={name:"jsonp",getAgent:Yn},Ta=dn;function ca(T,C,_){var I=T+(C.useTLS?"s":""),P=C.useTLS?C.hostTLS:C.hostNonTLS;return I+"://"+P+_}function V(T,C){var _="/app/"+T,I="?protocol="+h.PROTOCOL+"&client=js&version="+h.VERSION+(C?"&"+C:"");return _+I}var ve={getInitial:function(T,C){var _=(C.httpPath||"")+V(T,"flash=false");return ca("ws",C,_)}},me={getInitial:function(T,C){var _=(C.httpPath||"/pusher")+V(T);return ca("http",C,_)}},te={getInitial:function(T,C){return ca("http",C,C.httpPath||"/pusher")},getPath:function(T,C){return V(T)}};class _e{constructor(){this._callbacks={}}get(C){return this._callbacks[Ae(C)]}add(C,_,I){var P=Ae(C);this._callbacks[P]=this._callbacks[P]||[],this._callbacks[P].push({fn:_,context:I})}remove(C,_,I){if(!C&&!_&&!I){this._callbacks={};return}var P=C?[Ae(C)]:Ie(this._callbacks);_||I?this.removeCallback(P,_,I):this.removeAllCallbacks(P)}removeCallback(C,_,I){Tt(C,function(P){this._callbacks[P]=Qt(this._callbacks[P]||[],function(he){return _&&_!==he.fn||I&&I!==he.context}),this._callbacks[P].length===0&&delete this._callbacks[P]},this)}removeAllCallbacks(C){Tt(C,function(_){delete this._callbacks[_]},this)}}function Ae(T){return"_"+T}class Re{constructor(C){this.callbacks=new _e,this.global_callbacks=[],this.failThrough=C}bind(C,_,I){return this.callbacks.add(C,_,I),this}bind_global(C){return this.global_callbacks.push(C),this}unbind(C,_,I){return this.callbacks.remove(C,_,I),this}unbind_global(C){return C?(this.global_callbacks=Qt(this.global_callbacks||[],_=>_!==C),this):(this.global_callbacks=[],this)}unbind_all(){return this.unbind(),this.unbind_global(),this}emit(C,_,I){for(var P=0;P0)for(var P=0;P{this.onError(_),this.changeState("closed")}),!1}return this.bindListeners(),tt.debug("Connecting",{transport:this.name,url:C}),this.changeState("connecting"),!0}close(){return this.socket?(this.socket.close(),!0):!1}send(C){return this.state==="open"?(oe.defer(()=>{this.socket&&this.socket.send(C)}),!0):!1}ping(){this.state==="open"&&this.supportsPing()&&this.socket.ping()}onOpen(){this.hooks.beforeOpen&&this.hooks.beforeOpen(this.socket,this.hooks.urls.getPath(this.key,this.options)),this.changeState("open"),this.socket.onopen=void 0}onError(C){this.emit("error",{type:"WebSocketError",error:C}),this.timeline.error(this.buildTimelineMessage({error:C.toString()}))}onClose(C){C?this.changeState("closed",{code:C.code,reason:C.reason,wasClean:C.wasClean}):this.changeState("closed"),this.unbindListeners(),this.socket=void 0}onMessage(C){this.emit("message",C)}onActivity(){this.emit("activity")}bindListeners(){this.socket.onopen=()=>{this.onOpen()},this.socket.onerror=C=>{this.onError(C)},this.socket.onclose=C=>{this.onClose(C)},this.socket.onmessage=C=>{this.onMessage(C)},this.supportsPing()&&(this.socket.onactivity=()=>{this.onActivity()})}unbindListeners(){this.socket&&(this.socket.onopen=void 0,this.socket.onerror=void 0,this.socket.onclose=void 0,this.socket.onmessage=void 0,this.supportsPing()&&(this.socket.onactivity=void 0))}changeState(C,_){this.state=C,this.timeline.info(this.buildTimelineMessage({state:C,params:_})),this.emit(C,_)}buildTimelineMessage(C){return ke({cid:this.id},C)}}class Ue{constructor(C){this.hooks=C}isSupported(C){return this.hooks.isSupported(C)}createConnection(C,_,I,P){return new Pe(this.hooks,C,_,I,P)}}var Le=new Ue({urls:ve,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return!!Xe.getWebSocketAPI()},isSupported:function(){return!!Xe.getWebSocketAPI()},getSocket:function(T){return Xe.createWebSocket(T)}}),Fe={urls:me,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},We=ke({getSocket:function(T){return Xe.HTTPFactory.createStreamingSocket(T)}},Fe),Je=ke({getSocket:function(T){return Xe.HTTPFactory.createPollingSocket(T)}},Fe),st={isSupported:function(){return Xe.isXHRSupported()}},Be=new Ue(ke({},We,st)),De=new Ue(ke({},Je,st)),$e={ws:Le,xhr_streaming:Be,xhr_polling:De},mt=$e,zt=new Ue({file:"sockjs",urls:te,handlesActivityChecks:!0,supportsPing:!1,isSupported:function(){return!0},isInitialized:function(){return window.SockJS!==void 0},getSocket:function(T,C){return new window.SockJS(T,null,{js_path:y.getPath("sockjs",{useTLS:C.useTLS}),ignore_null_origin:C.ignoreNullOrigin})},beforeOpen:function(T,C){T.send(JSON.stringify({path:C}))}}),tn={isSupported:function(T){var C=Xe.isXDRSupported(T.useTLS);return C}},yn=new Ue(ke({},We,tn)),Jn=new Ue(ke({},Je,tn));mt.xdr_streaming=yn,mt.xdr_polling=Jn,mt.sockjs=zt;var Xn=mt;class Ga extends Re{constructor(){super();var C=this;window.addEventListener!==void 0&&(window.addEventListener("online",function(){C.emit("online")},!1),window.addEventListener("offline",function(){C.emit("offline")},!1))}isOnline(){return window.navigator.onLine===void 0?!0:window.navigator.onLine}}var In=new Ga;class un{constructor(C,_,I){this.manager=C,this.transport=_,this.minPingDelay=I.minPingDelay,this.maxPingDelay=I.maxPingDelay,this.pingDelay=void 0}createConnection(C,_,I,P){P=ke({},P,{activityTimeout:this.pingDelay});var he=this.transport.createConnection(C,_,I,P),Ne=null,ze=function(){he.unbind("open",ze),he.bind("closed",Qe),Ne=oe.now()},Qe=dt=>{if(he.unbind("closed",Qe),dt.code===1002||dt.code===1003)this.manager.reportDeath();else if(!dt.wasClean&&Ne){var yt=oe.now()-Ne;yt<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(yt/2,this.minPingDelay))}};return he.bind("open",ze),he}isSupported(C){return this.manager.isAlive()&&this.transport.isSupported(C)}}const vn={decodeMessage:function(T){try{var C=JSON.parse(T.data),_=C.data;if(typeof _=="string")try{_=JSON.parse(C.data)}catch{}var I={event:C.event,channel:C.channel,data:_};return C.user_id&&(I.user_id=C.user_id),I}catch(P){throw{type:"MessageParseError",error:P,data:T.data}}},encodeMessage:function(T){return JSON.stringify(T)},processHandshake:function(T){var C=vn.decodeMessage(T);if(C.event==="pusher:connection_established"){if(!C.data.activity_timeout)throw"No activity timeout specified in handshake";return{action:"connected",id:C.data.socket_id,activityTimeout:C.data.activity_timeout*1e3}}else{if(C.event==="pusher:error")return{action:this.getCloseAction(C.data),error:this.getCloseError(C.data)};throw"Invalid handshake"}},getCloseAction:function(T){return T.code<4e3?T.code>=1002&&T.code<=1004?"backoff":null:T.code===4e3?"tls_only":T.code<4100?"refused":T.code<4200?"backoff":T.code<4300?"retry":"refused"},getCloseError:function(T){return T.code!==1e3&&T.code!==1001?{type:"PusherError",data:{code:T.code,message:T.reason||T.message}}:null}};var zn=vn;class Wo extends Re{constructor(C,_){super(),this.id=C,this.transport=_,this.activityTimeout=_.activityTimeout,this.bindListeners()}handlesActivityChecks(){return this.transport.handlesActivityChecks()}send(C){return this.transport.send(C)}send_event(C,_,I){var P={event:C,data:_};return I&&(P.channel=I),tt.debug("Event sent",P),this.send(zn.encodeMessage(P))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var C={message:I=>{var P;try{P=zn.decodeMessage(I)}catch(he){this.emit("error",{type:"MessageParseError",error:he,data:I.data})}if(P!==void 0){switch(tt.debug("Event recd",P),P.event){case"pusher:error":this.emit("error",{type:"PusherError",data:P.data});break;case"pusher:ping":this.emit("ping");break;case"pusher:pong":this.emit("pong");break}this.emit("message",P)}},activity:()=>{this.emit("activity")},error:I=>{this.emit("error",I)},closed:I=>{_(),I&&I.code&&this.handleCloseEvent(I),this.transport=null,this.emit("closed")}},_=()=>{qe(C,(I,P)=>{this.transport.unbind(P,I)})};qe(C,(I,P)=>{this.transport.bind(P,I)})}handleCloseEvent(C){var _=zn.getCloseAction(C),I=zn.getCloseError(C);I&&this.emit("error",I),_&&this.emit(_,{action:_,error:I})}}class mh{constructor(C,_){this.transport=C,this.callback=_,this.bindListeners()}close(){this.unbindListeners(),this.transport.close()}bindListeners(){this.onMessage=C=>{this.unbindListeners();var _;try{_=zn.processHandshake(C)}catch(I){this.finish("error",{error:I}),this.transport.close();return}_.action==="connected"?this.finish("connected",{connection:new Wo(_.id,this.transport),activityTimeout:_.activityTimeout}):(this.finish(_.action,{error:_.error}),this.transport.close())},this.onClosed=C=>{this.unbindListeners();var _=zn.getCloseAction(C)||"backoff",I=zn.getCloseError(C);this.finish(_,{error:I})},this.transport.bind("message",this.onMessage),this.transport.bind("closed",this.onClosed)}unbindListeners(){this.transport.unbind("message",this.onMessage),this.transport.unbind("closed",this.onClosed)}finish(C,_){this.callback(ke({transport:this.transport,action:C},_))}}class yh{constructor(C,_){this.timeline=C,this.options=_||{}}send(C,_){this.timeline.isEmpty()||this.timeline.send(Xe.TimelineTransport.getAgent(this,C),_)}}class vi extends Re{constructor(C,_){super(function(I,P){tt.debug("No callbacks on "+C+" for "+I)}),this.name=C,this.pusher=_,this.subscribed=!1,this.subscriptionPending=!1,this.subscriptionCancelled=!1}authorize(C,_){return _(null,{auth:""})}trigger(C,_){if(C.indexOf("client-")!==0)throw new k("Event '"+C+"' does not start with 'client-'");if(!this.subscribed){var I=v.buildLogSuffix("triggeringClientEvents");tt.warn(`Client event triggered before channel 'subscription_succeeded' event . ${I}`)}return this.pusher.send_event(C,_,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(C){var _=C.event,I=C.data;if(_==="pusher_internal:subscription_succeeded")this.handleSubscriptionSucceededEvent(C);else if(_==="pusher_internal:subscription_count")this.handleSubscriptionCountEvent(C);else if(_.indexOf("pusher_internal:")!==0){var P={};this.emit(_,I,P)}}handleSubscriptionSucceededEvent(C){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):this.emit("pusher:subscription_succeeded",C.data)}handleSubscriptionCountEvent(C){C.data.subscription_count&&(this.subscriptionCount=C.data.subscription_count),this.emit("pusher:subscription_count",C.data)}subscribe(){this.subscribed||(this.subscriptionPending=!0,this.subscriptionCancelled=!1,this.authorize(this.pusher.connection.socket_id,(C,_)=>{C?(this.subscriptionPending=!1,tt.error(C.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:C.message},C instanceof K?{status:C.status}:{}))):this.pusher.send_event("pusher:subscribe",{auth:_.auth,channel_data:_.channel_data,channel:this.name})}))}unsubscribe(){this.subscribed=!1,this.pusher.send_event("pusher:unsubscribe",{channel:this.name})}cancelSubscription(){this.subscriptionCancelled=!0}reinstateSubscription(){this.subscriptionCancelled=!1}}class ds extends vi{authorize(C,_){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:C},_)}}class Yo{constructor(){this.reset()}get(C){return Object.prototype.hasOwnProperty.call(this.members,C)?{id:C,info:this.members[C]}:null}each(C){qe(this.members,(_,I)=>{C(this.get(I))})}setMyID(C){this.myID=C}onSubscription(C){this.members=C.presence.hash,this.count=C.presence.count,this.me=this.get(this.myID)}addMember(C){return this.get(C.user_id)===null&&this.count++,this.members[C.user_id]=C.user_info,this.get(C.user_id)}removeMember(C){var _=this.get(C.user_id);return _&&(delete this.members[C.user_id],this.count--),_}reset(){this.members={},this.count=0,this.myID=null,this.me=null}}var Ps=function(T,C,_,I){function P(he){return he instanceof _?he:new _(function(Ne){Ne(he)})}return new(_||(_=Promise))(function(he,Ne){function ze(yt){try{dt(I.next(yt))}catch(Kt){Ne(Kt)}}function Qe(yt){try{dt(I.throw(yt))}catch(Kt){Ne(Kt)}}function dt(yt){yt.done?he(yt.value):P(yt.value).then(ze,Qe)}dt((I=I.apply(T,C||[])).next())})};class Bs extends ds{constructor(C,_){super(C,_),this.members=new Yo}authorize(C,_){super.authorize(C,(I,P)=>Ps(this,void 0,void 0,function*(){if(!I)if(P=P,P.channel_data!=null){var he=JSON.parse(P.channel_data);this.members.setMyID(he.user_id)}else if(yield this.pusher.user.signinDonePromise,this.pusher.user.user_data!=null)this.members.setMyID(this.pusher.user.user_data.id);else{let Ne=v.buildLogSuffix("authorizationEndpoint");tt.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${Ne}, or the user should be signed in.`),_("Invalid auth response");return}_(I,P)}))}handleEvent(C){var _=C.event;if(_.indexOf("pusher_internal:")===0)this.handleInternalEvent(C);else{var I=C.data,P={};C.user_id&&(P.user_id=C.user_id),this.emit(_,I,P)}}handleInternalEvent(C){var _=C.event,I=C.data;switch(_){case"pusher_internal:subscription_succeeded":this.handleSubscriptionSucceededEvent(C);break;case"pusher_internal:subscription_count":this.handleSubscriptionCountEvent(C);break;case"pusher_internal:member_added":var P=this.members.addMember(I);this.emit("pusher:member_added",P);break;case"pusher_internal:member_removed":var he=this.members.removeMember(I);he&&this.emit("pusher:member_removed",he);break}}handleSubscriptionSucceededEvent(C){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):(this.members.onSubscription(C.data),this.emit("pusher:subscription_succeeded",this.members))}disconnect(){this.members.reset(),super.disconnect()}}var Ar=i(1),Fa=i(0);class nn extends ds{constructor(C,_,I){super(C,_),this.key=null,this.nacl=I}authorize(C,_){super.authorize(C,(I,P)=>{if(I){_(I,P);return}let he=P.shared_secret;if(!he){_(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null);return}this.key=Object(Fa.decode)(he),delete P.shared_secret,_(null,P)})}trigger(C,_){throw new $("Client events are not currently supported for encrypted channels")}handleEvent(C){var _=C.event,I=C.data;if(_.indexOf("pusher_internal:")===0||_.indexOf("pusher:")===0){super.handleEvent(C);return}this.handleEncryptedEvent(_,I)}handleEncryptedEvent(C,_){if(!this.key){tt.debug("Received encrypted event before key has been retrieved from the authEndpoint");return}if(!_.ciphertext||!_.nonce){tt.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+_);return}let I=Object(Fa.decode)(_.ciphertext);if(I.length{if(Ne){tt.error(`Failed to make a request to the authEndpoint: ${ze}. Unable to fetch new key, so dropping encrypted event`);return}if(he=this.nacl.secretbox.open(I,P,this.key),he===null){tt.error("Failed to decrypt event with new key. Dropping encrypted event");return}this.emit(C,this.getDataToEmit(he))});return}this.emit(C,this.getDataToEmit(he))}getDataToEmit(C){let _=Object(Ar.decode)(C);try{return JSON.parse(_)}catch{return _}}}class fd extends Re{constructor(C,_){super(),this.state="initialized",this.connection=null,this.key=C,this.options=_,this.timeline=this.options.timeline,this.usingTLS=this.options.useTLS,this.errorCallbacks=this.buildErrorCallbacks(),this.connectionCallbacks=this.buildConnectionCallbacks(this.errorCallbacks),this.handshakeCallbacks=this.buildHandshakeCallbacks(this.errorCallbacks);var I=Xe.getNetwork();I.bind("online",()=>{this.timeline.info({netinfo:"online"}),(this.state==="connecting"||this.state==="unavailable")&&this.retryIn(0)}),I.bind("offline",()=>{this.timeline.info({netinfo:"offline"}),this.connection&&this.sendActivityCheck()}),this.updateStrategy()}connect(){if(!(this.connection||this.runner)){if(!this.strategy.isSupported()){this.updateState("failed");return}this.updateState("connecting"),this.startConnecting(),this.setUnavailableTimer()}}send(C){return this.connection?this.connection.send(C):!1}send_event(C,_,I){return this.connection?this.connection.send_event(C,_,I):!1}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var C=(_,I)=>{_?this.runner=this.strategy.connect(0,C):I.action==="error"?(this.emit("error",{type:"HandshakeError",error:I.error}),this.timeline.error({handshakeError:I.error})):(this.abortConnecting(),this.handshakeCallbacks[I.action](I))};this.runner=this.strategy.connect(0,C)}abortConnecting(){this.runner&&(this.runner.abort(),this.runner=null)}disconnectInternally(){if(this.abortConnecting(),this.clearRetryTimer(),this.clearUnavailableTimer(),this.connection){var C=this.abandonConnection();C.close()}}updateStrategy(){this.strategy=this.options.getStrategy({key:this.key,timeline:this.timeline,useTLS:this.usingTLS})}retryIn(C){this.timeline.info({action:"retry",delay:C}),C>0&&this.emit("connecting_in",Math.round(C/1e3)),this.retryTimer=new U(C||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new U(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new U(this.options.pongTimeout,()=>{this.timeline.error({pong_timed_out:this.options.pongTimeout}),this.retryIn(0)})}resetActivityCheck(){this.stopActivityCheck(),this.connection&&!this.connection.handlesActivityChecks()&&(this.activityTimer=new U(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(C){return ke({},C,{message:_=>{this.resetActivityCheck(),this.emit("message",_)},ping:()=>{this.send_event("pusher:pong",{})},activity:()=>{this.resetActivityCheck()},error:_=>{this.emit("error",_)},closed:()=>{this.abandonConnection(),this.shouldRetry()&&this.retryIn(1e3)}})}buildHandshakeCallbacks(C){return ke({},C,{connected:_=>{this.activityTimeout=Math.min(this.options.activityTimeout,_.activityTimeout,_.connection.activityTimeout||1/0),this.clearUnavailableTimer(),this.setConnection(_.connection),this.socket_id=this.connection.id,this.updateState("connected",{socket_id:this.socket_id})}})}buildErrorCallbacks(){let C=_=>I=>{I.error&&this.emit("error",{type:"WebSocketError",error:I.error}),_(I)};return{tls_only:C(()=>{this.usingTLS=!0,this.updateStrategy(),this.retryIn(0)}),refused:C(()=>{this.disconnect()}),backoff:C(()=>{this.retryIn(1e3)}),retry:C(()=>{this.retryIn(0)})}}setConnection(C){this.connection=C;for(var _ in this.connectionCallbacks)this.connection.bind(_,this.connectionCallbacks[_]);this.resetActivityCheck()}abandonConnection(){if(this.connection){this.stopActivityCheck();for(var C in this.connectionCallbacks)this.connection.unbind(C,this.connectionCallbacks[C]);var _=this.connection;return this.connection=null,_}}updateState(C,_){var I=this.state;if(this.state=C,I!==C){var P=C;P==="connected"&&(P+=" with new socket ID "+_.socket_id),tt.debug("State changed",I+" -> "+P),this.timeline.info({state:C,params:_}),this.emit("state_change",{previous:I,current:C}),this.emit(C,_)}}shouldRetry(){return this.state==="connecting"||this.state==="connected"}}class pd{constructor(){this.channels={}}add(C,_){return this.channels[C]||(this.channels[C]=us(C,_)),this.channels[C]}all(){return Nt(this.channels)}find(C){return this.channels[C]}remove(C){var _=this.channels[C];return delete this.channels[C],_}disconnect(){qe(this.channels,function(C){C.disconnect()})}}function us(T,C){if(T.indexOf("private-encrypted-")===0){if(C.config.nacl)return Da.createEncryptedChannel(T,C,C.config.nacl);let _="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",I=v.buildLogSuffix("encryptedChannelSupport");throw new $(`${_}. ${I}`)}else{if(T.indexOf("private-")===0)return Da.createPrivateChannel(T,C);if(T.indexOf("presence-")===0)return Da.createPresenceChannel(T,C);if(T.indexOf("#")===0)throw new A('Cannot create a channel with name "'+T+'".');return Da.createChannel(T,C)}}var Us={createChannels(){return new pd},createConnectionManager(T,C){return new fd(T,C)},createChannel(T,C){return new vi(T,C)},createPrivateChannel(T,C){return new ds(T,C)},createPresenceChannel(T,C){return new Bs(T,C)},createEncryptedChannel(T,C,_){return new nn(T,C,_)},createTimelineSender(T,C){return new yh(T,C)},createHandshake(T,C){return new mh(T,C)},createAssistantToTheTransportManager(T,C,_){return new un(T,C,_)}},Da=Us;class Jo{constructor(C){this.options=C||{},this.livesLeft=this.options.lives||1/0}getAssistant(C){return Da.createAssistantToTheTransportManager(this,C,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class Va{constructor(C,_){this.strategies=C,this.loop=!!_.loop,this.failFast=!!_.failFast,this.timeout=_.timeout,this.timeoutLimit=_.timeoutLimit}isSupported(){return Ce(this.strategies,oe.method("isSupported"))}connect(C,_){var I=this.strategies,P=0,he=this.timeout,Ne=null,ze=(Qe,dt)=>{dt?_(null,dt):(P=P+1,this.loop&&(P=P%I.length),P0&&(he=new U(I.timeout,function(){Ne.abort(),P(!0)})),Ne=C.connect(_,function(ze,Qe){ze&&he&&he.isRunning()&&!I.failFast||(he&&he.ensureAborted(),P(ze,Qe))}),{abort:function(){he&&he.ensureAborted(),Ne.abort()},forceMinPriority:function(ze){Ne.forceMinPriority(ze)}}}}class Xo{constructor(C){this.strategies=C}isSupported(){return Ce(this.strategies,oe.method("isSupported"))}connect(C,_){return wi(this.strategies,C,function(I,P){return function(he,Ne){if(P[I].error=he,he){Si(P)&&_(!0);return}Tt(P,function(ze){ze.forceMinPriority(Ne.transport.priority)}),_(null,Ne)}})}}function wi(T,C,_){var I=Xt(T,function(P,he,Ne,ze){return P.connect(C,_(he,ze))});return{abort:function(){Tt(I,Ra)},forceMinPriority:function(P){Tt(I,function(he){he.forceMinPriority(P)})}}}function Si(T){return Ge(T,function(C){return!!C.error})}function Ra(T){!T.error&&!T.aborted&&(T.abort(),T.aborted=!0)}class Hn{constructor(C,_,I){this.strategy=C,this.transports=_,this.ttl=I.ttl||1800*1e3,this.usingTLS=I.useTLS,this.timeline=I.timeline}isSupported(){return this.strategy.isSupported()}connect(C,_){var I=this.usingTLS,P=xh(I),he=P&&P.cacheSkipCount?P.cacheSkipCount:0,Ne=[this.strategy];if(P&&P.timestamp+this.ttl>=oe.now()){var ze=this.transports[P.transport];ze&&(["ws","wss"].includes(P.transport)||he>3?(this.timeline.info({cached:!0,transport:P.transport,latency:P.latency}),Ne.push(new Va([ze],{timeout:P.latency*2+1e3,failFast:!0}))):he++)}var Qe=oe.now(),dt=Ne.pop().connect(C,function yt(Kt,Lr){Kt?(Zo(I),Ne.length>0?(Qe=oe.now(),dt=Ne.pop().connect(C,yt)):_(Kt)):(Qo(I,Lr.transport.name,oe.now()-Qe,he),_(null,Lr))});return{abort:function(){dt.abort()},forceMinPriority:function(yt){C=yt,dt&&dt.forceMinPriority(yt)}}}}function Ci(T){return"pusherTransport"+(T?"TLS":"NonTLS")}function xh(T){var C=Xe.getLocalStorage();if(C)try{var _=C[Ci(T)];if(_)return JSON.parse(_)}catch{Zo(T)}return null}function Qo(T,C,_,I){var P=Xe.getLocalStorage();if(P)try{P[Ci(T)]=Et({timestamp:oe.now(),transport:C,latency:_,cacheSkipCount:I})}catch{}}function Zo(T){var C=Xe.getLocalStorage();if(C)try{delete C[Ci(T)]}catch{}}class gs{constructor(C,{delay:_}){this.strategy=C,this.options={delay:_}}isSupported(){return this.strategy.isSupported()}connect(C,_){var I=this.strategy,P,he=new U(this.options.delay,function(){P=I.connect(C,_)});return{abort:function(){he.ensureAborted(),P&&P.abort()},forceMinPriority:function(Ne){C=Ne,P&&P.forceMinPriority(Ne)}}}}class Tr{constructor(C,_,I){this.test=C,this.trueBranch=_,this.falseBranch=I}isSupported(){var C=this.test()?this.trueBranch:this.falseBranch;return C.isSupported()}connect(C,_){var I=this.test()?this.trueBranch:this.falseBranch;return I.connect(C,_)}}class Pn{constructor(C){this.strategy=C}isSupported(){return this.strategy.isSupported()}connect(C,_){var I=this.strategy.connect(C,function(P,he){he&&I.abort(),_(P,he)});return I}}function hs(T){return function(){return T.isSupported()}}var md=function(T,C,_){var I={};function P(Mr,_d,Ad,ml,yl){var xl=_(T,Mr,_d,Ad,ml,yl);return I[Mr]=xl,xl}var he=Object.assign({},C,{hostNonTLS:T.wsHost+":"+T.wsPort,hostTLS:T.wsHost+":"+T.wssPort,httpPath:T.wsPath}),Ne=Object.assign({},he,{useTLS:!0}),ze=Object.assign({},C,{hostNonTLS:T.httpHost+":"+T.httpPort,hostTLS:T.httpHost+":"+T.httpsPort,httpPath:T.httpPath}),Qe={loop:!0,timeout:15e3,timeoutLimit:6e4},dt=new Jo({minPingDelay:1e4,maxPingDelay:T.activityTimeout}),yt=new Jo({lives:2,minPingDelay:1e4,maxPingDelay:T.activityTimeout}),Kt=P("ws","ws",3,he,dt),Lr=P("wss","ws",3,Ne,dt),kd=P("sockjs","sockjs",1,ze),ul=P("xhr_streaming","xhr_streaming",1,ze,yt),Nd=P("xdr_streaming","xdr_streaming",1,ze,yt),gl=P("xhr_polling","xhr_polling",1,ze),Ws=P("xdr_polling","xdr_polling",1,ze),Ed=new Va([Kt],Qe),Mh=new Va([Lr],Qe),$h=new Va([kd],Qe),hl=new Va([new Tr(hs(ul),ul,Nd)],Qe),fl=new Va([new Tr(hs(gl),gl,Ws)],Qe),Ys=new Va([new Tr(hs(hl),new Xo([hl,new gs(fl,{delay:4e3})]),fl)],Qe),ps=new Tr(hs(Ys),Ys,$h),pl;return C.useTLS?pl=new Xo([Ed,new gs(ps,{delay:2e3})]):pl=new Xo([Ed,new gs(Mh,{delay:2e3}),new gs(ps,{delay:5e3})]),new Hn(new Pn(new Tr(hs(Kt),pl,ps)),I,{ttl:18e5,timeline:C.timeline,useTLS:C.useTLS})},el=md,qs=(function(){var T=this;T.timeline.info(T.buildTimelineMessage({transport:T.name+(T.options.useTLS?"s":"")})),T.hooks.isInitialized()?T.changeState("initialized"):T.hooks.file?(T.changeState("initializing"),y.load(T.hooks.file,{useTLS:T.options.useTLS},function(C,_){T.hooks.isInitialized()?(T.changeState("initialized"),_(!0)):(C&&T.onError(C),T.onClose(),_(!1))})):T.onClose()}),yd={getRequest:function(T){var C=new window.XDomainRequest;return C.ontimeout=function(){T.emit("error",new O),T.close()},C.onerror=function(_){T.emit("error",_),T.close()},C.onprogress=function(){C.responseText&&C.responseText.length>0&&T.onChunk(200,C.responseText)},C.onload=function(){C.responseText&&C.responseText.length>0&&T.onChunk(200,C.responseText),T.emit("finished",200),T.close()},C},abortRequest:function(T){T.ontimeout=T.onerror=T.onprogress=T.onload=null,T.abort()}},xd=yd;const Gs=256*1024;class bh extends Re{constructor(C,_,I){super(),this.hooks=C,this.method=_,this.url=I}start(C){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},Xe.addUnloadListener(this.unloader),this.xhr.open(this.method,this.url,!0),this.xhr.setRequestHeader&&this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.send(C)}close(){this.unloader&&(Xe.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(C,_){for(;;){var I=this.advanceBuffer(_);if(I)this.emit("chunk",{status:C,data:I});else break}this.isBufferTooLong(_)&&this.emit("buffer_too_long")}advanceBuffer(C){var _=C.slice(this.position),I=_.indexOf(` -`);return I!==-1?(this.position+=I+1,_.slice(0,I)):null}isBufferTooLong(C){return this.position===C.length&&C.length>Gs}}var ji;(function(T){T[T.CONNECTING=0]="CONNECTING",T[T.OPEN=1]="OPEN",T[T.CLOSED=3]="CLOSED"})(ji||(ji={}));var Ka=ji,tl=1;class vh{constructor(C,_){this.hooks=C,this.session=Ni(1e3)+"/"+Fs(8),this.location=wh(_),this.readyState=Ka.CONNECTING,this.openStream()}send(C){return this.sendRaw(JSON.stringify([C]))}ping(){this.hooks.sendHeartbeat(this)}close(C,_){this.onClose(C,_,!0)}sendRaw(C){if(this.readyState===Ka.OPEN)try{return Xe.createSocketRequest("POST",da(ki(this.location,this.session))).start(C),!0}catch{return!1}else return!1}reconnect(){this.closeStream(),this.openStream()}onClose(C,_,I){this.closeStream(),this.readyState=Ka.CLOSED,this.onclose&&this.onclose({code:C,reason:_,wasClean:I})}onChunk(C){if(C.status===200){this.readyState===Ka.OPEN&&this.onActivity();var _,I=C.data.slice(0,1);switch(I){case"o":_=JSON.parse(C.data.slice(1)||"{}"),this.onOpen(_);break;case"a":_=JSON.parse(C.data.slice(1)||"[]");for(var P=0;P<_.length;P++)this.onEvent(_[P]);break;case"m":_=JSON.parse(C.data.slice(1)||"null"),this.onEvent(_);break;case"h":this.hooks.onHeartbeat(this);break;case"c":_=JSON.parse(C.data.slice(1)||"[]"),this.onClose(_[0],_[1],!0);break}}}onOpen(C){this.readyState===Ka.CONNECTING?(C&&C.hostname&&(this.location.base=nl(this.location.base,C.hostname)),this.readyState=Ka.OPEN,this.onopen&&this.onopen()):this.onClose(1006,"Server lost session",!0)}onEvent(C){this.readyState===Ka.OPEN&&this.onmessage&&this.onmessage({data:C})}onActivity(){this.onactivity&&this.onactivity()}onError(C){this.onerror&&this.onerror(C)}openStream(){this.stream=Xe.createSocketRequest("POST",da(this.hooks.getReceiveURL(this.location,this.session))),this.stream.bind("chunk",C=>{this.onChunk(C)}),this.stream.bind("finished",C=>{this.hooks.onFinished(this,C)}),this.stream.bind("buffer_too_long",()=>{this.reconnect()});try{this.stream.start()}catch(C){oe.defer(()=>{this.onError(C),this.onClose(1006,"Could not start streaming",!1)})}}closeStream(){this.stream&&(this.stream.unbind_all(),this.stream.close(),this.stream=null)}}function wh(T){var C=/([^\?]*)\/*(\??.*)/.exec(T);return{base:C[1],queryString:C[2]}}function ki(T,C){return T.base+"/"+C+"/xhr_send"}function da(T){var C=T.indexOf("?")===-1?"?":"&";return T+C+"t="+ +new Date+"&n="+tl++}function nl(T,C){var _=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(T);return _[1]+C+_[3]}function Ni(T){return Xe.randomInt(T)}function Fs(T){for(var C=[],_=0;_0&&T.onChunk(_.status,_.responseText);break;case 4:_.responseText&&_.responseText.length>0&&T.onChunk(_.status,_.responseText),T.emit("finished",_.status),T.close();break}},_},abortRequest:function(T){T.onreadystatechange=null,T.abort()}},sl=Oa,Rr={createStreamingSocket(T){return this.createSocket(al,T)},createPollingSocket(T){return this.createSocket(Dr,T)},createSocket(T,C){return new Vs(T,C)},createXHR(T,C){return this.createRequest(sl,T,C)},createRequest(T,C,_){return new bh(T,C,_)}},La=Rr;La.createXDR=function(T,C){return this.createRequest(xd,T,C)};var rl=La,Ei={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:d,DependenciesReceivers:p,getDefaultStrategy:el,Transports:Xn,transportConnectionInitializer:qs,HTTPFactory:rl,TimelineTransport:Ta,getXHRAPI(){return window.XMLHttpRequest},getWebSocketAPI(){return window.WebSocket||window.MozWebSocket},setup(T){window.Pusher=T;var C=()=>{this.onDocumentBody(T.ready)};window.JSON?C():y.load("json2",{},C)},getDocument(){return document},getProtocol(){return this.getDocument().location.protocol},getAuthorizers(){return{ajax:we,jsonp:wt}},onDocumentBody(T){document.body?T():setTimeout(()=>{this.onDocumentBody(T)},0)},createJSONPRequest(T,C){return new qt(T,C)},createScriptRequest(T){return new At(T)},getLocalStorage(){try{return window.localStorage}catch{return}},createXHR(){return this.getXHRAPI()?this.createXMLHttpRequest():this.createMicrosoftXHR()},createXMLHttpRequest(){var T=this.getXHRAPI();return new T},createMicrosoftXHR(){return new ActiveXObject("Microsoft.XMLHTTP")},getNetwork(){return In},createWebSocket(T){var C=this.getWebSocketAPI();return new C(T)},createSocketRequest(T,C){if(this.isXHRSupported())return this.HTTPFactory.createXHR(T,C);if(this.isXDRSupported(C.indexOf("https:")===0))return this.HTTPFactory.createXDR(T,C);throw"Cross-origin HTTP requests are not supported"},isXHRSupported(){var T=this.getXHRAPI();return!!T&&new T().withCredentials!==void 0},isXDRSupported(T){var C=T?"https:":"http:",_=this.getProtocol();return!!window.XDomainRequest&&_===C},addUnloadListener(T){window.addEventListener!==void 0?window.addEventListener("unload",T,!1):window.attachEvent!==void 0&&window.attachEvent("onunload",T)},removeUnloadListener(T){window.addEventListener!==void 0?window.removeEventListener("unload",T,!1):window.detachEvent!==void 0&&window.detachEvent("onunload",T)},randomInt(T){return Math.floor(function(){return(window.crypto||window.msCrypto).getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}()*T)}},Xe=Ei,Ks;(function(T){T[T.ERROR=3]="ERROR",T[T.INFO=6]="INFO",T[T.DEBUG=7]="DEBUG"})(Ks||(Ks={}));var fs=Ks;class wd{constructor(C,_,I){this.key=C,this.session=_,this.events=[],this.options=I||{},this.sent=0,this.uniqueID=0}log(C,_){C<=this.options.level&&(this.events.push(ke({},_,{timestamp:oe.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(C){this.log(fs.ERROR,C)}info(C){this.log(fs.INFO,C)}debug(C){this.log(fs.DEBUG,C)}isEmpty(){return this.events.length===0}send(C,_){var I=ke({session:this.session,bundle:this.sent+1,key:this.key,lib:"js",version:this.options.version,cluster:this.options.cluster,features:this.options.features,timeline:this.events},this.options.params);return this.events=[],C(I,(P,he)=>{P||this.sent++,_&&_(P,he)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class En{constructor(C,_,I,P){this.name=C,this.priority=_,this.transport=I,this.options=P||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(C,_){if(this.isSupported()){if(this.priority{I||(yt(),he?he.close():P.close())},forceMinPriority:Kt=>{I||this.priority{var _="socket_id="+encodeURIComponent(T.socketId);for(var I in C.params)_+="&"+encodeURIComponent(I)+"="+encodeURIComponent(C.params[I]);if(C.paramsProvider!=null){let P=C.paramsProvider();for(var I in P)_+="&"+encodeURIComponent(I)+"="+encodeURIComponent(P[I])}return _};var Ti=T=>{if(typeof Xe.getAuthorizers()[T.transport]>"u")throw`'${T.transport}' is not a recognized auth transport`;return(C,_)=>{const I=ol(C,T);Xe.getAuthorizers()[T.transport](Xe,I,T,w.UserAuthentication,_)}};const Sd=(T,C)=>{var _="socket_id="+encodeURIComponent(T.socketId);_+="&channel_name="+encodeURIComponent(T.channelName);for(var I in C.params)_+="&"+encodeURIComponent(I)+"="+encodeURIComponent(C.params[I]);if(C.paramsProvider!=null){let P=C.paramsProvider();for(var I in P)_+="&"+encodeURIComponent(I)+"="+encodeURIComponent(P[I])}return _};var Ch=T=>{if(typeof Xe.getAuthorizers()[T.transport]>"u")throw`'${T.transport}' is not a recognized auth transport`;return(C,_)=>{const I=Sd(C,T);Xe.getAuthorizers()[T.transport](Xe,I,T,w.ChannelAuthorization,_)}};const jh=(T,C,_)=>{const I={authTransport:C.transport,authEndpoint:C.endpoint,auth:{params:C.params,headers:C.headers}};return(P,he)=>{const Ne=T.channel(P.channelName);_(Ne,I).authorize(P.socketId,he)}};function ll(T,C){let _={activityTimeout:T.activityTimeout||h.activityTimeout,cluster:T.cluster,httpPath:T.httpPath||h.httpPath,httpPort:T.httpPort||h.httpPort,httpsPort:T.httpsPort||h.httpsPort,pongTimeout:T.pongTimeout||h.pongTimeout,statsHost:T.statsHost||h.stats_host,unavailableTimeout:T.unavailableTimeout||h.unavailableTimeout,wsPath:T.wsPath||h.wsPath,wsPort:T.wsPort||h.wsPort,wssPort:T.wssPort||h.wssPort,enableStats:Ah(T),httpHost:kh(T),useTLS:_h(T),wsHost:Nh(T),userAuthenticator:Cd(T),channelAuthorizer:Dh(T,C)};return"disabledTransports"in T&&(_.disabledTransports=T.disabledTransports),"enabledTransports"in T&&(_.enabledTransports=T.enabledTransports),"ignoreNullOrigin"in T&&(_.ignoreNullOrigin=T.ignoreNullOrigin),"timelineParams"in T&&(_.timelineParams=T.timelineParams),"nacl"in T&&(_.nacl=T.nacl),_}function kh(T){return T.httpHost?T.httpHost:T.cluster?`sockjs-${T.cluster}.pusher.com`:h.httpHost}function Nh(T){return T.wsHost?T.wsHost:Eh(T.cluster)}function Eh(T){return`ws-${T}.pusher.com`}function _h(T){return Xe.getProtocol()==="https:"?!0:T.forceTLS!==!1}function Ah(T){return"enableStats"in T?T.enableStats:"disableStats"in T?!T.disableStats:!1}function Cd(T){const C=Object.assign(Object.assign({},h.userAuthentication),T.userAuthentication);return"customHandler"in C&&C.customHandler!=null?C.customHandler:Ti(C)}function Th(T,C){let _;return"channelAuthorization"in T?_=Object.assign(Object.assign({},h.channelAuthorization),T.channelAuthorization):(_={transport:T.authTransport||h.authTransport,endpoint:T.authEndpoint||h.authEndpoint},"auth"in T&&("params"in T.auth&&(_.params=T.auth.params),"headers"in T.auth&&(_.headers=T.auth.headers)),"authorizer"in T&&(_.customHandler=jh(C,_,T.authorizer))),_}function Dh(T,C){const _=Th(T,C);return"customHandler"in _&&_.customHandler!=null?_.customHandler:Ch(_)}class Rh extends Re{constructor(C){super(function(_,I){tt.debug(`No callbacks on watchlist events for ${_}`)}),this.pusher=C,this.bindWatchlistInternalEvent()}handleEvent(C){C.data.events.forEach(_=>{this.emit(_.name,_)})}bindWatchlistInternalEvent(){this.pusher.connection.bind("message",C=>{var _=C.event;_==="pusher_internal:watchlist_events"&&this.handleEvent(C)})}}function Oh(){let T,C;return{promise:new Promise((I,P)=>{T=I,C=P}),resolve:T,reject:C}}var cl=Oh;class Lh extends Re{constructor(C){super(function(_,I){tt.debug("No callbacks on user for "+_)}),this.signin_requested=!1,this.user_data=null,this.serverToUserChannel=null,this.signinDonePromise=null,this._signinDoneResolve=null,this._onAuthorize=(_,I)=>{if(_){tt.warn(`Error during signin: ${_}`),this._cleanup();return}this.pusher.send_event("pusher:signin",{auth:I.auth,user_data:I.user_data})},this.pusher=C,this.pusher.connection.bind("state_change",({previous:_,current:I})=>{_!=="connected"&&I==="connected"&&this._signin(),_==="connected"&&I!=="connected"&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new Rh(C),this.pusher.connection.bind("message",_=>{var I=_.event;I==="pusher:signin_success"&&this._onSigninSuccess(_.data),this.serverToUserChannel&&this.serverToUserChannel.name===_.channel&&this.serverToUserChannel.handleEvent(_)})}signin(){this.signin_requested||(this.signin_requested=!0,this._signin())}_signin(){this.signin_requested&&(this._newSigninPromiseIfNeeded(),this.pusher.connection.state==="connected"&&this.pusher.config.userAuthenticator({socketId:this.pusher.connection.socket_id},this._onAuthorize))}_onSigninSuccess(C){try{this.user_data=JSON.parse(C.user_data)}catch{tt.error(`Failed parsing user data after signin: ${C.user_data}`),this._cleanup();return}if(typeof this.user_data.id!="string"||this.user_data.id===""){tt.error(`user_data doesn't contain an id. user_data: ${this.user_data}`),this._cleanup();return}this._signinDoneResolve(),this._subscribeChannels()}_subscribeChannels(){const C=_=>{_.subscriptionPending&&_.subscriptionCancelled?_.reinstateSubscription():!_.subscriptionPending&&this.pusher.connection.state==="connected"&&_.subscribe()};this.serverToUserChannel=new vi(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((_,I)=>{_.indexOf("pusher_internal:")===0||_.indexOf("pusher:")===0||this.emit(_,I)}),C(this.serverToUserChannel)}_cleanup(){this.user_data=null,this.serverToUserChannel&&(this.serverToUserChannel.unbind_all(),this.serverToUserChannel.disconnect(),this.serverToUserChannel=null),this.signin_requested&&this._signinDoneResolve()}_newSigninPromiseIfNeeded(){if(!this.signin_requested||this.signinDonePromise&&!this.signinDonePromise.done)return;const{promise:C,resolve:_}=cl();C.done=!1;const I=()=>{C.done=!0};C.then(I).catch(I),this.signinDonePromise=C,this._signinDoneResolve=_}}class gn{static ready(){gn.isReady=!0;for(var C=0,_=gn.instances.length;C<_;C++)gn.instances[C].connect()}static getClientFeatures(){return Ie(It({ws:Xe.Transports.ws},function(C){return C.isSupported({})}))}constructor(C,_){jd(C),il(_),this.key=C,this.config=ll(_,this),this.channels=Da.createChannels(),this.global_emitter=new Re,this.sessionID=Xe.randomInt(1e9),this.timeline=new wd(this.key,this.sessionID,{cluster:this.config.cluster,features:gn.getClientFeatures(),params:this.config.timelineParams||{},limit:50,level:fs.INFO,version:h.VERSION}),this.config.enableStats&&(this.timelineSender=Da.createTimelineSender(this.timeline,{host:this.config.statsHost,path:"/timeline/v2/"+Xe.TimelineTransport.name}));var I=P=>Xe.getDefaultStrategy(this.config,P,Or);this.connection=Da.createConnectionManager(this.key,{getStrategy:I,timeline:this.timeline,activityTimeout:this.config.activityTimeout,pongTimeout:this.config.pongTimeout,unavailableTimeout:this.config.unavailableTimeout,useTLS:!!this.config.useTLS}),this.connection.bind("connected",()=>{this.subscribeAll(),this.timelineSender&&this.timelineSender.send(this.connection.isUsingTLS())}),this.connection.bind("message",P=>{var he=P.event,Ne=he.indexOf("pusher_internal:")===0;if(P.channel){var ze=this.channel(P.channel);ze&&ze.handleEvent(P)}Ne||this.global_emitter.emit(P.event,P.data)}),this.connection.bind("connecting",()=>{this.channels.disconnect()}),this.connection.bind("disconnected",()=>{this.channels.disconnect()}),this.connection.bind("error",P=>{tt.warn(P)}),gn.instances.push(this),this.timeline.info({instances:gn.instances.length}),this.user=new Lh(this),gn.isReady&&this.connect()}channel(C){return this.channels.find(C)}allChannels(){return this.channels.all()}connect(){if(this.connection.connect(),this.timelineSender&&!this.timelineSenderTimer){var C=this.connection.isUsingTLS(),_=this.timelineSender;this.timelineSenderTimer=new re(6e4,function(){_.send(C)})}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(C,_,I){return this.global_emitter.bind(C,_,I),this}unbind(C,_,I){return this.global_emitter.unbind(C,_,I),this}bind_global(C){return this.global_emitter.bind_global(C),this}unbind_global(C){return this.global_emitter.unbind_global(C),this}unbind_all(C){return this.global_emitter.unbind_all(),this}subscribeAll(){var C;for(C in this.channels.channels)this.channels.channels.hasOwnProperty(C)&&this.subscribe(C)}subscribe(C){var _=this.channels.add(C,this);return _.subscriptionPending&&_.subscriptionCancelled?_.reinstateSubscription():!_.subscriptionPending&&this.connection.state==="connected"&&_.subscribe(),_}unsubscribe(C){var _=this.channels.find(C);_&&_.subscriptionPending?_.cancelSubscription():(_=this.channels.remove(C),_&&_.subscribed&&_.unsubscribe())}send_event(C,_,I){return this.connection.send_event(C,_,I)}shouldUseTLS(){return this.config.useTLS}signin(){this.user.signin()}}gn.instances=[],gn.isReady=!1,gn.logToConsole=!1,gn.Runtime=Xe,gn.ScriptReceivers=Xe.ScriptReceivers,gn.DependenciesReceivers=Xe.DependenciesReceivers,gn.auth_callbacks=Xe.auth_callbacks;var dl=a.default=gn;function jd(T){if(T==null)throw"You must pass your app key when you instantiate Pusher."}Xe.setup(gn)})])})})(Ig)),Ig.exports}var Uj=Bj();const Yy=es(Uj),Ft=it("WebSocketManager");class qj{constructor(){H(this,"echo",null);H(this,"subscriptions",new Map);H(this,"initialized",!1);H(this,"config",null)}configure(e){if(this.initialized){Ft.warn("[WebSocketManager] 이미 초기화되어 설정을 변경할 수 없습니다.");return}this.config=e,Ft.log("[WebSocketManager] 설정 완료:",{appKey:e.appKey?"***":"(없음)",host:e.host,port:e.port,scheme:e.scheme})}initialize(){if(this.initialized)return;if(!this.config||!this.config.appKey){Ft.warn("[WebSocketManager] WebSocket 설정이 없습니다. initTemplateApp에서 websocket 옵션을 전달해주세요.");return}const{appKey:e,host:t="localhost",port:a=80,scheme:i="https",authEndpoint:o="/api/broadcasting/auth"}=this.config,d=Number(a)||80,g=i==="https";Ft.log("[WebSocketManager] 연결 설정:",{host:t,port:d,scheme:i,useTLS:g,authEndpoint:o}),window.Pusher=Yy;const h=localStorage.getItem("auth_token"),f={wsHost:t,wsPort:d,wssPort:d,forceTLS:g,disableStats:!0,enabledTransports:["ws","wss"],cluster:"mt1",authEndpoint:o,auth:{headers:{Authorization:h?`Bearer ${h}`:"",Accept:"application/json"}}};Ft.log("[WebSocketManager] Pusher 옵션:",f);const p=new Yy(e,f);p.connection.bind("connecting",()=>{Ft.log("[WebSocketManager] 연결 시도 중...")}),p.connection.bind("connected",()=>{Ft.log("[WebSocketManager] 연결 성공! Socket ID:",p.connection.socket_id)}),p.connection.bind("failed",()=>{Ft.error("[WebSocketManager] 연결 실패 - WebSocket을 사용할 수 없습니다.")}),p.connection.bind("error",y=>{Ft.error("[WebSocketManager] 연결 오류:",y)}),p.connection.bind("state_change",y=>{Ft.log(`[WebSocketManager] 상태 변경: ${y.previous} → ${y.current}`)}),p.connection.bind("unavailable",()=>{Ft.error("[WebSocketManager] WebSocket 사용 불가 - 연결할 수 없습니다.")}),p.connection.bind("disconnected",()=>{Ft.warn("[WebSocketManager] 연결이 끊어졌습니다.")}),Ft.log("[WebSocketManager] 초기 연결 상태:",p.connection.state),this.echo=new Pj({broadcaster:"reverb",client:p}),Ft.log("[WebSocketManager] 연결 시작 시도..."),p.connect(),window.Echo=this.echo,this.initialized=!0,Ft.log("[WebSocketManager] Echo 초기화 완료")}subscribe(e,t,a,i={}){if(this.initialize(),!this.echo)return Ft.warn("[WebSocketManager] Echo가 초기화되지 않았습니다."),"";const{channelType:o="private"}=i,d=`${e}:${t}`;if(this.subscriptions.has(d))return Ft.log(`[WebSocketManager] 이미 구독 중: ${d}`),d;let g;switch(o){case"public":g=this.echo.channel(e);break;case"presence":g=this.echo.join(e);break;default:g=this.echo.private(e)}return g.listen(`.${t}`,a),this.subscriptions.set(d,g),Ft.log(`[WebSocketManager] 구독 완료: ${d} (${o})`),d}unsubscribe(e){const t=this.subscriptions.get(e);if(!t)return;const a=e.lastIndexOf(":"),i=a>=0?e.substring(a+1):"";if(i)try{t.stopListening(`.${i}`)}catch(o){Ft.warn(`[WebSocketManager] stopListening 실패: ${e}`,o)}this.subscriptions.delete(e),Ft.log(`[WebSocketManager] 구독 해제: ${e}`)}leaveChannel(e){if(!this.echo)return;this.echo.leave(e);const t=[];this.subscriptions.forEach((a,i)=>{i.startsWith(`${e}:`)&&t.push(i)}),t.forEach(a=>this.subscriptions.delete(a)),Ft.log(`[WebSocketManager] 채널 구독 해제: ${e}`)}disconnect(){this.echo&&(this.echo.disconnect(),this.subscriptions.clear(),this.initialized=!1,Ft.log("[WebSocketManager] 연결 종료"))}getEcho(){return this.echo}isInitialized(){return this.initialized}isConfigured(){return this.config!==null&&!!this.config.appKey}getSubscriptionCount(){return this.subscriptions.size}}const Lc=new qj,kt=it("DataSourceManager"),Gj=new _n;function Mc(r,e){const t=r.match(/^\{\{(.+)\}\}$/);if(t){const a=t[1].trim();try{return Gj.evaluateExpression(a,e)}catch(i){return kt.error("Failed to evaluate param expression:",a,i),r}}return ni(r,e,{skipCache:!0})}function Jy(r){const e={};for(const t of r.keys()){if(t in e)continue;const a=r.getAll(t);a.length>1?e[t]=a:a.length===1&&(t.endsWith("[]")?e[t]=a:e[t]=a[0])}return e}function Fj(){try{return window.G7Core?.devTools}catch{return}}const hd=class hd{constructor(e={}){H(this,"options");H(this,"dataCache",new Map);H(this,"bindingEngine");H(this,"globalHeaders",[]);this.options=e,this.bindingEngine=new _n}setGlobalHeaders(e){this.globalHeaders=e||[]}matchesPattern(e,t){if(t==="*")return!0;const a=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${a}$`).test(e)}toFormData(e){const t=new FormData;for(const[a,i]of Object.entries(e))i instanceof File||i instanceof Blob?t.append(a,i):i!=null&&t.append(a,typeof i=="object"?JSON.stringify(i):String(i));return t}getMatchingGlobalHeaders(e,t){const a={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([o,d])=>{const g=Mc(d,t);g!=null&&g!==""&&(a[o]=String(g))});return a}filterByCondition(e,t={}){const a=new Set,i=[];for(const o of e){if(a.has(o.id))continue;if(!o.if&&!o.conditions){a.add(o.id),i.push(o);continue}ti({if:o.if,conditions:o.conditions},t,this.bindingEngine,`data_source:${o.id}`)&&(a.add(o.id),i.push(o))}return i}checkErrorCondition(e,t){if(!e.errorCondition?.if||e.errorCondition?.errorCode===void 0)return null;try{const a={response:t};if(ti({if:e.errorCondition.if},a,this.bindingEngine,`errorCondition:${e.id}`))return kt.log(`errorCondition matched for ${e.id}, triggering error ${e.errorCondition.errorCode}`),e.errorCondition.errorCode}catch(a){kt.error(`Failed to evaluate errorCondition for ${e.id}:`,a)}return null}async fetchDataSources(e,t={},a=new URLSearchParams,i,o){const d={},g=e.filter(h=>h.auto_fetch!==!1&&h.type!=="websocket");return await Promise.all(g.map(async h=>{try{const f=await this.fetchDataSource(h,t,a,i,o);d[h.id]=f,this.dataCache.set(h.id,{data:f,timestamp:Date.now()});const p=this.checkErrorCondition(h,f);if(p!==null){const y={status:p,message:`Error condition matched for ${h.id}`,data:f},x=Sa(),S=x.resolve(p,{errorHandling:h.errorHandling,onError:h.onError});if(S.handler)try{await x.execute(S.handler,y)}catch(v){kt.error(`Error executing errorCondition handler for ${h.id}:`,v)}h.fallback!==void 0&&(d[h.id]=h.fallback,this.dataCache.set(h.id,{data:h.fallback,timestamp:Date.now()}),kt.log(`Using fallback data for ${h.id} (errorCondition)`));return}if(h.onSuccess)try{const y={data:f,sourceId:h.id};await this.executeOnSuccessHandler(h.onSuccess,y)}catch(y){kt.error(`Error executing onSuccess handler for ${h.id}:`,y)}}catch(f){kt.error(`Failed to fetch data source: ${h.id}`,f);const p=f?.response?.status||f?.status||500,y=f?.response?.data,x=y?.message||f.message||"Unknown error",S={status:p,message:x,errors:y?.errors,data:y,statusText:f?.response?.statusText},v=Sa(),w=v.resolve(p,{errorHandling:h.errorHandling,onError:h.onError});if(w.handler)try{await v.execute(w.handler,S)}catch(k){kt.error(`Error executing error handler for ${h.id}:`,k)}h.fallback!==void 0&&(d[h.id]=h.fallback,this.dataCache.set(h.id,{data:h.fallback,timestamp:Date.now()}),kt.log(`Using fallback data for ${h.id}`)),this.options.onError&&this.options.onError(f,h)}})),d}async fetchDataSourcesWithResults(e,t={},a=new URLSearchParams,i,o,d){if(e.some(p=>p.type==="websocket")){const p=e.filter(y=>y.type==="websocket").map(y=>y.id).join(", ");kt.warn(`fetchDataSourcesWithResults received WebSocket sources (caller should filter them out before calling): ${p}. WebSocket sources are event listeners, not data providers — they should not be passed to fetch.`)}const h=d?.ignoreAutoFetch?e.filter(p=>p.type!=="websocket"):e.filter(p=>p.auto_fetch!==!1&&p.type!=="websocket");return await Promise.all(h.map(async p=>{try{const y=await this.fetchDataSource(p,t,a,i,o);this.dataCache.set(p.id,{data:y,timestamp:Date.now()});const x=this.checkErrorCondition(p,y);if(x!==null){const S={status:x,message:`Error condition matched for ${p.id}`,data:y},v=Sa(),w=v.resolve(x,{errorHandling:p.errorHandling,onError:p.onError});let k=!1;if(w.handler)if(p.loading_strategy==="blocking")v.execute(w.handler,S).catch(A=>{kt.error(`Error executing errorCondition handler for ${p.id}:`,A)}),k=!0;else try{await v.execute(w.handler,S),k=!0}catch(A){kt.error(`Error executing errorCondition handler for ${p.id}:`,A)}return p.fallback!==void 0?(this.dataCache.set(p.id,{data:p.fallback,timestamp:Date.now()}),kt.log(`Using fallback data for ${p.id} (errorCondition)`),{id:p.id,state:"success",data:p.fallback}):{id:p.id,state:"error",error:new Error(`Error condition matched: ${x}`),errorCode:x,errorHandled:k}}if(p.onSuccess)try{const S={data:y,sourceId:p.id};await this.executeOnSuccessHandler(p.onSuccess,S)}catch(S){kt.error(`Error executing onSuccess handler for ${p.id}:`,S)}return{id:p.id,state:"success",data:y}}catch(y){kt.error(`Failed to fetch data source: ${p.id}`,y);const x=y?.response?.status||y?.status||500,S=y?.response?.data,v=S?.message||y.message||"Unknown error",w={status:x,message:v,errors:S?.errors,data:S,statusText:y?.response?.statusText},k=Sa(),A=k.resolve(x,{errorHandling:p.errorHandling,onError:p.onError});let O=!1;if(A.handler)if(p.loading_strategy==="blocking")k.execute(A.handler,w).catch(N=>{kt.error(`Error executing error handler for ${p.id}:`,N)}),O=!0;else try{await k.execute(A.handler,w),O=!0}catch(N){kt.error(`Error executing error handler for ${p.id}:`,N)}return p.fallback!==void 0?(this.dataCache.set(p.id,{data:p.fallback,timestamp:Date.now()}),kt.log(`Using fallback data for ${p.id}`),{id:p.id,state:"success",data:p.fallback}):(this.options.onError&&this.options.onError(y,p),{id:p.id,state:"error",error:y,errorCode:x,errorHandled:O})}}))}fetchDataSourcesInBackground(e,t={},a=new URLSearchParams,i){e.filter(d=>d.auto_fetch!==!1&&d.loading_strategy==="background"&&d.type!=="websocket").forEach(d=>{this.fetchDataSource(d,t,a).then(async g=>{this.dataCache.set(d.id,{data:g,timestamp:Date.now()});const h=this.checkErrorCondition(d,g);if(h!==null){const f={status:h,message:`Error condition matched for ${d.id}`,data:g},p=Sa(),y=p.resolve(h,{errorHandling:d.errorHandling,onError:d.onError});if(y.handler)try{await p.execute(y.handler,f)}catch(x){kt.error(`Error executing errorCondition handler for ${d.id}:`,x)}d.fallback!==void 0&&(this.dataCache.set(d.id,{data:d.fallback,timestamp:Date.now()}),kt.log(`Using fallback data for ${d.id} (errorCondition)`),i&&i(d.id,d.fallback));return}if(d.onSuccess)try{const f={data:g,sourceId:d.id};await this.executeOnSuccessHandler(d.onSuccess,f)}catch(f){kt.error(`Error executing onSuccess handler for ${d.id}:`,f)}i&&i(d.id,g)}).catch(async g=>{kt.error(`Background fetch failed: ${d.id}`,g);const h=g?.response?.status||g?.status||500,f=g?.response?.data,p=f?.message||g.message||"Unknown error",y={status:h,message:p,errors:f?.errors,data:f,statusText:g?.response?.statusText},x=Sa(),S=x.resolve(h,{errorHandling:d.errorHandling,onError:d.onError});if(S.handler)try{await x.execute(S.handler,y)}catch(v){kt.error(`Error executing error handler for ${d.id}:`,v)}if(d.fallback!==void 0){this.dataCache.set(d.id,{data:d.fallback,timestamp:Date.now()}),kt.log(`Using fallback data for ${d.id}`),i&&i(d.id,d.fallback);return}this.options.onError&&this.options.onError(g,d)})})}async fetchDataSource(e,t,a,i,o){switch(e.type){case"api":return this.fetchApiDataSource(e,t,a,i,o);case"static":return e.data;case"route_params":return t;case"query_params":return Jy(a);default:throw new Error(`Unknown data source type: ${e.type}`)}}async fetchApiDataSource(e,t,a,i,o){if(!e.endpoint)throw new Error(`API data source ${e.id} has no endpoint`);const d={route:t,query:Jy(a)};i&&(d._global=i),o&&(d._local=o);let g=ni(e.endpoint,d,{skipCache:!0});const h=e.method||"GET",p=(e.contentType?typeof e.contentType=="string"&&e.contentType.includes("{{")?ni(e.contentType,d,{skipCache:!0}):e.contentType:"application/json")==="multipart/form-data";let y=p?{...e.params||{}}:JSON.parse(JSON.stringify(e.params||{}));Object.entries(y).forEach(([v,w])=>{typeof w=="string"&&(y[v]=Mc(w,d))}),Object.keys(y).forEach(v=>{y[v]===""&&delete y[v]});const x=Fj();let S=null;if(x?.isEnabled()){x.trackDataSourceDefinition({id:e.id,type:e.type,endpoint:g,method:h,autoFetch:e.auto_fetch,initLocal:e.initLocal,initGlobal:e.initGlobal});let v=g;if(h==="GET"&&Object.keys(y).length>0){const w=new URLSearchParams;Object.entries(y).forEach(([A,O])=>{Array.isArray(O)?O.forEach(N=>w.append(A,String(N))):O!=null&&w.append(A,String(O))});const k=w.toString();v=k?`${g}?${k}`:g}S=x.trackRequest(v,h,{requestBody:h!=="GET"?y:void 0,dataSourceId:e.id}),x.trackDataSourceLoading(e.id)}try{let v;const w=e.auth_mode??(e.auth_required===!0?"required":"none"),k=as.getInstance().isAuthenticated();if(w==="required"&&!k){kt.log(`[DataSourceManager] Skipping ${e.id}: auth_mode is 'required' but no token available`),x?.isEnabled()&&(x.trackDataSourceError(e.id,"Skipped: auth_mode required but not authenticated"),S&&x.failRequest(S,"Skipped: not authenticated"));const O=new Error("Auth required but not authenticated");throw O.response={status:401,statusText:"Unauthorized",data:null},O.status=401,O._authSkipped=!0,O}const A=w==="required"||w==="optional"&&k;if(A){const O=ns(),N=g.startsWith("/api/")?g.substring(4):g.startsWith("/api")?g.substring(4)||"/":g;this.options.onError&&kt.log(`[DataSourceManager] Normalized endpoint: ${g} -> ${N}`);const D=this.getMatchingGlobalHeaders(g,d),$={};e.headers&&Object.entries(e.headers).forEach(([pe,we])=>{const J=Mc(we,d);J!=null&&J!==""&&($[pe]=String(J))});const M={...D,...$},z=Object.keys(M).length>0,K=p?this.toFormData(y):y;switch(h){case"GET":v=await O.get(N,{params:y,...z&&{headers:M}});break;case"POST":z?v=await O.post(N,K,{headers:M}):v=await O.post(N,K);break;case"PUT":z?v=await O.put(N,K,{headers:M}):v=await O.put(N,K);break;case"PATCH":z?v=await O.patch(N,K,{headers:M}):v=await O.patch(N,K);break;case"DELETE":v=await O.delete(N,{params:y,...z&&{headers:M}});break;default:throw new Error(`Unsupported HTTP method: ${h}`)}}else{let O=g;if(h==="GET"){const K=new URLSearchParams(y).toString();O=K?`${g}?${K}`:g}const N={...p?{}:{"Content-Type":"application/json"},Accept:"application/json"};if(typeof window<"u"){const K=localStorage.getItem("g7_locale");K&&(N["Accept-Language"]=K)}const D=this.getMatchingGlobalHeaders(g,d);Object.assign(N,D),e.headers&&Object.entries(e.headers).forEach(([K,pe])=>{const we=Mc(pe,d);we!=null&&we!==""&&(N[K]=String(we))});let $;h!=="GET"&&(p?($=this.toFormData(y),delete N["Content-Type"]):$=JSON.stringify(y));const M=await fetch(O,{method:h,headers:N,body:$});let z;try{z=await M.json()}catch{z=null}if(S&&x?.isEnabled()&&(x.completeRequest(S,M.status,z),S=null),!M.ok){x?.isEnabled()&&x.trackDataSourceError(e.id,`HTTP ${M.status}: ${M.statusText}`);const K=new Error(`HTTP error! status: ${M.status}`);throw K.response={status:M.status,statusText:M.statusText,data:z},K.status=M.status,K}v=z,x?.isEnabled()&&x.trackDataSourceLoaded(e.id,v)}return A&&S&&x?.isEnabled()&&(x.completeRequest(S,200,v),x.trackDataSourceLoaded(e.id,v)),v}catch(v){if(S&&x?.isEnabled()){const w=v;w?.response?x.completeRequest(S,w.response.status,w.response.data):x.failRequest(S,v instanceof Error?v.message:String(v)),x.trackDataSourceError(e.id,v instanceof Error?v.message:String(v))}throw v}}getCachedData(e){const t=this.dataCache.get(e);if(!t)return;if(Date.now()-t.timestamp>hd.DATA_CACHE_TTL){this.dataCache.delete(e);return}return t.data}clearCache(){this.dataCache.clear()}subscribeWebSockets(e,t,a={}){const i=[],o=e.filter(d=>d.type==="websocket");return o.length===0||o.forEach(d=>{if(!d.channel||!d.event){kt.warn(`WebSocket source ${d.id} missing channel or event`);return}let g,h;try{g=ni(d.channel,a,{skipCache:!0}),h=ni(d.event,a,{skipCache:!0})}catch(y){kt.error(`Failed to resolve WebSocket channel/event for source ${d.id}:`,y);return}const f=y=>!!(!y||y.trim()===""||y.includes("{{")||y.endsWith(".")||y.endsWith(":")||y.startsWith(".")||y.startsWith(":")||y.includes("..")||y.includes("::"));if(f(g)||f(h)){kt.warn(`WebSocket source ${d.id} has invalid channel/event after expression resolution, skipping. Original channel="${d.channel}", resolved="${g}". Original event="${d.event}", resolved="${h}". Available context keys: [${Object.keys(a).join(", ")}]`);return}const p=Lc.subscribe(g,h,y=>{const x=d.target_source||d.id;this.dataCache.set(x,{data:y,timestamp:Date.now()}),t(x,y)},{channelType:d.channel_type||"private"});p&&i.push(p)}),i}unsubscribeWebSockets(e){e.length!==0&&e.forEach(t=>{Lc.unsubscribe(t)})}async executeOnSuccessHandler(e,t){const a=Fm();if(!a){kt.warn("ActionDispatcher not available, skipping onSuccess handler");return}const i=Array.isArray(e)?e:[e];for(const o of i)try{await a.dispatchAction({type:"click",...o},{data:{response:t}})}catch(d){throw kt.error("Failed to execute onSuccess handler:",d),d}}};H(hd,"DATA_CACHE_TTL",3e5);let is=hd;new is;const Sr=it("ModalDataSourceWrapper");function Vj(r,e){if(!r||!e)return r;const a=e.replace(/\?\./g,".").split(/\.(?![^\[]*\])/).flatMap(o=>{const d=o.match(/^([^\[]*)((?:\[\d+\])*)$/);if(d){const[,g,h]=d,f=[];g&&f.push(g);const p=h.match(/\[\d+\]/g);return p&&f.push(...p),f}return[o]}).filter(o=>o!=="");let i=r;for(const o of a){if(i==null)return;if(o.startsWith("[")&&o.endsWith("]")){const d=parseInt(o.slice(1,-1),10);i=i[d]}else i=i[o]}return i}const Xy=({isOpen:r,modalId:e,dataSources:t,dataContext:a,globalStateUpdater:i,bindingEngine:o,debug:d=!1,children:g})=>{const[h,f]=j.useState(!1),[p,y]=j.useState(!1),x=j.useRef(!1),S=j.useRef(null);S.current||(S.current=new is);const v=j.useCallback(async()=>{if(!(!t||t.length===0)&&S.current){f(!0);try{const w=a.route||{},k=new URLSearchParams(window.location.search),A=t.map(N=>{let D={...N};if(N.endpoint&&o){const $=o.resolveBindings(N.endpoint,a,{skipCache:!0});D.endpoint=$}if(N.params&&o){const $={};Object.entries(N.params).forEach(([M,z])=>{typeof z=="string"?$[M]=o.resolveBindings(z,a,{skipCache:!0}):$[M]=z}),D.params=$}return D});d&&Sr.log(`[ModalDataSourceWrapper] Modal "${e}" fetching data sources:`,A.map(N=>({id:N.id,endpoint:N.endpoint})));const O=await S.current.fetchDataSourcesWithResults(A,w,k);i&&O.forEach(N=>{if(N.state==="success"&&N.data!==void 0){const D=A.find($=>$.id===N.id);if(D?.initGlobal){const $=N.data?.data??N.data,M=Array.isArray(D.initGlobal)?D.initGlobal:[D.initGlobal];for(const z of M)if(typeof z=="string")i({[z]:$}),d&&Sr.log(`[ModalDataSourceWrapper] Modal "${e}" initGlobal: ${N.id}.data -> _global.${z}`);else if(typeof z=="object"&&z.key){const{key:K,path:pe}=z,we=pe?Vj($,pe):$;i({[K]:we}),d&&Sr.log(`Modal "${e}" initGlobal: ${N.id}.data${pe?"."+pe:""} -> _global.${K}`)}}}else N.state==="error"&&Sr.error(`Modal "${e}" data source error:`,N.id,N.error)}),d&&Sr.log(`Modal "${e}" data sources fetched successfully`)}catch(w){Sr.error(`Modal "${e}" data source fetch error:`,w)}finally{f(!1),y(!0)}}},[t,a,i,o,e,d]);return j.useEffect(()=>{if(!t||t.length===0)return;const w=window.__templateApp;return w?.registerModalDataSources&&w.registerModalDataSources(e,t),()=>{w?.unregisterModalDataSources&&w.unregisterModalDataSources(e)}},[e,t]),j.useEffect(()=>{!r&&x.current&&(y(!1),d&&Sr.log(`[ModalDataSourceWrapper] Modal "${e}" closed, reset fetch state`)),r&&!x.current&&t&&t.length>0&&!p&&v(),x.current=r},[r,t,p,v,e,d]),l.jsx(l.Fragment,{children:g})};class $c extends Error{constructor(t,a,i={}){super(a);H(this,"code");H(this,"userMessageKey");H(this,"showStack");H(this,"icon");H(this,"recoverable");this.name="TemplateEngineError",this.code=t,this.userMessageKey=a,this.showStack=i.showStack??!0,this.icon=i.icon??"fa-circle-exclamation",this.recoverable=i.recoverable??!0,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}getUserMessage(t,a){if(!a||!t)return this.userMessageKey;try{return a.translate(this.userMessageKey,t)}catch{return this.userMessageKey}}}class Kj extends $c{constructor(){super("TEMPLATE_NOT_FOUND","$t:core.errors.template_not_found",{showStack:!1,icon:"fa-paint-brush",recoverable:!1}),this.name="TemplateNotFoundError"}}function Qy(r){if(r instanceof $c)return r;if(r instanceof Error){const e=new $c("TEMPLATE_INIT_ERROR",r.message||"$t:core.errors.template_init_error",{showStack:!0,icon:"fa-circle-exclamation",recoverable:!0});return e.stack=r.stack,e}return new $c("TEMPLATE_INIT_ERROR","$t:core.errors.template_init_error",{showStack:!1,icon:"fa-circle-exclamation",recoverable:!0})}const gi=it("Router");class Wj{constructor(e){H(this,"routes",[]);H(this,"templateIdentifier");H(this,"eventHandlers",new Map);H(this,"pendingNavigation",null);H(this,"isNavigating",!1);H(this,"handlePopState",()=>{this.navigateToCurrentPath()});this.templateIdentifier=e,this.initPopstateListener()}initPopstateListener(){window.addEventListener("popstate",this.handlePopState)}on(e,t){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(t)}async emit(e,...t){const a=this.eventHandlers.get(e);a&&await Promise.all(a.map(i=>i(...t)))}async loadRoutes(e){try{const t=e!==void 0&&e>0?`?v=${e}`:"",a=await fetch(`/api/templates/${this.templateIdentifier}/routes.json${t}`);if(!a.ok)throw new Error(`Failed to load routes: ${a.statusText}`);const i=await a.json();if(!i.success)throw new Error("Failed to load routes from API");if(i.data&&Array.isArray(i.data.routes))this.routes=i.data.routes,gi.log(`Loaded ${this.routes.length} routes${e?` (v=${e})`:""}`);else throw new Error("Invalid routes data format")}catch(t){throw gi.error("Error loading routes:",t),t}}setRoutes(e){this.routes=e,gi.log(`Set ${this.routes.length} routes`)}match(e){for(const t of this.routes){const a=this.matchPattern(t.path,e);if(a!==null)return{route:t,params:a}}return null}matchPattern(e,t){const a=[];let i=e.replace(/:([^/]+)/g,(h,f)=>(a.push(f),"([^/]+)"));i.startsWith("*/")&&(i="(?:/[^/]+)?"+i.slice(1)),i=i.replace(/\//g,"\\/");const o=new RegExp(`^${i}$`),d=t.match(o);if(!d)return null;const g={};return a.forEach((h,f)=>{g[h]=d[f+1]}),g}getRoutes(){return[...this.routes]}getAuthType(e,t){return e.auth_type?e.auth_type:t.startsWith("/admin")?"admin":"user"}async navigateToCurrentPath(){const e=window.location.pathname,t=window.location.search,a=this.match(e);if(!a){gi.warn(`No route matched for path: ${e}`),this.emit("routeNotFound",e);return}if(a.route.redirect){gi.log(`Redirecting from ${e} to ${a.route.redirect}`),this.navigate(a.route.redirect);return}if(a.route.auth_required){const d=this.getAuthType(a.route,e),g=as.getInstance();let h=g.isAuthenticated()&&g.getAuthType()===d;if(h||(h=await g.checkAuth(d)),!h){const f=g.getLoginRedirectUrl(d,e+t);gi.log(`Not authenticated, redirecting to: ${f}`),window.location.href=f;return}}const i=new URLSearchParams(t),o={};for(const d of i.keys()){if(d in o)continue;const g=i.getAll(d);g.length>1?o[d]=g:g.length===1&&(d.endsWith("[]")?o[d]=g:o[d]=g[0])}await this.emit("routeChange",{path:e,layout:a.route.layout,endpoint:a.route.endpoint,params:{...a.route.params||{},...a.params},query:o,auth_required:a.route.auth_required,auth_type:a.route.auth_type,meta:a.route.meta})}navigate(e){if(this.isNavigating){this.pendingNavigation=e;return}this.executeNavigation(e)}async executeNavigation(e){this.isNavigating=!0,this.pendingNavigation=null;try{window.history.pushState({},"",e),await this.navigateToCurrentPath()}finally{if(this.isNavigating=!1,this.pendingNavigation){const t=this.pendingNavigation;this.executeNavigation(t)}}}}const Yj=it("ErrorDisplay");class Zy{static render(e,t){const a=document.getElementById(e);if(!a){Yj.error(`Container #${e} not found`);return}const i=t.debug&&t.showStack&&t.stackTrace,o=window.matchMedia("(prefers-color-scheme: dark)").matches,d={container:` + */var Wy;function Uj(){return Wy||(Wy=1,(function(r,e){(function(a,i){r.exports=i()})(window,function(){return(function(t){var a={};function i(o){if(a[o])return a[o].exports;var d=a[o]={i:o,l:!1,exports:{}};return t[o].call(d.exports,d,d.exports,i),d.l=!0,d.exports}return i.m=t,i.c=a,i.d=function(o,d,g){i.o(o,d)||Object.defineProperty(o,d,{enumerable:!0,get:g})},i.r=function(o){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(o,"__esModule",{value:!0})},i.t=function(o,d){if(d&1&&(o=i(o)),d&8||d&4&&typeof o=="object"&&o&&o.__esModule)return o;var g=Object.create(null);if(i.r(g),Object.defineProperty(g,"default",{enumerable:!0,value:o}),d&2&&typeof o!="string")for(var h in o)i.d(g,h,function(f){return o[f]}.bind(null,h));return g},i.n=function(o){var d=o&&o.__esModule?function(){return o.default}:function(){return o};return i.d(d,"a",d),d},i.o=function(o,d){return Object.prototype.hasOwnProperty.call(o,d)},i.p="",i(i.s=2)})([(function(t,a,i){var o=this&&this.__extends||(function(){var w=function(k,A){return w=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(O,N){O.__proto__=N}||function(O,N){for(var D in N)N.hasOwnProperty(D)&&(O[D]=N[D])},w(k,A)};return function(k,A){w(k,A);function O(){this.constructor=k}k.prototype=A===null?Object.create(A):(O.prototype=A.prototype,new O)}})();Object.defineProperty(a,"__esModule",{value:!0});var d=256,g=(function(){function w(k){k===void 0&&(k="="),this._paddingCharacter=k}return w.prototype.encodedLength=function(k){return this._paddingCharacter?(k+2)/3*4|0:(k*8+5)/6|0},w.prototype.encode=function(k){for(var A="",O=0;O>>18&63),A+=this._encodeByte(N>>>12&63),A+=this._encodeByte(N>>>6&63),A+=this._encodeByte(N>>>0&63)}var D=k.length-O;if(D>0){var N=k[O]<<16|(D===2?k[O+1]<<8:0);A+=this._encodeByte(N>>>18&63),A+=this._encodeByte(N>>>12&63),D===2?A+=this._encodeByte(N>>>6&63):A+=this._paddingCharacter||"",A+=this._paddingCharacter||""}return A},w.prototype.maxDecodedLength=function(k){return this._paddingCharacter?k/4*3|0:(k*6+7)/8|0},w.prototype.decodedLength=function(k){return this.maxDecodedLength(k.length-this._getPaddingLength(k))},w.prototype.decode=function(k){if(k.length===0)return new Uint8Array(0);for(var A=this._getPaddingLength(k),O=k.length-A,N=new Uint8Array(this.maxDecodedLength(O)),D=0,$=0,M=0,z=0,K=0,ye=0,we=0;$>>4,N[D++]=K<<4|ye>>>2,N[D++]=ye<<6|we,M|=z&d,M|=K&d,M|=ye&d,M|=we&d;if($>>4,M|=z&d,M|=K&d),$>>2,M|=ye&d),$>>8&6,A+=51-k>>>8&-75,A+=61-k>>>8&-15,A+=62-k>>>8&3,String.fromCharCode(A)},w.prototype._decodeChar=function(k){var A=d;return A+=(42-k&k-44)>>>8&-d+k-43+62,A+=(46-k&k-48)>>>8&-d+k-47+63,A+=(47-k&k-58)>>>8&-d+k-48+52,A+=(64-k&k-91)>>>8&-d+k-65+0,A+=(96-k&k-123)>>>8&-d+k-97+26,A},w.prototype._getPaddingLength=function(k){var A=0;if(this._paddingCharacter){for(var O=k.length-1;O>=0&&k[O]===this._paddingCharacter;O--)A++;if(k.length<4||A>2)throw new Error("Base64Coder: incorrect padding")}return A},w})();a.Coder=g;var h=new g;function f(w){return h.encode(w)}a.encode=f;function p(w){return h.decode(w)}a.decode=p;var y=(function(w){o(k,w);function k(){return w!==null&&w.apply(this,arguments)||this}return k.prototype._encodeByte=function(A){var O=A;return O+=65,O+=25-A>>>8&6,O+=51-A>>>8&-75,O+=61-A>>>8&-13,O+=62-A>>>8&49,String.fromCharCode(O)},k.prototype._decodeChar=function(A){var O=d;return O+=(44-A&A-46)>>>8&-d+A-45+62,O+=(94-A&A-96)>>>8&-d+A-95+63,O+=(47-A&A-58)>>>8&-d+A-48+52,O+=(64-A&A-91)>>>8&-d+A-65+0,O+=(96-A&A-123)>>>8&-d+A-97+26,O},k})(g);a.URLSafeCoder=y;var x=new y;function S(w){return x.encode(w)}a.encodeURLSafe=S;function v(w){return x.decode(w)}a.decodeURLSafe=v,a.encodedLength=function(w){return h.encodedLength(w)},a.maxDecodedLength=function(w){return h.maxDecodedLength(w)},a.decodedLength=function(w){return h.decodedLength(w)}}),(function(t,a,i){Object.defineProperty(a,"__esModule",{value:!0});var o="utf8: invalid string",d="utf8: invalid source encoding";function g(p){for(var y=new Uint8Array(h(p)),x=0,S=0;S>6,y[x++]=128|v&63):v<55296?(y[x++]=224|v>>12,y[x++]=128|v>>6&63,y[x++]=128|v&63):(S++,v=(v&1023)<<10,v|=p.charCodeAt(S)&1023,v+=65536,y[x++]=240|v>>18,y[x++]=128|v>>12&63,y[x++]=128|v>>6&63,y[x++]=128|v&63)}return y}a.encode=g;function h(p){for(var y=0,x=0;x=p.length-1)throw new Error(o);x++,y+=4}else throw new Error(o)}return y}a.encodedLength=h;function f(p){for(var y=[],x=0;x=p.length)throw new Error(d);var w=p[++x];if((w&192)!==128)throw new Error(d);S=(S&31)<<6|w&63,v=128}else if(S<240){if(x>=p.length-1)throw new Error(d);var w=p[++x],k=p[++x];if((w&192)!==128||(k&192)!==128)throw new Error(d);S=(S&15)<<12|(w&63)<<6|k&63,v=2048}else if(S<248){if(x>=p.length-2)throw new Error(d);var w=p[++x],k=p[++x],A=p[++x];if((w&192)!==128||(k&192)!==128||(A&192)!==128)throw new Error(d);S=(S&15)<<18|(w&63)<<12|(k&63)<<6|A&63,v=65536}else throw new Error(d);if(S=55296&&S<=57343)throw new Error(d);if(S>=65536){if(S>1114111)throw new Error(d);S-=65536,y.push(String.fromCharCode(55296|S>>10)),S=56320|S&1023}}y.push(String.fromCharCode(S))}return y.join("")}a.decode=f}),(function(t,a,i){t.exports=i(3).default}),(function(t,a,i){i.r(a);class o{constructor(C,_){this.lastId=0,this.prefix=C,this.name=_}create(C){this.lastId++;var _=this.lastId,I=this.prefix+_,P=this.name+"["+_+"]",fe=!1,Ne=function(){fe||(C.apply(null,arguments),fe=!0)};return this[_]=Ne,{number:_,id:I,name:P,callback:Ne}}remove(C){delete this[C.number]}}var d=new o("_pusher_script_","Pusher.ScriptReceivers"),g={VERSION:"8.4.0",PROTOCOL:7,wsPort:80,wssPort:443,wsPath:"",httpHost:"sockjs.pusher.com",httpPort:80,httpsPort:443,httpPath:"/pusher",stats_host:"stats.pusher.com",authEndpoint:"/pusher/auth",authTransport:"ajax",activityTimeout:12e4,pongTimeout:3e4,unavailableTimeout:1e4,userAuthentication:{endpoint:"/pusher/user-auth",transport:"ajax"},channelAuthorization:{endpoint:"/pusher/auth",transport:"ajax"},cdn_http:"http://js.pusher.com",cdn_https:"https://js.pusher.com",dependency_suffix:""},h=g;class f{constructor(C){this.options=C,this.receivers=C.receivers||d,this.loading={}}load(C,_,I){var P=this;if(P.loading[C]&&P.loading[C].length>0)P.loading[C].push(I);else{P.loading[C]=[I];var fe=Xe.createScriptRequest(P.getPath(C,_)),Ne=P.receivers.create(function(ze){if(P.receivers.remove(Ne),P.loading[C]){var Qe=P.loading[C];delete P.loading[C];for(var ut=function(Kt){Kt||fe.cleanup()},yt=0;yt>>6)+ve(128|C&63):ve(224|C>>>12&15)+ve(128|C>>>6&63)+ve(128|C&63)},je=function(T){return T.replace(/[^\x00-\x7F]/g,de)},W=function(T){var C=[0,2,1][T.length%3],_=T.charCodeAt(0)<<16|(T.length>1?T.charCodeAt(1):0)<<8|(T.length>2?T.charCodeAt(2):0),I=[le.charAt(_>>>18),le.charAt(_>>>12&63),C>=2?"=":le.charAt(_>>>6&63),C>=1?"=":le.charAt(_&63)];return I.join("")},he=window.btoa||function(T){return T.replace(/[\s\S]{1,3}/g,W)};class ee{constructor(C,_,I,P){this.clear=_,this.timer=C(()=>{this.timer&&(this.timer=P(this.timer))},I)}isRunning(){return this.timer!==null}ensureAborted(){this.timer&&(this.clear(this.timer),this.timer=null)}}var X=ee;function ae(T){window.clearTimeout(T)}function R(T){window.clearInterval(T)}class U extends X{constructor(C,_){super(setTimeout,ae,C,function(I){return _(),null})}}class re extends X{constructor(C,_){super(setInterval,R,C,function(I){return _(),I})}}var xe={now(){return Date.now?Date.now():new Date().valueOf()},defer(T){return new U(0,T)},method(T,...C){var _=Array.prototype.slice.call(arguments,1);return function(I){return I[T].apply(I,_.concat(arguments))}}},oe=xe;function ke(T,...C){for(var _=0;_{window.console&&window.console.log&&window.console.log(C)}}debug(...C){this.log(this.globalLog,C)}warn(...C){this.log(this.globalLogWarn,C)}error(...C){this.log(this.globalLogError,C)}globalLogWarn(C){window.console&&window.console.warn?window.console.warn(C):this.globalLog(C)}globalLogError(C){window.console&&window.console.error?window.console.error(C):this.globalLogWarn(C)}log(C,..._){var I=Oe.apply(this,arguments);ul.log?ul.log(I):ul.logToConsole&&C.bind(this)(I)}}var tt=new mt,bn=function(T,C,_,I,P){(_.headers!==void 0||_.headersProvider!=null)&&tt.warn(`To send headers with the ${I.toString()} request, you must use AJAX, rather than JSONP.`);var fe=T.nextAuthCallbackID.toString();T.nextAuthCallbackID++;var Ne=T.getDocument(),ze=Ne.createElement("script");T.auth_callbacks[fe]=function(yt){P(null,yt)};var Qe="Pusher.auth_callbacks['"+fe+"']";ze.src=_.endpoint+"?callback="+encodeURIComponent(Qe)+"&"+C;var ut=Ne.getElementsByTagName("head")[0]||Ne.documentElement;ut.insertBefore(ze,ut.firstChild)},wt=bn;class Tt{constructor(C){this.src=C}send(C){var _=this,I="Error loading "+_.src;_.script=document.createElement("script"),_.script.id=C.id,_.script.src=_.src,_.script.type="text/javascript",_.script.charset="UTF-8",_.script.addEventListener?(_.script.onerror=function(){C.callback(I)},_.script.onload=function(){C.callback(null)}):_.script.onreadystatechange=function(){(_.script.readyState==="loaded"||_.script.readyState==="complete")&&C.callback(null)},_.script.async===void 0&&document.attachEvent&&/opera/i.test(navigator.userAgent)?(_.errorScript=document.createElement("script"),_.errorScript.id=C.id+"_error",_.errorScript.text=C.name+"('"+I+"');",_.script.async=_.errorScript.async=!1):_.script.async=!0;var P=document.getElementsByTagName("head")[0];P.insertBefore(_.script,P.firstChild),_.errorScript&&P.insertBefore(_.errorScript,_.script.nextSibling)}cleanup(){this.script&&(this.script.onload=this.script.onerror=null,this.script.onreadystatechange=null),this.script&&this.script.parentNode&&this.script.parentNode.removeChild(this.script),this.errorScript&&this.errorScript.parentNode&&this.errorScript.parentNode.removeChild(this.errorScript),this.script=null,this.errorScript=null}}class qt{constructor(C,_){this.url=C,this.data=_}send(C){if(!this.request){var _=pt(this.data),I=this.url+"/"+C.number+"?"+_;this.request=Xe.createScriptRequest(I),this.request.send(C)}}cleanup(){this.request&&this.request.cleanup()}}var Yn=function(T,C){return function(_,I){var P="http"+(C?"s":"")+"://",fe=P+(T.host||T.options.host)+T.options.path,Ne=Xe.createJSONPRequest(fe,_),ze=Xe.ScriptReceivers.create(function(Qe,ut){d.remove(ze),Ne.cleanup(),ut&&ut.host&&(T.host=ut.host),I&&I(Qe,ut)});Ne.send(ze)}},dn={name:"jsonp",getAgent:Yn},Ta=dn;function ca(T,C,_){var I=T+(C.useTLS?"s":""),P=C.useTLS?C.hostTLS:C.hostNonTLS;return I+"://"+P+_}function V(T,C){var _="/app/"+T,I="?protocol="+h.PROTOCOL+"&client=js&version="+h.VERSION+(C?"&"+C:"");return _+I}var me={getInitial:function(T,C){var _=(C.httpPath||"")+V(T,"flash=false");return ca("ws",C,_)}},ue={getInitial:function(T,C){var _=(C.httpPath||"/pusher")+V(T);return ca("http",C,_)}},ne={getInitial:function(T,C){return ca("http",C,C.httpPath||"/pusher")},getPath:function(T,C){return V(T)}};class _e{constructor(){this._callbacks={}}get(C){return this._callbacks[Ae(C)]}add(C,_,I){var P=Ae(C);this._callbacks[P]=this._callbacks[P]||[],this._callbacks[P].push({fn:_,context:I})}remove(C,_,I){if(!C&&!_&&!I){this._callbacks={};return}var P=C?[Ae(C)]:Ie(this._callbacks);_||I?this.removeCallback(P,_,I):this.removeAllCallbacks(P)}removeCallback(C,_,I){Rt(C,function(P){this._callbacks[P]=Qt(this._callbacks[P]||[],function(fe){return _&&_!==fe.fn||I&&I!==fe.context}),this._callbacks[P].length===0&&delete this._callbacks[P]},this)}removeAllCallbacks(C){Rt(C,function(_){delete this._callbacks[_]},this)}}function Ae(T){return"_"+T}class Re{constructor(C){this.callbacks=new _e,this.global_callbacks=[],this.failThrough=C}bind(C,_,I){return this.callbacks.add(C,_,I),this}bind_global(C){return this.global_callbacks.push(C),this}unbind(C,_,I){return this.callbacks.remove(C,_,I),this}unbind_global(C){return C?(this.global_callbacks=Qt(this.global_callbacks||[],_=>_!==C),this):(this.global_callbacks=[],this)}unbind_all(){return this.unbind(),this.unbind_global(),this}emit(C,_,I){for(var P=0;P0)for(var P=0;P{this.onError(_),this.changeState("closed")}),!1}return this.bindListeners(),tt.debug("Connecting",{transport:this.name,url:C}),this.changeState("connecting"),!0}close(){return this.socket?(this.socket.close(),!0):!1}send(C){return this.state==="open"?(oe.defer(()=>{this.socket&&this.socket.send(C)}),!0):!1}ping(){this.state==="open"&&this.supportsPing()&&this.socket.ping()}onOpen(){this.hooks.beforeOpen&&this.hooks.beforeOpen(this.socket,this.hooks.urls.getPath(this.key,this.options)),this.changeState("open"),this.socket.onopen=void 0}onError(C){this.emit("error",{type:"WebSocketError",error:C}),this.timeline.error(this.buildTimelineMessage({error:C.toString()}))}onClose(C){C?this.changeState("closed",{code:C.code,reason:C.reason,wasClean:C.wasClean}):this.changeState("closed"),this.unbindListeners(),this.socket=void 0}onMessage(C){this.emit("message",C)}onActivity(){this.emit("activity")}bindListeners(){this.socket.onopen=()=>{this.onOpen()},this.socket.onerror=C=>{this.onError(C)},this.socket.onclose=C=>{this.onClose(C)},this.socket.onmessage=C=>{this.onMessage(C)},this.supportsPing()&&(this.socket.onactivity=()=>{this.onActivity()})}unbindListeners(){this.socket&&(this.socket.onopen=void 0,this.socket.onerror=void 0,this.socket.onclose=void 0,this.socket.onmessage=void 0,this.supportsPing()&&(this.socket.onactivity=void 0))}changeState(C,_){this.state=C,this.timeline.info(this.buildTimelineMessage({state:C,params:_})),this.emit(C,_)}buildTimelineMessage(C){return ke({cid:this.id},C)}}class Ue{constructor(C){this.hooks=C}isSupported(C){return this.hooks.isSupported(C)}createConnection(C,_,I,P){return new Be(this.hooks,C,_,I,P)}}var Le=new Ue({urls:me,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return!!Xe.getWebSocketAPI()},isSupported:function(){return!!Xe.getWebSocketAPI()},getSocket:function(T){return Xe.createWebSocket(T)}}),Fe={urls:ue,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},We=ke({getSocket:function(T){return Xe.HTTPFactory.createStreamingSocket(T)}},Fe),Je=ke({getSocket:function(T){return Xe.HTTPFactory.createPollingSocket(T)}},Fe),st={isSupported:function(){return Xe.isXHRSupported()}},He=new Ue(ke({},We,st)),De=new Ue(ke({},Je,st)),$e={ws:Le,xhr_streaming:He,xhr_polling:De},lt=$e,Dt=new Ue({file:"sockjs",urls:ne,handlesActivityChecks:!0,supportsPing:!1,isSupported:function(){return!0},isInitialized:function(){return window.SockJS!==void 0},getSocket:function(T,C){return new window.SockJS(T,null,{js_path:y.getPath("sockjs",{useTLS:C.useTLS}),ignore_null_origin:C.ignoreNullOrigin})},beforeOpen:function(T,C){T.send(JSON.stringify({path:C}))}}),tn={isSupported:function(T){var C=Xe.isXDRSupported(T.useTLS);return C}},yn=new Ue(ke({},We,tn)),Jn=new Ue(ke({},Je,tn));lt.xdr_streaming=yn,lt.xdr_polling=Jn,lt.sockjs=Dt;var Xn=lt;class Ga extends Re{constructor(){super();var C=this;window.addEventListener!==void 0&&(window.addEventListener("online",function(){C.emit("online")},!1),window.addEventListener("offline",function(){C.emit("offline")},!1))}isOnline(){return window.navigator.onLine===void 0?!0:window.navigator.onLine}}var In=new Ga;class un{constructor(C,_,I){this.manager=C,this.transport=_,this.minPingDelay=I.minPingDelay,this.maxPingDelay=I.maxPingDelay,this.pingDelay=void 0}createConnection(C,_,I,P){P=ke({},P,{activityTimeout:this.pingDelay});var fe=this.transport.createConnection(C,_,I,P),Ne=null,ze=function(){fe.unbind("open",ze),fe.bind("closed",Qe),Ne=oe.now()},Qe=ut=>{if(fe.unbind("closed",Qe),ut.code===1002||ut.code===1003)this.manager.reportDeath();else if(!ut.wasClean&&Ne){var yt=oe.now()-Ne;yt<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(yt/2,this.minPingDelay))}};return fe.bind("open",ze),fe}isSupported(C){return this.manager.isAlive()&&this.transport.isSupported(C)}}const vn={decodeMessage:function(T){try{var C=JSON.parse(T.data),_=C.data;if(typeof _=="string")try{_=JSON.parse(C.data)}catch{}var I={event:C.event,channel:C.channel,data:_};return C.user_id&&(I.user_id=C.user_id),I}catch(P){throw{type:"MessageParseError",error:P,data:T.data}}},encodeMessage:function(T){return JSON.stringify(T)},processHandshake:function(T){var C=vn.decodeMessage(T);if(C.event==="pusher:connection_established"){if(!C.data.activity_timeout)throw"No activity timeout specified in handshake";return{action:"connected",id:C.data.socket_id,activityTimeout:C.data.activity_timeout*1e3}}else{if(C.event==="pusher:error")return{action:this.getCloseAction(C.data),error:this.getCloseError(C.data)};throw"Invalid handshake"}},getCloseAction:function(T){return T.code<4e3?T.code>=1002&&T.code<=1004?"backoff":null:T.code===4e3?"tls_only":T.code<4100?"refused":T.code<4200?"backoff":T.code<4300?"retry":"refused"},getCloseError:function(T){return T.code!==1e3&&T.code!==1001?{type:"PusherError",data:{code:T.code,message:T.reason||T.message}}:null}};var zn=vn;class Yo extends Re{constructor(C,_){super(),this.id=C,this.transport=_,this.activityTimeout=_.activityTimeout,this.bindListeners()}handlesActivityChecks(){return this.transport.handlesActivityChecks()}send(C){return this.transport.send(C)}send_event(C,_,I){var P={event:C,data:_};return I&&(P.channel=I),tt.debug("Event sent",P),this.send(zn.encodeMessage(P))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var C={message:I=>{var P;try{P=zn.decodeMessage(I)}catch(fe){this.emit("error",{type:"MessageParseError",error:fe,data:I.data})}if(P!==void 0){switch(tt.debug("Event recd",P),P.event){case"pusher:error":this.emit("error",{type:"PusherError",data:P.data});break;case"pusher:ping":this.emit("ping");break;case"pusher:pong":this.emit("pong");break}this.emit("message",P)}},activity:()=>{this.emit("activity")},error:I=>{this.emit("error",I)},closed:I=>{_(),I&&I.code&&this.handleCloseEvent(I),this.transport=null,this.emit("closed")}},_=()=>{qe(C,(I,P)=>{this.transport.unbind(P,I)})};qe(C,(I,P)=>{this.transport.bind(P,I)})}handleCloseEvent(C){var _=zn.getCloseAction(C),I=zn.getCloseError(C);I&&this.emit("error",I),_&&this.emit(_,{action:_,error:I})}}class mh{constructor(C,_){this.transport=C,this.callback=_,this.bindListeners()}close(){this.unbindListeners(),this.transport.close()}bindListeners(){this.onMessage=C=>{this.unbindListeners();var _;try{_=zn.processHandshake(C)}catch(I){this.finish("error",{error:I}),this.transport.close();return}_.action==="connected"?this.finish("connected",{connection:new Yo(_.id,this.transport),activityTimeout:_.activityTimeout}):(this.finish(_.action,{error:_.error}),this.transport.close())},this.onClosed=C=>{this.unbindListeners();var _=zn.getCloseAction(C)||"backoff",I=zn.getCloseError(C);this.finish(_,{error:I})},this.transport.bind("message",this.onMessage),this.transport.bind("closed",this.onClosed)}unbindListeners(){this.transport.unbind("message",this.onMessage),this.transport.unbind("closed",this.onClosed)}finish(C,_){this.callback(ke({transport:this.transport,action:C},_))}}class yh{constructor(C,_){this.timeline=C,this.options=_||{}}send(C,_){this.timeline.isEmpty()||this.timeline.send(Xe.TimelineTransport.getAgent(this,C),_)}}class vi extends Re{constructor(C,_){super(function(I,P){tt.debug("No callbacks on "+C+" for "+I)}),this.name=C,this.pusher=_,this.subscribed=!1,this.subscriptionPending=!1,this.subscriptionCancelled=!1}authorize(C,_){return _(null,{auth:""})}trigger(C,_){if(C.indexOf("client-")!==0)throw new k("Event '"+C+"' does not start with 'client-'");if(!this.subscribed){var I=v.buildLogSuffix("triggeringClientEvents");tt.warn(`Client event triggered before channel 'subscription_succeeded' event . ${I}`)}return this.pusher.send_event(C,_,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(C){var _=C.event,I=C.data;if(_==="pusher_internal:subscription_succeeded")this.handleSubscriptionSucceededEvent(C);else if(_==="pusher_internal:subscription_count")this.handleSubscriptionCountEvent(C);else if(_.indexOf("pusher_internal:")!==0){var P={};this.emit(_,I,P)}}handleSubscriptionSucceededEvent(C){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):this.emit("pusher:subscription_succeeded",C.data)}handleSubscriptionCountEvent(C){C.data.subscription_count&&(this.subscriptionCount=C.data.subscription_count),this.emit("pusher:subscription_count",C.data)}subscribe(){this.subscribed||(this.subscriptionPending=!0,this.subscriptionCancelled=!1,this.authorize(this.pusher.connection.socket_id,(C,_)=>{C?(this.subscriptionPending=!1,tt.error(C.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:C.message},C instanceof K?{status:C.status}:{}))):this.pusher.send_event("pusher:subscribe",{auth:_.auth,channel_data:_.channel_data,channel:this.name})}))}unsubscribe(){this.subscribed=!1,this.pusher.send_event("pusher:unsubscribe",{channel:this.name})}cancelSubscription(){this.subscriptionCancelled=!0}reinstateSubscription(){this.subscriptionCancelled=!1}}class ds extends vi{authorize(C,_){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:C},_)}}class Jo{constructor(){this.reset()}get(C){return Object.prototype.hasOwnProperty.call(this.members,C)?{id:C,info:this.members[C]}:null}each(C){qe(this.members,(_,I)=>{C(this.get(I))})}setMyID(C){this.myID=C}onSubscription(C){this.members=C.presence.hash,this.count=C.presence.count,this.me=this.get(this.myID)}addMember(C){return this.get(C.user_id)===null&&this.count++,this.members[C.user_id]=C.user_info,this.get(C.user_id)}removeMember(C){var _=this.get(C.user_id);return _&&(delete this.members[C.user_id],this.count--),_}reset(){this.members={},this.count=0,this.myID=null,this.me=null}}var Ps=function(T,C,_,I){function P(fe){return fe instanceof _?fe:new _(function(Ne){Ne(fe)})}return new(_||(_=Promise))(function(fe,Ne){function ze(yt){try{ut(I.next(yt))}catch(Kt){Ne(Kt)}}function Qe(yt){try{ut(I.throw(yt))}catch(Kt){Ne(Kt)}}function ut(yt){yt.done?fe(yt.value):P(yt.value).then(ze,Qe)}ut((I=I.apply(T,C||[])).next())})};class Bs extends ds{constructor(C,_){super(C,_),this.members=new Jo}authorize(C,_){super.authorize(C,(I,P)=>Ps(this,void 0,void 0,function*(){if(!I)if(P=P,P.channel_data!=null){var fe=JSON.parse(P.channel_data);this.members.setMyID(fe.user_id)}else if(yield this.pusher.user.signinDonePromise,this.pusher.user.user_data!=null)this.members.setMyID(this.pusher.user.user_data.id);else{let Ne=v.buildLogSuffix("authorizationEndpoint");tt.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${Ne}, or the user should be signed in.`),_("Invalid auth response");return}_(I,P)}))}handleEvent(C){var _=C.event;if(_.indexOf("pusher_internal:")===0)this.handleInternalEvent(C);else{var I=C.data,P={};C.user_id&&(P.user_id=C.user_id),this.emit(_,I,P)}}handleInternalEvent(C){var _=C.event,I=C.data;switch(_){case"pusher_internal:subscription_succeeded":this.handleSubscriptionSucceededEvent(C);break;case"pusher_internal:subscription_count":this.handleSubscriptionCountEvent(C);break;case"pusher_internal:member_added":var P=this.members.addMember(I);this.emit("pusher:member_added",P);break;case"pusher_internal:member_removed":var fe=this.members.removeMember(I);fe&&this.emit("pusher:member_removed",fe);break}}handleSubscriptionSucceededEvent(C){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):(this.members.onSubscription(C.data),this.emit("pusher:subscription_succeeded",this.members))}disconnect(){this.members.reset(),super.disconnect()}}var Ar=i(1),Fa=i(0);class nn extends ds{constructor(C,_,I){super(C,_),this.key=null,this.nacl=I}authorize(C,_){super.authorize(C,(I,P)=>{if(I){_(I,P);return}let fe=P.shared_secret;if(!fe){_(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null);return}this.key=Object(Fa.decode)(fe),delete P.shared_secret,_(null,P)})}trigger(C,_){throw new $("Client events are not currently supported for encrypted channels")}handleEvent(C){var _=C.event,I=C.data;if(_.indexOf("pusher_internal:")===0||_.indexOf("pusher:")===0){super.handleEvent(C);return}this.handleEncryptedEvent(_,I)}handleEncryptedEvent(C,_){if(!this.key){tt.debug("Received encrypted event before key has been retrieved from the authEndpoint");return}if(!_.ciphertext||!_.nonce){tt.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+_);return}let I=Object(Fa.decode)(_.ciphertext);if(I.length{if(Ne){tt.error(`Failed to make a request to the authEndpoint: ${ze}. Unable to fetch new key, so dropping encrypted event`);return}if(fe=this.nacl.secretbox.open(I,P,this.key),fe===null){tt.error("Failed to decrypt event with new key. Dropping encrypted event");return}this.emit(C,this.getDataToEmit(fe))});return}this.emit(C,this.getDataToEmit(fe))}getDataToEmit(C){let _=Object(Ar.decode)(C);try{return JSON.parse(_)}catch{return _}}}class fd extends Re{constructor(C,_){super(),this.state="initialized",this.connection=null,this.key=C,this.options=_,this.timeline=this.options.timeline,this.usingTLS=this.options.useTLS,this.errorCallbacks=this.buildErrorCallbacks(),this.connectionCallbacks=this.buildConnectionCallbacks(this.errorCallbacks),this.handshakeCallbacks=this.buildHandshakeCallbacks(this.errorCallbacks);var I=Xe.getNetwork();I.bind("online",()=>{this.timeline.info({netinfo:"online"}),(this.state==="connecting"||this.state==="unavailable")&&this.retryIn(0)}),I.bind("offline",()=>{this.timeline.info({netinfo:"offline"}),this.connection&&this.sendActivityCheck()}),this.updateStrategy()}connect(){if(!(this.connection||this.runner)){if(!this.strategy.isSupported()){this.updateState("failed");return}this.updateState("connecting"),this.startConnecting(),this.setUnavailableTimer()}}send(C){return this.connection?this.connection.send(C):!1}send_event(C,_,I){return this.connection?this.connection.send_event(C,_,I):!1}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var C=(_,I)=>{_?this.runner=this.strategy.connect(0,C):I.action==="error"?(this.emit("error",{type:"HandshakeError",error:I.error}),this.timeline.error({handshakeError:I.error})):(this.abortConnecting(),this.handshakeCallbacks[I.action](I))};this.runner=this.strategy.connect(0,C)}abortConnecting(){this.runner&&(this.runner.abort(),this.runner=null)}disconnectInternally(){if(this.abortConnecting(),this.clearRetryTimer(),this.clearUnavailableTimer(),this.connection){var C=this.abandonConnection();C.close()}}updateStrategy(){this.strategy=this.options.getStrategy({key:this.key,timeline:this.timeline,useTLS:this.usingTLS})}retryIn(C){this.timeline.info({action:"retry",delay:C}),C>0&&this.emit("connecting_in",Math.round(C/1e3)),this.retryTimer=new U(C||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new U(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new U(this.options.pongTimeout,()=>{this.timeline.error({pong_timed_out:this.options.pongTimeout}),this.retryIn(0)})}resetActivityCheck(){this.stopActivityCheck(),this.connection&&!this.connection.handlesActivityChecks()&&(this.activityTimer=new U(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(C){return ke({},C,{message:_=>{this.resetActivityCheck(),this.emit("message",_)},ping:()=>{this.send_event("pusher:pong",{})},activity:()=>{this.resetActivityCheck()},error:_=>{this.emit("error",_)},closed:()=>{this.abandonConnection(),this.shouldRetry()&&this.retryIn(1e3)}})}buildHandshakeCallbacks(C){return ke({},C,{connected:_=>{this.activityTimeout=Math.min(this.options.activityTimeout,_.activityTimeout,_.connection.activityTimeout||1/0),this.clearUnavailableTimer(),this.setConnection(_.connection),this.socket_id=this.connection.id,this.updateState("connected",{socket_id:this.socket_id})}})}buildErrorCallbacks(){let C=_=>I=>{I.error&&this.emit("error",{type:"WebSocketError",error:I.error}),_(I)};return{tls_only:C(()=>{this.usingTLS=!0,this.updateStrategy(),this.retryIn(0)}),refused:C(()=>{this.disconnect()}),backoff:C(()=>{this.retryIn(1e3)}),retry:C(()=>{this.retryIn(0)})}}setConnection(C){this.connection=C;for(var _ in this.connectionCallbacks)this.connection.bind(_,this.connectionCallbacks[_]);this.resetActivityCheck()}abandonConnection(){if(this.connection){this.stopActivityCheck();for(var C in this.connectionCallbacks)this.connection.unbind(C,this.connectionCallbacks[C]);var _=this.connection;return this.connection=null,_}}updateState(C,_){var I=this.state;if(this.state=C,I!==C){var P=C;P==="connected"&&(P+=" with new socket ID "+_.socket_id),tt.debug("State changed",I+" -> "+P),this.timeline.info({state:C,params:_}),this.emit("state_change",{previous:I,current:C}),this.emit(C,_)}}shouldRetry(){return this.state==="connecting"||this.state==="connected"}}class pd{constructor(){this.channels={}}add(C,_){return this.channels[C]||(this.channels[C]=us(C,_)),this.channels[C]}all(){return Nt(this.channels)}find(C){return this.channels[C]}remove(C){var _=this.channels[C];return delete this.channels[C],_}disconnect(){qe(this.channels,function(C){C.disconnect()})}}function us(T,C){if(T.indexOf("private-encrypted-")===0){if(C.config.nacl)return Da.createEncryptedChannel(T,C,C.config.nacl);let _="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",I=v.buildLogSuffix("encryptedChannelSupport");throw new $(`${_}. ${I}`)}else{if(T.indexOf("private-")===0)return Da.createPrivateChannel(T,C);if(T.indexOf("presence-")===0)return Da.createPresenceChannel(T,C);if(T.indexOf("#")===0)throw new A('Cannot create a channel with name "'+T+'".');return Da.createChannel(T,C)}}var Us={createChannels(){return new pd},createConnectionManager(T,C){return new fd(T,C)},createChannel(T,C){return new vi(T,C)},createPrivateChannel(T,C){return new ds(T,C)},createPresenceChannel(T,C){return new Bs(T,C)},createEncryptedChannel(T,C,_){return new nn(T,C,_)},createTimelineSender(T,C){return new yh(T,C)},createHandshake(T,C){return new mh(T,C)},createAssistantToTheTransportManager(T,C,_){return new un(T,C,_)}},Da=Us;class Xo{constructor(C){this.options=C||{},this.livesLeft=this.options.lives||1/0}getAssistant(C){return Da.createAssistantToTheTransportManager(this,C,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class Va{constructor(C,_){this.strategies=C,this.loop=!!_.loop,this.failFast=!!_.failFast,this.timeout=_.timeout,this.timeoutLimit=_.timeoutLimit}isSupported(){return Ce(this.strategies,oe.method("isSupported"))}connect(C,_){var I=this.strategies,P=0,fe=this.timeout,Ne=null,ze=(Qe,ut)=>{ut?_(null,ut):(P=P+1,this.loop&&(P=P%I.length),P0&&(fe=new U(I.timeout,function(){Ne.abort(),P(!0)})),Ne=C.connect(_,function(ze,Qe){ze&&fe&&fe.isRunning()&&!I.failFast||(fe&&fe.ensureAborted(),P(ze,Qe))}),{abort:function(){fe&&fe.ensureAborted(),Ne.abort()},forceMinPriority:function(ze){Ne.forceMinPriority(ze)}}}}class Qo{constructor(C){this.strategies=C}isSupported(){return Ce(this.strategies,oe.method("isSupported"))}connect(C,_){return wi(this.strategies,C,function(I,P){return function(fe,Ne){if(P[I].error=fe,fe){Si(P)&&_(!0);return}Rt(P,function(ze){ze.forceMinPriority(Ne.transport.priority)}),_(null,Ne)}})}}function wi(T,C,_){var I=Xt(T,function(P,fe,Ne,ze){return P.connect(C,_(fe,ze))});return{abort:function(){Rt(I,Ra)},forceMinPriority:function(P){Rt(I,function(fe){fe.forceMinPriority(P)})}}}function Si(T){return Ge(T,function(C){return!!C.error})}function Ra(T){!T.error&&!T.aborted&&(T.abort(),T.aborted=!0)}class Hn{constructor(C,_,I){this.strategy=C,this.transports=_,this.ttl=I.ttl||1800*1e3,this.usingTLS=I.useTLS,this.timeline=I.timeline}isSupported(){return this.strategy.isSupported()}connect(C,_){var I=this.usingTLS,P=xh(I),fe=P&&P.cacheSkipCount?P.cacheSkipCount:0,Ne=[this.strategy];if(P&&P.timestamp+this.ttl>=oe.now()){var ze=this.transports[P.transport];ze&&(["ws","wss"].includes(P.transport)||fe>3?(this.timeline.info({cached:!0,transport:P.transport,latency:P.latency}),Ne.push(new Va([ze],{timeout:P.latency*2+1e3,failFast:!0}))):fe++)}var Qe=oe.now(),ut=Ne.pop().connect(C,function yt(Kt,Lr){Kt?(el(I),Ne.length>0?(Qe=oe.now(),ut=Ne.pop().connect(C,yt)):_(Kt)):(Zo(I,Lr.transport.name,oe.now()-Qe,fe),_(null,Lr))});return{abort:function(){ut.abort()},forceMinPriority:function(yt){C=yt,ut&&ut.forceMinPriority(yt)}}}}function Ci(T){return"pusherTransport"+(T?"TLS":"NonTLS")}function xh(T){var C=Xe.getLocalStorage();if(C)try{var _=C[Ci(T)];if(_)return JSON.parse(_)}catch{el(T)}return null}function Zo(T,C,_,I){var P=Xe.getLocalStorage();if(P)try{P[Ci(T)]=_t({timestamp:oe.now(),transport:C,latency:_,cacheSkipCount:I})}catch{}}function el(T){var C=Xe.getLocalStorage();if(C)try{delete C[Ci(T)]}catch{}}class gs{constructor(C,{delay:_}){this.strategy=C,this.options={delay:_}}isSupported(){return this.strategy.isSupported()}connect(C,_){var I=this.strategy,P,fe=new U(this.options.delay,function(){P=I.connect(C,_)});return{abort:function(){fe.ensureAborted(),P&&P.abort()},forceMinPriority:function(Ne){C=Ne,P&&P.forceMinPriority(Ne)}}}}class Tr{constructor(C,_,I){this.test=C,this.trueBranch=_,this.falseBranch=I}isSupported(){var C=this.test()?this.trueBranch:this.falseBranch;return C.isSupported()}connect(C,_){var I=this.test()?this.trueBranch:this.falseBranch;return I.connect(C,_)}}class Pn{constructor(C){this.strategy=C}isSupported(){return this.strategy.isSupported()}connect(C,_){var I=this.strategy.connect(C,function(P,fe){fe&&I.abort(),_(P,fe)});return I}}function hs(T){return function(){return T.isSupported()}}var md=function(T,C,_){var I={};function P(Mr,_d,Ad,yl,xl){var bl=_(T,Mr,_d,Ad,yl,xl);return I[Mr]=bl,bl}var fe=Object.assign({},C,{hostNonTLS:T.wsHost+":"+T.wsPort,hostTLS:T.wsHost+":"+T.wssPort,httpPath:T.wsPath}),Ne=Object.assign({},fe,{useTLS:!0}),ze=Object.assign({},C,{hostNonTLS:T.httpHost+":"+T.httpPort,hostTLS:T.httpHost+":"+T.httpsPort,httpPath:T.httpPath}),Qe={loop:!0,timeout:15e3,timeoutLimit:6e4},ut=new Xo({minPingDelay:1e4,maxPingDelay:T.activityTimeout}),yt=new Xo({lives:2,minPingDelay:1e4,maxPingDelay:T.activityTimeout}),Kt=P("ws","ws",3,fe,ut),Lr=P("wss","ws",3,Ne,ut),kd=P("sockjs","sockjs",1,ze),gl=P("xhr_streaming","xhr_streaming",1,ze,yt),Nd=P("xdr_streaming","xdr_streaming",1,ze,yt),hl=P("xhr_polling","xhr_polling",1,ze),Ws=P("xdr_polling","xdr_polling",1,ze),Ed=new Va([Kt],Qe),Mh=new Va([Lr],Qe),$h=new Va([kd],Qe),fl=new Va([new Tr(hs(gl),gl,Nd)],Qe),pl=new Va([new Tr(hs(hl),hl,Ws)],Qe),Ys=new Va([new Tr(hs(fl),new Qo([fl,new gs(pl,{delay:4e3})]),pl)],Qe),ps=new Tr(hs(Ys),Ys,$h),ml;return C.useTLS?ml=new Qo([Ed,new gs(ps,{delay:2e3})]):ml=new Qo([Ed,new gs(Mh,{delay:2e3}),new gs(ps,{delay:5e3})]),new Hn(new Pn(new Tr(hs(Kt),ml,ps)),I,{ttl:18e5,timeline:C.timeline,useTLS:C.useTLS})},tl=md,qs=(function(){var T=this;T.timeline.info(T.buildTimelineMessage({transport:T.name+(T.options.useTLS?"s":"")})),T.hooks.isInitialized()?T.changeState("initialized"):T.hooks.file?(T.changeState("initializing"),y.load(T.hooks.file,{useTLS:T.options.useTLS},function(C,_){T.hooks.isInitialized()?(T.changeState("initialized"),_(!0)):(C&&T.onError(C),T.onClose(),_(!1))})):T.onClose()}),yd={getRequest:function(T){var C=new window.XDomainRequest;return C.ontimeout=function(){T.emit("error",new O),T.close()},C.onerror=function(_){T.emit("error",_),T.close()},C.onprogress=function(){C.responseText&&C.responseText.length>0&&T.onChunk(200,C.responseText)},C.onload=function(){C.responseText&&C.responseText.length>0&&T.onChunk(200,C.responseText),T.emit("finished",200),T.close()},C},abortRequest:function(T){T.ontimeout=T.onerror=T.onprogress=T.onload=null,T.abort()}},xd=yd;const Gs=256*1024;class bh extends Re{constructor(C,_,I){super(),this.hooks=C,this.method=_,this.url=I}start(C){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},Xe.addUnloadListener(this.unloader),this.xhr.open(this.method,this.url,!0),this.xhr.setRequestHeader&&this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.send(C)}close(){this.unloader&&(Xe.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(C,_){for(;;){var I=this.advanceBuffer(_);if(I)this.emit("chunk",{status:C,data:I});else break}this.isBufferTooLong(_)&&this.emit("buffer_too_long")}advanceBuffer(C){var _=C.slice(this.position),I=_.indexOf(` +`);return I!==-1?(this.position+=I+1,_.slice(0,I)):null}isBufferTooLong(C){return this.position===C.length&&C.length>Gs}}var ji;(function(T){T[T.CONNECTING=0]="CONNECTING",T[T.OPEN=1]="OPEN",T[T.CLOSED=3]="CLOSED"})(ji||(ji={}));var Ka=ji,nl=1;class vh{constructor(C,_){this.hooks=C,this.session=Ni(1e3)+"/"+Fs(8),this.location=wh(_),this.readyState=Ka.CONNECTING,this.openStream()}send(C){return this.sendRaw(JSON.stringify([C]))}ping(){this.hooks.sendHeartbeat(this)}close(C,_){this.onClose(C,_,!0)}sendRaw(C){if(this.readyState===Ka.OPEN)try{return Xe.createSocketRequest("POST",da(ki(this.location,this.session))).start(C),!0}catch{return!1}else return!1}reconnect(){this.closeStream(),this.openStream()}onClose(C,_,I){this.closeStream(),this.readyState=Ka.CLOSED,this.onclose&&this.onclose({code:C,reason:_,wasClean:I})}onChunk(C){if(C.status===200){this.readyState===Ka.OPEN&&this.onActivity();var _,I=C.data.slice(0,1);switch(I){case"o":_=JSON.parse(C.data.slice(1)||"{}"),this.onOpen(_);break;case"a":_=JSON.parse(C.data.slice(1)||"[]");for(var P=0;P<_.length;P++)this.onEvent(_[P]);break;case"m":_=JSON.parse(C.data.slice(1)||"null"),this.onEvent(_);break;case"h":this.hooks.onHeartbeat(this);break;case"c":_=JSON.parse(C.data.slice(1)||"[]"),this.onClose(_[0],_[1],!0);break}}}onOpen(C){this.readyState===Ka.CONNECTING?(C&&C.hostname&&(this.location.base=al(this.location.base,C.hostname)),this.readyState=Ka.OPEN,this.onopen&&this.onopen()):this.onClose(1006,"Server lost session",!0)}onEvent(C){this.readyState===Ka.OPEN&&this.onmessage&&this.onmessage({data:C})}onActivity(){this.onactivity&&this.onactivity()}onError(C){this.onerror&&this.onerror(C)}openStream(){this.stream=Xe.createSocketRequest("POST",da(this.hooks.getReceiveURL(this.location,this.session))),this.stream.bind("chunk",C=>{this.onChunk(C)}),this.stream.bind("finished",C=>{this.hooks.onFinished(this,C)}),this.stream.bind("buffer_too_long",()=>{this.reconnect()});try{this.stream.start()}catch(C){oe.defer(()=>{this.onError(C),this.onClose(1006,"Could not start streaming",!1)})}}closeStream(){this.stream&&(this.stream.unbind_all(),this.stream.close(),this.stream=null)}}function wh(T){var C=/([^\?]*)\/*(\??.*)/.exec(T);return{base:C[1],queryString:C[2]}}function ki(T,C){return T.base+"/"+C+"/xhr_send"}function da(T){var C=T.indexOf("?")===-1?"?":"&";return T+C+"t="+ +new Date+"&n="+nl++}function al(T,C){var _=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(T);return _[1]+C+_[3]}function Ni(T){return Xe.randomInt(T)}function Fs(T){for(var C=[],_=0;_0&&T.onChunk(_.status,_.responseText);break;case 4:_.responseText&&_.responseText.length>0&&T.onChunk(_.status,_.responseText),T.emit("finished",_.status),T.close();break}},_},abortRequest:function(T){T.onreadystatechange=null,T.abort()}},rl=Oa,Rr={createStreamingSocket(T){return this.createSocket(sl,T)},createPollingSocket(T){return this.createSocket(Dr,T)},createSocket(T,C){return new Vs(T,C)},createXHR(T,C){return this.createRequest(rl,T,C)},createRequest(T,C,_){return new bh(T,C,_)}},La=Rr;La.createXDR=function(T,C){return this.createRequest(xd,T,C)};var il=La,Ei={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:d,DependenciesReceivers:p,getDefaultStrategy:tl,Transports:Xn,transportConnectionInitializer:qs,HTTPFactory:il,TimelineTransport:Ta,getXHRAPI(){return window.XMLHttpRequest},getWebSocketAPI(){return window.WebSocket||window.MozWebSocket},setup(T){window.Pusher=T;var C=()=>{this.onDocumentBody(T.ready)};window.JSON?C():y.load("json2",{},C)},getDocument(){return document},getProtocol(){return this.getDocument().location.protocol},getAuthorizers(){return{ajax:we,jsonp:wt}},onDocumentBody(T){document.body?T():setTimeout(()=>{this.onDocumentBody(T)},0)},createJSONPRequest(T,C){return new qt(T,C)},createScriptRequest(T){return new Tt(T)},getLocalStorage(){try{return window.localStorage}catch{return}},createXHR(){return this.getXHRAPI()?this.createXMLHttpRequest():this.createMicrosoftXHR()},createXMLHttpRequest(){var T=this.getXHRAPI();return new T},createMicrosoftXHR(){return new ActiveXObject("Microsoft.XMLHTTP")},getNetwork(){return In},createWebSocket(T){var C=this.getWebSocketAPI();return new C(T)},createSocketRequest(T,C){if(this.isXHRSupported())return this.HTTPFactory.createXHR(T,C);if(this.isXDRSupported(C.indexOf("https:")===0))return this.HTTPFactory.createXDR(T,C);throw"Cross-origin HTTP requests are not supported"},isXHRSupported(){var T=this.getXHRAPI();return!!T&&new T().withCredentials!==void 0},isXDRSupported(T){var C=T?"https:":"http:",_=this.getProtocol();return!!window.XDomainRequest&&_===C},addUnloadListener(T){window.addEventListener!==void 0?window.addEventListener("unload",T,!1):window.attachEvent!==void 0&&window.attachEvent("onunload",T)},removeUnloadListener(T){window.addEventListener!==void 0?window.removeEventListener("unload",T,!1):window.detachEvent!==void 0&&window.detachEvent("onunload",T)},randomInt(T){return Math.floor(function(){return(window.crypto||window.msCrypto).getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}()*T)}},Xe=Ei,Ks;(function(T){T[T.ERROR=3]="ERROR",T[T.INFO=6]="INFO",T[T.DEBUG=7]="DEBUG"})(Ks||(Ks={}));var fs=Ks;class wd{constructor(C,_,I){this.key=C,this.session=_,this.events=[],this.options=I||{},this.sent=0,this.uniqueID=0}log(C,_){C<=this.options.level&&(this.events.push(ke({},_,{timestamp:oe.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(C){this.log(fs.ERROR,C)}info(C){this.log(fs.INFO,C)}debug(C){this.log(fs.DEBUG,C)}isEmpty(){return this.events.length===0}send(C,_){var I=ke({session:this.session,bundle:this.sent+1,key:this.key,lib:"js",version:this.options.version,cluster:this.options.cluster,features:this.options.features,timeline:this.events},this.options.params);return this.events=[],C(I,(P,fe)=>{P||this.sent++,_&&_(P,fe)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class En{constructor(C,_,I,P){this.name=C,this.priority=_,this.transport=I,this.options=P||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(C,_){if(this.isSupported()){if(this.priority{I||(yt(),fe?fe.close():P.close())},forceMinPriority:Kt=>{I||this.priority{var _="socket_id="+encodeURIComponent(T.socketId);for(var I in C.params)_+="&"+encodeURIComponent(I)+"="+encodeURIComponent(C.params[I]);if(C.paramsProvider!=null){let P=C.paramsProvider();for(var I in P)_+="&"+encodeURIComponent(I)+"="+encodeURIComponent(P[I])}return _};var Ti=T=>{if(typeof Xe.getAuthorizers()[T.transport]>"u")throw`'${T.transport}' is not a recognized auth transport`;return(C,_)=>{const I=ll(C,T);Xe.getAuthorizers()[T.transport](Xe,I,T,w.UserAuthentication,_)}};const Sd=(T,C)=>{var _="socket_id="+encodeURIComponent(T.socketId);_+="&channel_name="+encodeURIComponent(T.channelName);for(var I in C.params)_+="&"+encodeURIComponent(I)+"="+encodeURIComponent(C.params[I]);if(C.paramsProvider!=null){let P=C.paramsProvider();for(var I in P)_+="&"+encodeURIComponent(I)+"="+encodeURIComponent(P[I])}return _};var Ch=T=>{if(typeof Xe.getAuthorizers()[T.transport]>"u")throw`'${T.transport}' is not a recognized auth transport`;return(C,_)=>{const I=Sd(C,T);Xe.getAuthorizers()[T.transport](Xe,I,T,w.ChannelAuthorization,_)}};const jh=(T,C,_)=>{const I={authTransport:C.transport,authEndpoint:C.endpoint,auth:{params:C.params,headers:C.headers}};return(P,fe)=>{const Ne=T.channel(P.channelName);_(Ne,I).authorize(P.socketId,fe)}};function cl(T,C){let _={activityTimeout:T.activityTimeout||h.activityTimeout,cluster:T.cluster,httpPath:T.httpPath||h.httpPath,httpPort:T.httpPort||h.httpPort,httpsPort:T.httpsPort||h.httpsPort,pongTimeout:T.pongTimeout||h.pongTimeout,statsHost:T.statsHost||h.stats_host,unavailableTimeout:T.unavailableTimeout||h.unavailableTimeout,wsPath:T.wsPath||h.wsPath,wsPort:T.wsPort||h.wsPort,wssPort:T.wssPort||h.wssPort,enableStats:Ah(T),httpHost:kh(T),useTLS:_h(T),wsHost:Nh(T),userAuthenticator:Cd(T),channelAuthorizer:Dh(T,C)};return"disabledTransports"in T&&(_.disabledTransports=T.disabledTransports),"enabledTransports"in T&&(_.enabledTransports=T.enabledTransports),"ignoreNullOrigin"in T&&(_.ignoreNullOrigin=T.ignoreNullOrigin),"timelineParams"in T&&(_.timelineParams=T.timelineParams),"nacl"in T&&(_.nacl=T.nacl),_}function kh(T){return T.httpHost?T.httpHost:T.cluster?`sockjs-${T.cluster}.pusher.com`:h.httpHost}function Nh(T){return T.wsHost?T.wsHost:Eh(T.cluster)}function Eh(T){return`ws-${T}.pusher.com`}function _h(T){return Xe.getProtocol()==="https:"?!0:T.forceTLS!==!1}function Ah(T){return"enableStats"in T?T.enableStats:"disableStats"in T?!T.disableStats:!1}function Cd(T){const C=Object.assign(Object.assign({},h.userAuthentication),T.userAuthentication);return"customHandler"in C&&C.customHandler!=null?C.customHandler:Ti(C)}function Th(T,C){let _;return"channelAuthorization"in T?_=Object.assign(Object.assign({},h.channelAuthorization),T.channelAuthorization):(_={transport:T.authTransport||h.authTransport,endpoint:T.authEndpoint||h.authEndpoint},"auth"in T&&("params"in T.auth&&(_.params=T.auth.params),"headers"in T.auth&&(_.headers=T.auth.headers)),"authorizer"in T&&(_.customHandler=jh(C,_,T.authorizer))),_}function Dh(T,C){const _=Th(T,C);return"customHandler"in _&&_.customHandler!=null?_.customHandler:Ch(_)}class Rh extends Re{constructor(C){super(function(_,I){tt.debug(`No callbacks on watchlist events for ${_}`)}),this.pusher=C,this.bindWatchlistInternalEvent()}handleEvent(C){C.data.events.forEach(_=>{this.emit(_.name,_)})}bindWatchlistInternalEvent(){this.pusher.connection.bind("message",C=>{var _=C.event;_==="pusher_internal:watchlist_events"&&this.handleEvent(C)})}}function Oh(){let T,C;return{promise:new Promise((I,P)=>{T=I,C=P}),resolve:T,reject:C}}var dl=Oh;class Lh extends Re{constructor(C){super(function(_,I){tt.debug("No callbacks on user for "+_)}),this.signin_requested=!1,this.user_data=null,this.serverToUserChannel=null,this.signinDonePromise=null,this._signinDoneResolve=null,this._onAuthorize=(_,I)=>{if(_){tt.warn(`Error during signin: ${_}`),this._cleanup();return}this.pusher.send_event("pusher:signin",{auth:I.auth,user_data:I.user_data})},this.pusher=C,this.pusher.connection.bind("state_change",({previous:_,current:I})=>{_!=="connected"&&I==="connected"&&this._signin(),_==="connected"&&I!=="connected"&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new Rh(C),this.pusher.connection.bind("message",_=>{var I=_.event;I==="pusher:signin_success"&&this._onSigninSuccess(_.data),this.serverToUserChannel&&this.serverToUserChannel.name===_.channel&&this.serverToUserChannel.handleEvent(_)})}signin(){this.signin_requested||(this.signin_requested=!0,this._signin())}_signin(){this.signin_requested&&(this._newSigninPromiseIfNeeded(),this.pusher.connection.state==="connected"&&this.pusher.config.userAuthenticator({socketId:this.pusher.connection.socket_id},this._onAuthorize))}_onSigninSuccess(C){try{this.user_data=JSON.parse(C.user_data)}catch{tt.error(`Failed parsing user data after signin: ${C.user_data}`),this._cleanup();return}if(typeof this.user_data.id!="string"||this.user_data.id===""){tt.error(`user_data doesn't contain an id. user_data: ${this.user_data}`),this._cleanup();return}this._signinDoneResolve(),this._subscribeChannels()}_subscribeChannels(){const C=_=>{_.subscriptionPending&&_.subscriptionCancelled?_.reinstateSubscription():!_.subscriptionPending&&this.pusher.connection.state==="connected"&&_.subscribe()};this.serverToUserChannel=new vi(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((_,I)=>{_.indexOf("pusher_internal:")===0||_.indexOf("pusher:")===0||this.emit(_,I)}),C(this.serverToUserChannel)}_cleanup(){this.user_data=null,this.serverToUserChannel&&(this.serverToUserChannel.unbind_all(),this.serverToUserChannel.disconnect(),this.serverToUserChannel=null),this.signin_requested&&this._signinDoneResolve()}_newSigninPromiseIfNeeded(){if(!this.signin_requested||this.signinDonePromise&&!this.signinDonePromise.done)return;const{promise:C,resolve:_}=dl();C.done=!1;const I=()=>{C.done=!0};C.then(I).catch(I),this.signinDonePromise=C,this._signinDoneResolve=_}}class gn{static ready(){gn.isReady=!0;for(var C=0,_=gn.instances.length;C<_;C++)gn.instances[C].connect()}static getClientFeatures(){return Ie(Et({ws:Xe.Transports.ws},function(C){return C.isSupported({})}))}constructor(C,_){jd(C),ol(_),this.key=C,this.config=cl(_,this),this.channels=Da.createChannels(),this.global_emitter=new Re,this.sessionID=Xe.randomInt(1e9),this.timeline=new wd(this.key,this.sessionID,{cluster:this.config.cluster,features:gn.getClientFeatures(),params:this.config.timelineParams||{},limit:50,level:fs.INFO,version:h.VERSION}),this.config.enableStats&&(this.timelineSender=Da.createTimelineSender(this.timeline,{host:this.config.statsHost,path:"/timeline/v2/"+Xe.TimelineTransport.name}));var I=P=>Xe.getDefaultStrategy(this.config,P,Or);this.connection=Da.createConnectionManager(this.key,{getStrategy:I,timeline:this.timeline,activityTimeout:this.config.activityTimeout,pongTimeout:this.config.pongTimeout,unavailableTimeout:this.config.unavailableTimeout,useTLS:!!this.config.useTLS}),this.connection.bind("connected",()=>{this.subscribeAll(),this.timelineSender&&this.timelineSender.send(this.connection.isUsingTLS())}),this.connection.bind("message",P=>{var fe=P.event,Ne=fe.indexOf("pusher_internal:")===0;if(P.channel){var ze=this.channel(P.channel);ze&&ze.handleEvent(P)}Ne||this.global_emitter.emit(P.event,P.data)}),this.connection.bind("connecting",()=>{this.channels.disconnect()}),this.connection.bind("disconnected",()=>{this.channels.disconnect()}),this.connection.bind("error",P=>{tt.warn(P)}),gn.instances.push(this),this.timeline.info({instances:gn.instances.length}),this.user=new Lh(this),gn.isReady&&this.connect()}channel(C){return this.channels.find(C)}allChannels(){return this.channels.all()}connect(){if(this.connection.connect(),this.timelineSender&&!this.timelineSenderTimer){var C=this.connection.isUsingTLS(),_=this.timelineSender;this.timelineSenderTimer=new re(6e4,function(){_.send(C)})}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(C,_,I){return this.global_emitter.bind(C,_,I),this}unbind(C,_,I){return this.global_emitter.unbind(C,_,I),this}bind_global(C){return this.global_emitter.bind_global(C),this}unbind_global(C){return this.global_emitter.unbind_global(C),this}unbind_all(C){return this.global_emitter.unbind_all(),this}subscribeAll(){var C;for(C in this.channels.channels)this.channels.channels.hasOwnProperty(C)&&this.subscribe(C)}subscribe(C){var _=this.channels.add(C,this);return _.subscriptionPending&&_.subscriptionCancelled?_.reinstateSubscription():!_.subscriptionPending&&this.connection.state==="connected"&&_.subscribe(),_}unsubscribe(C){var _=this.channels.find(C);_&&_.subscriptionPending?_.cancelSubscription():(_=this.channels.remove(C),_&&_.subscribed&&_.unsubscribe())}send_event(C,_,I){return this.connection.send_event(C,_,I)}shouldUseTLS(){return this.config.useTLS}signin(){this.user.signin()}}gn.instances=[],gn.isReady=!1,gn.logToConsole=!1,gn.Runtime=Xe,gn.ScriptReceivers=Xe.ScriptReceivers,gn.DependenciesReceivers=Xe.DependenciesReceivers,gn.auth_callbacks=Xe.auth_callbacks;var ul=a.default=gn;function jd(T){if(T==null)throw"You must pass your app key when you instantiate Pusher."}Xe.setup(gn)})])})})(Ig)),Ig.exports}var qj=Uj();const Yy=es(qj),Ft=it("WebSocketManager");class Gj{constructor(){H(this,"echo",null);H(this,"subscriptions",new Map);H(this,"initialized",!1);H(this,"config",null)}configure(e){if(this.initialized){Ft.warn("[WebSocketManager] 이미 초기화되어 설정을 변경할 수 없습니다.");return}this.config=e,Ft.log("[WebSocketManager] 설정 완료:",{appKey:e.appKey?"***":"(없음)",host:e.host,port:e.port,scheme:e.scheme})}initialize(){if(this.initialized)return;if(!this.config||!this.config.appKey){Ft.warn("[WebSocketManager] WebSocket 설정이 없습니다. initTemplateApp에서 websocket 옵션을 전달해주세요.");return}const{appKey:e,host:t="localhost",port:a=80,scheme:i="https",authEndpoint:o="/api/broadcasting/auth"}=this.config,d=Number(a)||80,g=i==="https";Ft.log("[WebSocketManager] 연결 설정:",{host:t,port:d,scheme:i,useTLS:g,authEndpoint:o}),window.Pusher=Yy;const h=localStorage.getItem("auth_token"),f={wsHost:t,wsPort:d,wssPort:d,forceTLS:g,disableStats:!0,enabledTransports:["ws","wss"],cluster:"mt1",authEndpoint:o,auth:{headers:{Authorization:h?`Bearer ${h}`:"",Accept:"application/json"}}};Ft.log("[WebSocketManager] Pusher 옵션:",f);const p=new Yy(e,f);p.connection.bind("connecting",()=>{Ft.log("[WebSocketManager] 연결 시도 중...")}),p.connection.bind("connected",()=>{Ft.log("[WebSocketManager] 연결 성공! Socket ID:",p.connection.socket_id)}),p.connection.bind("failed",()=>{Ft.error("[WebSocketManager] 연결 실패 - WebSocket을 사용할 수 없습니다.")}),p.connection.bind("error",y=>{Ft.error("[WebSocketManager] 연결 오류:",y)}),p.connection.bind("state_change",y=>{Ft.log(`[WebSocketManager] 상태 변경: ${y.previous} → ${y.current}`)}),p.connection.bind("unavailable",()=>{Ft.error("[WebSocketManager] WebSocket 사용 불가 - 연결할 수 없습니다.")}),p.connection.bind("disconnected",()=>{Ft.warn("[WebSocketManager] 연결이 끊어졌습니다.")}),Ft.log("[WebSocketManager] 초기 연결 상태:",p.connection.state),this.echo=new Bj({broadcaster:"reverb",client:p}),Ft.log("[WebSocketManager] 연결 시작 시도..."),p.connect(),window.Echo=this.echo,this.initialized=!0,Ft.log("[WebSocketManager] Echo 초기화 완료")}subscribe(e,t,a,i={}){if(this.initialize(),!this.echo)return Ft.warn("[WebSocketManager] Echo가 초기화되지 않았습니다."),"";const{channelType:o="private"}=i,d=`${e}:${t}`;if(this.subscriptions.has(d))return Ft.log(`[WebSocketManager] 이미 구독 중: ${d}`),d;let g;switch(o){case"public":g=this.echo.channel(e);break;case"presence":g=this.echo.join(e);break;default:g=this.echo.private(e)}return g.listen(`.${t}`,a),this.subscriptions.set(d,g),Ft.log(`[WebSocketManager] 구독 완료: ${d} (${o})`),d}unsubscribe(e){const t=this.subscriptions.get(e);if(!t)return;const a=e.lastIndexOf(":"),i=a>=0?e.substring(a+1):"";if(i)try{t.stopListening(`.${i}`)}catch(o){Ft.warn(`[WebSocketManager] stopListening 실패: ${e}`,o)}this.subscriptions.delete(e),Ft.log(`[WebSocketManager] 구독 해제: ${e}`)}leaveChannel(e){if(!this.echo)return;this.echo.leave(e);const t=[];this.subscriptions.forEach((a,i)=>{i.startsWith(`${e}:`)&&t.push(i)}),t.forEach(a=>this.subscriptions.delete(a)),Ft.log(`[WebSocketManager] 채널 구독 해제: ${e}`)}disconnect(){this.echo&&(this.echo.disconnect(),this.subscriptions.clear(),this.initialized=!1,Ft.log("[WebSocketManager] 연결 종료"))}getEcho(){return this.echo}isInitialized(){return this.initialized}isConfigured(){return this.config!==null&&!!this.config.appKey}getSubscriptionCount(){return this.subscriptions.size}}const Mc=new Gj,kt=it("DataSourceManager"),Fj=new _n;function $c(r,e){const t=r.match(/^\{\{(.+)\}\}$/);if(t){const a=t[1].trim();try{return Fj.evaluateExpression(a,e)}catch(i){return kt.error("Failed to evaluate param expression:",a,i),r}}return ni(r,e,{skipCache:!0})}function Jy(r){const e={};for(const t of r.keys()){if(t in e)continue;const a=r.getAll(t);a.length>1?e[t]=a:a.length===1&&(t.endsWith("[]")?e[t]=a:e[t]=a[0])}return e}function Vj(){try{return window.G7Core?.devTools}catch{return}}const hd=class hd{constructor(e={}){H(this,"options");H(this,"dataCache",new Map);H(this,"bindingEngine");H(this,"globalHeaders",[]);this.options=e,this.bindingEngine=new _n}setGlobalHeaders(e){this.globalHeaders=e||[]}matchesPattern(e,t){if(t==="*")return!0;const a=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${a}$`).test(e)}toFormData(e){const t=new FormData;for(const[a,i]of Object.entries(e))i instanceof File||i instanceof Blob?t.append(a,i):i!=null&&t.append(a,typeof i=="object"?JSON.stringify(i):String(i));return t}getMatchingGlobalHeaders(e,t){const a={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([o,d])=>{const g=$c(d,t);g!=null&&g!==""&&(a[o]=String(g))});return a}filterByCondition(e,t={}){const a=new Set,i=[];for(const o of e){if(a.has(o.id))continue;if(!o.if&&!o.conditions){a.add(o.id),i.push(o);continue}ti({if:o.if,conditions:o.conditions},t,this.bindingEngine,`data_source:${o.id}`)&&(a.add(o.id),i.push(o))}return i}checkErrorCondition(e,t){if(!e.errorCondition?.if||e.errorCondition?.errorCode===void 0)return null;try{const a={response:t};if(ti({if:e.errorCondition.if},a,this.bindingEngine,`errorCondition:${e.id}`))return kt.log(`errorCondition matched for ${e.id}, triggering error ${e.errorCondition.errorCode}`),e.errorCondition.errorCode}catch(a){kt.error(`Failed to evaluate errorCondition for ${e.id}:`,a)}return null}async fetchDataSources(e,t={},a=new URLSearchParams,i,o){const d={},g=e.filter(h=>h.auto_fetch!==!1&&h.type!=="websocket");return await Promise.all(g.map(async h=>{try{const f=await this.fetchDataSource(h,t,a,i,o);d[h.id]=f,this.dataCache.set(h.id,{data:f,timestamp:Date.now()});const p=this.checkErrorCondition(h,f);if(p!==null){const y={status:p,message:`Error condition matched for ${h.id}`,data:f},x=Sa(),S=x.resolve(p,{errorHandling:h.errorHandling,onError:h.onError});if(S.handler)try{await x.execute(S.handler,y)}catch(v){kt.error(`Error executing errorCondition handler for ${h.id}:`,v)}h.fallback!==void 0&&(d[h.id]=h.fallback,this.dataCache.set(h.id,{data:h.fallback,timestamp:Date.now()}),kt.log(`Using fallback data for ${h.id} (errorCondition)`));return}if(h.onSuccess)try{const y={data:f,sourceId:h.id};await this.executeOnSuccessHandler(h.onSuccess,y)}catch(y){kt.error(`Error executing onSuccess handler for ${h.id}:`,y)}}catch(f){kt.error(`Failed to fetch data source: ${h.id}`,f);const p=f?.response?.status||f?.status||500,y=f?.response?.data,x=y?.message||f.message||"Unknown error",S={status:p,message:x,errors:y?.errors,data:y,statusText:f?.response?.statusText},v=Sa(),w=v.resolve(p,{errorHandling:h.errorHandling,onError:h.onError});if(w.handler)try{await v.execute(w.handler,S)}catch(k){kt.error(`Error executing error handler for ${h.id}:`,k)}h.fallback!==void 0&&(d[h.id]=h.fallback,this.dataCache.set(h.id,{data:h.fallback,timestamp:Date.now()}),kt.log(`Using fallback data for ${h.id}`)),this.options.onError&&this.options.onError(f,h)}})),d}async fetchDataSourcesWithResults(e,t={},a=new URLSearchParams,i,o,d){if(e.some(p=>p.type==="websocket")){const p=e.filter(y=>y.type==="websocket").map(y=>y.id).join(", ");kt.warn(`fetchDataSourcesWithResults received WebSocket sources (caller should filter them out before calling): ${p}. WebSocket sources are event listeners, not data providers — they should not be passed to fetch.`)}const h=d?.ignoreAutoFetch?e.filter(p=>p.type!=="websocket"):e.filter(p=>p.auto_fetch!==!1&&p.type!=="websocket");return await Promise.all(h.map(async p=>{try{const y=await this.fetchDataSource(p,t,a,i,o);this.dataCache.set(p.id,{data:y,timestamp:Date.now()});const x=this.checkErrorCondition(p,y);if(x!==null){const S={status:x,message:`Error condition matched for ${p.id}`,data:y},v=Sa(),w=v.resolve(x,{errorHandling:p.errorHandling,onError:p.onError});let k=!1;if(w.handler)if(p.loading_strategy==="blocking")v.execute(w.handler,S).catch(A=>{kt.error(`Error executing errorCondition handler for ${p.id}:`,A)}),k=!0;else try{await v.execute(w.handler,S),k=!0}catch(A){kt.error(`Error executing errorCondition handler for ${p.id}:`,A)}return p.fallback!==void 0?(this.dataCache.set(p.id,{data:p.fallback,timestamp:Date.now()}),kt.log(`Using fallback data for ${p.id} (errorCondition)`),{id:p.id,state:"success",data:p.fallback}):{id:p.id,state:"error",error:new Error(`Error condition matched: ${x}`),errorCode:x,errorHandled:k}}if(p.onSuccess)try{const S={data:y,sourceId:p.id};await this.executeOnSuccessHandler(p.onSuccess,S)}catch(S){kt.error(`Error executing onSuccess handler for ${p.id}:`,S)}return{id:p.id,state:"success",data:y}}catch(y){kt.error(`Failed to fetch data source: ${p.id}`,y);const x=y?.response?.status||y?.status||500,S=y?.response?.data,v=S?.message||y.message||"Unknown error",w={status:x,message:v,errors:S?.errors,data:S,statusText:y?.response?.statusText},k=Sa(),A=k.resolve(x,{errorHandling:p.errorHandling,onError:p.onError});let O=!1;if(A.handler)if(p.loading_strategy==="blocking")k.execute(A.handler,w).catch(N=>{kt.error(`Error executing error handler for ${p.id}:`,N)}),O=!0;else try{await k.execute(A.handler,w),O=!0}catch(N){kt.error(`Error executing error handler for ${p.id}:`,N)}return p.fallback!==void 0?(this.dataCache.set(p.id,{data:p.fallback,timestamp:Date.now()}),kt.log(`Using fallback data for ${p.id}`),{id:p.id,state:"success",data:p.fallback}):(this.options.onError&&this.options.onError(y,p),{id:p.id,state:"error",error:y,errorCode:x,errorHandled:O})}}))}fetchDataSourcesInBackground(e,t={},a=new URLSearchParams,i){e.filter(d=>d.auto_fetch!==!1&&d.loading_strategy==="background"&&d.type!=="websocket").forEach(d=>{this.fetchDataSource(d,t,a).then(async g=>{this.dataCache.set(d.id,{data:g,timestamp:Date.now()});const h=this.checkErrorCondition(d,g);if(h!==null){const f={status:h,message:`Error condition matched for ${d.id}`,data:g},p=Sa(),y=p.resolve(h,{errorHandling:d.errorHandling,onError:d.onError});if(y.handler)try{await p.execute(y.handler,f)}catch(x){kt.error(`Error executing errorCondition handler for ${d.id}:`,x)}d.fallback!==void 0&&(this.dataCache.set(d.id,{data:d.fallback,timestamp:Date.now()}),kt.log(`Using fallback data for ${d.id} (errorCondition)`),i&&i(d.id,d.fallback));return}if(d.onSuccess)try{const f={data:g,sourceId:d.id};await this.executeOnSuccessHandler(d.onSuccess,f)}catch(f){kt.error(`Error executing onSuccess handler for ${d.id}:`,f)}i&&i(d.id,g)}).catch(async g=>{kt.error(`Background fetch failed: ${d.id}`,g);const h=g?.response?.status||g?.status||500,f=g?.response?.data,p=f?.message||g.message||"Unknown error",y={status:h,message:p,errors:f?.errors,data:f,statusText:g?.response?.statusText},x=Sa(),S=x.resolve(h,{errorHandling:d.errorHandling,onError:d.onError});if(S.handler)try{await x.execute(S.handler,y)}catch(v){kt.error(`Error executing error handler for ${d.id}:`,v)}if(d.fallback!==void 0){this.dataCache.set(d.id,{data:d.fallback,timestamp:Date.now()}),kt.log(`Using fallback data for ${d.id}`),i&&i(d.id,d.fallback);return}this.options.onError&&this.options.onError(g,d)})})}async fetchDataSource(e,t,a,i,o){switch(e.type){case"api":return this.fetchApiDataSource(e,t,a,i,o);case"static":return e.data;case"route_params":return t;case"query_params":return Jy(a);default:throw new Error(`Unknown data source type: ${e.type}`)}}async fetchApiDataSource(e,t,a,i,o){if(!e.endpoint)throw new Error(`API data source ${e.id} has no endpoint`);const d={route:t,query:Jy(a)};i&&(d._global=i),o&&(d._local=o);let g=ni(e.endpoint,d,{skipCache:!0});const h=e.method||"GET",p=(e.contentType?typeof e.contentType=="string"&&e.contentType.includes("{{")?ni(e.contentType,d,{skipCache:!0}):e.contentType:"application/json")==="multipart/form-data";let y=p?{...e.params||{}}:JSON.parse(JSON.stringify(e.params||{}));Object.entries(y).forEach(([v,w])=>{typeof w=="string"&&(y[v]=$c(w,d))}),Object.keys(y).forEach(v=>{y[v]===""&&delete y[v]});const x=Vj();let S=null;if(x?.isEnabled()){x.trackDataSourceDefinition({id:e.id,type:e.type,endpoint:g,method:h,autoFetch:e.auto_fetch,initLocal:e.initLocal,initGlobal:e.initGlobal});let v=g;if(h==="GET"&&Object.keys(y).length>0){const w=new URLSearchParams;Object.entries(y).forEach(([A,O])=>{Array.isArray(O)?O.forEach(N=>w.append(A,String(N))):O!=null&&w.append(A,String(O))});const k=w.toString();v=k?`${g}?${k}`:g}S=x.trackRequest(v,h,{requestBody:h!=="GET"?y:void 0,dataSourceId:e.id}),x.trackDataSourceLoading(e.id)}try{let v;const w=e.auth_mode??(e.auth_required===!0?"required":"none"),k=as.getInstance().isAuthenticated();if(w==="required"&&!k){kt.log(`[DataSourceManager] Skipping ${e.id}: auth_mode is 'required' but no token available`),x?.isEnabled()&&(x.trackDataSourceError(e.id,"Skipped: auth_mode required but not authenticated"),S&&x.failRequest(S,"Skipped: not authenticated"));const O=new Error("Auth required but not authenticated");throw O.response={status:401,statusText:"Unauthorized",data:null},O.status=401,O._authSkipped=!0,O}const A=w==="required"||w==="optional"&&k;if(A){const O=ns(),N=g.startsWith("/api/")?g.substring(4):g.startsWith("/api")?g.substring(4)||"/":g;this.options.onError&&kt.log(`[DataSourceManager] Normalized endpoint: ${g} -> ${N}`);const D=this.getMatchingGlobalHeaders(g,d),$={};e.headers&&Object.entries(e.headers).forEach(([ye,we])=>{const J=$c(we,d);J!=null&&J!==""&&($[ye]=String(J))});const M={...D,...$},z=Object.keys(M).length>0,K=p?this.toFormData(y):y;switch(h){case"GET":v=await O.get(N,{params:y,...z&&{headers:M}});break;case"POST":z?v=await O.post(N,K,{headers:M}):v=await O.post(N,K);break;case"PUT":z?v=await O.put(N,K,{headers:M}):v=await O.put(N,K);break;case"PATCH":z?v=await O.patch(N,K,{headers:M}):v=await O.patch(N,K);break;case"DELETE":v=await O.delete(N,{params:y,...z&&{headers:M}});break;default:throw new Error(`Unsupported HTTP method: ${h}`)}}else{let O=g;if(h==="GET"){const K=new URLSearchParams(y).toString();O=K?`${g}?${K}`:g}const N={...p?{}:{"Content-Type":"application/json"},Accept:"application/json"};if(typeof window<"u"){const K=localStorage.getItem("g7_locale");K&&(N["Accept-Language"]=K)}const D=this.getMatchingGlobalHeaders(g,d);Object.assign(N,D),e.headers&&Object.entries(e.headers).forEach(([K,ye])=>{const we=$c(ye,d);we!=null&&we!==""&&(N[K]=String(we))});let $;h!=="GET"&&(p?($=this.toFormData(y),delete N["Content-Type"]):$=JSON.stringify(y));const M=await fetch(O,{method:h,headers:N,body:$});let z;try{z=await M.json()}catch{z=null}if(S&&x?.isEnabled()&&(x.completeRequest(S,M.status,z),S=null),!M.ok){x?.isEnabled()&&x.trackDataSourceError(e.id,`HTTP ${M.status}: ${M.statusText}`);const K=new Error(`HTTP error! status: ${M.status}`);throw K.response={status:M.status,statusText:M.statusText,data:z},K.status=M.status,K}v=z,x?.isEnabled()&&x.trackDataSourceLoaded(e.id,v)}return A&&S&&x?.isEnabled()&&(x.completeRequest(S,200,v),x.trackDataSourceLoaded(e.id,v)),v}catch(v){if(S&&x?.isEnabled()){const w=v;w?.response?x.completeRequest(S,w.response.status,w.response.data):x.failRequest(S,v instanceof Error?v.message:String(v)),x.trackDataSourceError(e.id,v instanceof Error?v.message:String(v))}throw v}}getCachedData(e){const t=this.dataCache.get(e);if(!t)return;if(Date.now()-t.timestamp>hd.DATA_CACHE_TTL){this.dataCache.delete(e);return}return t.data}clearCache(){this.dataCache.clear()}subscribeWebSockets(e,t,a={}){const i=[],o=e.filter(d=>d.type==="websocket");return o.length===0||o.forEach(d=>{if(!d.channel||!d.event){kt.warn(`WebSocket source ${d.id} missing channel or event`);return}let g,h;try{g=ni(d.channel,a,{skipCache:!0}),h=ni(d.event,a,{skipCache:!0})}catch(y){kt.error(`Failed to resolve WebSocket channel/event for source ${d.id}:`,y);return}const f=y=>!!(!y||y.trim()===""||y.includes("{{")||y.endsWith(".")||y.endsWith(":")||y.startsWith(".")||y.startsWith(":")||y.includes("..")||y.includes("::"));if(f(g)||f(h)){kt.warn(`WebSocket source ${d.id} has invalid channel/event after expression resolution, skipping. Original channel="${d.channel}", resolved="${g}". Original event="${d.event}", resolved="${h}". Available context keys: [${Object.keys(a).join(", ")}]`);return}const p=Mc.subscribe(g,h,y=>{const x=d.target_source||d.id;this.dataCache.set(x,{data:y,timestamp:Date.now()}),t(x,y)},{channelType:d.channel_type||"private"});p&&i.push(p)}),i}unsubscribeWebSockets(e){e.length!==0&&e.forEach(t=>{Mc.unsubscribe(t)})}async executeOnSuccessHandler(e,t){const a=Fm();if(!a){kt.warn("ActionDispatcher not available, skipping onSuccess handler");return}const i=Array.isArray(e)?e:[e];for(const o of i)try{await a.dispatchAction({type:"click",...o},{data:{response:t}})}catch(d){throw kt.error("Failed to execute onSuccess handler:",d),d}}};H(hd,"DATA_CACHE_TTL",3e5);let is=hd;new is;const Sr=it("ModalDataSourceWrapper");function Kj(r,e){if(!r||!e)return r;const a=e.replace(/\?\./g,".").split(/\.(?![^\[]*\])/).flatMap(o=>{const d=o.match(/^([^\[]*)((?:\[\d+\])*)$/);if(d){const[,g,h]=d,f=[];g&&f.push(g);const p=h.match(/\[\d+\]/g);return p&&f.push(...p),f}return[o]}).filter(o=>o!=="");let i=r;for(const o of a){if(i==null)return;if(o.startsWith("[")&&o.endsWith("]")){const d=parseInt(o.slice(1,-1),10);i=i[d]}else i=i[o]}return i}const Xy=({isOpen:r,modalId:e,dataSources:t,dataContext:a,globalStateUpdater:i,bindingEngine:o,debug:d=!1,children:g})=>{const[h,f]=j.useState(!1),[p,y]=j.useState(!1),x=j.useRef(!1),S=j.useRef(null);S.current||(S.current=new is);const v=j.useCallback(async()=>{if(!(!t||t.length===0)&&S.current){f(!0);try{const w=a.route||{},k=new URLSearchParams(window.location.search),A=t.map(N=>{let D={...N};if(N.endpoint&&o){const $=o.resolveBindings(N.endpoint,a,{skipCache:!0});D.endpoint=$}if(N.params&&o){const $={};Object.entries(N.params).forEach(([M,z])=>{typeof z=="string"?$[M]=o.resolveBindings(z,a,{skipCache:!0}):$[M]=z}),D.params=$}return D});d&&Sr.log(`[ModalDataSourceWrapper] Modal "${e}" fetching data sources:`,A.map(N=>({id:N.id,endpoint:N.endpoint})));const O=await S.current.fetchDataSourcesWithResults(A,w,k);i&&O.forEach(N=>{if(N.state==="success"&&N.data!==void 0){const D=A.find($=>$.id===N.id);if(D?.initGlobal){const $=N.data?.data??N.data,M=Array.isArray(D.initGlobal)?D.initGlobal:[D.initGlobal];for(const z of M)if(typeof z=="string")i({[z]:$}),d&&Sr.log(`[ModalDataSourceWrapper] Modal "${e}" initGlobal: ${N.id}.data -> _global.${z}`);else if(typeof z=="object"&&z.key){const{key:K,path:ye}=z,we=ye?Kj($,ye):$;i({[K]:we}),d&&Sr.log(`Modal "${e}" initGlobal: ${N.id}.data${ye?"."+ye:""} -> _global.${K}`)}}}else N.state==="error"&&Sr.error(`Modal "${e}" data source error:`,N.id,N.error)}),d&&Sr.log(`Modal "${e}" data sources fetched successfully`)}catch(w){Sr.error(`Modal "${e}" data source fetch error:`,w)}finally{f(!1),y(!0)}}},[t,a,i,o,e,d]);return j.useEffect(()=>{if(!t||t.length===0)return;const w=window.__templateApp;return w?.registerModalDataSources&&w.registerModalDataSources(e,t),()=>{w?.unregisterModalDataSources&&w.unregisterModalDataSources(e)}},[e,t]),j.useEffect(()=>{!r&&x.current&&(y(!1),d&&Sr.log(`[ModalDataSourceWrapper] Modal "${e}" closed, reset fetch state`)),r&&!x.current&&t&&t.length>0&&!p&&v(),x.current=r},[r,t,p,v,e,d]),l.jsx(l.Fragment,{children:g})};class Ic extends Error{constructor(t,a,i={}){super(a);H(this,"code");H(this,"userMessageKey");H(this,"showStack");H(this,"icon");H(this,"recoverable");this.name="TemplateEngineError",this.code=t,this.userMessageKey=a,this.showStack=i.showStack??!0,this.icon=i.icon??"fa-circle-exclamation",this.recoverable=i.recoverable??!0,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}getUserMessage(t,a){if(!a||!t)return this.userMessageKey;try{return a.translate(this.userMessageKey,t)}catch{return this.userMessageKey}}}class Wj extends Ic{constructor(){super("TEMPLATE_NOT_FOUND","$t:core.errors.template_not_found",{showStack:!1,icon:"fa-paint-brush",recoverable:!1}),this.name="TemplateNotFoundError"}}function Qy(r){if(r instanceof Ic)return r;if(r instanceof Error){const e=new Ic("TEMPLATE_INIT_ERROR",r.message||"$t:core.errors.template_init_error",{showStack:!0,icon:"fa-circle-exclamation",recoverable:!0});return e.stack=r.stack,e}return new Ic("TEMPLATE_INIT_ERROR","$t:core.errors.template_init_error",{showStack:!1,icon:"fa-circle-exclamation",recoverable:!0})}const gi=it("Router");class Yj{constructor(e){H(this,"routes",[]);H(this,"templateIdentifier");H(this,"eventHandlers",new Map);H(this,"pendingNavigation",null);H(this,"isNavigating",!1);H(this,"handlePopState",()=>{this.navigateToCurrentPath()});this.templateIdentifier=e,this.initPopstateListener()}initPopstateListener(){window.addEventListener("popstate",this.handlePopState)}on(e,t){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(t)}async emit(e,...t){const a=this.eventHandlers.get(e);a&&await Promise.all(a.map(i=>i(...t)))}async loadRoutes(e){try{const t=e!==void 0&&e>0?`?v=${e}`:"",a=await fetch(`/api/templates/${this.templateIdentifier}/routes.json${t}`);if(!a.ok)throw new Error(`Failed to load routes: ${a.statusText}`);const i=await a.json();if(!i.success)throw new Error("Failed to load routes from API");if(i.data&&Array.isArray(i.data.routes))this.routes=i.data.routes,gi.log(`Loaded ${this.routes.length} routes${e?` (v=${e})`:""}`);else throw new Error("Invalid routes data format")}catch(t){throw gi.error("Error loading routes:",t),t}}setRoutes(e){this.routes=e,gi.log(`Set ${this.routes.length} routes`)}match(e){for(const t of this.routes){const a=this.matchPattern(t.path,e);if(a!==null)return{route:t,params:a}}return null}matchPattern(e,t){const a=[];let i=e.replace(/:([^/]+)/g,(h,f)=>(a.push(f),"([^/]+)"));i.startsWith("*/")&&(i="(?:/[^/]+)?"+i.slice(1)),i=i.replace(/\//g,"\\/");const o=new RegExp(`^${i}$`),d=t.match(o);if(!d)return null;const g={};return a.forEach((h,f)=>{g[h]=d[f+1]}),g}getRoutes(){return[...this.routes]}getAuthType(e,t){return e.auth_type?e.auth_type:t.startsWith("/admin")?"admin":"user"}async navigateToCurrentPath(){const e=window.location.pathname,t=window.location.search,a=this.match(e);if(!a){gi.warn(`No route matched for path: ${e}`),this.emit("routeNotFound",e);return}if(a.route.redirect){gi.log(`Redirecting from ${e} to ${a.route.redirect}`),this.navigate(a.route.redirect);return}if(a.route.auth_required){const d=this.getAuthType(a.route,e),g=as.getInstance();let h=g.isAuthenticated()&&g.getAuthType()===d;if(h||(h=await g.checkAuth(d)),!h){const f=g.getLoginRedirectUrl(d,e+t);gi.log(`Not authenticated, redirecting to: ${f}`),window.location.href=f;return}}const i=new URLSearchParams(t),o={};for(const d of i.keys()){if(d in o)continue;const g=i.getAll(d);g.length>1?o[d]=g:g.length===1&&(d.endsWith("[]")?o[d]=g:o[d]=g[0])}await this.emit("routeChange",{path:e,layout:a.route.layout,endpoint:a.route.endpoint,params:{...a.route.params||{},...a.params},query:o,auth_required:a.route.auth_required,auth_type:a.route.auth_type,meta:a.route.meta})}navigate(e){if(this.isNavigating){this.pendingNavigation=e;return}this.executeNavigation(e)}async executeNavigation(e){this.isNavigating=!0,this.pendingNavigation=null;try{window.history.pushState({},"",e),await this.navigateToCurrentPath()}finally{if(this.isNavigating=!1,this.pendingNavigation){const t=this.pendingNavigation;this.executeNavigation(t)}}}}const Jj=it("ErrorDisplay");class Zy{static render(e,t){const a=document.getElementById(e);if(!a){Jj.error(`Container #${e} not found`);return}const i=t.debug&&t.showStack&&t.stackTrace,o=window.matchMedia("(prefers-color-scheme: dark)").matches,d={container:` display: flex; align-items: center; justify-content: center; @@ -267,7 +267,7 @@ Error generating stack: `+u.message+` `:""} - `}static renderFromError(e,t,a,i=!1,o,d,g){let h,f;if(t.userMessageKey.startsWith("$t:"))if(d&&o)try{h=d.translate(t.userMessageKey,o)}catch{h=t.userMessageKey.replace("$t:","")}else h=t.userMessageKey.replace("$t:","");else h=t.userMessageKey;if(g){const p=g;p.details?.apiMessage?f=p.details.apiMessage:p.response?.data?.message&&(f=p.response.data.message)}this.render(e,{title:a,message:h,detailMessage:f,icon:t.icon,showStack:t.showStack,stackTrace:t.stack,showReloadButton:t.recoverable,debug:i})}static escapeHtml(e){if(!e)return"";const t=document.createElement("div");return t.textContent=e,t.innerHTML}}const Vt=it("ErrorPageHandler");class Jj{constructor(e){H(this,"templateId");H(this,"layoutLoader");H(this,"locale");H(this,"debug");H(this,"renderFunction");H(this,"dataSourceManager");H(this,"globalState");H(this,"errorConfig",null);H(this,"configLoaded",!1);this.templateId=e.templateId,this.layoutLoader=e.layoutLoader,this.locale=e.locale,this.debug=e.debug,this.renderFunction=e.renderFunction,this.dataSourceManager=e.dataSourceManager,this.globalState=e.globalState||{}}async loadConfig(){if(this.configLoaded)return this.errorConfig;try{const e=await fetch(`/api/templates/${this.templateId}/config.json`);if(!e.ok)return this.debug&&Vt.warn("Failed to load template config:",e.statusText),this.configLoaded=!0,null;const t=await e.json();if(!t.success||!t.data)return this.debug&&Vt.warn("Invalid template config response"),this.configLoaded=!0,null;const a=t.data;return!a.error_config||!a.error_config.layouts?(this.debug&&Vt.warn("No error_config found in template.json"),this.configLoaded=!0,null):(this.errorConfig=a.error_config,this.configLoaded=!0,this.debug&&Vt.log("Error config loaded:",this.errorConfig),this.errorConfig)}catch(e){return Vt.error("Failed to load error config:",e),this.configLoaded=!0,null}}async renderError(e,t="app"){try{const a=await this.loadConfig();if(!a)return this.debug&&Vt.warn("No error config available, cannot render error page"),!1;const i=a.layouts[e]||a.layouts[String(e)];if(!i)return this.debug&&Vt.warn(`No layout defined for error code: ${e}`),!1;this.debug&&Vt.log(`Loading error layout: ${i} for code: ${e}`);const o=await this.layoutLoader.loadLayout(this.templateId,i);if(!o)return this.debug&&Vt.error(`Failed to load error layout: ${i}`),!1;this.debug&&Vt.log("Error layout loaded:",o);let d={};const g=o.data_sources||[];if(g.length>0){this.debug&&Vt.log("Fetching data sources:",g.map(S=>S.id));const p=g.filter(S=>S.loading_strategy==="blocking"),y=g.filter(S=>!S.loading_strategy||S.loading_strategy==="progressive"),x=[...p,...y];if(x.length>0)try{d=await this.dataSourceManager.fetchDataSources(x,{},new URLSearchParams),this.debug&&Vt.log("Data sources fetched:",Object.keys(d))}catch(S){Vt.error("Failed to fetch data sources:",S)}}const h={};g.length>0&&(this.processInitOptions(g,d,h),this.debug&&Vt.log("initOptions processed:",{globalKeys:Object.keys(this.globalState),localKeys:Object.keys(h)}));const f={...d,errorCode:e,_global:{...this.globalState},_local:{...h}};return await this.renderFunction({containerId:t,layoutJson:o,dataContext:f,translationContext:{templateId:this.templateId,locale:this.locale}}),this.debug&&Vt.log(`Error page ${e} rendered successfully`),!0}catch(a){return Vt.error(`Failed to render error page ${e}:`,a),!1}}processInitOptions(e,t,a){for(const i of e){const o=t[i.id];if(!o)continue;const d=o?.data??o;if(i.initLocal){if(typeof i.initLocal=="string")a[i.initLocal]=d,Vt.log(`initLocal: ${i.id}.data -> _local.${i.initLocal}`);else if(typeof i.initLocal=="object"&&"key"in i.initLocal){const{key:g,path:h}=i.initLocal;a[g]=h?this.getValueByPath(d,h):d,Vt.log(`initLocal: ${i.id}.data${h?"."+h:""} -> _local.${g}`)}}if(i.initGlobal){const g=Array.isArray(i.initGlobal)?i.initGlobal:[i.initGlobal];for(const h of g)if(typeof h=="string")this.globalState[h]=d,Vt.log(`initGlobal: ${i.id}.data -> _global.${h}`);else if(typeof h=="object"&&h!==null&&"key"in h){const{key:f,path:p}=h;this.globalState[f]=p?this.getValueByPath(d,p):d,Vt.log(`initGlobal: ${i.id}.data${p?"."+p:""} -> _global.${f}`)}}}}getValueByPath(e,t){return t.split(".").reduce((a,i)=>a?.[i],e)}updateGlobalState(e){this.globalState={...this.globalState,...e}}updateLocale(e){this.locale=e,this.debug&&Vt.log("Locale updated:",e)}isConfigLoaded(){return this.configLoaded}async hasErrorLayout(e){const t=await this.loadConfig();return t?!!(t.layouts[e]||t.layouts[String(e)]):!1}clearConfigCache(){this.errorConfig=null,this.configLoaded=!1,this.debug&&Vt.log("Config cache cleared")}}const Mn=it("ModuleAssetLoader");class Xj{constructor(){H(this,"loadedAssets",new Map);H(this,"loadingPromises",new Map)}async loadActiveExtensionAssets(e){if(!e||e.length===0){Mn.log("No module assets to load");return}const t=[...e].sort((o,d)=>o.priority-d.priority);Mn.log("Loading module assets:",t.map(o=>o.identifier));const a=t.filter(o=>o.css).map(o=>this.loadCSS(o.identifier,o.css)),i=t.filter(o=>o.js).map(o=>this.loadJS(o.identifier,o.js));await Promise.all([...a,...i]),Mn.log("All module assets loaded successfully")}async loadCSS(e,t){const a=`module-css-${e}`;if(document.getElementById(a)){Mn.log(`CSS already loaded: ${e}`);return}return new Promise((i,o)=>{const d=document.createElement("link");d.rel="stylesheet",d.href=t,d.id=a,d.onload=()=>{Mn.log(`CSS loaded: ${e}`),this.registerLoadedAsset(e,{type:"css",element:d}),i()},d.onerror=()=>{Mn.warn(`Failed to load CSS: ${e} (${t})`),i()},document.head.appendChild(d)})}async loadJS(e,t){const a=`module-js-${e}`;if(document.getElementById(a)){Mn.log(`JS already loaded: ${e}`);return}const i=this.loadingPromises.get(e);if(i)return Mn.log(`JS already loading: ${e}`),i;const o=new Promise((d,g)=>{const h=document.createElement("script");h.src=t,h.id=a,h.async=!1,h.onload=()=>{Mn.log(`JS loaded: ${e}`),this.registerLoadedAsset(e,{type:"js",element:h}),this.loadingPromises.delete(e),d()},h.onerror=()=>{Mn.warn(`Failed to load JS: ${e} (${t})`),this.loadingPromises.delete(e),d()},document.head.appendChild(h)});return this.loadingPromises.set(e,o),o}registerLoadedAsset(e,t){const a=this.loadedAssets.get(e)||[];a.push(t),this.loadedAssets.set(e,a)}unloadExtensionAsset(e){const t=this.loadedAssets.get(e);if(!t||t.length===0){Mn.log(`No assets to unload for: ${e}`);return}t.forEach(a=>{a.element.parentNode&&(a.element.parentNode.removeChild(a.element),Mn.log(`${a.type.toUpperCase()} unloaded: ${e}`))}),this.loadedAssets.delete(e),Mn.log(`All assets unloaded for: ${e}`)}unloadAllAssets(){Array.from(this.loadedAssets.keys()).forEach(t=>{this.unloadExtensionAsset(t)}),Mn.log("All module assets unloaded")}isLoaded(e){return this.loadedAssets.has(e)}getLoadedModules(){return Array.from(this.loadedAssets.keys())}}let zg=null;function Qj(){return zg||(zg=new Xj),zg}function Zj(){if(typeof window>"u")return[];const r=window.G7Config;if(!r?.moduleAssets)return[];const e=[];for(const[t,a]of Object.entries(r.moduleAssets)){const i=a;e.push({identifier:t,js:i.js,css:i.css,priority:i.priority,external:i.external})}return e}function ek(){if(typeof window>"u")return[];const r=window.G7Config;if(!r?.pluginAssets)return[];const e=[];for(const[t,a]of Object.entries(r.pluginAssets)){const i=a;e.push({identifier:t,js:i.js,css:i.css,priority:i.priority,external:i.external})}return e}const Hg=it("SystemBannerManager");class Ic{static show(e){this.banners.set(e.id,e),this.render(),Hg.log(`Banner shown: ${e.id}`)}static hide(e){this.banners.delete(e)&&(this.render(),Hg.log(`Banner hidden: ${e}`))}static hideAll(){this.banners.clear(),this.render(),Hg.log("All banners hidden")}static detectLocale(){try{const t=window.G7Core;if(t?.locale?.current)return t.locale.current()}catch{}return(navigator.language||"ko").split("-")[0]}static resolveMessage(e,t){return typeof e=="string"?e:e[t]||e.en||e.ko||Object.values(e)[0]||""}static render(){if(typeof document>"u")return;let e=document.getElementById(this.containerId);if(this.banners.size===0){e&&(e.remove(),this.adjustAppPadding(0));return}e||(e=document.createElement("div"),e.id=this.containerId,e.style.cssText="position:fixed;top:0;left:0;right:0;z-index:99999;",document.body.prepend(e));const t=Array.from(this.banners.values()).sort((i,o)=>(i.order??0)-(o.order??0)),a=this.detectLocale();e.innerHTML=t.map(i=>{const o=this.resolveMessage(i.message,a),d=i.background||"#f59e0b",g=i.color||"white";return`
${o}
`}).join(""),requestAnimationFrame(()=>{e&&this.adjustAppPadding(e.offsetHeight)})}static adjustAppPadding(e){const t=document.getElementById("app");t&&(t.style.paddingTop=e>0?`${e}px`:"")}}H(Ic,"banners",new Map),H(Ic,"containerId","g7-system-banners");const G=it("TemplateApp");function tk(r){const e={};for(const t of r.keys()){if(t in e)continue;const a=r.getAll(t);a.length>1?e[t]=a:a.length===1&&(t.endsWith("[]")?e[t]=a:e[t]=a[0])}return e}const Aa=class Aa{constructor(e){H(this,"router",null);H(this,"layoutLoader",null);H(this,"errorPageHandler",null);H(this,"config");H(this,"globalState");H(this,"globalStateListeners",new Set);H(this,"currentRouteChangeId",0);H(this,"currentDataSources",[]);H(this,"currentRouteParams",{});H(this,"currentQueryParams",new URLSearchParams);H(this,"currentFetchedData",{});H(this,"currentLayoutName","");H(this,"templateErrorHandling",null);H(this,"currentWebSocketSubscriptions",[]);H(this,"extensionCacheVersion",0);H(this,"currentGlobalHeaders",[]);H(this,"transitionOverlayEl",null);H(this,"skeletonOverlayRoot",null);H(this,"skeletonOverlayContainer",null);H(this,"_spinnerState",null);H(this,"modalDataSources",new Map);this.globalState={sidebarOpen:!1},this.loadG7Config(),this.migrateLocaleStorage();const t=this.loadLocaleFromStorage(),a=t||e.locale||"ko";this.config={...e,locale:a},!t&&e.locale&&this.saveLocaleToStorage(e.locale)}loadG7Config(){if(typeof window<"u"&&window.G7Config){const e=window.G7Config;e.settings&&(this.globalState.settings=e.settings,G.log("Loaded settings from G7Config:",Object.keys(e.settings)),e.settings.upload&&(this.globalState.uploadSettings=e.settings.upload)),e.plugins&&(this.globalState.plugins=e.plugins,G.log("Loaded plugin settings from G7Config:",Object.keys(e.plugins))),e.modules&&(this.globalState.modules=e.modules,G.log("Loaded module settings from G7Config:",Object.keys(e.modules))),e.appConfig&&(this.globalState.appConfig=e.appConfig,G.log("Loaded appConfig from G7Config:",Object.keys(e.appConfig)))}}resolveRouteExpressions(e){const t=new _n,a={_global:this.globalState};return e.map(i=>{const o={...i};if(o.path&&o.path.includes("{{")){const d=o.path;o.path=t.resolveBindings(o.path,a),o.path=o.path.replace(/\/\/+/g,"/")||"/",o.path.includes("{{")&&(G.warn("Route expression resolution failed, using fallback:",d),o.path=d.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}if(o.redirect&&o.redirect.includes("{{")){const d=o.redirect;o.redirect=t.resolveBindings(o.redirect,a),o.redirect=o.redirect.replace(/\/\/+/g,"/")||"/",o.redirect.includes("{{")&&(G.warn("Route redirect expression resolution failed:",d),o.redirect=d.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}return o})}migrateLocaleStorage(){const e=["locale","g7_template_locale"];for(const t of e)try{const a=localStorage.getItem(t);a&&a!==localStorage.getItem(Aa.LOCALE_STORAGE_KEY)&&(localStorage.setItem(Aa.LOCALE_STORAGE_KEY,a),G.log(`Migrated locale from '${t}' to '${Aa.LOCALE_STORAGE_KEY}'`)),localStorage.removeItem(t)}catch(a){G.warn(`Failed to migrate locale key '${t}':`,a)}}async init(){try{oo.getInstance().setDebug(this.config.debug),G.log("Initializing with config:",this.config);const e=ba.getInstance(),t=as.getInstance(),a=this.loadCacheVersionFromStorage()||0,[i,o,d,g,h]=await Promise.all([Mo({templateId:this.config.templateId,templateType:this.config.templateType,locale:this.config.locale,debug:this.config.debug,cacheVersion:a}),e.loadComponents(this.config.templateId,this.config.templateType),fetch(`/api/templates/${this.config.templateId}/routes.json${a>0?`?v=${a}`:""}`).then(w=>{if(!w.ok)throw new Error(`Failed to load routes: ${w.statusText}`);return w.json()}).then(w=>{if(!w.success)throw new Error("Failed to load routes from API");return w.data}).catch(w=>{throw G.error("Error loading routes:",w),w}),t.preloadAuth(this.config.templateType==="admin"?"admin":"user"),fetch(`/api/templates/${this.config.templateId}/config.json`).then(w=>w.ok?w.json():null).then(w=>!w?.success||!w?.data?null:w.data).catch(w=>(G.warn("Error loading template config:",w),null))]);if(G.log("Template Engine initialized"),G.log("ComponentRegistry loaded"),G.log("Routes data loaded"),G.log("User info preloaded"),G.log("Template config loaded:",h),h?.cache_version!==void 0){const w=this.loadCacheVersionFromStorage();if(this.extensionCacheVersion=h.cache_version,this.saveCacheVersionToStorage(this.extensionCacheVersion),G.log("Extension cache version:",this.extensionCacheVersion),w!==null&&w!==this.extensionCacheVersion){G.log("Cache version changed, reloading routes...");const k=await fetch(`/api/templates/${this.config.templateId}/routes.json?v=${this.extensionCacheVersion}`).then(A=>{if(!A.ok)throw new Error(`Failed to reload routes: ${A.statusText}`);return A.json()}).then(A=>{if(!A.success)throw new Error("Failed to reload routes from API");return A.data});Array.isArray(k.routes)&&(k.routes=this.resolveRouteExpressions(k.routes),Object.assign(d,k),G.log("Routes reloaded with new cache version"));try{const{TranslationEngine:A}=await Promise.resolve().then(()=>Bp),O=A.getInstance();O.setCacheVersion(this.extensionCacheVersion);const N=this.config.locale||"ko",D="en";await O.loadTranslations(this.config.templateId,N,"/api",!0),N!==D&&await O.loadTranslations(this.config.templateId,D,"/api",!0),G.log("Translations reloaded with new cache version")}catch(A){G.error("Failed to reload translations:",A)}}}h?.errorHandling&&(this.templateErrorHandling=h.errorHandling,Sa().setTemplateConfig(this.templateErrorHandling),G.log("Template errorHandling registered:",this.templateErrorHandling)),t.on("logout",()=>{G.log("User logged out")}),t.on("authStateChange",w=>{G.log("Auth state changed:",w)}),G.log("AuthManager event handlers registered");const f=ns(),p=this.config.templateType==="admin"?"admin":"user",y=t.getConfig(p);f.setOnUnauthorized(()=>{G.log("Unauthorized - redirecting to login page"),f.removeToken();const w=window.location.pathname+window.location.search,k=t.getLoginRedirectUrl(p,w);window.location.href=k}),G.log("ApiClient onUnauthorized callback registered"),this.layoutLoader=new Rg(e),this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),G.log("LayoutLoader initialized:",this.layoutLoader);const x=new is({onUnauthorized:()=>{G.warn("Unauthorized request in error page")}});if(this.errorPageHandler=new Jj({templateId:this.config.templateId,layoutLoader:this.layoutLoader,locale:this.config.locale,debug:this.config.debug,renderFunction:$o,dataSourceManager:x,globalState:this.globalState}),G.log("ErrorPageHandler initialized with DataSourceManager"),await this.handleServerError()){G.log("Server error handled, skipping normal initialization");return}if(this.router=new Wj(this.config.templateId),Array.isArray(d.routes)){const w=this.resolveRouteExpressions(d.routes);this.router.setRoutes(w)}else throw new Error("Invalid routes data format");G.log("Router initialized:",this.router),G.log("Routes set:",this.router.getRoutes());const{getActionDispatcher:S}=await Promise.resolve().then(()=>qa),v=S();v&&(v.setDefaultContext({navigate:w=>this.router?.navigate(w)}),v.setGlobalStateUpdater((w,k)=>this.setGlobalState(w,k)),G.log("Navigate function and setGlobalState injected to ActionDispatcher")),await this.loadExtensionAssets(),this.reinitializeTemplateHandlers(),this.router.on("routeChange",w=>this.handleRouteChange(w)),this.router.on("routeNotFound",w=>this.handleRouteNotFound(w)),this.router.navigateToCurrentPath(),G.log("Template App initialized successfully")}catch(e){G.error("Initialization failed:",e),this.showInitError(e)}}async loadExtensionAssets(){try{const e=Qj(),t=Zj();t.length>0&&(G.log("Loading module assets:",t.map(i=>i.identifier)),await e.loadActiveExtensionAssets(t));const a=ek();a.length>0&&(G.log("Loading plugin assets:",a.map(i=>i.identifier)),await e.loadActiveExtensionAssets(a)),(t.length>0||a.length>0)&&G.log("Extension assets loaded successfully")}catch(e){G.warn("Failed to load extension assets:",e)}}async handleRouteChange(e){const t=++this.currentRouteChangeId;window.__g7ForcedLocalFields=void 0,window.__g7ActionContext=void 0,window.__g7PendingLocalState=void 0,window.__g7LastSetLocalSnapshot=void 0,window.__g7SetLocalOverrideKeys=void 0,window.__g7SequenceLocalSync=void 0;try{if(G.log("Route changed:",e,"requestId:",t),!this.layoutLoader)throw new Error("LayoutLoader is not initialized");if(!e.layout)throw new Error("Route layout is not defined");let a=e.layout;const i=a==="__preview__";i&&e.params?.token&&(a=`__preview__/${e.params.token}`);const o=await this.layoutLoader.loadLayout(this.config.templateId,a);if(t!==this.currentRouteChangeId){G.log("Route change cancelled (newer request exists):",t);return}G.log("Layout loaded:",o);const d=Sa();o.errorHandling?(d.setLayoutConfig(o.errorHandling),G.log("Layout errorHandling registered:",o.errorHandling)):d.clearLayoutConfig();const g=o.data_sources||[],h=e.query||{},f=new URLSearchParams;for(const[X,ae]of Object.entries(h))if(Array.isArray(ae))for(const R of ae)f.append(X,R);else f.set(X,ae);const p={route:e.params||{},query:h,_global:this.globalState};o.scripts&&Array.isArray(o.scripts)&&await this.loadLayoutScripts(o.scripts,p);const{DataSourceManager:y,getActionDispatcher:x}=await Promise.resolve().then(()=>qa),S=new y;if(i){const X=x();X&&X.setPreviewMode(!0),this.setGlobalState({__isPreview:!0}),Ic.show({id:"preview-mode",message:{ko:"⚠ 미리보기 모드 — 페이지 이동이 비활성화됩니다",en:"⚠ Preview Mode — Navigation is disabled"},background:"linear-gradient(90deg, #f59e0b, #d97706)",color:"white"}),G.log("Preview mode activated")}else{const X=x();X?.isPreviewMode()&&(X.setPreviewMode(!1),Ic.hide("preview-mode"))}if(this.currentGlobalHeaders=o.globalHeaders||[],this.currentGlobalHeaders.length>0){S.setGlobalHeaders(this.currentGlobalHeaders);const X=x();X&&X.setGlobalHeaders(this.currentGlobalHeaders),G.log("globalHeaders set:",this.currentGlobalHeaders.map(ae=>ae.pattern))}if(o.named_actions&&Object.keys(o.named_actions).length>0){const X=x();X&&X.setNamedActions(o.named_actions)}const v=S.filterByCondition(g,p);g.length!==v.length&&G.log("Data sources filtered by condition:",{before:g.map(X=>X.id),after:v.map(X=>X.id)});const w=v.filter(X=>X.loading_strategy==="blocking"),k=v.filter(X=>(X.loading_strategy||"progressive")!=="blocking"&&X.type!=="websocket"),A=Array.isArray(o.transition_overlay?.wait_for)?o.transition_overlay.wait_for:[],O=A.length>0&&v.some(X=>A.includes(X.id)&&X.type!=="websocket"&&(X.loading_strategy||"progressive")!=="background");if((w.length>0||O)&&o.transition_overlay){const X=typeof o.transition_overlay=="boolean"?{enabled:o.transition_overlay,style:"opaque"}:o.transition_overlay;X.enabled&&X.style==="skeleton"&&X.skeleton?.component&&X.target?this.renderSkeletonOverlay(X.target,X.skeleton,o,X.fallback_target):X.enabled&&X.style==="spinner"&&X.target&&this.renderSpinnerOverlay(X.target,X.spinner,X.fallback_target)}let N={},D={},$={},M={};this.currentWebSocketSubscriptions.length>0&&(G.log("Unsubscribing previous WebSocket subscriptions:",this.currentWebSocketSubscriptions),S.unsubscribeWebSockets(this.currentWebSocketSubscriptions),this.currentWebSocketSubscriptions=[]),this.currentDataSources=v,this.currentRouteParams=e.params||{},this.currentQueryParams=f,G.log(`handleRouteChange #${t} - queryObject:`,h),G.log(`handleRouteChange #${t} - queryParams:`,f.toString()),w.length>0&&(G.log("Fetching blocking data sources:",w.map(ae=>ae.id)),(await S.fetchDataSourcesWithResults(w,e.params||{},f)).forEach(ae=>{if(ae.state==="success"&&ae.data!==void 0)N[ae.id]=ae.data;else if(ae.state==="error"&&ae.error){const R=ae.error,U=R.response?.data?.message;D[ae.id]={message:U||ae.error.message,status:R.response?.status||R.status}}}),this.processInitOptions(w,N,$,M),this.currentFetchedData={...N},G.log("Blocking data loaded:",Object.keys(N)),Object.keys(D).length>0&&G.log("Data source errors:",D),Object.keys($).length>0&&G.log("Local state init (blocking):",Object.keys($)),Object.keys(M).length>0&&G.log("Isolated state init (blocking):",Object.keys(M)));const z=k.length>0;if(z&&(Pa.setPending(!0),G.log("Transition started before rendering")),t!==this.currentRouteChangeId){G.log("Route change cancelled after blocking data (newer request exists):",t);return}const{getState:K}=await Promise.resolve().then(()=>qa),pe=K().currentDataContext||{},we=k.map(X=>X.id),J={};if(z){we.forEach(ae=>{pe[ae]!==void 0?J[ae]=pe[ae]:J[ae]=void 0});const X=Object.keys(J).filter(ae=>J[ae]!==void 0);X.length>0&&G.log("Preserving previous progressive data:",X),G.log("Progressive data sources initialized:",we)}const be=o.defines||{},le={...J,...e.params,...N,route:{...e.params||{},path:e.path},query:h,_global:{...this.globalState},_globalSetState:X=>this.setGlobalState(X),_dataSourceErrors:Object.keys(D).length>0?D:void 0,_localInit:Object.keys($).length>0?$:void 0,_isolatedInit:Object.keys(M).length>0?M:void 0,_defines:Object.keys(be).length>0?be:void 0};if(o.computed&&Object.keys(o.computed).length>0){const X=this.calculateComputed(o.computed,le);Object.keys(X).length>0&&(le._computed=X,this.globalState._computed=X,G.log("Computed values calculated:",Object.keys(X))),le._computedDefinitions=o.computed}const de=o.layout_name||e.layout;this.currentLayoutName!==""&&this.currentLayoutName!==de&&(G.log("_local reset due to layout change:",{from:this.currentLayoutName,to:de}),this.globalState._local={}),this.currentLayoutName=de;const W=o.initLocal||o.state;if(W&&Object.keys(W).length>0){this.globalState._local||(this.globalState._local={});for(const[X,ae]of Object.entries(W))this.globalState._local[X]===void 0&&(this.globalState._local[X]=JSON.parse(JSON.stringify(ae)));le._local={...this.globalState._local},G.log("initLocal applied to _local:",Object.keys(W))}if(o.initGlobal&&Object.keys(o.initGlobal).length>0){for(const[X,ae]of Object.entries(o.initGlobal))this.globalState[X]===void 0&&(this.globalState[X]=JSON.parse(JSON.stringify(ae)));G.log("initGlobal applied to _global:",Object.keys(o.initGlobal))}if(o.initIsolated&&Object.keys(o.initIsolated).length>0){for(const[X,ae]of Object.entries(o.initIsolated))M[X]===void 0&&(M[X]=JSON.parse(JSON.stringify(ae)));G.log("initIsolated applied:",Object.keys(o.initIsolated))}le._global={...this.globalState,layoutWarnings:o.warnings||[]};const ge=o.initActions||o.init_actions;if(ge&&ge.length>0){await this.executeInitActions(ge,le),G.log("initActions executed before render");const X=this.globalState;if(X._local){if(Object.keys($).length>0){for(const[ae,R]of Object.entries($))X._local[ae]!==void 0?X._local[ae]=this.deepMerge(X._local[ae],R):X._local[ae]=R;G.log("localInit merged into _local after initActions:",Object.keys($))}le._local=X._local,G.log("_local merged into dataContext:",X._local)}if(le._global={...this.globalState,layoutWarnings:o.warnings||[]},G.log("_global merged into dataContext after initActions"),o.computed&&Object.keys(o.computed).length>0){const ae=this.calculateComputed(o.computed,le);Object.keys(ae).length>0&&(le._computed=ae,this.globalState._computed=ae,G.log("Computed values recalculated after init_actions:",Object.keys(ae)))}if(Object.keys(this.currentFetchedData).length>0){for(const[ae,R]of Object.entries(this.currentFetchedData))le[ae]=R;G.log("Fetched data sources merged into dataContext after initActions:",Object.keys(this.currentFetchedData))}}if(o.transition_overlay&&!this.skeletonOverlayContainer&&this.showTransitionOverlay(o.transition_overlay,o),await $o({containerId:"app",layoutJson:o,dataContext:le,translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),G.log("Initial render complete with blocking data"),this.reattachSpinnerOverlay(),k.length>0){if(t!==this.currentRouteChangeId){G.log("Route change cancelled before progressive fetch (newer request exists):",t),Pa.setPending(!1),this.hideTransitionOverlay();return}G.log("Fetching progressive/background data sources:",k.map(R=>R.id));const{updateTemplateData:X,getState:ae}=await Promise.resolve().then(()=>qa);try{const R=k.map(async U=>{try{const ye=(await S.fetchDataSourcesWithResults([U],e.params||{},f,this.globalState))[0];if(!ye){G.log(`Data source ${U.id} skipped (no fetch result)`);return}if(t!==this.currentRouteChangeId){G.log(`Data source ${U.id} fetch cancelled (newer request exists)`);return}if(ye.state==="success"&&ye.data!==void 0){G.log(`Progressive data source loaded: ${U.id}`),this.currentFetchedData[U.id]=ye.data;const oe={};this.processInitOptions([U],{[U.id]:ye.data},oe);const ke=ae();if(ke.bindingEngine){const Te=[U.id];U.initGlobal&&Te.push("_global"),U.initLocal&&Te.push("_local"),ke.bindingEngine.invalidateCacheByKeys(Te)}const Oe={[U.id]:ye.data};Object.keys(oe).length>0&&(Oe._localInit=oe,Object.assign($,oe)),U.initGlobal&&(Oe._global={...this.globalState}),X(Oe)}else if(ye.state==="error"&&ye.error){const oe=ye.error,ke=oe.response?.data?.message;D[U.id]={message:ke||ye.error.message,status:oe.response?.status||oe.status},G.log(`Progressive data source error: ${U.id}`,D[U.id]),X({[U.id]:null,_dataSourceErrors:{...D}})}}catch(re){G.error(`Failed to fetch data source: ${U.id}`,re)}});if(await Promise.all(R),t!==this.currentRouteChangeId){G.log("Route change cancelled after progressive fetch (newer request exists):",t);return}G.log("All progressive data sources loaded")}finally{Pa.setPending(!1),this.hideTransitionOverlay()}}else this.hideTransitionOverlay();const ne=v.filter(X=>X.type==="websocket");if(ne.length>0){G.log("Subscribing WebSocket data sources:",ne.map(U=>U.id));const{updateTemplateData:X,getState:ae}=await Promise.resolve().then(()=>qa),R={...this.currentFetchedData,...e.params,route:{...e.params||{},path:e.path},query:h,_global:{...this.globalState}};G.log("WebSocket binding context keys:",Object.keys(R)),this.currentWebSocketSubscriptions=S.subscribeWebSockets(v,(U,re)=>{G.log(`WebSocket data received for: ${U}`,re),this.currentFetchedData[U]=re;const ye=v.find(Te=>Te.id===U),oe=ae();if(oe.bindingEngine){const Te=[U];ye?.initGlobal&&Te.push("_global"),ye?.initLocal&&Te.push("_local"),oe.bindingEngine.invalidateCacheByKeys(Te)}X({[U]:re});const Oe=v.find(Te=>Te.type==="websocket"&&(Te.target_source||Te.id)===U)?.onReceive;Array.isArray(Oe)&&Oe.length>0&&window.G7Core?.dispatch&&(async()=>{for(const qe of Oe)try{const Ie=this.getActionDispatcher?.();Ie&&await Ie.dispatchAction(qe,{navigate:this.getRouter?.()?(Nt,Tt)=>this.getRouter().navigate(Nt,Tt):void 0,setState:Nt=>this.setGlobalState(Nt),state:this.globalState,data:{...this.globalState,$args:[re],$event:re},_isDispatchFallbackContext:!0})}catch(Ie){G.error(`WebSocket onReceive action failed for ${U}:`,Ie)}})()},R),G.log("WebSocket subscriptions established:",this.currentWebSocketSubscriptions)}G.log("Layout rendered successfully")}catch(a){G.error("Route change handling failed:",a),this.hideTransitionOverlay(),this.showRouteError(a)}}processInitOptions(e,t,a,i){e.some(d=>d.refetchOnMount===!0&&d.initLocal)&&(a._forceLocalInit=Date.now(),G.log("refetchOnMount detected, forcing local state init")),e.forEach(d=>{const g=t[d.id];if(!g)return;const h=g.data??g;if(d.initLocal){if(typeof d.initLocal=="string"){let f=h;if(d.initLocalDefaults&&typeof d.initLocalDefaults=="object"){const y=this.evaluateDefaults(d.initLocalDefaults,t);f={...y,...h},G.log(`initLocalDefaults applied for ${d.initLocal}:`,Object.keys(y))}const p=this.globalState._local?.[d.initLocal];p!==void 0&&typeof p=="object"&&typeof f=="object"?(a[d.initLocal]=this.deepMerge(p,f),G.log(`initLocal (merged): ${d.id}.data -> _local.${d.initLocal}`)):(a[d.initLocal]=f,G.log(`initLocal: ${d.id}.data -> _local.${d.initLocal}`))}else if(typeof d.initLocal=="object"&&d.initLocal.key){const{key:f,path:p}=d.initLocal;let y=p?this.extractValueByPathOrExpression(h,p,d.id):h;if(d.initLocalDefaults&&typeof d.initLocalDefaults=="object"){const S=this.evaluateDefaults(d.initLocalDefaults,t);y={...S,...y},G.log(`initLocalDefaults applied for ${f}:`,Object.keys(S))}const x=this.globalState._local?.[f];x!==void 0&&typeof x=="object"&&typeof y=="object"?(a[f]=this.deepMerge(x,y),G.log(`initLocal (merged): ${d.id}.data${p?"."+p:""} -> _local.${f}`)):(a[f]=y,G.log(`initLocal: ${d.id}.data${p?"."+p:""} -> _local.${f}`))}else if(typeof d.initLocal=="object"){const f=d.initLocal._merge||"deep",p=this.flattenNestedObjectToMappings(d.initLocal);for(const{targetPath:y,sourcePath:x}of p){const S=this.extractValueByPathOrExpression(h,x,d.id);if(y.includes(".")){const v=y.split(".")[0];a[v]===void 0&&this.globalState._local?.[v]!==void 0&&(a[v]=JSON.parse(JSON.stringify(this.globalState._local[v]))),this.setValueAtPath(a,y,S,f),G.log(`initLocal map (${f}): ${d.id} ${x} -> _local.${y}`)}else{const v=this.globalState._local?.[y];f==="replace"?(a[y]=S,G.log(`initLocal map (replace): ${d.id} ${x} -> _local.${y}`)):f==="shallow"?v!==void 0&&typeof v=="object"&&typeof S=="object"?(a[y]={...v,...S},G.log(`initLocal map (shallow): ${d.id} ${x} -> _local.${y}`)):(a[y]=S,G.log(`initLocal map: ${d.id} ${x} -> _local.${y}`)):v!==void 0&&typeof v=="object"&&typeof S=="object"?(a[y]=this.deepMerge(v,S),G.log(`initLocal map (deep): ${d.id} ${x} -> _local.${y}`)):(a[y]=S,G.log(`initLocal map: ${d.id} ${x} -> _local.${y}`))}}}}if(d.initGlobal)if(typeof d.initGlobal=="object"&&!Array.isArray(d.initGlobal)&&!("key"in d.initGlobal))for(const[p,y]of Object.entries(d.initGlobal)){if(typeof y!="string"){G.warn(`initGlobal map value must be string, got ${typeof y} for key ${p}`);continue}const x=this.extractValueByPathOrExpression(h,y,d.id),S=this.globalState[p];S!==void 0&&typeof S=="object"&&typeof x=="object"?(this.globalState[p]=this.deepMerge(S,x),G.log(`initGlobal map (merged): ${d.id} ${y} -> _global.${p}`)):(this.globalState[p]=x,G.log(`initGlobal map: ${d.id} ${y} -> _global.${p}`))}else{const p=Array.isArray(d.initGlobal)?d.initGlobal:[d.initGlobal];for(const y of p)if(typeof y=="string"){const x=this.globalState[y];x!==void 0&&typeof x=="object"&&typeof h=="object"?(this.globalState[y]=this.deepMerge(x,h),G.log(`initGlobal (merged): ${d.id}.data -> _global.${y}`)):(this.globalState[y]=h,G.log(`initGlobal: ${d.id}.data -> _global.${y}`))}else if(typeof y=="object"&&y.key){const{key:x,path:S}=y,v=S?this.extractValueByPathOrExpression(h,S,d.id):h,w=this.globalState[x];w!==void 0&&typeof w=="object"&&typeof v=="object"?(this.globalState[x]=this.deepMerge(w,v),G.log(`initGlobal (merged): ${d.id}.data${S?"."+S:""} -> _global.${x}`)):(this.globalState[x]=v,G.log(`initGlobal: ${d.id}.data${S?"."+S:""} -> _global.${x}`))}}if(i&&d.initIsolated){if(typeof d.initIsolated=="string"){const f=i[d.initIsolated];f!==void 0&&typeof f=="object"&&typeof h=="object"?(i[d.initIsolated]=this.deepMerge(f,h),G.log(`initIsolated (merged): ${d.id}.data -> _isolated.${d.initIsolated}`)):(i[d.initIsolated]=h,G.log(`initIsolated: ${d.id}.data -> _isolated.${d.initIsolated}`))}else if(typeof d.initIsolated=="object"&&d.initIsolated.key){const{key:f,path:p}=d.initIsolated,y=p?this.extractValueByPathOrExpression(h,p,d.id):h,x=i[f];x!==void 0&&typeof x=="object"&&typeof y=="object"?(i[f]=this.deepMerge(x,y),G.log(`initIsolated (merged): ${d.id}.data${p?"."+p:""} -> _isolated.${f}`)):(i[f]=y,G.log(`initIsolated: ${d.id}.data${p?"."+p:""} -> _isolated.${f}`))}else if(typeof d.initIsolated=="object")for(const[f,p]of Object.entries(d.initIsolated)){if(typeof p!="string"){G.warn(`initIsolated map value must be string, got ${typeof p} for key ${f}`);continue}const y=this.extractValueByPathOrExpression(h,p,d.id),x=i[f];x!==void 0&&typeof x=="object"&&typeof y=="object"?(i[f]=this.deepMerge(x,y),G.log(`initIsolated map (merged): ${d.id} ${p} -> _isolated.${f}`)):(i[f]=y,G.log(`initIsolated map: ${d.id} ${p} -> _isolated.${f}`))}}})}evaluateDefaults(e,t){const a={};for(const[i,o]of Object.entries(e))if(typeof o=="string"&&o.startsWith("{{")&&o.endsWith("}}")){const d=o.slice(2,-2).trim();a[i]=this.evaluateExpression(d,t)}else a[i]=o;return a}evaluateExpression(e,t){try{const a=e.split("??").map(i=>i.trim());for(const i of a){if(/^['"].*['"]$/.test(i))return i.slice(1,-1);if(i==="true")return!0;if(i==="false")return!1;if(/^-?\d+(\.\d+)?$/.test(i))return Number(i);const o=this.getNestedValue(t,i);if(o!=null)return o}return}catch(a){G.warn(`Expression evaluation failed: ${e}`,a);return}}getNestedValue(e,t){const a=t.replace(/\?\./g,".");let i=e;const o=a.split(/\.(?![^\[]*\])/).flatMap(d=>{const g=d.match(/^([^\[]*)((?:\[\d+\])*)$/);if(g){const[,h,f]=g,p=[];h&&p.push(h);const y=f.match(/\[\d+\]/g);return y&&p.push(...y),p}return[d]}).filter(d=>d!=="");for(const d of o){if(i==null)return;if(d.startsWith("[")&&d.endsWith("]")){const g=parseInt(d.slice(1,-1),10);i=i[g]}else i=i[d]}return i}extractValueByPathOrExpression(e,t,a){const i=t.match(/^\{\{(.+)\}\}$/);if(i){const o=i[1].trim(),d=new _n,g={data:e,_global:this.globalState,_local:this.globalState._local||{}};try{const h=d.evaluateExpression(o,g);return G.log(`initLocal/initGlobal expression evaluated: ${t} -> `,h),h}catch(h){G.warn(`initLocal/initGlobal expression evaluation failed for ${a}:`,t,h);return}}return this.getNestedValue(e,t)}async loadLayoutScripts(e,t){const a=[];for(const i of e){if((i.if!==void 0||i.conditions!==void 0)&&!ti({if:i.if,conditions:i.conditions},t,this.bindingEngine,`script:${i.id}`)){G.log(`Script skipped (condition not met): ${i.id}`);continue}if(document.getElementById(i.id)){G.log(`Script already loaded: ${i.id}`);continue}const d=new Promise((g,h)=>{const f=document.createElement("script");f.src=i.src,f.id=i.id,f.async=i.async??!0,f.onload=()=>{G.log(`Script loaded successfully: ${i.id}`),g()},f.onerror=()=>{G.warn(`Failed to load script: ${i.id} (${i.src})`),g()},document.head.appendChild(f)});a.push(d)}a.length>0&&(await Promise.all(a),G.log(`All scripts loaded: ${e.filter(i=>!document.getElementById(i.id)||a.length>0).map(i=>i.id).join(", ")}`))}evaluateScriptCondition(e,t){try{if(e.startsWith("{{")&&e.endsWith("}}")){const a=e.slice(2,-2).trim();return new Function("ctx",` + `}static renderFromError(e,t,a,i=!1,o,d,g){let h,f;if(t.userMessageKey.startsWith("$t:"))if(d&&o)try{h=d.translate(t.userMessageKey,o)}catch{h=t.userMessageKey.replace("$t:","")}else h=t.userMessageKey.replace("$t:","");else h=t.userMessageKey;if(g){const p=g;p.details?.apiMessage?f=p.details.apiMessage:p.response?.data?.message&&(f=p.response.data.message)}this.render(e,{title:a,message:h,detailMessage:f,icon:t.icon,showStack:t.showStack,stackTrace:t.stack,showReloadButton:t.recoverable,debug:i})}static escapeHtml(e){if(!e)return"";const t=document.createElement("div");return t.textContent=e,t.innerHTML}}const Vt=it("ErrorPageHandler");class Xj{constructor(e){H(this,"templateId");H(this,"layoutLoader");H(this,"locale");H(this,"debug");H(this,"renderFunction");H(this,"dataSourceManager");H(this,"globalState");H(this,"errorConfig",null);H(this,"configLoaded",!1);this.templateId=e.templateId,this.layoutLoader=e.layoutLoader,this.locale=e.locale,this.debug=e.debug,this.renderFunction=e.renderFunction,this.dataSourceManager=e.dataSourceManager,this.globalState=e.globalState||{}}async loadConfig(){if(this.configLoaded)return this.errorConfig;try{const e=await fetch(`/api/templates/${this.templateId}/config.json`);if(!e.ok)return this.debug&&Vt.warn("Failed to load template config:",e.statusText),this.configLoaded=!0,null;const t=await e.json();if(!t.success||!t.data)return this.debug&&Vt.warn("Invalid template config response"),this.configLoaded=!0,null;const a=t.data;return!a.error_config||!a.error_config.layouts?(this.debug&&Vt.warn("No error_config found in template.json"),this.configLoaded=!0,null):(this.errorConfig=a.error_config,this.configLoaded=!0,this.debug&&Vt.log("Error config loaded:",this.errorConfig),this.errorConfig)}catch(e){return Vt.error("Failed to load error config:",e),this.configLoaded=!0,null}}async renderError(e,t="app"){try{const a=await this.loadConfig();if(!a)return this.debug&&Vt.warn("No error config available, cannot render error page"),!1;const i=a.layouts[e]||a.layouts[String(e)];if(!i)return this.debug&&Vt.warn(`No layout defined for error code: ${e}`),!1;this.debug&&Vt.log(`Loading error layout: ${i} for code: ${e}`);const o=await this.layoutLoader.loadLayout(this.templateId,i);if(!o)return this.debug&&Vt.error(`Failed to load error layout: ${i}`),!1;this.debug&&Vt.log("Error layout loaded:",o);let d={};const g=o.data_sources||[];if(g.length>0){this.debug&&Vt.log("Fetching data sources:",g.map(S=>S.id));const p=g.filter(S=>S.loading_strategy==="blocking"),y=g.filter(S=>!S.loading_strategy||S.loading_strategy==="progressive"),x=[...p,...y];if(x.length>0)try{d=await this.dataSourceManager.fetchDataSources(x,{},new URLSearchParams),this.debug&&Vt.log("Data sources fetched:",Object.keys(d))}catch(S){Vt.error("Failed to fetch data sources:",S)}}const h={};g.length>0&&(this.processInitOptions(g,d,h),this.debug&&Vt.log("initOptions processed:",{globalKeys:Object.keys(this.globalState),localKeys:Object.keys(h)}));const f={...d,errorCode:e,_global:{...this.globalState},_local:{...h}};return await this.renderFunction({containerId:t,layoutJson:o,dataContext:f,translationContext:{templateId:this.templateId,locale:this.locale}}),this.debug&&Vt.log(`Error page ${e} rendered successfully`),!0}catch(a){return Vt.error(`Failed to render error page ${e}:`,a),!1}}processInitOptions(e,t,a){for(const i of e){const o=t[i.id];if(!o)continue;const d=o?.data??o;if(i.initLocal){if(typeof i.initLocal=="string")a[i.initLocal]=d,Vt.log(`initLocal: ${i.id}.data -> _local.${i.initLocal}`);else if(typeof i.initLocal=="object"&&"key"in i.initLocal){const{key:g,path:h}=i.initLocal;a[g]=h?this.getValueByPath(d,h):d,Vt.log(`initLocal: ${i.id}.data${h?"."+h:""} -> _local.${g}`)}}if(i.initGlobal){const g=Array.isArray(i.initGlobal)?i.initGlobal:[i.initGlobal];for(const h of g)if(typeof h=="string")this.globalState[h]=d,Vt.log(`initGlobal: ${i.id}.data -> _global.${h}`);else if(typeof h=="object"&&h!==null&&"key"in h){const{key:f,path:p}=h;this.globalState[f]=p?this.getValueByPath(d,p):d,Vt.log(`initGlobal: ${i.id}.data${p?"."+p:""} -> _global.${f}`)}}}}getValueByPath(e,t){return t.split(".").reduce((a,i)=>a?.[i],e)}updateGlobalState(e){this.globalState={...this.globalState,...e}}updateLocale(e){this.locale=e,this.debug&&Vt.log("Locale updated:",e)}isConfigLoaded(){return this.configLoaded}async hasErrorLayout(e){const t=await this.loadConfig();return t?!!(t.layouts[e]||t.layouts[String(e)]):!1}clearConfigCache(){this.errorConfig=null,this.configLoaded=!1,this.debug&&Vt.log("Config cache cleared")}}const Mn=it("ModuleAssetLoader");class Qj{constructor(){H(this,"loadedAssets",new Map);H(this,"loadingPromises",new Map)}async loadActiveExtensionAssets(e){if(!e||e.length===0){Mn.log("No module assets to load");return}const t=[...e].sort((o,d)=>o.priority-d.priority);Mn.log("Loading module assets:",t.map(o=>o.identifier));const a=t.filter(o=>o.css).map(o=>this.loadCSS(o.identifier,o.css)),i=t.filter(o=>o.js).map(o=>this.loadJS(o.identifier,o.js));await Promise.all([...a,...i]),Mn.log("All module assets loaded successfully")}async loadCSS(e,t){const a=`module-css-${e}`;if(document.getElementById(a)){Mn.log(`CSS already loaded: ${e}`);return}return new Promise((i,o)=>{const d=document.createElement("link");d.rel="stylesheet",d.href=t,d.id=a,d.onload=()=>{Mn.log(`CSS loaded: ${e}`),this.registerLoadedAsset(e,{type:"css",element:d}),i()},d.onerror=()=>{Mn.warn(`Failed to load CSS: ${e} (${t})`),i()},document.head.appendChild(d)})}async loadJS(e,t){const a=`module-js-${e}`;if(document.getElementById(a)){Mn.log(`JS already loaded: ${e}`);return}const i=this.loadingPromises.get(e);if(i)return Mn.log(`JS already loading: ${e}`),i;const o=new Promise((d,g)=>{const h=document.createElement("script");h.src=t,h.id=a,h.async=!1,h.onload=()=>{Mn.log(`JS loaded: ${e}`),this.registerLoadedAsset(e,{type:"js",element:h}),this.loadingPromises.delete(e),d()},h.onerror=()=>{Mn.warn(`Failed to load JS: ${e} (${t})`),this.loadingPromises.delete(e),d()},document.head.appendChild(h)});return this.loadingPromises.set(e,o),o}registerLoadedAsset(e,t){const a=this.loadedAssets.get(e)||[];a.push(t),this.loadedAssets.set(e,a)}unloadExtensionAsset(e){const t=this.loadedAssets.get(e);if(!t||t.length===0){Mn.log(`No assets to unload for: ${e}`);return}t.forEach(a=>{a.element.parentNode&&(a.element.parentNode.removeChild(a.element),Mn.log(`${a.type.toUpperCase()} unloaded: ${e}`))}),this.loadedAssets.delete(e),Mn.log(`All assets unloaded for: ${e}`)}unloadAllAssets(){Array.from(this.loadedAssets.keys()).forEach(t=>{this.unloadExtensionAsset(t)}),Mn.log("All module assets unloaded")}isLoaded(e){return this.loadedAssets.has(e)}getLoadedModules(){return Array.from(this.loadedAssets.keys())}}let zg=null;function Zj(){return zg||(zg=new Qj),zg}function ek(){if(typeof window>"u")return[];const r=window.G7Config;if(!r?.moduleAssets)return[];const e=[];for(const[t,a]of Object.entries(r.moduleAssets)){const i=a;e.push({identifier:t,js:i.js,css:i.css,priority:i.priority,external:i.external})}return e}function tk(){if(typeof window>"u")return[];const r=window.G7Config;if(!r?.pluginAssets)return[];const e=[];for(const[t,a]of Object.entries(r.pluginAssets)){const i=a;e.push({identifier:t,js:i.js,css:i.css,priority:i.priority,external:i.external})}return e}const Hg=it("SystemBannerManager");class zc{static show(e){this.banners.set(e.id,e),this.render(),Hg.log(`Banner shown: ${e.id}`)}static hide(e){this.banners.delete(e)&&(this.render(),Hg.log(`Banner hidden: ${e}`))}static hideAll(){this.banners.clear(),this.render(),Hg.log("All banners hidden")}static detectLocale(){try{const t=window.G7Core;if(t?.locale?.current)return t.locale.current()}catch{}return(navigator.language||"ko").split("-")[0]}static resolveMessage(e,t){return typeof e=="string"?e:e[t]||e.en||e.ko||Object.values(e)[0]||""}static render(){if(typeof document>"u")return;let e=document.getElementById(this.containerId);if(this.banners.size===0){e&&(e.remove(),this.adjustAppPadding(0));return}e||(e=document.createElement("div"),e.id=this.containerId,e.style.cssText="position:fixed;top:0;left:0;right:0;z-index:99999;",document.body.prepend(e));const t=Array.from(this.banners.values()).sort((i,o)=>(i.order??0)-(o.order??0)),a=this.detectLocale();e.innerHTML=t.map(i=>{const o=this.resolveMessage(i.message,a),d=i.background||"#f59e0b",g=i.color||"white";return`
${o}
`}).join(""),requestAnimationFrame(()=>{e&&this.adjustAppPadding(e.offsetHeight)})}static adjustAppPadding(e){const t=document.getElementById("app");t&&(t.style.paddingTop=e>0?`${e}px`:"")}}H(zc,"banners",new Map),H(zc,"containerId","g7-system-banners");const G=it("TemplateApp");function nk(r){const e={};for(const t of r.keys()){if(t in e)continue;const a=r.getAll(t);a.length>1?e[t]=a:a.length===1&&(t.endsWith("[]")?e[t]=a:e[t]=a[0])}return e}const Aa=class Aa{constructor(e){H(this,"router",null);H(this,"layoutLoader",null);H(this,"errorPageHandler",null);H(this,"config");H(this,"globalState");H(this,"globalStateListeners",new Set);H(this,"currentRouteChangeId",0);H(this,"currentDataSources",[]);H(this,"currentRouteParams",{});H(this,"currentQueryParams",new URLSearchParams);H(this,"currentFetchedData",{});H(this,"currentLayoutName","");H(this,"templateErrorHandling",null);H(this,"currentWebSocketSubscriptions",[]);H(this,"extensionCacheVersion",0);H(this,"currentGlobalHeaders",[]);H(this,"transitionOverlayEl",null);H(this,"skeletonOverlayRoot",null);H(this,"skeletonOverlayContainer",null);H(this,"_spinnerState",null);H(this,"modalDataSources",new Map);this.globalState={sidebarOpen:!1},this.loadG7Config(),this.migrateLocaleStorage();const t=this.loadLocaleFromStorage(),a=t||e.locale||"ko";this.config={...e,locale:a},!t&&e.locale&&this.saveLocaleToStorage(e.locale)}loadG7Config(){if(typeof window<"u"&&window.G7Config){const e=window.G7Config;e.settings&&(this.globalState.settings=e.settings,G.log("Loaded settings from G7Config:",Object.keys(e.settings)),e.settings.upload&&(this.globalState.uploadSettings=e.settings.upload)),e.plugins&&(this.globalState.plugins=e.plugins,G.log("Loaded plugin settings from G7Config:",Object.keys(e.plugins))),e.modules&&(this.globalState.modules=e.modules,G.log("Loaded module settings from G7Config:",Object.keys(e.modules))),e.appConfig&&(this.globalState.appConfig=e.appConfig,G.log("Loaded appConfig from G7Config:",Object.keys(e.appConfig)))}}resolveRouteExpressions(e){const t=new _n,a={_global:this.globalState};return e.map(i=>{const o={...i};if(o.path&&o.path.includes("{{")){const d=o.path;o.path=t.resolveBindings(o.path,a),o.path=o.path.replace(/\/\/+/g,"/")||"/",o.path.includes("{{")&&(G.warn("Route expression resolution failed, using fallback:",d),o.path=d.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}if(o.redirect&&o.redirect.includes("{{")){const d=o.redirect;o.redirect=t.resolveBindings(o.redirect,a),o.redirect=o.redirect.replace(/\/\/+/g,"/")||"/",o.redirect.includes("{{")&&(G.warn("Route redirect expression resolution failed:",d),o.redirect=d.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}return o})}migrateLocaleStorage(){const e=["locale","g7_template_locale"];for(const t of e)try{const a=localStorage.getItem(t);a&&a!==localStorage.getItem(Aa.LOCALE_STORAGE_KEY)&&(localStorage.setItem(Aa.LOCALE_STORAGE_KEY,a),G.log(`Migrated locale from '${t}' to '${Aa.LOCALE_STORAGE_KEY}'`)),localStorage.removeItem(t)}catch(a){G.warn(`Failed to migrate locale key '${t}':`,a)}}async init(){try{oo.getInstance().setDebug(this.config.debug),G.log("Initializing with config:",this.config);const e=ba.getInstance(),t=as.getInstance(),a=this.loadCacheVersionFromStorage()||0,[i,o,d,g,h]=await Promise.all([$o({templateId:this.config.templateId,templateType:this.config.templateType,locale:this.config.locale,debug:this.config.debug,cacheVersion:a}),e.loadComponents(this.config.templateId,this.config.templateType),fetch(`/api/templates/${this.config.templateId}/routes.json${a>0?`?v=${a}`:""}`).then(w=>{if(!w.ok)throw new Error(`Failed to load routes: ${w.statusText}`);return w.json()}).then(w=>{if(!w.success)throw new Error("Failed to load routes from API");return w.data}).catch(w=>{throw G.error("Error loading routes:",w),w}),t.preloadAuth(this.config.templateType==="admin"?"admin":"user"),fetch(`/api/templates/${this.config.templateId}/config.json`).then(w=>w.ok?w.json():null).then(w=>!w?.success||!w?.data?null:w.data).catch(w=>(G.warn("Error loading template config:",w),null))]);if(G.log("Template Engine initialized"),G.log("ComponentRegistry loaded"),G.log("Routes data loaded"),G.log("User info preloaded"),G.log("Template config loaded:",h),h?.cache_version!==void 0){const w=this.loadCacheVersionFromStorage();if(this.extensionCacheVersion=h.cache_version,this.saveCacheVersionToStorage(this.extensionCacheVersion),G.log("Extension cache version:",this.extensionCacheVersion),w!==null&&w!==this.extensionCacheVersion){G.log("Cache version changed, reloading routes...");const k=await fetch(`/api/templates/${this.config.templateId}/routes.json?v=${this.extensionCacheVersion}`).then(A=>{if(!A.ok)throw new Error(`Failed to reload routes: ${A.statusText}`);return A.json()}).then(A=>{if(!A.success)throw new Error("Failed to reload routes from API");return A.data});Array.isArray(k.routes)&&(k.routes=this.resolveRouteExpressions(k.routes),Object.assign(d,k),G.log("Routes reloaded with new cache version"));try{const{TranslationEngine:A}=await Promise.resolve().then(()=>Bp),O=A.getInstance();O.setCacheVersion(this.extensionCacheVersion);const N=this.config.locale||"ko",D="en";await O.loadTranslations(this.config.templateId,N,"/api",!0),N!==D&&await O.loadTranslations(this.config.templateId,D,"/api",!0),G.log("Translations reloaded with new cache version")}catch(A){G.error("Failed to reload translations:",A)}}}h?.errorHandling&&(this.templateErrorHandling=h.errorHandling,Sa().setTemplateConfig(this.templateErrorHandling),G.log("Template errorHandling registered:",this.templateErrorHandling)),t.on("logout",()=>{G.log("User logged out")}),t.on("authStateChange",w=>{G.log("Auth state changed:",w)}),G.log("AuthManager event handlers registered");const f=ns(),p=this.config.templateType==="admin"?"admin":"user",y=t.getConfig(p);f.setOnUnauthorized(()=>{G.log("Unauthorized - redirecting to login page"),f.removeToken();const w=window.location.pathname+window.location.search,k=t.getLoginRedirectUrl(p,w);window.location.href=k}),G.log("ApiClient onUnauthorized callback registered"),this.layoutLoader=new Rg(e),this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),G.log("LayoutLoader initialized:",this.layoutLoader);const x=new is({onUnauthorized:()=>{G.warn("Unauthorized request in error page")}});if(this.errorPageHandler=new Xj({templateId:this.config.templateId,layoutLoader:this.layoutLoader,locale:this.config.locale,debug:this.config.debug,renderFunction:Io,dataSourceManager:x,globalState:this.globalState}),G.log("ErrorPageHandler initialized with DataSourceManager"),await this.handleServerError()){G.log("Server error handled, skipping normal initialization");return}if(this.router=new Yj(this.config.templateId),Array.isArray(d.routes)){const w=this.resolveRouteExpressions(d.routes);this.router.setRoutes(w)}else throw new Error("Invalid routes data format");G.log("Router initialized:",this.router),G.log("Routes set:",this.router.getRoutes());const{getActionDispatcher:S}=await Promise.resolve().then(()=>qa),v=S();v&&(v.setDefaultContext({navigate:w=>this.router?.navigate(w)}),v.setGlobalStateUpdater((w,k)=>this.setGlobalState(w,k)),G.log("Navigate function and setGlobalState injected to ActionDispatcher")),await this.loadExtensionAssets(),this.reinitializeTemplateHandlers(),this.router.on("routeChange",w=>this.handleRouteChange(w)),this.router.on("routeNotFound",w=>this.handleRouteNotFound(w)),this.router.navigateToCurrentPath(),G.log("Template App initialized successfully")}catch(e){G.error("Initialization failed:",e),this.showInitError(e)}}async loadExtensionAssets(){try{const e=Zj(),t=ek();t.length>0&&(G.log("Loading module assets:",t.map(i=>i.identifier)),await e.loadActiveExtensionAssets(t));const a=tk();a.length>0&&(G.log("Loading plugin assets:",a.map(i=>i.identifier)),await e.loadActiveExtensionAssets(a)),(t.length>0||a.length>0)&&G.log("Extension assets loaded successfully")}catch(e){G.warn("Failed to load extension assets:",e)}}async handleRouteChange(e){const t=++this.currentRouteChangeId;window.__g7ForcedLocalFields=void 0,window.__g7ActionContext=void 0,window.__g7PendingLocalState=void 0,window.__g7LastSetLocalSnapshot=void 0,window.__g7SetLocalOverrideKeys=void 0,window.__g7SequenceLocalSync=void 0,window.__g7AutoBindingPaths=new Map;try{if(G.log("Route changed:",e,"requestId:",t),!this.layoutLoader)throw new Error("LayoutLoader is not initialized");if(!e.layout)throw new Error("Route layout is not defined");let a=e.layout;const i=a==="__preview__";i&&e.params?.token&&(a=`__preview__/${e.params.token}`);const o=await this.layoutLoader.loadLayout(this.config.templateId,a);if(t!==this.currentRouteChangeId){G.log("Route change cancelled (newer request exists):",t);return}G.log("Layout loaded:",o);const d=Sa();o.errorHandling?(d.setLayoutConfig(o.errorHandling),G.log("Layout errorHandling registered:",o.errorHandling)):d.clearLayoutConfig();const g=o.data_sources||[],h=e.query||{},f=new URLSearchParams;for(const[X,ae]of Object.entries(h))if(Array.isArray(ae))for(const R of ae)f.append(X,R);else f.set(X,ae);const p={route:e.params||{},query:h,_global:this.globalState};o.scripts&&Array.isArray(o.scripts)&&await this.loadLayoutScripts(o.scripts,p);const{DataSourceManager:y,getActionDispatcher:x}=await Promise.resolve().then(()=>qa),S=new y;if(i){const X=x();X&&X.setPreviewMode(!0),this.setGlobalState({__isPreview:!0}),zc.show({id:"preview-mode",message:{ko:"⚠ 미리보기 모드 — 페이지 이동이 비활성화됩니다",en:"⚠ Preview Mode — Navigation is disabled"},background:"linear-gradient(90deg, #f59e0b, #d97706)",color:"white"}),G.log("Preview mode activated")}else{const X=x();X?.isPreviewMode()&&(X.setPreviewMode(!1),zc.hide("preview-mode"))}if(this.currentGlobalHeaders=o.globalHeaders||[],this.currentGlobalHeaders.length>0){S.setGlobalHeaders(this.currentGlobalHeaders);const X=x();X&&X.setGlobalHeaders(this.currentGlobalHeaders),G.log("globalHeaders set:",this.currentGlobalHeaders.map(ae=>ae.pattern))}if(o.named_actions&&Object.keys(o.named_actions).length>0){const X=x();X&&X.setNamedActions(o.named_actions)}const v=S.filterByCondition(g,p);g.length!==v.length&&G.log("Data sources filtered by condition:",{before:g.map(X=>X.id),after:v.map(X=>X.id)});const w=v.filter(X=>X.loading_strategy==="blocking"),k=v.filter(X=>(X.loading_strategy||"progressive")!=="blocking"&&X.type!=="websocket"),A=Array.isArray(o.transition_overlay?.wait_for)?o.transition_overlay.wait_for:[],O=A.length>0&&v.some(X=>A.includes(X.id)&&X.type!=="websocket"&&(X.loading_strategy||"progressive")!=="background");if((w.length>0||O)&&o.transition_overlay){const X=typeof o.transition_overlay=="boolean"?{enabled:o.transition_overlay,style:"opaque"}:o.transition_overlay;X.enabled&&X.style==="skeleton"&&X.skeleton?.component&&X.target?this.renderSkeletonOverlay(X.target,X.skeleton,o,X.fallback_target):X.enabled&&X.style==="spinner"&&X.target&&this.renderSpinnerOverlay(X.target,X.spinner,X.fallback_target)}let N={},D={},$={},M={};this.currentWebSocketSubscriptions.length>0&&(G.log("Unsubscribing previous WebSocket subscriptions:",this.currentWebSocketSubscriptions),S.unsubscribeWebSockets(this.currentWebSocketSubscriptions),this.currentWebSocketSubscriptions=[]),this.currentDataSources=v,this.currentRouteParams=e.params||{},this.currentQueryParams=f,G.log(`handleRouteChange #${t} - queryObject:`,h),G.log(`handleRouteChange #${t} - queryParams:`,f.toString()),w.length>0&&(G.log("Fetching blocking data sources:",w.map(ae=>ae.id)),(await S.fetchDataSourcesWithResults(w,e.params||{},f)).forEach(ae=>{if(ae.state==="success"&&ae.data!==void 0)N[ae.id]=ae.data;else if(ae.state==="error"&&ae.error){const R=ae.error,U=R.response?.data?.message;D[ae.id]={message:U||ae.error.message,status:R.response?.status||R.status}}}),this.processInitOptions(w,N,$,M),this.currentFetchedData={...N},G.log("Blocking data loaded:",Object.keys(N)),Object.keys(D).length>0&&G.log("Data source errors:",D),Object.keys($).length>0&&G.log("Local state init (blocking):",Object.keys($)),Object.keys(M).length>0&&G.log("Isolated state init (blocking):",Object.keys(M)));const z=k.length>0;if(z&&(Pa.setPending(!0),G.log("Transition started before rendering")),t!==this.currentRouteChangeId){G.log("Route change cancelled after blocking data (newer request exists):",t);return}const{getState:K}=await Promise.resolve().then(()=>qa),ye=K().currentDataContext||{},we=k.map(X=>X.id),J={};if(z){we.forEach(ae=>{ye[ae]!==void 0?J[ae]=ye[ae]:J[ae]=void 0});const X=Object.keys(J).filter(ae=>J[ae]!==void 0);X.length>0&&G.log("Preserving previous progressive data:",X),G.log("Progressive data sources initialized:",we)}const ve=o.defines||{},le={...J,...e.params,...N,route:{...e.params||{},path:e.path},query:h,_global:{...this.globalState},_globalSetState:X=>this.setGlobalState(X),_dataSourceErrors:Object.keys(D).length>0?D:void 0,_localInit:Object.keys($).length>0?$:void 0,_isolatedInit:Object.keys(M).length>0?M:void 0,_defines:Object.keys(ve).length>0?ve:void 0};if(o.computed&&Object.keys(o.computed).length>0){const X=this.calculateComputed(o.computed,le);Object.keys(X).length>0&&(le._computed=X,this.globalState._computed=X,G.log("Computed values calculated:",Object.keys(X))),le._computedDefinitions=o.computed}const de=o.layout_name||e.layout;this.currentLayoutName!==""&&this.currentLayoutName!==de&&(G.log("_local reset due to layout change:",{from:this.currentLayoutName,to:de}),this.globalState._local={}),this.currentLayoutName=de;const W=o.initLocal||o.state;if(W&&Object.keys(W).length>0){this.globalState._local||(this.globalState._local={});for(const[X,ae]of Object.entries(W))this.globalState._local[X]===void 0&&(this.globalState._local[X]=JSON.parse(JSON.stringify(ae)));le._local={...this.globalState._local},G.log("initLocal applied to _local:",Object.keys(W))}if(o.initGlobal&&Object.keys(o.initGlobal).length>0){for(const[X,ae]of Object.entries(o.initGlobal))this.globalState[X]===void 0&&(this.globalState[X]=JSON.parse(JSON.stringify(ae)));G.log("initGlobal applied to _global:",Object.keys(o.initGlobal))}if(o.initIsolated&&Object.keys(o.initIsolated).length>0){for(const[X,ae]of Object.entries(o.initIsolated))M[X]===void 0&&(M[X]=JSON.parse(JSON.stringify(ae)));G.log("initIsolated applied:",Object.keys(o.initIsolated))}le._global={...this.globalState,layoutWarnings:o.warnings||[]};const he=o.initActions||o.init_actions;if(he&&he.length>0){await this.executeInitActions(he,le),G.log("initActions executed before render");const X=this.globalState;if(X._local){if(Object.keys($).length>0){for(const[ae,R]of Object.entries($))X._local[ae]!==void 0?X._local[ae]=this.deepMerge(X._local[ae],R):X._local[ae]=R;G.log("localInit merged into _local after initActions:",Object.keys($))}le._local=X._local,G.log("_local merged into dataContext:",X._local)}if(le._global={...this.globalState,layoutWarnings:o.warnings||[]},G.log("_global merged into dataContext after initActions"),o.computed&&Object.keys(o.computed).length>0){const ae=this.calculateComputed(o.computed,le);Object.keys(ae).length>0&&(le._computed=ae,this.globalState._computed=ae,G.log("Computed values recalculated after init_actions:",Object.keys(ae)))}if(Object.keys(this.currentFetchedData).length>0){for(const[ae,R]of Object.entries(this.currentFetchedData))le[ae]=R;G.log("Fetched data sources merged into dataContext after initActions:",Object.keys(this.currentFetchedData))}}if(o.transition_overlay&&!this.skeletonOverlayContainer&&this.showTransitionOverlay(o.transition_overlay,o),await Io({containerId:"app",layoutJson:o,dataContext:le,translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),G.log("Initial render complete with blocking data"),this.reattachSpinnerOverlay(),k.length>0){if(t!==this.currentRouteChangeId){G.log("Route change cancelled before progressive fetch (newer request exists):",t),Pa.setPending(!1),this.hideTransitionOverlay();return}G.log("Fetching progressive/background data sources:",k.map(R=>R.id));const{updateTemplateData:X,getState:ae}=await Promise.resolve().then(()=>qa);try{const R=k.map(async U=>{try{const xe=(await S.fetchDataSourcesWithResults([U],e.params||{},f,this.globalState))[0];if(!xe){G.log(`Data source ${U.id} skipped (no fetch result)`);return}if(t!==this.currentRouteChangeId){G.log(`Data source ${U.id} fetch cancelled (newer request exists)`);return}if(xe.state==="success"&&xe.data!==void 0){G.log(`Progressive data source loaded: ${U.id}`),this.currentFetchedData[U.id]=xe.data;const oe={};this.processInitOptions([U],{[U.id]:xe.data},oe);const ke=ae();if(ke.bindingEngine){const Te=[U.id];U.initGlobal&&Te.push("_global"),U.initLocal&&Te.push("_local"),ke.bindingEngine.invalidateCacheByKeys(Te)}const Oe={[U.id]:xe.data};Object.keys(oe).length>0&&(Oe._localInit=oe,Object.assign($,oe)),U.initGlobal&&(Oe._global={...this.globalState}),X(Oe)}else if(xe.state==="error"&&xe.error){const oe=xe.error,ke=oe.response?.data?.message;D[U.id]={message:ke||xe.error.message,status:oe.response?.status||oe.status},G.log(`Progressive data source error: ${U.id}`,D[U.id]),X({[U.id]:null,_dataSourceErrors:{...D}})}}catch(re){G.error(`Failed to fetch data source: ${U.id}`,re)}});if(await Promise.all(R),t!==this.currentRouteChangeId){G.log("Route change cancelled after progressive fetch (newer request exists):",t);return}G.log("All progressive data sources loaded")}finally{Pa.setPending(!1),this.hideTransitionOverlay()}}else this.hideTransitionOverlay();const ee=v.filter(X=>X.type==="websocket");if(ee.length>0){G.log("Subscribing WebSocket data sources:",ee.map(U=>U.id));const{updateTemplateData:X,getState:ae}=await Promise.resolve().then(()=>qa),R={...this.currentFetchedData,...e.params,route:{...e.params||{},path:e.path},query:h,_global:{...this.globalState}};G.log("WebSocket binding context keys:",Object.keys(R)),this.currentWebSocketSubscriptions=S.subscribeWebSockets(v,(U,re)=>{G.log(`WebSocket data received for: ${U}`,re),this.currentFetchedData[U]=re;const xe=v.find(Te=>Te.id===U),oe=ae();if(oe.bindingEngine){const Te=[U];xe?.initGlobal&&Te.push("_global"),xe?.initLocal&&Te.push("_local"),oe.bindingEngine.invalidateCacheByKeys(Te)}X({[U]:re});const Oe=v.find(Te=>Te.type==="websocket"&&(Te.target_source||Te.id)===U)?.onReceive;Array.isArray(Oe)&&Oe.length>0&&window.G7Core?.dispatch&&(async()=>{for(const qe of Oe)try{const Ie=this.getActionDispatcher?.();Ie&&await Ie.dispatchAction(qe,{navigate:this.getRouter?.()?(Nt,Rt)=>this.getRouter().navigate(Nt,Rt):void 0,setState:Nt=>this.setGlobalState(Nt),state:this.globalState,data:{...this.globalState,$args:[re],$event:re},_isDispatchFallbackContext:!0})}catch(Ie){G.error(`WebSocket onReceive action failed for ${U}:`,Ie)}})()},R),G.log("WebSocket subscriptions established:",this.currentWebSocketSubscriptions)}G.log("Layout rendered successfully")}catch(a){G.error("Route change handling failed:",a),this.hideTransitionOverlay(),this.showRouteError(a)}}processInitOptions(e,t,a,i){e.some(d=>d.refetchOnMount===!0&&d.initLocal)&&(a._forceLocalInit=Date.now(),G.log("refetchOnMount detected, forcing local state init")),e.forEach(d=>{const g=t[d.id];if(!g)return;const h=g.data??g;if(d.initLocal){if(typeof d.initLocal=="string"){let f=h;if(d.initLocalDefaults&&typeof d.initLocalDefaults=="object"){const y=this.evaluateDefaults(d.initLocalDefaults,t);f={...y,...h},G.log(`initLocalDefaults applied for ${d.initLocal}:`,Object.keys(y))}const p=this.globalState._local?.[d.initLocal];p!==void 0&&typeof p=="object"&&typeof f=="object"?(a[d.initLocal]=this.deepMerge(p,f),G.log(`initLocal (merged): ${d.id}.data -> _local.${d.initLocal}`)):(a[d.initLocal]=f,G.log(`initLocal: ${d.id}.data -> _local.${d.initLocal}`))}else if(typeof d.initLocal=="object"&&d.initLocal.key){const{key:f,path:p}=d.initLocal;let y=p?this.extractValueByPathOrExpression(h,p,d.id):h;if(d.initLocalDefaults&&typeof d.initLocalDefaults=="object"){const S=this.evaluateDefaults(d.initLocalDefaults,t);y={...S,...y},G.log(`initLocalDefaults applied for ${f}:`,Object.keys(S))}const x=this.globalState._local?.[f];x!==void 0&&typeof x=="object"&&typeof y=="object"?(a[f]=this.deepMerge(x,y),G.log(`initLocal (merged): ${d.id}.data${p?"."+p:""} -> _local.${f}`)):(a[f]=y,G.log(`initLocal: ${d.id}.data${p?"."+p:""} -> _local.${f}`))}else if(typeof d.initLocal=="object"){const f=d.initLocal._merge||"deep",p=this.flattenNestedObjectToMappings(d.initLocal);for(const{targetPath:y,sourcePath:x}of p){const S=this.extractValueByPathOrExpression(h,x,d.id);if(y.includes(".")){const v=y.split(".")[0];a[v]===void 0&&this.globalState._local?.[v]!==void 0&&(a[v]=JSON.parse(JSON.stringify(this.globalState._local[v]))),this.setValueAtPath(a,y,S,f),G.log(`initLocal map (${f}): ${d.id} ${x} -> _local.${y}`)}else{const v=this.globalState._local?.[y];f==="replace"?(a[y]=S,G.log(`initLocal map (replace): ${d.id} ${x} -> _local.${y}`)):f==="shallow"?v!==void 0&&typeof v=="object"&&typeof S=="object"?(a[y]={...v,...S},G.log(`initLocal map (shallow): ${d.id} ${x} -> _local.${y}`)):(a[y]=S,G.log(`initLocal map: ${d.id} ${x} -> _local.${y}`)):v!==void 0&&typeof v=="object"&&typeof S=="object"?(a[y]=this.deepMerge(v,S),G.log(`initLocal map (deep): ${d.id} ${x} -> _local.${y}`)):(a[y]=S,G.log(`initLocal map: ${d.id} ${x} -> _local.${y}`))}}}}if(d.initGlobal)if(typeof d.initGlobal=="object"&&!Array.isArray(d.initGlobal)&&!("key"in d.initGlobal))for(const[p,y]of Object.entries(d.initGlobal)){if(typeof y!="string"){G.warn(`initGlobal map value must be string, got ${typeof y} for key ${p}`);continue}const x=this.extractValueByPathOrExpression(h,y,d.id),S=this.globalState[p];S!==void 0&&typeof S=="object"&&typeof x=="object"?(this.globalState[p]=this.deepMerge(S,x),G.log(`initGlobal map (merged): ${d.id} ${y} -> _global.${p}`)):(this.globalState[p]=x,G.log(`initGlobal map: ${d.id} ${y} -> _global.${p}`))}else{const p=Array.isArray(d.initGlobal)?d.initGlobal:[d.initGlobal];for(const y of p)if(typeof y=="string"){const x=this.globalState[y];x!==void 0&&typeof x=="object"&&typeof h=="object"?(this.globalState[y]=this.deepMerge(x,h),G.log(`initGlobal (merged): ${d.id}.data -> _global.${y}`)):(this.globalState[y]=h,G.log(`initGlobal: ${d.id}.data -> _global.${y}`))}else if(typeof y=="object"&&y.key){const{key:x,path:S}=y,v=S?this.extractValueByPathOrExpression(h,S,d.id):h,w=this.globalState[x];w!==void 0&&typeof w=="object"&&typeof v=="object"?(this.globalState[x]=this.deepMerge(w,v),G.log(`initGlobal (merged): ${d.id}.data${S?"."+S:""} -> _global.${x}`)):(this.globalState[x]=v,G.log(`initGlobal: ${d.id}.data${S?"."+S:""} -> _global.${x}`))}}if(i&&d.initIsolated){if(typeof d.initIsolated=="string"){const f=i[d.initIsolated];f!==void 0&&typeof f=="object"&&typeof h=="object"?(i[d.initIsolated]=this.deepMerge(f,h),G.log(`initIsolated (merged): ${d.id}.data -> _isolated.${d.initIsolated}`)):(i[d.initIsolated]=h,G.log(`initIsolated: ${d.id}.data -> _isolated.${d.initIsolated}`))}else if(typeof d.initIsolated=="object"&&d.initIsolated.key){const{key:f,path:p}=d.initIsolated,y=p?this.extractValueByPathOrExpression(h,p,d.id):h,x=i[f];x!==void 0&&typeof x=="object"&&typeof y=="object"?(i[f]=this.deepMerge(x,y),G.log(`initIsolated (merged): ${d.id}.data${p?"."+p:""} -> _isolated.${f}`)):(i[f]=y,G.log(`initIsolated: ${d.id}.data${p?"."+p:""} -> _isolated.${f}`))}else if(typeof d.initIsolated=="object")for(const[f,p]of Object.entries(d.initIsolated)){if(typeof p!="string"){G.warn(`initIsolated map value must be string, got ${typeof p} for key ${f}`);continue}const y=this.extractValueByPathOrExpression(h,p,d.id),x=i[f];x!==void 0&&typeof x=="object"&&typeof y=="object"?(i[f]=this.deepMerge(x,y),G.log(`initIsolated map (merged): ${d.id} ${p} -> _isolated.${f}`)):(i[f]=y,G.log(`initIsolated map: ${d.id} ${p} -> _isolated.${f}`))}}})}evaluateDefaults(e,t){const a={};for(const[i,o]of Object.entries(e))if(typeof o=="string"&&o.startsWith("{{")&&o.endsWith("}}")){const d=o.slice(2,-2).trim();a[i]=this.evaluateExpression(d,t)}else a[i]=o;return a}evaluateExpression(e,t){try{const a=e.split("??").map(i=>i.trim());for(const i of a){if(/^['"].*['"]$/.test(i))return i.slice(1,-1);if(i==="true")return!0;if(i==="false")return!1;if(/^-?\d+(\.\d+)?$/.test(i))return Number(i);const o=this.getNestedValue(t,i);if(o!=null)return o}return}catch(a){G.warn(`Expression evaluation failed: ${e}`,a);return}}getNestedValue(e,t){const a=t.replace(/\?\./g,".");let i=e;const o=a.split(/\.(?![^\[]*\])/).flatMap(d=>{const g=d.match(/^([^\[]*)((?:\[\d+\])*)$/);if(g){const[,h,f]=g,p=[];h&&p.push(h);const y=f.match(/\[\d+\]/g);return y&&p.push(...y),p}return[d]}).filter(d=>d!=="");for(const d of o){if(i==null)return;if(d.startsWith("[")&&d.endsWith("]")){const g=parseInt(d.slice(1,-1),10);i=i[g]}else i=i[d]}return i}extractValueByPathOrExpression(e,t,a){const i=t.match(/^\{\{(.+)\}\}$/);if(i){const o=i[1].trim(),d=new _n,g={data:e,_global:this.globalState,_local:this.globalState._local||{}};try{const h=d.evaluateExpression(o,g);return G.log(`initLocal/initGlobal expression evaluated: ${t} -> `,h),h}catch(h){G.warn(`initLocal/initGlobal expression evaluation failed for ${a}:`,t,h);return}}return this.getNestedValue(e,t)}async loadLayoutScripts(e,t){const a=[];for(const i of e){if((i.if!==void 0||i.conditions!==void 0)&&!ti({if:i.if,conditions:i.conditions},t,this.bindingEngine,`script:${i.id}`)){G.log(`Script skipped (condition not met): ${i.id}`);continue}if(document.getElementById(i.id)){G.log(`Script already loaded: ${i.id}`);continue}const d=new Promise((g,h)=>{const f=document.createElement("script");f.src=i.src,f.id=i.id,f.async=i.async??!0,f.onload=()=>{G.log(`Script loaded successfully: ${i.id}`),g()},f.onerror=()=>{G.warn(`Failed to load script: ${i.id} (${i.src})`),g()},document.head.appendChild(f)});a.push(d)}a.length>0&&(await Promise.all(a),G.log(`All scripts loaded: ${e.filter(i=>!document.getElementById(i.id)||a.length>0).map(i=>i.id).join(", ")}`))}evaluateScriptCondition(e,t){try{if(e.startsWith("{{")&&e.endsWith("}}")){const a=e.slice(2,-2).trim();return new Function("ctx",` with(ctx) { try { return Boolean(${a}); @@ -275,7 +275,7 @@ Error generating stack: `+u.message+` return false; } } - `)(t)}return!!e}catch(a){return G.warn(`Failed to evaluate script condition: ${e}`,a),!1}}showInitError(e){const t=Qy(e);Zy.renderFromError("app",t,"초기화 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}showTransitionOverlay(e,t){const a=typeof e=="boolean"?{enabled:e,style:"opaque",target:void 0,skeleton:void 0,spinner:void 0}:{enabled:e.enabled,style:e.style||"opaque",target:e.target,skeleton:e.skeleton,spinner:e.spinner,fallback_target:e.fallback_target};if(!a.enabled)return;if(this.hideTransitionOverlay(),a.style==="skeleton"&&a.skeleton?.component&&a.target&&t){this.renderSkeletonOverlay(a.target,a.skeleton,t,a.fallback_target);return}if(a.style==="spinner"&&a.target){this.renderSpinnerOverlay(a.target,a.spinner,a.fallback_target);return}const i=document.documentElement.classList.contains("dark");let o,d="";switch(a.style){case"blur":o=i?"rgba(17,24,39,0.3)":"rgba(255,255,255,0.3)",d="backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px);";break;case"fade":o=i?"rgba(17,24,39,0.8)":"rgba(255,255,255,0.8)";break;case"skeleton":o=i?"rgb(17,24,39)":"rgb(249,250,251)";break;case"opaque":default:o=i?"rgb(17,24,39)":"rgb(249,250,251)";break}if(a.target){const g=`#${CSS.escape(a.target)}`,h=document.createElement("style");h.id="g7-transition-overlay",h.textContent=`${g}{position:relative;z-index:0;}${g}::after{content:'';position:absolute;inset:0;background:${o};${d}z-index:2147483647;pointer-events:none;}`,document.head.appendChild(h),this.transitionOverlayEl=h}else{const g=document.createElement("div");g.id="g7-transition-overlay",g.setAttribute("aria-hidden","true"),g.style.cssText=`position:fixed;inset:0;z-index:9999;pointer-events:none;background:${o};${d}`,document.body.appendChild(g),this.transitionOverlayEl=g}}hideTransitionOverlay(){this.transitionOverlayEl&&(this.transitionOverlayEl.remove(),this.transitionOverlayEl=null),this.hideSkeletonOverlay()}renderSkeletonOverlay(e,t,a,i){const d=ba.getInstance().getComponent(t.component);if(!d){G.log(`Skeleton component "${t.component}" not found in registry, falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}let g=document.getElementById(e),h="target";if(!g&&i&&(g=document.getElementById(i),h="fallback"),g||(g=document.getElementById("app"),h="fullpage"),!g){G.log(`Skeleton overlay: no target found (target="#${e}", fallback="${i||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const p=document.documentElement.classList.contains("dark")?"rgb(17,24,39)":"rgb(249,250,251)",y=h==="fullpage"?"app":h==="fallback"?i:e,x=`#${CSS.escape(y)}`,S=document.createElement("style");S.id="g7-skeleton-overlay-style",S.textContent=`${x}{position:relative;z-index:0;}${x}::after{content:'';position:absolute;inset:0;background:${p};z-index:2147483646;pointer-events:none;}`,document.head.appendChild(S),this.transitionOverlayEl=S;const v=document.createElement("div");if(v.id="g7-skeleton-overlay",v.setAttribute("role","status"),v.setAttribute("aria-busy","true"),v.setAttribute("aria-label","Loading..."),h==="fullpage")v.style.cssText=["position:fixed","inset:0","z-index:20","overflow:hidden","pointer-events:none",`background:${p}`].join(";")+";";else{const N=g.getBoundingClientRect(),D=window.scrollX||document.documentElement.scrollLeft,$=window.scrollY||document.documentElement.scrollTop;v.style.cssText=["position:absolute",`top:${N.top+$}px`,`left:${N.left+D}px`,`width:${N.width}px`,`height:${N.height}px`,"z-index:20","overflow:hidden","pointer-events:none",`background:${p}`].join(";")+";"}document.body.appendChild(v),this.skeletonOverlayContainer=v;const w=a.components||[];let k;if(h==="fullpage")k=w;else{const N=h==="fallback"?i:e;k=this.findComponentChildrenById(w,N)}const A=zu.createRoot(v);this.skeletonOverlayRoot=A,Os.flushSync(()=>{A.render(Ke.createElement(d,{components:k,options:{animation:t.animation||"pulse",iteration_count:t.iteration_count||5}}))});const O=h==="fullpage"?"fullpage (#app)":h==="fallback"?`fallback (#${i})`:`target (#${e})`;G.log(`Skeleton overlay rendered [${O}] with "${t.component}" (${k.length} components)`)}findComponentChildrenById(e,t){const a=i=>{for(const o of i){if(o.id===t)return o.children||[];if(o.children&&Array.isArray(o.children)){const d=a(o.children);if(d!==null)return d}}return null};return a(e)||e}renderSpinnerOverlay(e,t,a){let i=document.getElementById(e),o="target";if(!i&&a&&(i=document.getElementById(a),o="fallback"),i||(i=document.getElementById("app"),o="fullpage"),!i){G.log(`Spinner overlay: no target found (target="#${e}", fallback="${a||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const d=o==="fullpage"?"app":o==="fallback"?a:e,g=`#${CSS.escape(d)}`,h=document.createElement("style");h.id="g7-skeleton-overlay-style",h.textContent=[`${g}{position:relative;}`,"@keyframes g7-spin{to{transform:rotate(360deg)}}"].join(""),document.head.appendChild(h),this.transitionOverlayEl=h;const f=t?.text||window.G7Core?.t?.("nav.loading")||"";this._spinnerState={target:e,fallbackTarget:a,spinnerConfig:t,resolvedText:f},this._mountSpinnerInTarget(i);const p=o==="fullpage"?"fullpage (#app)":o==="fallback"?`fallback (#${a})`:`target (#${e})`,y=t?.component||"default spinner";G.log(`Spinner overlay rendered [${p}] with "${y}"`)}_mountSpinnerInTarget(e){if(!this._spinnerState)return;const{spinnerConfig:t,resolvedText:a}=this._spinnerState;if(this.skeletonOverlayRoot){try{this.skeletonOverlayRoot.unmount()}catch{}this.skeletonOverlayRoot=null}if(this.skeletonOverlayContainer){try{this.skeletonOverlayContainer.remove()}catch{}this.skeletonOverlayContainer=null}const i=document.createElement("div");if(i.id="g7-skeleton-overlay",i.setAttribute("role","status"),i.setAttribute("aria-busy","true"),e.appendChild(i),this.skeletonOverlayContainer=i,t?.component){const d=ba.getInstance().getComponent(t.component);if(d){const g=zu.createRoot(i);this.skeletonOverlayRoot=g,Os.flushSync(()=>{g.render(Ke.createElement(d,{options:{text:a}}))});return}G.log(`Spinner component "${t.component}" not found in registry, using default spinner`)}i.innerHTML='
'}reattachSpinnerOverlay(){if(!this._spinnerState)return;const{target:e,fallbackTarget:t}=this._spinnerState;let a=document.getElementById(e);!a&&t&&(a=document.getElementById(t)),a||(a=document.getElementById("app")),a&&(this._mountSpinnerInTarget(a),G.log("Spinner overlay reattached to new DOM target"))}hideSkeletonOverlay(){if(this.skeletonOverlayRoot){try{this.skeletonOverlayRoot.unmount()}catch{}this.skeletonOverlayRoot=null}if(this.skeletonOverlayContainer){try{this.skeletonOverlayContainer.parentNode&&this.skeletonOverlayContainer.remove()}catch{}this.skeletonOverlayContainer=null}const e=document.getElementById("g7-skeleton-overlay-style");e&&e.remove(),this._spinnerState=null}showRouteError(e){const t=Qy(e);Zy.renderFromError("app",t,"페이지 로딩 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}async handleServerError(){const e=window.G7Error;if(!e)return!1;G.warn("Server error detected:",e);try{return this.errorPageHandler&&(e.data&&(this.globalState.errorData=e.data),this.errorPageHandler.updateGlobalState(this.globalState),this.errorPageHandler.updateLocale(this.config.locale),await this.errorPageHandler.renderError(e.code,"app"))?(G.log(`${e.code} error page rendered successfully`),!0):(G.log(`Falling back to ErrorDisplay for ${e.code}`),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0)}catch(t){return G.error(`Failed to render ${e.code} page:`,t),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0}}async handleRouteNotFound(e){G.warn("Route not found:",e);try{if(this.errorPageHandler&&(this.errorPageHandler.updateGlobalState(this.globalState),this.errorPageHandler.updateLocale(this.config.locale),await this.errorPageHandler.renderError(404,"app"))){G.log("404 error page rendered successfully");return}G.log("Falling back to ErrorDisplay for 404"),this.showRouteError(new Error(`Page not found: ${e}`))}catch(t){G.error("Failed to render 404 page:",t),this.showRouteError(new Error(`Page not found: ${e}`))}}getRouter(){return this.router}getConfig(){return this.config}getLayoutLoader(){return this.layoutLoader}async reloadExtensionState(){G.log("reloadExtensionState: start");let e;try{const t=await fetch(`/api/templates/${this.config.templateId}/config.json?_=${Date.now()}`);if(t.ok){const a=await t.json();a?.success&&a?.data?.cache_version!==void 0&&(e=a.data.cache_version)}}catch(t){G.warn("reloadExtensionState: failed to fetch config.json",t)}e!==void 0&&e!==this.extensionCacheVersion&&(G.log(`reloadExtensionState: cache version ${this.extensionCacheVersion} -> ${e}`),this.extensionCacheVersion=e,this.saveCacheVersionToStorage(e));try{this.router&&(await this.router.loadRoutes(this.extensionCacheVersion),G.log("reloadExtensionState: routes reloaded"))}catch(t){G.error("reloadExtensionState: routes reload failed",t)}try{this.layoutLoader&&(this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),this.layoutLoader.clear(),G.log("reloadExtensionState: layout cache cleared"))}catch(t){G.error("reloadExtensionState: layout cache clear failed",t)}try{const{TranslationEngine:t}=await Promise.resolve().then(()=>Bp),a=t.getInstance();this.extensionCacheVersion>0&&a.setCacheVersion(this.extensionCacheVersion);const i=this.config.locale||"ko",o="en";await a.loadTranslations(this.config.templateId,i,"/api",!0),i!==o&&await a.loadTranslations(this.config.templateId,o,"/api",!0),G.log("reloadExtensionState: translations reloaded")}catch(t){G.error("reloadExtensionState: translations reload failed",t)}G.log("reloadExtensionState: done")}getActionDispatcher(){return Is().actionDispatcher}async changeLocale(e){try{if(G.log("Changing locale to:",e),this.config.locale===e){G.log("Locale is already",e);return}this.config.locale=e,this.saveLocaleToStorage(e),await this.saveLocaleToDatabase(e),this.layoutLoader&&(this.layoutLoader.clear(),G.log("Layout cache cleared")),this.errorPageHandler&&(this.errorPageHandler.updateLocale(e),G.log("ErrorPageHandler locale updated")),Bc(),await Mo({templateId:this.config.templateId,templateType:this.config.templateType,locale:e,debug:this.config.debug,cacheVersion:this.extensionCacheVersion}),G.log("Template Engine re-initialized with new locale");const{getActionDispatcher:t}=await Promise.resolve().then(()=>qa),a=t();a&&(a.setDefaultContext({navigate:i=>this.router?.navigate(i)}),a.setGlobalStateUpdater((i,o)=>this.setGlobalState(i,o)),G.log("Navigate function and setGlobalState re-injected to ActionDispatcher")),this.reinitializeModuleHandlers(),G.log("Module handlers re-initialized"),this.reinitializeTemplateHandlers(),G.log("Template handlers re-initialized"),this.reinitializePluginHandlers(),G.log("Plugin handlers re-initialized"),this.router&&this.router.navigateToCurrentPath(),G.log("Locale changed successfully to",e)}catch(t){throw G.error("Failed to change locale:",t),t}}loadLocaleFromStorage(){try{return localStorage.getItem(Aa.LOCALE_STORAGE_KEY)}catch(e){return G.warn("Failed to load locale from storage:",e),null}}saveLocaleToStorage(e){try{localStorage.setItem(Aa.LOCALE_STORAGE_KEY,e)}catch(t){G.warn("Failed to save locale to storage:",t)}}async saveLocaleToDatabase(e){const t=localStorage.getItem("auth_token");if(!t){G.log("No auth token, skipping DB locale save");return}let a,i;if(this.config.localeApi)a=this.config.localeApi.endpoint,i=this.config.localeApi.method;else{const o=this.config.templateType==="admin";a=o?"/api/admin/users/me/language":"/api/user/profile/update-language",i=o?"PATCH":"POST"}try{const o=this.getXsrfToken(),d=await fetch(a,{method:i,headers:{"Content-Type":"application/json",Accept:"application/json",...o&&{"X-XSRF-TOKEN":o},Authorization:`Bearer ${t}`},credentials:"include",body:JSON.stringify({language:e})});d.ok?G.log("Locale saved to DB:",e):G.warn("Failed to save locale to DB (UI will still change):",d.statusText)}catch(o){G.warn("Failed to call locale API (UI will still change):",o)}}getXsrfToken(){if(typeof document>"u")return null;const t=`; ${document.cookie}`.split("; XSRF-TOKEN=");return t.length===2?decodeURIComponent(t.pop()?.split(";").shift()||""):null}loadCacheVersionFromStorage(){try{const e=localStorage.getItem(Aa.CACHE_VERSION_STORAGE_KEY);return e?parseInt(e,10):null}catch(e){return G.warn("Failed to load cache version from storage:",e),null}}saveCacheVersionToStorage(e){try{localStorage.setItem(Aa.CACHE_VERSION_STORAGE_KEY,String(e))}catch(t){G.warn("Failed to save cache version to storage:",t)}}reinitializeModuleHandlers(){if(typeof window>"u")return;const e="__",t=window;Object.keys(t).forEach(a=>{if(a.startsWith(e)&&typeof t[a]?.initModule=="function")try{t[a].initModule(),G.log(`Module handler re-initialized: ${a}`)}catch(i){G.warn(`Failed to re-initialize module handlers for ${a}:`,i)}})}reinitializeTemplateHandlers(){if(typeof window>"u")return;const e=window.G7TemplateHandlers;if(!e){G.warn("Template handlers not found on window.G7TemplateHandlers");return}const t=this.getActionDispatcher();if(!t){G.warn("ActionDispatcher not available for template handler registration");return}Object.entries(e).forEach(([a,i])=>{t.registerHandler(a,i)}),G.log(`${Object.keys(e).length} template handler(s) re-registered:`,Object.keys(e))}reinitializePluginHandlers(){if(typeof window>"u")return;const e="__",t=window;Object.keys(t).forEach(a=>{if(a.startsWith(e)&&typeof t[a]?.initPlugin=="function")try{t[a].initPlugin(),G.log(`Plugin handler re-initialized: ${a}`)}catch(i){G.warn(`Failed to re-initialize plugin handlers for ${a}:`,i)}})}getLocale(){return this.config.locale}getErrorPageHandler(){return this.errorPageHandler}getGlobalState(){return{...this.globalState}}setGlobalState(e,t){const a={...this.globalState};typeof e=="function"?this.globalState=e(this.globalState):this.globalState={...this.globalState,...e},G.log("Global state updated:",this.globalState),window.G7Core?.devTools?.captureStateSnapshot?.({source:"setGlobalState",prev:a,next:this.globalState}),this.globalStateListeners.forEach(o=>{o(this.globalState)}),t?.render!==!1&&Promise.resolve().then(()=>qa).then(({updateTemplateData:o,getState:d})=>{const g=d();g.reactRoot&&g.currentLayoutJson&&o({_global:{...this.globalState},_local:this.globalState._local||{}})})}onGlobalStateChange(e){this.globalStateListeners.add(e)}offGlobalStateChange(e){this.globalStateListeners.delete(e)}async refetchDataSource(e,t){let a=this.currentDataSources.find(i=>i.id===e);if(!a)for(const[,i]of this.modalDataSources){const o=i.find(d=>d.id===e);if(o){a=o;break}}if(!a){G.warn(`Data source not found: ${e}`);return}G.log(`Refetching data source: ${e}`,t?.sync?"(sync mode)":"",t?.globalStateOverride?"(with global override)":"",t?.localStateOverride?"(with local override)":""),Pa.setPending(!0);try{const i=new is;this.currentGlobalHeaders.length>0&&i.setGlobalHeaders(this.currentGlobalHeaders);const o=Is(),d=o.currentDataContext?._global||{},g=t?.globalStateOverride?{...d,...t.globalStateOverride}:d,h=o.currentDataContext?._local||{},f=t?.localStateOverride?{...h,...t.localStateOverride}:h,y=(await i.fetchDataSourcesWithResults([a],this.currentRouteParams,this.currentQueryParams,g,f,{ignoreAutoFetch:!0}))[0];if(y.state==="success"&&y.data!==void 0){this.currentFetchedData[e]=y.data;const x={};this.processInitOptions([a],{[e]:y.data},x);const S=Is();if(S.bindingEngine){const w=[e];a.initGlobal&&w.push("_global"),a.initLocal&&w.push("_local"),S.bindingEngine.invalidateCacheByKeys(w)}const v={[e]:y.data};return Object.keys(x).length>0&&(v._localInit=x),a.initGlobal&&(v._global={...this.globalState}),fi(v,t?.sync?{sync:!0}:void 0),G.log(`Data source refetched successfully: ${e}`),y.data}else if(y.state==="error"){G.error(`Failed to refetch data source: ${e}`,y.error);return}}catch(i){G.error(`Error refetching data source: ${e}`,i);return}finally{Pa.setPending(!1)}}registerModalDataSources(e,t){this.modalDataSources.set(e,t),G.log(`Modal data sources registered: ${e} (${t.length} sources)`)}unregisterModalDataSources(e){this.modalDataSources.delete(e),G.log(`Modal data sources unregistered: ${e}`)}getDataSource(e){return this.currentFetchedData[e]}setDataSource(e,t,a){if(!e){G.warn("setDataSource: dataSourceId is required");return}const{merge:i=!1,sync:o=!1}=a||{};i&&this.currentFetchedData[e]?this.currentFetchedData[e]={...this.currentFetchedData[e],...t}:this.currentFetchedData[e]=t,Promise.resolve().then(()=>qa).then(({updateTemplateData:d})=>{d({[e]:this.currentFetchedData[e]},o?{sync:!0}:void 0)}),G.log(`setDataSource: Updated ${e}`,i?"(merged)":"(replaced)")}updateDataSourceItem(e,t,a,i,o){const{idField:d="id",merge:g=!0,skipRender:h=!1}=o||{},f=this.currentFetchedData[e];if(!f)return G.warn(`updateDataSourceItem: DataSource '${e}' not found`),!1;const p=this.parseItemPath(t);let y=f;for(const v of p)if(y=y?.[v],y===void 0)return G.warn(`updateDataSourceItem: Path '${t}' not found in dataSource`),!1;if(!Array.isArray(y))return G.warn(`updateDataSourceItem: Target at '${t}' is not an array`),!1;const x=y.findIndex(v=>String(v[d])===String(a));if(x===-1)return G.warn(`updateDataSourceItem: Item with ${d}='${a}' not found`),!1;g?y[x]=this.deepMerge(y[x],i):y[x]={...y[x],...i};const S=window.G7Core?.devTools;return S?.isEnabled?.()&&S.trackDataSourceUpdate?.({dataSourceId:e,updateType:"partial",itemPath:t,itemId:a,updates:i,timestamp:Date.now()}),h||Promise.resolve().then(()=>qa).then(({updateTemplateData:v})=>{v({[e]:this.currentFetchedData[e]},{sync:!1})}),G.log(`updateDataSourceItem: Updated ${e}.${t}[${d}=${a}]`),!0}parseItemPath(e){const t=[],a=/([^\.\[\]]+)|\[(\d+)\]/g;let i;for(;(i=a.exec(e))!==null;)i[1]!==void 0?t.push(i[1]):i[2]!==void 0&&t.push(parseInt(i[2],10));return t}deepMerge(e,t){if(t==null)return e;if(typeof t!="object"||Array.isArray(t))return t;const a={...e};for(const i of Object.keys(t))typeof t[i]=="object"&&t[i]!==null&&!Array.isArray(t[i])?a[i]=this.deepMerge(a[i]||{},t[i]):a[i]=t[i];return a}setValueAtPath(e,t,a,i="deep"){const o=t.split(".");let d=e;for(let f=0;fy.auto_fetch!==!1&&y.type!=="websocket");if(o.length===0){G.log("No auto_fetch data sources to refetch");return}G.log(`Refetching ${o.length} auto_fetch data sources`),Pa.setPending(!0);const d=Is().currentLayoutJson,g=d?.transition_overlay,h=Array.isArray(g?.wait_for)?g.wait_for:[],f=o.some(y=>(y.loading_strategy||"progressive")==="blocking"),p=h.length>0&&o.some(y=>h.includes(y.id)&&y.type!=="websocket"&&(y.loading_strategy||"progressive")!=="background");if((f||p)&&g&&typeof g=="object"){const y=t?.transitionOverlayTarget||g.target;g.enabled&&g.style==="skeleton"&&g.skeleton?.component&&y?this.renderSkeletonOverlay(y,g.skeleton,d,g.fallback_target):g.enabled&&g.style==="spinner"&&y&&this.renderSpinnerOverlay(y,g.spinner,g.fallback_target)}try{const y=new is;this.currentGlobalHeaders.length>0&&y.setGlobalHeaders(this.currentGlobalHeaders);const x=Is(),S=x.currentDataContext?._global||{},v=await y.fetchDataSourcesWithResults(o,this.currentRouteParams,this.currentQueryParams,S,void 0,{ignoreAutoFetch:!1}),w={},k={},A=new Map(o.map(O=>[O.id,O]));for(const O of v){const N=A.get(O.id);if(!N){G.warn(`Refetch result id not found in autoFetchDataSources: ${O.id}`);continue}const D=O.id;O.state==="success"&&O.data!==void 0?(this.currentFetchedData[D]=O.data,w[D]=O.data,this.processInitOptions([N],{[D]:O.data},k),G.log(`Data source refetched: ${D}`)):O.state==="error"&&G.error(`Failed to refetch data source: ${D}`,O.error)}if(x.bindingEngine){const O=Object.keys(w);O.push("query"),x.bindingEngine.invalidateCacheByKeys(O)}if(Object.keys(k).length>0&&(w._localInit=k),Object.keys(w).length>0){if(w.query=tk(this.currentQueryParams),x.currentLayoutJson?.computed&&Object.keys(x.currentLayoutJson.computed).length>0){const O={...x.currentDataContext,...w,query:w.query},N=this.calculateComputed(x.currentLayoutJson.computed,O);Object.keys(N).length>0&&(w._computed=N,this.globalState._computed=N,G.log("Computed values recalculated in updateQueryParams:",Object.keys(N)))}fi(w,{sync:!0}),G.log("Template data updated with new query params")}}catch(y){G.error("Error in updateQueryParams:",y)}finally{Pa.setPending(!1),this.hideTransitionOverlay()}}calculateComputed(e,t){const a={},i=new _n;for(const[o,d]of Object.entries(e))try{let g;if(this.isComputedSwitchDefinition(d))g=i.resolveSwitch(d,t,{skipCache:!0});else if(typeof d=="string")if(d.startsWith("{{")&&d.endsWith("}}")){const h=d.slice(2,-2).trim();g=this.evaluateComputedExpression(h,t)}else g=d;a[o]=g,G.log(`Computed ${o}:`,g)}catch(g){G.warn(`Failed to calculate computed value: ${o}`,g),a[o]=void 0}return a}isComputedSwitchDefinition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"$switch"in e&&"$cases"in e}evaluateComputedExpression(e,t){try{return new Function("ctx",` + `)(t)}return!!e}catch(a){return G.warn(`Failed to evaluate script condition: ${e}`,a),!1}}showInitError(e){const t=Qy(e);Zy.renderFromError("app",t,"초기화 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}showTransitionOverlay(e,t){const a=typeof e=="boolean"?{enabled:e,style:"opaque",target:void 0,skeleton:void 0,spinner:void 0}:{enabled:e.enabled,style:e.style||"opaque",target:e.target,skeleton:e.skeleton,spinner:e.spinner,fallback_target:e.fallback_target};if(!a.enabled)return;if(this.hideTransitionOverlay(),a.style==="skeleton"&&a.skeleton?.component&&a.target&&t){this.renderSkeletonOverlay(a.target,a.skeleton,t,a.fallback_target);return}if(a.style==="spinner"&&a.target){this.renderSpinnerOverlay(a.target,a.spinner,a.fallback_target);return}const i=document.documentElement.classList.contains("dark");let o,d="";switch(a.style){case"blur":o=i?"rgba(17,24,39,0.3)":"rgba(255,255,255,0.3)",d="backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px);";break;case"fade":o=i?"rgba(17,24,39,0.8)":"rgba(255,255,255,0.8)";break;case"skeleton":o=i?"rgb(17,24,39)":"rgb(249,250,251)";break;case"opaque":default:o=i?"rgb(17,24,39)":"rgb(249,250,251)";break}if(a.target){const g=`#${CSS.escape(a.target)}`,h=document.createElement("style");h.id="g7-transition-overlay",h.textContent=`${g}{position:relative;z-index:0;}${g}::after{content:'';position:absolute;inset:0;background:${o};${d}z-index:2147483647;pointer-events:none;}`,document.head.appendChild(h),this.transitionOverlayEl=h}else{const g=document.createElement("div");g.id="g7-transition-overlay",g.setAttribute("aria-hidden","true"),g.style.cssText=`position:fixed;inset:0;z-index:9999;pointer-events:none;background:${o};${d}`,document.body.appendChild(g),this.transitionOverlayEl=g}}hideTransitionOverlay(){this.transitionOverlayEl&&(this.transitionOverlayEl.remove(),this.transitionOverlayEl=null),this.hideSkeletonOverlay()}renderSkeletonOverlay(e,t,a,i){const d=ba.getInstance().getComponent(t.component);if(!d){G.log(`Skeleton component "${t.component}" not found in registry, falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}let g=document.getElementById(e),h="target";if(!g&&i&&(g=document.getElementById(i),h="fallback"),g||(g=document.getElementById("app"),h="fullpage"),!g){G.log(`Skeleton overlay: no target found (target="#${e}", fallback="${i||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const p=document.documentElement.classList.contains("dark")?"rgb(17,24,39)":"rgb(249,250,251)",y=h==="fullpage"?"app":h==="fallback"?i:e,x=`#${CSS.escape(y)}`,S=document.createElement("style");S.id="g7-skeleton-overlay-style",S.textContent=`${x}{position:relative;z-index:0;}${x}::after{content:'';position:absolute;inset:0;background:${p};z-index:2147483646;pointer-events:none;}`,document.head.appendChild(S),this.transitionOverlayEl=S;const v=document.createElement("div");if(v.id="g7-skeleton-overlay",v.setAttribute("role","status"),v.setAttribute("aria-busy","true"),v.setAttribute("aria-label","Loading..."),h==="fullpage")v.style.cssText=["position:fixed","inset:0","z-index:20","overflow:hidden","pointer-events:none",`background:${p}`].join(";")+";";else{const N=g.getBoundingClientRect(),D=window.scrollX||document.documentElement.scrollLeft,$=window.scrollY||document.documentElement.scrollTop;v.style.cssText=["position:absolute",`top:${N.top+$}px`,`left:${N.left+D}px`,`width:${N.width}px`,`height:${N.height}px`,"z-index:20","overflow:hidden","pointer-events:none",`background:${p}`].join(";")+";"}document.body.appendChild(v),this.skeletonOverlayContainer=v;const w=a.components||[];let k;if(h==="fullpage")k=w;else{const N=h==="fallback"?i:e;k=this.findComponentChildrenById(w,N)}const A=zu.createRoot(v);this.skeletonOverlayRoot=A,Os.flushSync(()=>{A.render(Ke.createElement(d,{components:k,options:{animation:t.animation||"pulse",iteration_count:t.iteration_count||5}}))});const O=h==="fullpage"?"fullpage (#app)":h==="fallback"?`fallback (#${i})`:`target (#${e})`;G.log(`Skeleton overlay rendered [${O}] with "${t.component}" (${k.length} components)`)}findComponentChildrenById(e,t){const a=i=>{for(const o of i){if(o.id===t)return o.children||[];if(o.children&&Array.isArray(o.children)){const d=a(o.children);if(d!==null)return d}}return null};return a(e)||e}renderSpinnerOverlay(e,t,a){let i=document.getElementById(e),o="target";if(!i&&a&&(i=document.getElementById(a),o="fallback"),i||(i=document.getElementById("app"),o="fullpage"),!i){G.log(`Spinner overlay: no target found (target="#${e}", fallback="${a||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const d=o==="fullpage"?"app":o==="fallback"?a:e,g=`#${CSS.escape(d)}`,h=document.createElement("style");h.id="g7-skeleton-overlay-style",h.textContent=[`${g}{position:relative;}`,"@keyframes g7-spin{to{transform:rotate(360deg)}}"].join(""),document.head.appendChild(h),this.transitionOverlayEl=h;const f=t?.text||window.G7Core?.t?.("nav.loading")||"";this._spinnerState={target:e,fallbackTarget:a,spinnerConfig:t,resolvedText:f},this._mountSpinnerInTarget(i);const p=o==="fullpage"?"fullpage (#app)":o==="fallback"?`fallback (#${a})`:`target (#${e})`,y=t?.component||"default spinner";G.log(`Spinner overlay rendered [${p}] with "${y}"`)}_mountSpinnerInTarget(e){if(!this._spinnerState)return;const{spinnerConfig:t,resolvedText:a}=this._spinnerState;if(this.skeletonOverlayRoot){try{this.skeletonOverlayRoot.unmount()}catch{}this.skeletonOverlayRoot=null}if(this.skeletonOverlayContainer){try{this.skeletonOverlayContainer.remove()}catch{}this.skeletonOverlayContainer=null}const i=document.createElement("div");if(i.id="g7-skeleton-overlay",i.setAttribute("role","status"),i.setAttribute("aria-busy","true"),e.appendChild(i),this.skeletonOverlayContainer=i,t?.component){const d=ba.getInstance().getComponent(t.component);if(d){const g=zu.createRoot(i);this.skeletonOverlayRoot=g,Os.flushSync(()=>{g.render(Ke.createElement(d,{options:{text:a}}))});return}G.log(`Spinner component "${t.component}" not found in registry, using default spinner`)}i.innerHTML='
'}reattachSpinnerOverlay(){if(!this._spinnerState)return;const{target:e,fallbackTarget:t}=this._spinnerState;let a=document.getElementById(e);!a&&t&&(a=document.getElementById(t)),a||(a=document.getElementById("app")),a&&(this._mountSpinnerInTarget(a),G.log("Spinner overlay reattached to new DOM target"))}hideSkeletonOverlay(){if(this.skeletonOverlayRoot){try{this.skeletonOverlayRoot.unmount()}catch{}this.skeletonOverlayRoot=null}if(this.skeletonOverlayContainer){try{this.skeletonOverlayContainer.parentNode&&this.skeletonOverlayContainer.remove()}catch{}this.skeletonOverlayContainer=null}const e=document.getElementById("g7-skeleton-overlay-style");e&&e.remove(),this._spinnerState=null}showRouteError(e){const t=Qy(e);Zy.renderFromError("app",t,"페이지 로딩 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}async handleServerError(){const e=window.G7Error;if(!e)return!1;G.warn("Server error detected:",e);try{return this.errorPageHandler&&(e.data&&(this.globalState.errorData=e.data),this.errorPageHandler.updateGlobalState(this.globalState),this.errorPageHandler.updateLocale(this.config.locale),await this.errorPageHandler.renderError(e.code,"app"))?(G.log(`${e.code} error page rendered successfully`),!0):(G.log(`Falling back to ErrorDisplay for ${e.code}`),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0)}catch(t){return G.error(`Failed to render ${e.code} page:`,t),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0}}async handleRouteNotFound(e){G.warn("Route not found:",e);try{if(this.errorPageHandler&&(this.errorPageHandler.updateGlobalState(this.globalState),this.errorPageHandler.updateLocale(this.config.locale),await this.errorPageHandler.renderError(404,"app"))){G.log("404 error page rendered successfully");return}G.log("Falling back to ErrorDisplay for 404"),this.showRouteError(new Error(`Page not found: ${e}`))}catch(t){G.error("Failed to render 404 page:",t),this.showRouteError(new Error(`Page not found: ${e}`))}}getRouter(){return this.router}getConfig(){return this.config}getLayoutLoader(){return this.layoutLoader}async reloadExtensionState(){G.log("reloadExtensionState: start");let e;try{const t=await fetch(`/api/templates/${this.config.templateId}/config.json?_=${Date.now()}`);if(t.ok){const a=await t.json();a?.success&&a?.data?.cache_version!==void 0&&(e=a.data.cache_version)}}catch(t){G.warn("reloadExtensionState: failed to fetch config.json",t)}e!==void 0&&e!==this.extensionCacheVersion&&(G.log(`reloadExtensionState: cache version ${this.extensionCacheVersion} -> ${e}`),this.extensionCacheVersion=e,this.saveCacheVersionToStorage(e));try{this.router&&(await this.router.loadRoutes(this.extensionCacheVersion),G.log("reloadExtensionState: routes reloaded"))}catch(t){G.error("reloadExtensionState: routes reload failed",t)}try{this.layoutLoader&&(this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),this.layoutLoader.clear(),G.log("reloadExtensionState: layout cache cleared"))}catch(t){G.error("reloadExtensionState: layout cache clear failed",t)}try{const{TranslationEngine:t}=await Promise.resolve().then(()=>Bp),a=t.getInstance();this.extensionCacheVersion>0&&a.setCacheVersion(this.extensionCacheVersion);const i=this.config.locale||"ko",o="en";await a.loadTranslations(this.config.templateId,i,"/api",!0),i!==o&&await a.loadTranslations(this.config.templateId,o,"/api",!0),G.log("reloadExtensionState: translations reloaded")}catch(t){G.error("reloadExtensionState: translations reload failed",t)}G.log("reloadExtensionState: done")}getActionDispatcher(){return Is().actionDispatcher}async changeLocale(e){try{if(G.log("Changing locale to:",e),this.config.locale===e){G.log("Locale is already",e);return}this.config.locale=e,this.saveLocaleToStorage(e),await this.saveLocaleToDatabase(e),this.layoutLoader&&(this.layoutLoader.clear(),G.log("Layout cache cleared")),this.errorPageHandler&&(this.errorPageHandler.updateLocale(e),G.log("ErrorPageHandler locale updated")),Bc(),await $o({templateId:this.config.templateId,templateType:this.config.templateType,locale:e,debug:this.config.debug,cacheVersion:this.extensionCacheVersion}),G.log("Template Engine re-initialized with new locale");const{getActionDispatcher:t}=await Promise.resolve().then(()=>qa),a=t();a&&(a.setDefaultContext({navigate:i=>this.router?.navigate(i)}),a.setGlobalStateUpdater((i,o)=>this.setGlobalState(i,o)),G.log("Navigate function and setGlobalState re-injected to ActionDispatcher")),this.reinitializeModuleHandlers(),G.log("Module handlers re-initialized"),this.reinitializeTemplateHandlers(),G.log("Template handlers re-initialized"),this.reinitializePluginHandlers(),G.log("Plugin handlers re-initialized"),this.router&&this.router.navigateToCurrentPath(),G.log("Locale changed successfully to",e)}catch(t){throw G.error("Failed to change locale:",t),t}}loadLocaleFromStorage(){try{return localStorage.getItem(Aa.LOCALE_STORAGE_KEY)}catch(e){return G.warn("Failed to load locale from storage:",e),null}}saveLocaleToStorage(e){try{localStorage.setItem(Aa.LOCALE_STORAGE_KEY,e)}catch(t){G.warn("Failed to save locale to storage:",t)}}async saveLocaleToDatabase(e){const t=localStorage.getItem("auth_token");if(!t){G.log("No auth token, skipping DB locale save");return}let a,i;if(this.config.localeApi)a=this.config.localeApi.endpoint,i=this.config.localeApi.method;else{const o=this.config.templateType==="admin";a=o?"/api/admin/users/me/language":"/api/user/profile/update-language",i=o?"PATCH":"POST"}try{const o=this.getXsrfToken(),d=await fetch(a,{method:i,headers:{"Content-Type":"application/json",Accept:"application/json",...o&&{"X-XSRF-TOKEN":o},Authorization:`Bearer ${t}`},credentials:"include",body:JSON.stringify({language:e})});d.ok?G.log("Locale saved to DB:",e):G.warn("Failed to save locale to DB (UI will still change):",d.statusText)}catch(o){G.warn("Failed to call locale API (UI will still change):",o)}}getXsrfToken(){if(typeof document>"u")return null;const t=`; ${document.cookie}`.split("; XSRF-TOKEN=");return t.length===2?decodeURIComponent(t.pop()?.split(";").shift()||""):null}loadCacheVersionFromStorage(){try{const e=localStorage.getItem(Aa.CACHE_VERSION_STORAGE_KEY);return e?parseInt(e,10):null}catch(e){return G.warn("Failed to load cache version from storage:",e),null}}saveCacheVersionToStorage(e){try{localStorage.setItem(Aa.CACHE_VERSION_STORAGE_KEY,String(e))}catch(t){G.warn("Failed to save cache version to storage:",t)}}reinitializeModuleHandlers(){if(typeof window>"u")return;const e="__",t=window;Object.keys(t).forEach(a=>{if(a.startsWith(e)&&typeof t[a]?.initModule=="function")try{t[a].initModule(),G.log(`Module handler re-initialized: ${a}`)}catch(i){G.warn(`Failed to re-initialize module handlers for ${a}:`,i)}})}reinitializeTemplateHandlers(){if(typeof window>"u")return;const e=window.G7TemplateHandlers;if(!e){G.warn("Template handlers not found on window.G7TemplateHandlers");return}const t=this.getActionDispatcher();if(!t){G.warn("ActionDispatcher not available for template handler registration");return}Object.entries(e).forEach(([a,i])=>{t.registerHandler(a,i)}),G.log(`${Object.keys(e).length} template handler(s) re-registered:`,Object.keys(e))}reinitializePluginHandlers(){if(typeof window>"u")return;const e="__",t=window;Object.keys(t).forEach(a=>{if(a.startsWith(e)&&typeof t[a]?.initPlugin=="function")try{t[a].initPlugin(),G.log(`Plugin handler re-initialized: ${a}`)}catch(i){G.warn(`Failed to re-initialize plugin handlers for ${a}:`,i)}})}getLocale(){return this.config.locale}getErrorPageHandler(){return this.errorPageHandler}getGlobalState(){return{...this.globalState}}setGlobalState(e,t){const a={...this.globalState};typeof e=="function"?this.globalState=e(this.globalState):this.globalState={...this.globalState,...e},G.log("Global state updated:",this.globalState),window.G7Core?.devTools?.captureStateSnapshot?.({source:"setGlobalState",prev:a,next:this.globalState}),this.globalStateListeners.forEach(o=>{o(this.globalState)}),t?.render!==!1&&Promise.resolve().then(()=>qa).then(({updateTemplateData:o,getState:d})=>{const g=d();g.reactRoot&&g.currentLayoutJson&&o({_global:{...this.globalState},_local:this.globalState._local||{}})})}onGlobalStateChange(e){this.globalStateListeners.add(e)}offGlobalStateChange(e){this.globalStateListeners.delete(e)}async refetchDataSource(e,t){let a=this.currentDataSources.find(i=>i.id===e);if(!a)for(const[,i]of this.modalDataSources){const o=i.find(d=>d.id===e);if(o){a=o;break}}if(!a){G.warn(`Data source not found: ${e}`);return}G.log(`Refetching data source: ${e}`,t?.sync?"(sync mode)":"",t?.globalStateOverride?"(with global override)":"",t?.localStateOverride?"(with local override)":""),Pa.setPending(!0);try{const i=new is;this.currentGlobalHeaders.length>0&&i.setGlobalHeaders(this.currentGlobalHeaders);const o=Is(),d=o.currentDataContext?._global||{},g=t?.globalStateOverride?{...d,...t.globalStateOverride}:d,h=o.currentDataContext?._local||{},f=t?.localStateOverride?{...h,...t.localStateOverride}:h,y=(await i.fetchDataSourcesWithResults([a],this.currentRouteParams,this.currentQueryParams,g,f,{ignoreAutoFetch:!0}))[0];if(y.state==="success"&&y.data!==void 0){this.currentFetchedData[e]=y.data;const x={};this.processInitOptions([a],{[e]:y.data},x);const S=Is();if(S.bindingEngine){const w=[e];a.initGlobal&&w.push("_global"),a.initLocal&&w.push("_local"),S.bindingEngine.invalidateCacheByKeys(w)}const v={[e]:y.data};return Object.keys(x).length>0&&(v._localInit=x),a.initGlobal&&(v._global={...this.globalState}),fi(v,t?.sync?{sync:!0}:void 0),G.log(`Data source refetched successfully: ${e}`),y.data}else if(y.state==="error"){G.error(`Failed to refetch data source: ${e}`,y.error);return}}catch(i){G.error(`Error refetching data source: ${e}`,i);return}finally{Pa.setPending(!1)}}registerModalDataSources(e,t){this.modalDataSources.set(e,t),G.log(`Modal data sources registered: ${e} (${t.length} sources)`)}unregisterModalDataSources(e){this.modalDataSources.delete(e),G.log(`Modal data sources unregistered: ${e}`)}getDataSource(e){return this.currentFetchedData[e]}setDataSource(e,t,a){if(!e){G.warn("setDataSource: dataSourceId is required");return}const{merge:i=!1,sync:o=!1}=a||{};i&&this.currentFetchedData[e]?this.currentFetchedData[e]={...this.currentFetchedData[e],...t}:this.currentFetchedData[e]=t,Promise.resolve().then(()=>qa).then(({updateTemplateData:d})=>{d({[e]:this.currentFetchedData[e]},o?{sync:!0}:void 0)}),G.log(`setDataSource: Updated ${e}`,i?"(merged)":"(replaced)")}updateDataSourceItem(e,t,a,i,o){const{idField:d="id",merge:g=!0,skipRender:h=!1}=o||{},f=this.currentFetchedData[e];if(!f)return G.warn(`updateDataSourceItem: DataSource '${e}' not found`),!1;const p=this.parseItemPath(t);let y=f;for(const v of p)if(y=y?.[v],y===void 0)return G.warn(`updateDataSourceItem: Path '${t}' not found in dataSource`),!1;if(!Array.isArray(y))return G.warn(`updateDataSourceItem: Target at '${t}' is not an array`),!1;const x=y.findIndex(v=>String(v[d])===String(a));if(x===-1)return G.warn(`updateDataSourceItem: Item with ${d}='${a}' not found`),!1;g?y[x]=this.deepMerge(y[x],i):y[x]={...y[x],...i};const S=window.G7Core?.devTools;return S?.isEnabled?.()&&S.trackDataSourceUpdate?.({dataSourceId:e,updateType:"partial",itemPath:t,itemId:a,updates:i,timestamp:Date.now()}),h||Promise.resolve().then(()=>qa).then(({updateTemplateData:v})=>{v({[e]:this.currentFetchedData[e]},{sync:!1})}),G.log(`updateDataSourceItem: Updated ${e}.${t}[${d}=${a}]`),!0}parseItemPath(e){const t=[],a=/([^\.\[\]]+)|\[(\d+)\]/g;let i;for(;(i=a.exec(e))!==null;)i[1]!==void 0?t.push(i[1]):i[2]!==void 0&&t.push(parseInt(i[2],10));return t}deepMerge(e,t){if(t==null)return e;if(typeof t!="object"||Array.isArray(t))return t;const a={...e};for(const i of Object.keys(t))typeof t[i]=="object"&&t[i]!==null&&!Array.isArray(t[i])?a[i]=this.deepMerge(a[i]||{},t[i]):a[i]=t[i];return a}setValueAtPath(e,t,a,i="deep"){const o=t.split(".");let d=e;for(let f=0;fy.auto_fetch!==!1&&y.type!=="websocket");if(o.length===0){G.log("No auto_fetch data sources to refetch");return}G.log(`Refetching ${o.length} auto_fetch data sources`),Pa.setPending(!0);const d=Is().currentLayoutJson,g=d?.transition_overlay,h=Array.isArray(g?.wait_for)?g.wait_for:[],f=o.some(y=>(y.loading_strategy||"progressive")==="blocking"),p=h.length>0&&o.some(y=>h.includes(y.id)&&y.type!=="websocket"&&(y.loading_strategy||"progressive")!=="background");if((f||p)&&g&&typeof g=="object"){const y=t?.transitionOverlayTarget||g.target;g.enabled&&g.style==="skeleton"&&g.skeleton?.component&&y?this.renderSkeletonOverlay(y,g.skeleton,d,g.fallback_target):g.enabled&&g.style==="spinner"&&y&&this.renderSpinnerOverlay(y,g.spinner,g.fallback_target)}try{const y=new is;this.currentGlobalHeaders.length>0&&y.setGlobalHeaders(this.currentGlobalHeaders);const x=Is(),S=x.currentDataContext?._global||{},v=await y.fetchDataSourcesWithResults(o,this.currentRouteParams,this.currentQueryParams,S,void 0,{ignoreAutoFetch:!1}),w={},k={},A=new Map(o.map(O=>[O.id,O]));for(const O of v){const N=A.get(O.id);if(!N){G.warn(`Refetch result id not found in autoFetchDataSources: ${O.id}`);continue}const D=O.id;O.state==="success"&&O.data!==void 0?(this.currentFetchedData[D]=O.data,w[D]=O.data,this.processInitOptions([N],{[D]:O.data},k),G.log(`Data source refetched: ${D}`)):O.state==="error"&&G.error(`Failed to refetch data source: ${D}`,O.error)}if(x.bindingEngine){const O=Object.keys(w);O.push("query"),x.bindingEngine.invalidateCacheByKeys(O)}if(Object.keys(k).length>0&&(w._localInit=k),Object.keys(w).length>0){if(w.query=nk(this.currentQueryParams),x.currentLayoutJson?.computed&&Object.keys(x.currentLayoutJson.computed).length>0){const O={...x.currentDataContext,...w,query:w.query},N=this.calculateComputed(x.currentLayoutJson.computed,O);Object.keys(N).length>0&&(w._computed=N,this.globalState._computed=N,G.log("Computed values recalculated in updateQueryParams:",Object.keys(N)))}fi(w,{sync:!0}),G.log("Template data updated with new query params")}}catch(y){G.error("Error in updateQueryParams:",y)}finally{Pa.setPending(!1),this.hideTransitionOverlay()}}calculateComputed(e,t){const a={},i=new _n;for(const[o,d]of Object.entries(e))try{let g;if(this.isComputedSwitchDefinition(d))g=i.resolveSwitch(d,t,{skipCache:!0});else if(typeof d=="string")if(d.startsWith("{{")&&d.endsWith("}}")){const h=d.slice(2,-2).trim();g=this.evaluateComputedExpression(h,t)}else g=d;a[o]=g,G.log(`Computed ${o}:`,g)}catch(g){G.warn(`Failed to calculate computed value: ${o}`,g),a[o]=void 0}return a}isComputedSwitchDefinition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"$switch"in e&&"$cases"in e}evaluateComputedExpression(e,t){try{return new Function("ctx",` with(ctx) { try { return ${e}; @@ -283,7 +283,7 @@ Error generating stack: `+u.message+` return undefined; } } - `)(t)}catch(a){G.warn(`Expression evaluation failed: ${e}`,a);return}}async executeInitActions(e,t={}){const{getActionDispatcher:a}=await Promise.resolve().then(()=>qa),i=a();if(!i){G.warn("ActionDispatcher not available for init_actions");return}G.log("Executing init_actions:",e.map(g=>g.handler)),G.log("Init actions dataContext:",t),G.log("Init actions dataContext._global:",t._global);const o=e.map(g=>g.handler).filter(g=>g.includes("."));o.length>0&&await this.waitForHandlers(i,o);let d={...t};for(const g of e)try{const h={type:"click",handler:g.handler,target:g.target,params:g.params,resultTo:g.resultTo,onSuccess:g.onSuccess,onError:g.onError,if:g.if,conditions:g.conditions,auth_mode:g.auth_mode,auth_required:g.auth_required},f=i.createHandler(h,d),p=new Event("init");await f(p),G.log(`Init action executed: ${g.handler}`);const y=this.globalState;d={...d,_global:{...y},_local:y._local||d._local||{}},G.log(`Data context refreshed after ${g.handler}:`,{cartKey:d._global?.cartKey})}catch(h){G.error(`Failed to execute init action: ${g.handler}`,h)}}async waitForHandlers(e,t,a=5e3){const i=Date.now(),o=50,d=()=>t.every(g=>e.customHandlers?.has(g));if(d()){G.log("All module handlers already registered");return}return G.log("Waiting for module handlers:",t),new Promise(g=>{const h=()=>{if(d()){G.log("All module handlers now registered"),g();return}if(Date.now()-i>=a){const f=t.filter(p=>!e.customHandlers?.has(p));G.warn("Timeout waiting for handlers:",f),g();return}setTimeout(h,o)};h()})}};H(Aa,"LOCALE_STORAGE_KEY","g7_locale"),H(Aa,"CACHE_VERSION_STORAGE_KEY","g7_cache_version");let Oo=Aa;function Pg(r){const e=new Oo(r);return r.websocket&&(Lc.configure(r.websocket),G.log("WebSocket 설정 완료")),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{e.init(),window.__templateApp=e}):(e.init(),window.__templateApp=e),e}typeof window<"u"&&(window.G7Core=window.G7Core||{},window.G7Core.initTemplateApp=Pg,window.G7Core.dataSource={refetch:async(r,e)=>{const t=window.__templateApp;if(!t){G.warn("TemplateApp not initialized (G7Core.dataSource.refetch)");return}return t.refetchDataSource(r,e)},get:r=>{const e=window.__templateApp;if(!e){G.warn("TemplateApp not initialized (G7Core.dataSource.get)");return}return e.getDataSource(r)}});const zc=[{id:"stale-closure",name:"Stale Closure",category:"state",symptoms:["이전 값이 전송됨","저장 시 오래된 데이터","API 호출 시 첫 값만 전송","클릭할 때마다 같은 값"],detector:r=>{const t=r.actionHistory.slice(-10).filter(a=>a.type==="apiCall");if(t.length<2)return!1;for(let a=1;aqa),i=a();if(!i){G.warn("ActionDispatcher not available for init_actions");return}G.log("Executing init_actions:",e.map(g=>g.handler)),G.log("Init actions dataContext:",t),G.log("Init actions dataContext._global:",t._global);const o=e.map(g=>g.handler).filter(g=>g.includes("."));o.length>0&&await this.waitForHandlers(i,o);let d={...t};for(const g of e)try{const h={type:"click",handler:g.handler,target:g.target,params:g.params,resultTo:g.resultTo,onSuccess:g.onSuccess,onError:g.onError,if:g.if,conditions:g.conditions,auth_mode:g.auth_mode,auth_required:g.auth_required},f=i.createHandler(h,d),p=new Event("init");await f(p),G.log(`Init action executed: ${g.handler}`);const y=this.globalState;d={...d,_global:{...y},_local:y._local||d._local||{}},G.log(`Data context refreshed after ${g.handler}:`,{cartKey:d._global?.cartKey})}catch(h){G.error(`Failed to execute init action: ${g.handler}`,h)}}async waitForHandlers(e,t,a=5e3){const i=Date.now(),o=50,d=()=>t.every(g=>e.customHandlers?.has(g));if(d()){G.log("All module handlers already registered");return}return G.log("Waiting for module handlers:",t),new Promise(g=>{const h=()=>{if(d()){G.log("All module handlers now registered"),g();return}if(Date.now()-i>=a){const f=t.filter(p=>!e.customHandlers?.has(p));G.warn("Timeout waiting for handlers:",f),g();return}setTimeout(h,o)};h()})}};H(Aa,"LOCALE_STORAGE_KEY","g7_locale"),H(Aa,"CACHE_VERSION_STORAGE_KEY","g7_cache_version");let Oo=Aa;function Pg(r){const e=new Oo(r);return r.websocket&&(Mc.configure(r.websocket),G.log("WebSocket 설정 완료")),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{e.init(),window.__templateApp=e}):(e.init(),window.__templateApp=e),e}typeof window<"u"&&(window.G7Core=window.G7Core||{},window.G7Core.initTemplateApp=Pg,window.G7Core.dataSource={refetch:async(r,e)=>{const t=window.__templateApp;if(!t){G.warn("TemplateApp not initialized (G7Core.dataSource.refetch)");return}return t.refetchDataSource(r,e)},get:r=>{const e=window.__templateApp;if(!e){G.warn("TemplateApp not initialized (G7Core.dataSource.get)");return}return e.getDataSource(r)}});const Hc=[{id:"stale-closure",name:"Stale Closure",category:"state",symptoms:["이전 값이 전송됨","저장 시 오래된 데이터","API 호출 시 첫 값만 전송","클릭할 때마다 같은 값"],detector:r=>{const t=r.actionHistory.slice(-10).filter(a=>a.type==="apiCall");if(t.length<2)return!1;for(let a=1;ar.form.some(e=>!e.dataKey),probability:.9,solution:"Form에 dataKey prop 추가",docLink:"troubleshooting-components.md#form-datakey"},{id:"input-no-name",name:"Input name 미설정",category:"form",symptoms:["자동 바인딩 안됨","Input 값 변경이 상태에 반영 안됨"],detector:r=>r.form.some(e=>e.inputs.some(t=>!t.name)),probability:.95,solution:"Input에 name prop 추가",docLink:"troubleshooting-components.md#input-name"},{id:"i18n-key-missing",name:"번역 키 누락",category:"i18n",symptoms:["$t:key가 그대로 표시됨","번역되지 않은 텍스트"],detector:r=>typeof document<"u"?document.body.innerHTML.includes("$t:"):!1,probability:.95,solution:"번역 파일에 키 추가",docLink:"troubleshooting-components.md#i18n"}];class ex{constructor(){H(this,"devTools");this.devTools=ka.getInstance()}analyze(e){const t=this.buildContext(),a=[];for(const i of zc){const o=e.some(g=>i.symptoms.some(h=>h.toLowerCase().includes(g.toLowerCase())||g.toLowerCase().includes(h.toLowerCase())));let d=!1;try{d=i.detector(t)}catch{}(o||d)&&a.push({rule:i,confidence:this.calculateConfidence(i,e,o,d),evidence:this.collectEvidence(i,t)})}return a.sort((i,o)=>o.confidence-i.confidence)}suggestFix(e){return{title:e.rule.name,description:e.rule.solution,codeExample:e.rule.codeExample,docLink:e.rule.docLink}}getCommonIssues(){const e=this.buildContext(),t=[];for(const a of zc)try{a.detector(e)&&t.push({rule:a,count:1})}catch{}return t.sort((a,i)=>i.count-a.count).map(a=>({id:a.rule.id,name:a.rule.name,description:a.rule.solution,frequency:a.count}))}getRulesByCategory(e){return zc.filter(t=>t.category===e)}getAllRules(){return[...zc]}buildContext(){return{stateHistory:this.devTools.getStateHistory(),actionHistory:this.devTools.getActionHistory(),cacheStats:this.devTools.getCacheStats(),currentState:this.devTools.getState(),lifecycle:this.devTools.getLifecycleInfo(),performance:this.devTools.getPerformanceInfo(),network:this.devTools.getNetworkInfo(),conditional:this.devTools.getConditionalInfo(),form:this.devTools.getFormInfo(),websocket:this.devTools.getWebSocketInfo(),stateAtTime:e=>this.devTools.getStateAtTime(e),layoutHas:(e,t)=>this.checkLayoutHas(e,t)}}calculateConfidence(e,t,a,i){let o=e.probability;if(a){const d=t.filter(g=>e.symptoms.some(h=>h.toLowerCase().includes(g.toLowerCase())||g.toLowerCase().includes(h.toLowerCase()))).length;o+=d*.05}return i&&(o+=.1),Math.min(o,.99)}collectEvidence(e,t){const a=[];switch(e.category){case"state":t.stateHistory.length>0&&a.push(`상태 변경 이력: ${t.stateHistory.length}개`);break;case"cache":a.push(`캐시 히트율: ${((t.cacheStats.hitRate??0)*100).toFixed(1)}%`);break;case"lifecycle":t.lifecycle.orphanedListeners.length>0&&a.push(`정리되지 않은 리스너: ${t.lifecycle.orphanedListeners.length}개`);break;case"performance":a.push(`바인딩 평가 횟수: ${t.performance.bindingEvalCount}`);break;case"network":a.push(`진행 중인 요청: ${t.network.activeRequests.length}개`);break;case"form":a.push(`추적 중인 Form: ${t.form.length}개`);break}return a}checkLayoutHas(e,t){try{const i=window.G7Core?.getCurrentLayout?.();if(!i)return!1;const o=JSON.stringify(i);return o.includes(`"${e}":"${t}`)||o.includes(`"${e}": "${t}`)}catch{return!1}}}const nk=Object.freeze(Object.defineProperty({__proto__:null,DiagnosticEngine:ex},Symbol.toStringTag,{value:"Module"})),ak={dumpEndpoint:"/_boost/g7-debug/dump-state",logEndpoint:"/_boost/g7-debug/log",timeout:1e4,autoCapture:!1,autoCaptureInterval:3e4};class sk{constructor(e){H(this,"config");H(this,"devTools");H(this,"connected",!1);H(this,"autoCaptureTimer",null);H(this,"CHUNK_SIZE",2*1024*1024);H(this,"BULK_THRESHOLD",4*1024*1024);this.config={...ak,...e},this.devTools=ka.getInstance(),this.config.autoCapture&&this.startAutoCapture()}async dumpState(e=!1){const t=`${Date.now()}_${Math.random().toString(36).substring(2,9)}`,a=Date.now(),i=this.devTools.getPerformanceInfo(),o={renderCounts:Object.fromEntries(i.renderCounts),bindingEvalCount:i.bindingEvalCount,memoryWarnings:i.memoryWarnings},d={state:()=>this.devTools.getState(),actions:()=>this.devTools.getActionHistory(),cache:()=>this.devTools.getCacheStats(),lifecycle:()=>this.devTools.getLifecycleInfo(),network:()=>this.devTools.getNetworkInfo(),expressions:()=>this.devTools.getExpressions(),forms:()=>this.devTools.getForms(),performance:()=>o,conditionals:()=>this.devTools.getConditionalInfo(),dataSources:()=>this.devTools.getDataSources(),handlers:()=>this.devTools.getHandlers(),componentEvents:()=>this.devTools.getComponentEventInfo(),stateRendering:()=>this.devTools.getStateRenderingInfo(),stateHierarchy:()=>this.devTools.getStateHierarchyInfo(),contextFlow:()=>this.devTools.getContextFlowInfo(),styleValidation:()=>this.devTools.getStyleValidationInfo(),authDebug:()=>this.devTools.getAuthDebugInfo(),logs:()=>this.devTools.getLogInfo(),layout:()=>this.devTools.getLayoutDebugInfo(),changeDetection:()=>this.devTools.getChangeDetectionInfo(),sequenceTracking:()=>this.devTools.getSequenceTrackingInfo(),staleClosureTracking:()=>this.devTools.getStaleClosureTrackingInfo(),cacheDecisionTracking:()=>this.devTools.getCacheDecisionTrackingInfo(),dataPathTransformTracking:()=>this.devTools.getDataPathTransformTrackingInfo(),nestedContextTracking:()=>this.devTools.getNestedContextTrackingInfo(),formBindingValidationTracking:()=>this.devTools.getFormBindingValidationTrackingInfo(),computedDependencyTracking:()=>this.devTools.getComputedDependencyTrackingInfo(),modalStateScopeTracking:()=>this.devTools.getModalStateScopeTrackingInfo(),namedActionTracking:()=>this.devTools.getNamedActionTrackingInfo()},g={},h=[];let f=0;for(const[x,S]of Object.entries(d))try{const v=S(),w=this.safeStringify(v,x);w===null?(h.push(`${x}: 직렬화 실패`),g[x]=JSON.stringify({_error:`${x} 섹션 직렬화 실패`})):g[x]=w,f+=g[x].length}catch(v){const w=v instanceof Error?v.message:String(v);h.push(`${x}: ${w}`),g[x]=JSON.stringify({_error:`${x} 섹션 수집 실패: ${w}`}),f+=g[x].length}const p=Object.keys(g).length,y=p-h.length;try{return f<=this.BULK_THRESHOLD?(await this.sendBulkDump(g,a,e),console.log(`[G7DevTools] 상태 덤프 완료 - 일괄 전송 (${(f/1024).toFixed(1)}KB, ${y}/${p} 섹션 성공)`)):(await this.sendChunkedDump(t,g,a,e),console.log(`[G7DevTools] 상태 덤프 완료 - 분할 전송 (${(f/1024/1024).toFixed(2)}MB, ${y}/${p} 섹션 성공)`)),this.connected=!0,h.length>0&&console.warn("[G7DevTools] 일부 섹션 실패:",h.join(", ")),t}catch(x){throw this.connected=!1,console.error("[G7DevTools] 상태 덤프 실패:",x),x}}async sendBulkDump(e,t,a){const i={};for(const[o,d]of Object.entries(e))try{i[o]=JSON.parse(d)}catch{i[o]={_error:"파싱 실패"}}await this.sendRequest(this.config.dumpEndpoint,{bulk:!0,sections:i,timestamp:t,saveHistory:a})}async sendChunkedDump(e,t,a,i){const o=Object.keys(t),d=o.length;for(let g=0;g0?t:[""]}safeStringify(e,t){const a=new WeakSet;try{return JSON.stringify(e,(o,d)=>{if(typeof d=="object"&&d!==null){if(a.has(d))return"[Circular Reference]";a.add(d)}return typeof d=="function"?"[Function]":typeof d=="symbol"?"[Symbol]":typeof d=="bigint"?d.toString():d})}catch(i){return console.warn(`[G7DevTools] ${t} 직렬화 오류:`,i),null}}async sendLog(e){console.log("[G7:DEBUG]",JSON.stringify(e));try{await this.sendRequest(this.config.logEndpoint,{type:"debug",data:e,timestamp:Date.now()})}catch{}}async sendError(e,t){const a={name:e.name,message:e.message,stack:e.stack,context:t,state:this.devTools.getState(),actions:this.devTools.getActionHistory().slice(-10),timestamp:Date.now()};console.log("[G7:ERROR]",JSON.stringify(a));try{await this.sendRequest(this.config.logEndpoint,{type:"error",data:a,timestamp:Date.now()})}catch{}}async sendProfile(e){console.log("[G7:PROFILE]",JSON.stringify(e));try{await this.sendRequest(this.config.logEndpoint,{type:"profile",data:e,timestamp:Date.now()})}catch{}}isConnected(){return this.connected}async testConnection(){try{const e=await this.sendRequest(this.config.dumpEndpoint,{test:!0,timestamp:Date.now()});return this.connected=e.status==="success",this.connected}catch{return this.connected=!1,!1}}startAutoCapture(){this.autoCaptureTimer&&this.stopAutoCapture(),this.autoCaptureTimer=setInterval(()=>{this.devTools.isEnabled()&&this.dumpState().catch(()=>{})},this.config.autoCaptureInterval),console.log("[G7DevTools] 자동 캡처 시작 (간격:",this.config.autoCaptureInterval,"ms)")}stopAutoCapture(){this.autoCaptureTimer&&(clearInterval(this.autoCaptureTimer),this.autoCaptureTimer=null,console.log("[G7DevTools] 자동 캡처 중지"))}updateConfig(e){this.config={...this.config,...e},("autoCapture"in e||"autoCaptureInterval"in e)&&(this.stopAutoCapture(),this.config.autoCapture&&this.startAutoCapture())}async sendRequest(e,t){const a=new AbortController,i=setTimeout(()=>a.abort(),this.config.timeout);try{const o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},body:JSON.stringify(t),signal:a.signal});if(clearTimeout(i),!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);const d=await o.text();if(d.trim().startsWith("<")||d.includes("
")||d.includes("")){const g=this.extractErrorFromHtml(d);throw new Error(`서버 오류: ${g}`)}try{return JSON.parse(d)}catch{throw new Error(`잘못된 JSON 응답: ${d.substring(0,100)}...`)}}catch(o){throw clearTimeout(i),o instanceof Error&&o.name==="AbortError"?new Error("요청 타임아웃"):o}}extractErrorFromHtml(e){const t=[/(Fatal error|Warning|Notice|Parse error)<\/b>:\s*([^<]+)/i,/Exception:\s*([^<\n]+)/i,/Error:\s*([^<\n]+)/i,/(TypeError|ArgumentCountError|ValueError)[^:]*:\s*([^<\n]+)/i];for(const i of t){const o=e.match(i);if(o)return(o[o.length-1]||o[1]).replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').trim().substring(0,200)}return e.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,200)||"Unknown server error"}destroy(){this.stopAutoCapture()}}let Bg=null;function tx(){return Bg||(Bg=new sk),Bg}const rk=` + `},{id:"form-no-datakey",name:"Form dataKey 미설정",category:"form",symptoms:["Input 값이 저장 안됨","Form 제출 시 빈 값"],detector:r=>r.form.some(e=>!e.dataKey),probability:.9,solution:"Form에 dataKey prop 추가",docLink:"troubleshooting-components.md#form-datakey"},{id:"input-no-name",name:"Input name 미설정",category:"form",symptoms:["자동 바인딩 안됨","Input 값 변경이 상태에 반영 안됨"],detector:r=>r.form.some(e=>e.inputs.some(t=>!t.name)),probability:.95,solution:"Input에 name prop 추가",docLink:"troubleshooting-components.md#input-name"},{id:"i18n-key-missing",name:"번역 키 누락",category:"i18n",symptoms:["$t:key가 그대로 표시됨","번역되지 않은 텍스트"],detector:r=>typeof document<"u"?document.body.innerHTML.includes("$t:"):!1,probability:.95,solution:"번역 파일에 키 추가",docLink:"troubleshooting-components.md#i18n"}];class ex{constructor(){H(this,"devTools");this.devTools=ka.getInstance()}analyze(e){const t=this.buildContext(),a=[];for(const i of Hc){const o=e.some(g=>i.symptoms.some(h=>h.toLowerCase().includes(g.toLowerCase())||g.toLowerCase().includes(h.toLowerCase())));let d=!1;try{d=i.detector(t)}catch{}(o||d)&&a.push({rule:i,confidence:this.calculateConfidence(i,e,o,d),evidence:this.collectEvidence(i,t)})}return a.sort((i,o)=>o.confidence-i.confidence)}suggestFix(e){return{title:e.rule.name,description:e.rule.solution,codeExample:e.rule.codeExample,docLink:e.rule.docLink}}getCommonIssues(){const e=this.buildContext(),t=[];for(const a of Hc)try{a.detector(e)&&t.push({rule:a,count:1})}catch{}return t.sort((a,i)=>i.count-a.count).map(a=>({id:a.rule.id,name:a.rule.name,description:a.rule.solution,frequency:a.count}))}getRulesByCategory(e){return Hc.filter(t=>t.category===e)}getAllRules(){return[...Hc]}buildContext(){return{stateHistory:this.devTools.getStateHistory(),actionHistory:this.devTools.getActionHistory(),cacheStats:this.devTools.getCacheStats(),currentState:this.devTools.getState(),lifecycle:this.devTools.getLifecycleInfo(),performance:this.devTools.getPerformanceInfo(),network:this.devTools.getNetworkInfo(),conditional:this.devTools.getConditionalInfo(),form:this.devTools.getFormInfo(),websocket:this.devTools.getWebSocketInfo(),stateAtTime:e=>this.devTools.getStateAtTime(e),layoutHas:(e,t)=>this.checkLayoutHas(e,t)}}calculateConfidence(e,t,a,i){let o=e.probability;if(a){const d=t.filter(g=>e.symptoms.some(h=>h.toLowerCase().includes(g.toLowerCase())||g.toLowerCase().includes(h.toLowerCase()))).length;o+=d*.05}return i&&(o+=.1),Math.min(o,.99)}collectEvidence(e,t){const a=[];switch(e.category){case"state":t.stateHistory.length>0&&a.push(`상태 변경 이력: ${t.stateHistory.length}개`);break;case"cache":a.push(`캐시 히트율: ${((t.cacheStats.hitRate??0)*100).toFixed(1)}%`);break;case"lifecycle":t.lifecycle.orphanedListeners.length>0&&a.push(`정리되지 않은 리스너: ${t.lifecycle.orphanedListeners.length}개`);break;case"performance":a.push(`바인딩 평가 횟수: ${t.performance.bindingEvalCount}`);break;case"network":a.push(`진행 중인 요청: ${t.network.activeRequests.length}개`);break;case"form":a.push(`추적 중인 Form: ${t.form.length}개`);break}return a}checkLayoutHas(e,t){try{const i=window.G7Core?.getCurrentLayout?.();if(!i)return!1;const o=JSON.stringify(i);return o.includes(`"${e}":"${t}`)||o.includes(`"${e}": "${t}`)}catch{return!1}}}const ak=Object.freeze(Object.defineProperty({__proto__:null,DiagnosticEngine:ex},Symbol.toStringTag,{value:"Module"})),sk={dumpEndpoint:"/_boost/g7-debug/dump-state",logEndpoint:"/_boost/g7-debug/log",timeout:1e4,autoCapture:!1,autoCaptureInterval:3e4};class rk{constructor(e){H(this,"config");H(this,"devTools");H(this,"connected",!1);H(this,"autoCaptureTimer",null);H(this,"CHUNK_SIZE",2*1024*1024);H(this,"BULK_THRESHOLD",4*1024*1024);this.config={...sk,...e},this.devTools=ka.getInstance(),this.config.autoCapture&&this.startAutoCapture()}async dumpState(e=!1){const t=`${Date.now()}_${Math.random().toString(36).substring(2,9)}`,a=Date.now(),i=this.devTools.getPerformanceInfo(),o={renderCounts:Object.fromEntries(i.renderCounts),bindingEvalCount:i.bindingEvalCount,memoryWarnings:i.memoryWarnings},d={state:()=>this.devTools.getState(),actions:()=>this.devTools.getActionHistory(),cache:()=>this.devTools.getCacheStats(),lifecycle:()=>this.devTools.getLifecycleInfo(),network:()=>this.devTools.getNetworkInfo(),expressions:()=>this.devTools.getExpressions(),forms:()=>this.devTools.getForms(),performance:()=>o,conditionals:()=>this.devTools.getConditionalInfo(),dataSources:()=>this.devTools.getDataSources(),handlers:()=>this.devTools.getHandlers(),componentEvents:()=>this.devTools.getComponentEventInfo(),stateRendering:()=>this.devTools.getStateRenderingInfo(),stateHierarchy:()=>this.devTools.getStateHierarchyInfo(),contextFlow:()=>this.devTools.getContextFlowInfo(),styleValidation:()=>this.devTools.getStyleValidationInfo(),authDebug:()=>this.devTools.getAuthDebugInfo(),logs:()=>this.devTools.getLogInfo(),layout:()=>this.devTools.getLayoutDebugInfo(),changeDetection:()=>this.devTools.getChangeDetectionInfo(),sequenceTracking:()=>this.devTools.getSequenceTrackingInfo(),staleClosureTracking:()=>this.devTools.getStaleClosureTrackingInfo(),cacheDecisionTracking:()=>this.devTools.getCacheDecisionTrackingInfo(),dataPathTransformTracking:()=>this.devTools.getDataPathTransformTrackingInfo(),nestedContextTracking:()=>this.devTools.getNestedContextTrackingInfo(),formBindingValidationTracking:()=>this.devTools.getFormBindingValidationTrackingInfo(),computedDependencyTracking:()=>this.devTools.getComputedDependencyTrackingInfo(),modalStateScopeTracking:()=>this.devTools.getModalStateScopeTrackingInfo(),namedActionTracking:()=>this.devTools.getNamedActionTrackingInfo()},g={},h=[];let f=0;for(const[x,S]of Object.entries(d))try{const v=S(),w=this.safeStringify(v,x);w===null?(h.push(`${x}: 직렬화 실패`),g[x]=JSON.stringify({_error:`${x} 섹션 직렬화 실패`})):g[x]=w,f+=g[x].length}catch(v){const w=v instanceof Error?v.message:String(v);h.push(`${x}: ${w}`),g[x]=JSON.stringify({_error:`${x} 섹션 수집 실패: ${w}`}),f+=g[x].length}const p=Object.keys(g).length,y=p-h.length;try{return f<=this.BULK_THRESHOLD?(await this.sendBulkDump(g,a,e),console.log(`[G7DevTools] 상태 덤프 완료 - 일괄 전송 (${(f/1024).toFixed(1)}KB, ${y}/${p} 섹션 성공)`)):(await this.sendChunkedDump(t,g,a,e),console.log(`[G7DevTools] 상태 덤프 완료 - 분할 전송 (${(f/1024/1024).toFixed(2)}MB, ${y}/${p} 섹션 성공)`)),this.connected=!0,h.length>0&&console.warn("[G7DevTools] 일부 섹션 실패:",h.join(", ")),t}catch(x){throw this.connected=!1,console.error("[G7DevTools] 상태 덤프 실패:",x),x}}async sendBulkDump(e,t,a){const i={};for(const[o,d]of Object.entries(e))try{i[o]=JSON.parse(d)}catch{i[o]={_error:"파싱 실패"}}await this.sendRequest(this.config.dumpEndpoint,{bulk:!0,sections:i,timestamp:t,saveHistory:a})}async sendChunkedDump(e,t,a,i){const o=Object.keys(t),d=o.length;for(let g=0;g0?t:[""]}safeStringify(e,t){const a=new WeakSet;try{return JSON.stringify(e,(o,d)=>{if(typeof d=="object"&&d!==null){if(a.has(d))return"[Circular Reference]";a.add(d)}return typeof d=="function"?"[Function]":typeof d=="symbol"?"[Symbol]":typeof d=="bigint"?d.toString():d})}catch(i){return console.warn(`[G7DevTools] ${t} 직렬화 오류:`,i),null}}async sendLog(e){console.log("[G7:DEBUG]",JSON.stringify(e));try{await this.sendRequest(this.config.logEndpoint,{type:"debug",data:e,timestamp:Date.now()})}catch{}}async sendError(e,t){const a={name:e.name,message:e.message,stack:e.stack,context:t,state:this.devTools.getState(),actions:this.devTools.getActionHistory().slice(-10),timestamp:Date.now()};console.log("[G7:ERROR]",JSON.stringify(a));try{await this.sendRequest(this.config.logEndpoint,{type:"error",data:a,timestamp:Date.now()})}catch{}}async sendProfile(e){console.log("[G7:PROFILE]",JSON.stringify(e));try{await this.sendRequest(this.config.logEndpoint,{type:"profile",data:e,timestamp:Date.now()})}catch{}}isConnected(){return this.connected}async testConnection(){try{const e=await this.sendRequest(this.config.dumpEndpoint,{test:!0,timestamp:Date.now()});return this.connected=e.status==="success",this.connected}catch{return this.connected=!1,!1}}startAutoCapture(){this.autoCaptureTimer&&this.stopAutoCapture(),this.autoCaptureTimer=setInterval(()=>{this.devTools.isEnabled()&&this.dumpState().catch(()=>{})},this.config.autoCaptureInterval),console.log("[G7DevTools] 자동 캡처 시작 (간격:",this.config.autoCaptureInterval,"ms)")}stopAutoCapture(){this.autoCaptureTimer&&(clearInterval(this.autoCaptureTimer),this.autoCaptureTimer=null,console.log("[G7DevTools] 자동 캡처 중지"))}updateConfig(e){this.config={...this.config,...e},("autoCapture"in e||"autoCaptureInterval"in e)&&(this.stopAutoCapture(),this.config.autoCapture&&this.startAutoCapture())}async sendRequest(e,t){const a=new AbortController,i=setTimeout(()=>a.abort(),this.config.timeout);try{const o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},body:JSON.stringify(t),signal:a.signal});if(clearTimeout(i),!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);const d=await o.text();if(d.trim().startsWith("<")||d.includes("
")||d.includes("")){const g=this.extractErrorFromHtml(d);throw new Error(`서버 오류: ${g}`)}try{return JSON.parse(d)}catch{throw new Error(`잘못된 JSON 응답: ${d.substring(0,100)}...`)}}catch(o){throw clearTimeout(i),o instanceof Error&&o.name==="AbortError"?new Error("요청 타임아웃"):o}}extractErrorFromHtml(e){const t=[/(Fatal error|Warning|Notice|Parse error)<\/b>:\s*([^<]+)/i,/Exception:\s*([^<\n]+)/i,/Error:\s*([^<\n]+)/i,/(TypeError|ArgumentCountError|ValueError)[^:]*:\s*([^<\n]+)/i];for(const i of t){const o=e.match(i);if(o)return(o[o.length-1]||o[1]).replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').trim().substring(0,200)}return e.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,200)||"Unknown server error"}destroy(){this.stopAutoCapture()}}let Bg=null;function tx(){return Bg||(Bg=new rk),Bg}const ik=` #g7-devtools-root { /* 기본 폰트 설정 */ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; @@ -1841,16 +1841,16 @@ details[open] > .g7dt-summary::before { .g7dt-cursor-pointer { cursor: pointer; } -`,ik=()=>{const r="g7-devtools-styles";if(document.getElementById(r))return;const e=document.createElement("style");e.id=r,e.textContent=rk,document.head.appendChild(e)},nx={state:"상태",actions:"액션",cache:"캐시",diagnose:"진단",performance:"성능",lifecycle:"라이프사이클",network:"네트워크",form:"Form",conditional:"조건부",expression:"표현식",handlers:"핸들러",events:"이벤트",datasources:"데이터소스",renders:"렌더링",styles:"스타일",auth:"인증",logs:"로그",layout:"레이아웃",changedetection:"변경감지",staleclosure:"Stale Closure",nestedcontext:"Context",modalscope:"모달스코프",namedactions:"Named Actions"},ok=700,lk=500,ax=400,sx=300,rx="g7-devtools-panel",Ug=r=>r===null||r===void 0?"g7dt-text-gray":typeof r=="string"?"g7dt-text-yellow":typeof r=="number"?"g7dt-text-cyan":typeof r=="boolean"?"g7dt-text-pink":Array.isArray(r)?"g7dt-text-orange":typeof r=="object"?"g7dt-text-blue":"g7dt-text-white",ck=r=>r===null?"null":r===void 0?"undefined":Array.isArray(r)?`Array(${r.length})`:typeof r=="object"?`Object(${Object.keys(r).length})`:typeof r,dk=r=>r===null?"null":r===void 0?"undefined":typeof r=="string"?r.length>50?`"${r.substring(0,50)}..."`:`"${r}"`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):"",ix=()=>{try{const r=localStorage.getItem(rx);if(r)return JSON.parse(r)}catch(r){console.warn("[G7DevTools] 설정 로드 실패:",r)}return{}},ox=r=>{try{const t={...ix(),...r};localStorage.setItem(rx,JSON.stringify(t))}catch(e){console.warn("[G7DevTools] 설정 저장 실패:",e)}},hi=({keyName:r,value:e,path:t,expandedPaths:a,onToggle:i,searchTerm:o,depth:d=0})=>{const g=e!==null&&typeof e=="object",h=a.has(t),f=Array.isArray(e),p=o&&(r.toLowerCase().includes(o.toLowerCase())||typeof e=="string"&&e.toLowerCase().includes(o.toLowerCase())||typeof e=="number"&&String(e).includes(o)),y=S=>{S.stopPropagation(),g&&i(t)},x=g?Object.entries(e):[];return l.jsxs("div",{style:{marginLeft:d>0?"16px":"0"},children:[l.jsxs("div",{className:`g7dt-tree-node g7dt-flex g7dt-items-center g7dt-gap-1 ${p?"g7dt-ring-highlight":""}`,onClick:y,children:[g?l.jsx("span",{className:"g7dt-text-gray g7dt-w-4 g7dt-text-xs g7dt-select-none",style:{textAlign:"center"},children:h?"▼":"▶"}):l.jsx("span",{className:"g7dt-w-4"}),l.jsx("span",{className:"g7dt-text-purple g7dt-text-xs",children:r}),l.jsx("span",{className:"g7dt-text-gray-dark g7dt-text-xs",children:":"}),g?l.jsxs("span",{className:`g7dt-text-xs ${Ug(e)}`,children:[f?"[":"{",!h&&l.jsx("span",{className:"g7dt-text-gray",style:{margin:"0 4px"},children:ck(e)}),!h&&(f?"]":"}")]}):l.jsx("span",{className:`g7dt-text-xs ${Ug(e)}`,children:dk(e)}),!g&&l.jsxs("span",{className:"g7dt-text-gray-dark g7dt-text-xs g7dt-ml-1",children:["(",typeof e,")"]})]}),g&&h&&l.jsxs("div",{className:"g7dt-border-l",style:{marginLeft:"8px"},children:[x.map(([S,v])=>l.jsx(hi,{keyName:f?`[${S}]`:S,value:v,path:`${t}.${S}`,expandedPaths:a,onToggle:i,searchTerm:o,depth:d+1},`${t}.${S}`)),l.jsx("div",{className:"g7dt-ml-4 g7dt-text-xs",children:l.jsx("span",{className:Ug(e),children:f?"]":"}"})})]})]})},uk=({state:r,devTools:e})=>{const[t,a]=j.useState(new Set(["_global","_local","_computed","_isolated","$parent"])),[i,o]=j.useState(""),[d,g]=j.useState(!1),[h,f]=j.useState(!1),[p,y]=j.useState(null),x=j.useCallback(()=>{e&&y(e.getComputedDependencyTrackingInfo())},[e]);j.useEffect(()=>{if(h&&e){x();const M=setInterval(x,2e3);return()=>clearInterval(M)}},[h,e,x]);const S=M=>{switch(M){case"state-change":return"📊";case"prop-change":return"📥";case"dependency-change":return"🔗";case"manual":return"👆";case"initial":return"🚀";default:return"❓"}},v=j.useCallback(M=>{a(z=>{const K=new Set(z);return K.has(M)?K.delete(M):K.add(M),K})},[]),w=j.useCallback((M,z)=>{const K=[z];if(M!==null&&typeof M=="object")for(const[pe,we]of Object.entries(M))K.push(...w(we,`${z}.${pe}`));return K},[]),k=j.useCallback(()=>{if(d)a(new Set(["_global","_local","_computed","_isolated","$parent"]));else{const M=new Set;w(r._global,"_global").forEach(z=>M.add(z)),w(r._local,"_local").forEach(z=>M.add(z)),w(r._computed,"_computed").forEach(z=>M.add(z)),w(r._isolated,"_isolated").forEach(z=>M.add(z)),r.$parent&&w(r.$parent,"$parent").forEach(z=>M.add(z)),a(M)}g(!d)},[d,r,w]),A=Object.keys(r._global||{}).length,O=Object.keys(r._local||{}).length,N=Object.keys(r._computed||{}).length,D=Object.keys(r._isolated||{}).length,$=Object.keys(r.$parent||{}).length;return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-items-center g7dt-flex-shrink-0",children:[l.jsx("input",{type:"text",placeholder:"키 또는 값 검색...",value:i,onChange:M=>o(M.target.value),className:"g7dt-input g7dt-flex-1"}),l.jsx("button",{onClick:k,className:"g7dt-btn g7dt-bg-gray-700",children:d?"모두 접기":"모두 펼치기"})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-3 g7dt-text-xs g7dt-text-gray g7dt-flex-wrap g7dt-flex-shrink-0",children:[l.jsxs("span",{children:[l.jsx("span",{className:"g7dt-text-yellow",children:"●"})," string"]}),l.jsxs("span",{children:[l.jsx("span",{className:"g7dt-text-cyan",children:"●"})," number"]}),l.jsxs("span",{children:[l.jsx("span",{className:"g7dt-text-pink",children:"●"})," boolean"]}),l.jsxs("span",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"●"})," null"]}),l.jsxs("span",{children:[l.jsx("span",{className:"g7dt-text-orange",children:"●"})," array"]}),l.jsxs("span",{children:[l.jsx("span",{className:"g7dt-text-blue",children:"●"})," object"]})]}),l.jsxs("div",{className:"g7dt-bg-gray-800 g7dt-rounded g7dt-p-2 g7dt-overflow-auto g7dt-border",style:{flex:1,minHeight:0},children:[l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-green g7dt-mb-1 g7dt-cursor-pointer",onClick:()=>v("_global"),children:[l.jsx("span",{children:t.has("_global")?"▼":"▶"}),l.jsx("span",{children:"_global"}),l.jsxs("span",{className:"g7dt-text-gray g7dt-text-xs",style:{fontWeight:"normal"},children:["(",A,"개 키)"]})]}),t.has("_global")&&l.jsx("div",{className:"g7dt-ml-2 g7dt-border-l",children:Object.entries(r._global||{}).map(([M,z])=>l.jsx(hi,{keyName:M,value:z,path:`_global.${M}`,expandedPaths:t,onToggle:v,searchTerm:i},`_global.${M}`))})]}),l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-blue g7dt-mb-1 g7dt-cursor-pointer",onClick:()=>v("_local"),children:[l.jsx("span",{children:t.has("_local")?"▼":"▶"}),l.jsx("span",{children:"_local"}),l.jsxs("span",{className:"g7dt-text-gray g7dt-text-xs",style:{fontWeight:"normal"},children:["(",O,"개 키)"]})]}),t.has("_local")&&l.jsx("div",{className:"g7dt-ml-2 g7dt-border-l",children:Object.entries(r._local||{}).map(([M,z])=>l.jsx(hi,{keyName:M,value:z,path:`_local.${M}`,expandedPaths:t,onToggle:v,searchTerm:i},`_local.${M}`))})]}),l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-purple g7dt-mb-1 g7dt-cursor-pointer",onClick:()=>v("_computed"),children:[l.jsx("span",{children:t.has("_computed")?"▼":"▶"}),l.jsx("span",{children:"_computed"}),l.jsxs("span",{className:"g7dt-text-gray g7dt-text-xs",style:{fontWeight:"normal"},children:["(",N,"개 키)"]})]}),t.has("_computed")&&l.jsx("div",{className:"g7dt-ml-2 g7dt-border-l",children:Object.entries(r._computed||{}).map(([M,z])=>l.jsx(hi,{keyName:M,value:z,path:`_computed.${M}`,expandedPaths:t,onToggle:v,searchTerm:i},`_computed.${M}`))})]}),D>0&&l.jsxs("div",{children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-orange g7dt-mb-1 g7dt-cursor-pointer",onClick:()=>v("_isolated"),children:[l.jsx("span",{children:t.has("_isolated")?"▼":"▶"}),l.jsx("span",{children:"_isolated"}),l.jsxs("span",{className:"g7dt-text-gray g7dt-text-xs",style:{fontWeight:"normal"},children:["(",D,"개 스코프)"]})]}),t.has("_isolated")&&l.jsx("div",{className:"g7dt-ml-2 g7dt-border-l",children:Object.entries(r._isolated||{}).map(([M,z])=>l.jsx(hi,{keyName:M,value:z,path:`_isolated.${M}`,expandedPaths:t,onToggle:v,searchTerm:i},`_isolated.${M}`))})]}),$>0&&l.jsxs("div",{children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-cyan g7dt-mb-1 g7dt-cursor-pointer",onClick:()=>v("$parent"),children:[l.jsx("span",{children:t.has("$parent")?"▼":"▶"}),l.jsx("span",{children:"$parent"}),l.jsxs("span",{className:"g7dt-text-gray g7dt-text-xs",style:{fontWeight:"normal"},children:["(",$,"개 키)"]})]}),t.has("$parent")&&l.jsx("div",{className:"g7dt-ml-2 g7dt-border-l",children:Object.entries(r.$parent||{}).map(([M,z])=>l.jsx(hi,{keyName:M,value:z,path:`$parent.${M}`,expandedPaths:t,onToggle:v,searchTerm:i},`$parent.${M}`))})]})]}),e&&l.jsx("div",{className:"g7dt-flex g7dt-justify-end g7dt-mt-2",children:l.jsx("button",{onClick:()=>f(!h),className:`g7dt-tab-button ${h?"g7dt-tab-active":""}`,children:"🧮 Computed 추적"})}),h&&p&&l.jsxs("div",{className:"g7dt-card g7dt-mt-2",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:["Computed 의존성 추적 (",p.properties.length,"개)"]}),l.jsxs("div",{className:"g7dt-stats-grid g7dt-mb-3",children:[l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-purple",children:p.stats.totalComputed}),l.jsx("div",{className:"g7dt-stat-label",children:"Computed"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-blue",children:p.stats.totalRecalculations}),l.jsx("div",{className:"g7dt-stat-label",children:"재계산"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-yellow",children:p.stats.unnecessaryRecalculations}),l.jsx("div",{className:"g7dt-stat-label",children:"불필요"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsxs("div",{className:"g7dt-stat-value g7dt-text-green",children:[p.stats.avgComputationTime.toFixed(1),"ms"]}),l.jsx("div",{className:"g7dt-stat-label",children:"평균시간"})]})]}),p.stats.cycleDetectionCount>0&&l.jsxs("div",{className:"g7dt-text-xs g7dt-text-red g7dt-mb-3 g7dt-p-2 g7dt-bg-red-900 g7dt-rounded",children:["⚠️ 순환 의존성 감지: ",p.stats.cycleDetectionCount,"건"]}),p.stats.topRecalculated.length>0&&l.jsxs("div",{className:"g7dt-mb-3",children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"자주 재계산되는 속성"}),l.jsx("div",{className:"g7dt-space-y-1",children:p.stats.topRecalculated.slice(0,3).map((M,z)=>l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-text-xs",children:[l.jsx("span",{className:"g7dt-text-purple g7dt-font-mono",children:M.name}),l.jsxs("span",{className:"g7dt-text-muted",children:[M.count,"회"]})]},z))})]}),p.recalcLogs.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"재계산 로그가 없습니다"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-40 g7dt-overflow-y-auto",children:p.recalcLogs.slice().reverse().slice(0,20).map(M=>l.jsxs("div",{className:`g7dt-list-item ${M.valueChanged?"":"g7dt-border-yellow"}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{children:S(M.trigger)}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-purple g7dt-font-mono",children:M.computedName}),!M.valueChanged&&l.jsx("span",{className:"g7dt-badge g7dt-text-xs g7dt-text-yellow",children:"값 변경 없음"}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:[M.computationTime.toFixed(1),"ms"]})]}),M.triggeredBy&&l.jsxs("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-1",children:["트리거: ",l.jsx("span",{className:"g7dt-text-blue",children:M.triggeredBy.path})]})]},M.id))})]})]})},gk=({actions:r,devTools:e})=>{const[t,a]=j.useState(""),[i,o]=j.useState("actions"),[d,g]=j.useState(null),[h,f]=j.useState(null),p=j.useCallback(()=>{e&&g(e.getSequenceTrackingInfo())},[e]);j.useEffect(()=>{if(i==="sequences"&&e){p();const w=setInterval(p,2e3);return()=>clearInterval(w)}},[i,e,p]);const y=t?r.filter(w=>w.type.toLowerCase().includes(t.toLowerCase())||w.status===t):r,x=w=>{switch(w){case"success":return"g7dt-status-success";case"error":return"g7dt-status-error";case"started":return"g7dt-status-started";default:return"g7dt-status-default"}},S=w=>{switch(w){case"success":return"g7dt-badge-success";case"error":return"g7dt-badge-error";default:return"g7dt-badge-warning"}},v=h&&d?d.executions.find(w=>w.id===h):null;return l.jsxs("div",{className:"g7dt-space-y-4",children:[e&&l.jsx("div",{className:"g7dt-card",children:l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsxs("button",{className:`g7dt-tab-button ${i==="actions"?"g7dt-tab-active":""}`,onClick:()=>o("actions"),children:["📋 액션 (",r.length,")"]}),l.jsxs("button",{className:`g7dt-tab-button ${i==="sequences"?"g7dt-tab-active":""}`,onClick:()=>o("sequences"),children:["🔗 Sequence (",d?.executions.length||0,")"]})]})}),i==="actions"&&l.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-flex-shrink-0",children:[l.jsx("input",{type:"text",placeholder:"액션 타입 또는 상태로 필터...",value:t,onChange:w=>a(w.target.value),className:"g7dt-input g7dt-flex-1"}),l.jsx("button",{onClick:()=>a(""),className:"g7dt-btn-text",children:"초기화"})]}),i==="sequences"&&d&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"Sequence 통계"}),l.jsxs("div",{className:"g7dt-stats-grid-3",children:[l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-blue",children:d.stats.totalSequences}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"총 실행"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-green",children:d.stats.successCount}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"성공"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-red",children:d.stats.errorCount}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"실패"})]})]})]}),l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"Sequence 실행 목록"}),d.executions.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"실행된 Sequence가 없습니다"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-40 g7dt-overflow-y-auto",children:d.executions.slice().reverse().map(w=>l.jsx("div",{className:`g7dt-list-item g7dt-cursor-pointer ${h===w.id?"g7dt-selected":""} ${w.status==="error"?"g7dt-border-red":""}`,onClick:()=>f(h===w.id?null:w.id),children:l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{children:w.status==="completed"?"✅":w.status==="error"?"❌":"⏳"}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-white",children:[w.actions.length,"개 액션"]}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:[w.totalDuration.toFixed(0),"ms"]})]})},w.id))})]}),v&&l.jsxs("div",{className:"g7dt-card g7dt-border-blue",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:["🔗 Sequence 상세 (",v.actions.length,"개 액션)"]}),l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:v.actions.map((w,k)=>l.jsxs("div",{className:`g7dt-list-item ${w.status==="error"?"g7dt-border-red":""}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted",children:["#",w.index+1]}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-white g7dt-font-mono",children:w.handler}),l.jsx("span",{className:`g7dt-text-xs ${w.status==="success"?"g7dt-text-green":"g7dt-text-red"}`,children:w.status==="success"?"✓":"✕"}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:[w.duration.toFixed(0),"ms"]})]}),w.stateChanges&&w.stateChanges.length>0&&l.jsxs("div",{className:"g7dt-mt-1",children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"상태 변경:"}),w.stateChanges.slice(0,3).map((A,O)=>l.jsx("div",{className:"g7dt-text-xs g7dt-text-yellow g7dt-ml-2",children:A.path},O)),w.stateChanges.length>3&&l.jsxs("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-2",children:["...외 ",w.stateChanges.length-3,"개"]})]})]},k))})]})]}),i==="actions"&&l.jsx("div",{className:"g7dt-section",children:l.jsx("div",{className:"g7dt-scroll-list g7dt-space-y-2-flat g7dt-action-list",children:y.length===0?l.jsx("div",{className:"g7dt-empty-message",children:"액션 이력이 없습니다"}):y.slice(-30).reverse().map((w,k)=>l.jsxs("div",{className:`g7dt-action-item ${x(w.status)}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-start",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-font-mono g7dt-font-bold",children:w.type}),l.jsx("span",{className:`g7dt-status-badge ${S(w.status)}`,children:w.status})]}),l.jsx("span",{className:"g7dt-text-gray",children:w.duration?`${w.duration.toFixed(2)}ms`:"-"})]}),w.error&&l.jsx("div",{className:"g7dt-error-box",children:w.error.message}),w.params&&Object.keys(w.params).length>0&&l.jsxs("details",{className:"g7dt-details",children:[l.jsx("summary",{className:"g7dt-summary",children:"파라미터"}),l.jsx("pre",{className:"g7dt-pre",children:JSON.stringify(w.params,null,2)})]})]},`${w.id}-${k}`))})})]})},hk=({stats:r,devTools:e})=>{const[t,a]=j.useState(null),[i,o]=j.useState(!1),d=j.useCallback(()=>{a(e.getCacheDecisionTrackingInfo())},[e]);j.useEffect(()=>{if(i){d();const f=setInterval(d,2e3);return()=>clearInterval(f)}},[i,d]);const g=()=>{e.resetCacheStats(),console.log("[G7DevTools] 캐시 통계 초기화")},h=f=>{switch(f){case"use_cache":return"✅";case"skip_cache":return"⏭️";case"invalidate":return"🗑️";default:return"❓"}};return l.jsxs("div",{className:"g7dt-space-y-6",children:[l.jsxs("div",{className:"g7dt-stats-grid",children:[l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-green",children:r.hits}),l.jsx("div",{className:"g7dt-stat-label",children:"Cache Hits"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-red",children:r.misses}),l.jsx("div",{className:"g7dt-stat-label",children:"Cache Misses"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-blue",children:r.entries}),l.jsx("div",{className:"g7dt-stat-label",children:"Entries"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsxs("div",{className:"g7dt-stat-value g7dt-text-purple",children:[(r.hitRate*100).toFixed(1),"%"]}),l.jsx("div",{className:"g7dt-stat-label",children:"Hit Rate"})]})]}),l.jsxs("div",{className:"g7dt-space-y-2",children:[l.jsx("div",{className:"g7dt-text-sm g7dt-text-gray",children:"캐시 히트율"}),l.jsx("div",{className:"g7dt-progress-bar",children:l.jsx("div",{className:"g7dt-progress-fill",style:{width:`${r.hitRate*100}%`}})})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsx("button",{onClick:g,className:"g7dt-btn-danger",children:"캐시 통계 초기화"}),l.jsx("button",{onClick:()=>o(!i),className:`g7dt-tab-button ${i?"g7dt-tab-active":""}`,children:"📋 Decision Log"})]}),i&&t&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:["캐시 결정 로그 (",t.decisions.length,"개)"]}),t.decisions.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"캐시 결정 기록이 없습니다"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:t.decisions.slice().reverse().slice(0,50).map(f=>l.jsxs("div",{className:`g7dt-list-item ${f.decision==="skip_cache"?"g7dt-border-yellow":f.decision==="invalidate"?"g7dt-border-red":""}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{children:h(f.decision)}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-white g7dt-font-mono g7dt-truncate",style:{maxWidth:"200px"},children:f.expression}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:f.decision})]}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-1",children:f.reason}),f.context&&l.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-mt-1",children:[f.context.isInIteration&&l.jsx("span",{className:"g7dt-badge g7dt-text-xs",children:"🔄 iteration"}),f.context.isInAction&&l.jsx("span",{className:"g7dt-badge g7dt-text-xs",children:"⚡ action"})]})]},f.id))})]})]})},fk=()=>{const[r,e]=j.useState([]),[t,a]=j.useState([]),[i,o]=j.useState(""),d=["이전 값이 전송됨","모든 행이 같은 값","상태가 업데이트 안됨","API 호출이 안됨","초기값이 없음","무한 로딩","Form 값이 저장 안됨","iteration 데이터 중복"],g=p=>{e(y=>y.includes(p)?y.filter(x=>x!==p):[...y,p])},h=()=>{i&&!r.includes(i)&&(e(p=>[...p,i]),o(""))},f=async()=>{const{DiagnosticEngine:p}=await Promise.resolve().then(()=>nk),x=new p().analyze(r);a(x)};return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"증상 선택"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-2",children:d.map(p=>l.jsx("button",{onClick:()=>g(p),className:r.includes(p)?"g7dt-symptom-btn g7dt-symptom-active":"g7dt-symptom-btn",children:p},p))})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsx("input",{type:"text",placeholder:"직접 증상 입력...",value:i,onChange:p=>o(p.target.value),onKeyDown:p=>p.key==="Enter"&&h(),className:"g7dt-input g7dt-flex-1"}),l.jsx("button",{onClick:h,className:"g7dt-btn-secondary",children:"추가"})]}),l.jsxs("button",{onClick:f,disabled:r.length===0,className:r.length===0?"g7dt-btn-primary g7dt-btn-disabled g7dt-w-full":"g7dt-btn-primary g7dt-w-full",children:["진단 실행 (",r.length,"개 증상)"]}),t.length>0&&l.jsxs("div",{className:"g7dt-space-y-3",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:"진단 결과"}),t.slice(0,5).map((p,y)=>l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("span",{className:"g7dt-font-bold g7dt-text-yellow",children:p.rule.name}),l.jsxs("span",{className:"g7dt-confidence-badge",children:[(p.confidence*100).toFixed(0),"%"]})]}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-lightgray",children:p.rule.solution}),p.rule.codeExample&&l.jsx("pre",{className:"g7dt-pre g7dt-mt-2",children:p.rule.codeExample})]},y))]})]})},pk=({devTools:r})=>{const e=r.getPerformanceInfo();return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-stats-grid-2",children:[l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-blue",children:e.bindingEvalCount}),l.jsx("div",{className:"g7dt-stat-label",children:"바인딩 평가 횟수"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-purple",children:e.renderCounts.size}),l.jsx("div",{className:"g7dt-stat-label",children:"렌더링된 컴포넌트"})]})]}),e.memoryWarnings.length>0&&l.jsxs("div",{children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-red g7dt-mb-2",children:"메모리 경고"}),l.jsx("div",{className:"g7dt-space-y-2",children:e.memoryWarnings.map((t,a)=>l.jsxs("div",{className:"g7dt-warning-card",children:[l.jsx("div",{className:"g7dt-font-bold",children:t.type}),l.jsx("div",{className:"g7dt-text-lightgray",children:t.message}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-gray g7dt-mt-1",children:t.suggestion})]},a))})]}),e.renderCounts.size>0&&l.jsxs("div",{children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"컴포넌트별 렌더링"}),l.jsx("div",{className:"g7dt-space-y-1 g7dt-scroll-list",children:Array.from(e.renderCounts.entries()).sort((t,a)=>a[1]-t[1]).slice(0,10).map(([t,a])=>l.jsxs("div",{className:"g7dt-list-item",children:[l.jsx("span",{className:"g7dt-text-lightgray g7dt-truncate",children:t}),l.jsxs("span",{className:a>50?"g7dt-text-red":"g7dt-text-gray",children:[a,"회"]})]},t))})]})]})},mk=({devTools:r})=>{const e=r.getLifecycleInfo();return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-section",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-green g7dt-mb-2 g7dt-flex-shrink-0",children:["마운트된 컴포넌트 (",e.mountedComponents.length,")"]}),l.jsx("div",{className:"g7dt-scroll-list",children:e.mountedComponents.length===0?l.jsx("div",{className:"g7dt-empty-message",children:"추적된 컴포넌트 없음"}):e.mountedComponents.map(t=>l.jsxs("div",{className:"g7dt-list-item g7dt-text-xs",children:[l.jsx("span",{className:"g7dt-text-lightgray",children:t.name}),l.jsx("span",{className:"g7dt-text-gray",children:t.id})]},t.id))})]}),e.orphanedListeners.length>0&&l.jsxs("div",{className:"g7dt-section",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-red g7dt-mb-2 g7dt-flex-shrink-0",children:["정리되지 않은 리스너 (",e.orphanedListeners.length,")"]}),l.jsx("div",{className:"g7dt-scroll-list",children:e.orphanedListeners.map((t,a)=>l.jsxs("div",{className:"g7dt-warning-card g7dt-text-xs",children:[l.jsx("span",{className:"g7dt-text-lightgray",children:t.type}),l.jsxs("span",{className:"g7dt-text-gray g7dt-ml-2",children:["on ",t.target]})]},a))})]})]})},yk=({devTools:r})=>{const e=r.getNetworkInfo(),t=d=>{switch(d){case"success":return"g7dt-text-green";case"error":return"g7dt-text-red";case"pending":return"g7dt-text-yellow";default:return"g7dt-text-gray"}},a=d=>d.queryParams&&Object.keys(d.queryParams).length>0,i=d=>Object.entries(d).map(([g,h])=>l.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-text-xs",children:[l.jsxs("span",{className:"g7dt-text-purple",children:[g,":"]}),l.jsx("span",{className:"g7dt-text-lightgray",children:Array.isArray(h)?JSON.stringify(h):h})]},g)),o=(d,g=5e3)=>{try{const h=JSON.stringify(d,null,2);return h.length>g?h.substring(0,g)+` -... (truncated)`:h}catch{return"(직렬화 불가)"}};return l.jsxs("div",{className:"g7dt-space-y-4",children:[e.activeRequests.length>0&&l.jsxs("div",{children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-yellow g7dt-mb-2",children:["진행 중 (",e.activeRequests.length,")"]}),l.jsx("div",{className:"g7dt-space-y-1",children:e.activeRequests.map(d=>l.jsxs("details",{className:"g7dt-details",children:[l.jsxs("summary",{className:"g7dt-summary g7dt-pending-request",children:[l.jsx("span",{className:"g7dt-font-bold",children:d.method}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-lightgray g7dt-truncate",children:d.fullUrl||d.url})]}),l.jsxs("div",{className:"g7dt-card g7dt-mt-1 g7dt-text-xs",children:[a(d)&&l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsx("div",{className:"g7dt-text-blue g7dt-font-bold g7dt-mb-1",children:"쿼리 파라미터"}),l.jsx("div",{className:"g7dt-pl-2 g7dt-border-l-2 g7dt-border-blue",children:i(d.queryParams)})]}),d.requestBody&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-orange g7dt-font-bold g7dt-mb-1",children:"요청 본문"}),l.jsx("pre",{className:"g7dt-pre g7dt-text-xs",children:o(d.requestBody,2e3)})]})]})]},d.id))})]}),l.jsxs("div",{children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"요청 이력"}),l.jsx("div",{className:"g7dt-space-y-1 g7dt-scroll-list-lg",children:e.requestHistory.length===0?l.jsx("div",{className:"g7dt-empty-message",children:"요청 이력 없음"}):e.requestHistory.slice(-20).reverse().map(d=>l.jsxs("details",{className:"g7dt-details",children:[l.jsxs("summary",{className:"g7dt-summary g7dt-card g7dt-text-xs",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-w-full",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-font-bold",children:d.method}),l.jsx("span",{className:`g7dt-ml-2 ${t(d.status)}`,children:d.statusCode||d.status})]}),l.jsxs("span",{className:"g7dt-text-gray",children:[d.duration,"ms"]})]}),l.jsx("div",{className:"g7dt-text-gray g7dt-truncate g7dt-mt-1",children:d.fullUrl||d.url})]}),l.jsxs("div",{className:"g7dt-card g7dt-mt-1 g7dt-text-xs g7dt-ml-2 g7dt-border-l-2 g7dt-border-gray",children:[l.jsx("div",{className:"g7dt-mb-2",children:l.jsxs("div",{className:"g7dt-text-xs g7dt-space-y-1",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"URL:"})," ",l.jsx("span",{className:"g7dt-text-lightgray",children:d.fullUrl||d.url})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"상태:"})," ",l.jsx("span",{className:t(d.status),children:d.statusCode||d.status})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"소요시간:"})," ",l.jsxs("span",{className:"g7dt-text-lightgray",children:[d.duration,"ms"]})]}),d.dataSourceId&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"데이터소스:"})," ",l.jsx("span",{className:"g7dt-text-blue",children:d.dataSourceId})]}),d.error&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"에러:"})," ",l.jsx("span",{className:"g7dt-text-red",children:d.error})]})]})}),a(d)&&l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsx("div",{className:"g7dt-text-blue g7dt-font-bold g7dt-mb-1",children:"쿼리 파라미터"}),l.jsx("div",{className:"g7dt-pl-2 g7dt-border-l-2 g7dt-border-blue",children:i(d.queryParams)})]}),d.requestBody&&l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsx("div",{className:"g7dt-text-orange g7dt-font-bold g7dt-mb-1",children:"요청 본문"}),l.jsx("pre",{className:"g7dt-pre g7dt-text-xs g7dt-max-h-40 g7dt-overflow-auto",children:o(d.requestBody,2e3)})]}),d.response!==void 0&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-green g7dt-font-bold g7dt-mb-1",children:"응답 내용"}),l.jsx("pre",{className:"g7dt-pre g7dt-text-xs g7dt-max-h-60 g7dt-overflow-auto",children:o(d.response,5e3)})]})]})]},d.id))})]}),e.pendingDataSources.length>0&&l.jsxs("div",{children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-blue g7dt-mb-2",children:["대기 중인 데이터소스 (",e.pendingDataSources.length,")"]}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-2",children:e.pendingDataSources.map(d=>l.jsx("span",{className:"g7dt-tag-blue",children:d},d))})]})]})},xk=({devTools:r})=>{const e=r.getFormInfo(),[t,a]=j.useState(!1),[i,o]=j.useState(null),d=j.useCallback(()=>{o(r.getFormBindingValidationTrackingInfo())},[r]);j.useEffect(()=>{if(t){d();const f=setInterval(d,2e3);return()=>clearInterval(f)}},[t,d]);const g=f=>{switch(f){case"missing-datakey":return"🔑";case"missing-input-name":return"📝";case"context-not-propagated":return"🔗";case"sortable-context-break":return"📊";case"modal-context-isolation":return"🪟";case"duplicate-input-name":return"👯";case"value-type-mismatch":return"⚠️";case"binding-path-invalid":return"❌";default:return"❓"}},h=f=>{switch(f){case"error":return"g7dt-text-red";case"warning":return"g7dt-text-yellow";case"info":return"g7dt-text-blue";default:return"g7dt-text-gray"}};return l.jsxs("div",{className:"g7dt-space-y-4",children:[e.length===0?l.jsx("div",{className:"g7dt-empty-message g7dt-py-8",children:"추적된 Form이 없습니다"}):e.map(f=>l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("span",{className:"g7dt-font-bold g7dt-text-blue",children:f.dataKey||"(no dataKey)"}),!f.dataKey&&l.jsx("span",{className:"g7dt-text-red g7dt-text-xs",children:"dataKey 필요"})]}),l.jsx("div",{className:"g7dt-space-y-1 g7dt-mb-2",children:f.inputs.map((p,y)=>l.jsxs("div",{className:"g7dt-text-xs g7dt-flex g7dt-justify-between",children:[l.jsx("span",{children:p.name||l.jsx("span",{className:"g7dt-text-red",children:"name 없음"})}),l.jsx("span",{className:"g7dt-text-gray",children:p.type})]},y))}),l.jsxs("details",{className:"g7dt-details",children:[l.jsx("summary",{className:"g7dt-summary",children:"현재 값 보기"}),l.jsx("pre",{className:"g7dt-pre",children:JSON.stringify(f,null,2)})]})]},f.id)),l.jsx("div",{className:"g7dt-flex g7dt-justify-end",children:l.jsx("button",{onClick:()=>a(!t),className:`g7dt-tab-button ${t?"g7dt-tab-active":""}`,children:"🔍 Auto-Binding Check"})}),t&&i&&l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"Form 바인딩 검증 결과"}),l.jsxs("div",{className:"g7dt-stats-grid g7dt-mb-3",children:[l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-blue",children:i.stats.totalFormsValidated}),l.jsx("div",{className:"g7dt-stat-label",children:"검증된 Form"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-green",children:i.stats.validForms}),l.jsx("div",{className:"g7dt-stat-label",children:"유효"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-red",children:i.stats.formsWithIssues}),l.jsx("div",{className:"g7dt-stat-label",children:"문제 있음"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-yellow",children:i.stats.totalIssues}),l.jsx("div",{className:"g7dt-stat-label",children:"총 이슈"})]})]}),i.stats.topIssues.length>0&&l.jsxs("div",{className:"g7dt-mb-3",children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"자주 발생하는 이슈"}),l.jsx("div",{className:"g7dt-space-y-1",children:i.stats.topIssues.slice(0,3).map((f,p)=>l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-xs",children:[l.jsx("span",{children:g(f.type)}),l.jsx("span",{className:"g7dt-text-white",children:f.description}),l.jsxs("span",{className:"g7dt-text-muted",children:["(",f.count,")"]})]},p))})]}),i.issues.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"바인딩 이슈가 없습니다 ✅"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:i.issues.slice().reverse().slice(0,30).map(f=>l.jsxs("div",{className:`g7dt-list-item ${f.severity==="error"?"g7dt-border-red":f.severity==="warning"?"g7dt-border-yellow":""}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{children:g(f.type)}),l.jsx("span",{className:`g7dt-text-xs g7dt-font-bold ${h(f.severity)}`,children:f.type}),f.formDataKey&&l.jsx("span",{className:"g7dt-text-xs g7dt-text-blue g7dt-font-mono",children:f.formDataKey})]}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-white g7dt-mt-1",children:f.description}),l.jsxs("div",{className:"g7dt-text-xs g7dt-text-green g7dt-mt-1",children:["💡 ",f.suggestion]}),f.contextInfo&&l.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-mt-1",children:[f.contextInfo.isInsideModal&&l.jsx("span",{className:"g7dt-badge g7dt-text-xs",children:"🪟 modal"}),f.contextInfo.isInsideSortable&&l.jsx("span",{className:"g7dt-badge g7dt-text-xs",children:"📊 sortable"}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted",children:["depth: ",f.contextInfo.depth]})]})]},f.id))})]})]})},bk=({devTools:r})=>{const e=r.getConditionalInfo();return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-purple g7dt-mb-2",children:["if 조건 (",e.ifConditions.length,")"]}),l.jsx("div",{className:"g7dt-space-y-1 g7dt-scroll-list",children:e.ifConditions.length===0?l.jsx("div",{className:"g7dt-empty-message",children:"추적된 if 조건 없음"}):e.ifConditions.map(t=>l.jsx("div",{className:`g7dt-condition-item ${t.evaluatedValue?"g7dt-condition-true":"g7dt-condition-false"}`,children:l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsx("span",{className:"g7dt-font-mono g7dt-text-lightgray g7dt-truncate-60",children:t.expression}),l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{className:t.evaluatedValue?"g7dt-badge-success":"g7dt-badge-error",children:t.evaluatedValue?"true":"false"}),l.jsxs("span",{className:"g7dt-text-gray",children:[t.evaluationCount,"회"]})]})]})},t.id))})]}),l.jsxs("div",{children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-cyan g7dt-mb-2",children:["iteration (",e.iterations.length,")"]}),l.jsx("div",{className:"g7dt-space-y-1 g7dt-scroll-list",children:e.iterations.length===0?l.jsx("div",{className:"g7dt-empty-message",children:"추적된 iteration 없음"}):e.iterations.map(t=>l.jsxs("div",{className:"g7dt-card g7dt-text-xs",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-1",children:[l.jsx("span",{className:"g7dt-font-mono g7dt-text-lightgray g7dt-truncate-60",children:t.source}),l.jsxs("span",{className:t.sourceLength>0?"g7dt-badge-blue":"g7dt-badge-warning",children:[t.sourceLength,"개 항목"]})]}),l.jsxs("div",{className:"g7dt-text-gray",children:[l.jsxs("span",{className:"g7dt-mr-2",children:["item_var: ",t.itemVar]}),t.indexVar&&l.jsxs("span",{children:["index_var: ",t.indexVar]})]})]},t.id))})]}),(e.ifConditions.some(t=>t.evaluatedValue===!1&&t.evaluationCount>5)||e.iterations.some(t=>t.sourceLength===0))&&l.jsxs("div",{className:"g7dt-warning-box",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-yellow g7dt-mb-2",children:"잠재적 문제"}),l.jsxs("div",{className:"g7dt-space-y-1 g7dt-text-xs",children:[e.ifConditions.filter(t=>t.evaluatedValue===!1&&t.evaluationCount>5).map(t=>l.jsxs("div",{className:"g7dt-text-lightgray",children:["⚠️ if 조건 항상 false: ",t.expression]},t.id)),e.iterations.filter(t=>t.sourceLength===0).map(t=>l.jsxs("div",{className:"g7dt-text-lightgray",children:["⚠️ iteration 소스 비어있음: ",t.source]},t.id))]})]})]})},vk=({devTools:r})=>{const[e,t]=j.useState([]),[a,i]=j.useState({totalEvaluations:0,uniqueExpressions:0,warningCount:0,cacheHitRate:0,averageDuration:0,byType:{},byWarning:{}}),[o,d]=j.useState(""),[g,h]=j.useState(!1),[f,p]=j.useState(null),y=j.useCallback(()=>{const A=r.getExpressionInfo();t(A.expressions),i(A.stats)},[r]);j.useEffect(()=>{y();const A=r.watchExpressions(()=>{y()}),O=setInterval(y,2e3);return()=>{A(),clearInterval(O)}},[r,y]);const x=e.filter(A=>{if(g&&!A.warning)return!1;if(o){const O=o.toLowerCase();return A.expression.toLowerCase().includes(O)||A.componentName?.toLowerCase().includes(O)||A.propName?.toLowerCase().includes(O)||A.resultType.toLowerCase().includes(O)}return!0}),S=A=>{switch(A){case"string":return"g7dt-text-green";case"number":return"g7dt-text-blue";case"boolean":return"g7dt-text-purple";case"array":return"g7dt-text-cyan";case"object":return"g7dt-text-yellow";case"undefined":case"null":return"g7dt-text-red";default:return"g7dt-text-gray"}},v=A=>{switch(A){case"undefined-result":return"undefined 결과";case"null-result":return"null 결과";case"array-to-string":return"배열→문자열";case"object-to-string":return"객체→문자열";case"missing-optional-chain":return"?. 누락 의심";case"wrong-iteration-var":return"잘못된 반복 변수";case"type-mismatch":return"타입 불일치";case"cache-stale":return"캐시 오래됨";case"slow-evaluation":return"느린 평가";default:return A}},w=(A,O)=>O==="undefined"?"undefined":O==="null"?"null":O==="string"?`"${String(A).substring(0,50)}${String(A).length>50?"...":""}"`:O==="array"?`Array(${Array.isArray(A)?A.length:"?"})`:O==="object"?"Object{...}":String(A),k=()=>{r.clearExpressions(),t([]),p(null)};return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-stats-grid-5",children:[l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-lg g7dt-text-blue",children:a.totalEvaluations}),l.jsx("div",{className:"g7dt-stat-label-xs",children:"총 평가"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-lg g7dt-text-green",children:a.uniqueExpressions}),l.jsx("div",{className:"g7dt-stat-label-xs",children:"고유 표현식"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-lg g7dt-text-yellow",children:a.warningCount}),l.jsx("div",{className:"g7dt-stat-label-xs",children:"경고"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsxs("div",{className:"g7dt-stat-value-lg g7dt-text-purple",children:[(a.cacheHitRate*100).toFixed(0),"%"]}),l.jsx("div",{className:"g7dt-stat-label-xs",children:"캐시 히트"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsxs("div",{className:"g7dt-stat-value-lg g7dt-text-cyan",children:[a.averageDuration.toFixed(1),"ms"]}),l.jsx("div",{className:"g7dt-stat-label-xs",children:"평균 시간"})]})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-items-center",children:[l.jsx("input",{type:"text",placeholder:"표현식, 컴포넌트, prop 검색...",value:o,onChange:A=>d(A.target.value),className:"g7dt-input g7dt-flex-1"}),l.jsxs("label",{className:"g7dt-checkbox-label",children:[l.jsx("input",{type:"checkbox",checked:g,onChange:A=>h(A.target.checked),className:"g7dt-checkbox"}),"경고만"]}),l.jsx("button",{onClick:k,className:"g7dt-btn-danger-sm",children:"초기화"})]}),Object.keys(a.byType).length>0&&l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1",children:Object.entries(a.byType).map(([A,O])=>l.jsxs("span",{className:`g7dt-type-tag ${S(A)}`,children:[A,": ",O]},A))}),l.jsx("div",{className:"g7dt-space-y-1 g7dt-expr-list",children:x.length===0?l.jsx("div",{className:"g7dt-empty-message g7dt-py-4",children:o||g?"조건에 맞는 표현식이 없습니다":"추적된 표현식이 없습니다"}):x.slice(-50).reverse().map(A=>l.jsx("div",{onClick:()=>p(A),className:`g7dt-expr-item ${f?.id===A.id?"g7dt-expr-selected":A.warning?"g7dt-expr-warning":""}`,children:l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-start g7dt-gap-2",children:[l.jsxs("div",{className:"g7dt-flex-1 g7dt-min-w-0",children:[l.jsx("div",{className:"g7dt-font-mono g7dt-text-white g7dt-truncate",title:A.expression,children:A.expression}),l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-mt-1 g7dt-text-xxs",children:[A.componentName&&l.jsxs("span",{className:"g7dt-text-gray",children:[A.componentName,A.propName&&`.${A.propName}`]}),l.jsx("span",{className:S(A.resultType),children:w(A.result,A.resultType)})]})]}),l.jsxs("div",{className:"g7dt-flex g7dt-flex-col g7dt-items-end g7dt-gap-1",children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-1",children:[A.fromCache&&l.jsx("span",{className:"g7dt-mini-badge g7dt-badge-success",children:"캐시"}),A.warning&&l.jsx("span",{className:"g7dt-mini-badge g7dt-badge-warning",children:v(A.warning.type)})]}),A.duration!==void 0&&l.jsxs("span",{className:"g7dt-text-xxs g7dt-text-gray",children:[A.duration.toFixed(2),"ms"]})]})]})},A.id))}),f&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:"표현식 상세"}),l.jsx("button",{onClick:()=>p(null),className:"g7dt-btn-close",children:"✕"})]}),l.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"표현식:"}),l.jsx("code",{className:"g7dt-code g7dt-text-green",children:f.expression})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"결과:"}),l.jsx("span",{className:`g7dt-ml-2 ${S(f.resultType)}`,children:JSON.stringify(f.result,null,2)?.substring(0,200)}),l.jsxs("span",{className:"g7dt-ml-2 g7dt-text-darkgray",children:["(",f.resultType,")"]})]}),f.componentName&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"컴포넌트:"}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-blue",children:f.componentName}),f.propName&&l.jsxs("span",{className:"g7dt-text-gray",children:[".",f.propName]})]}),f.method&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"메서드:"}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-purple",children:f.method})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"캐시:"}),l.jsxs("span",{className:`g7dt-ml-2 ${f.fromCache?"g7dt-text-green":"g7dt-text-gray"}`,children:[f.fromCache?"캐시에서 로드":"새로 평가",f.skipCache&&" (skipCache)"]})]}),f.duration!==void 0&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"소요 시간:"}),l.jsxs("span",{className:`g7dt-ml-2 ${f.duration>10?"g7dt-text-red":"g7dt-text-lightgray"}`,children:[f.duration.toFixed(3),"ms"]})]}),f.warning&&l.jsxs("div",{className:"g7dt-warning-box-light",children:[l.jsxs("div",{className:"g7dt-text-yellow g7dt-font-bold",children:["⚠️ ",v(f.warning.type)]}),l.jsx("div",{className:"g7dt-text-lightgray g7dt-mt-1",children:f.warning.message}),f.warning.suggestion&&l.jsxs("div",{className:"g7dt-text-gray g7dt-mt-1 g7dt-text-xxs",children:["💡 ",f.warning.suggestion]})]}),f.steps&&f.steps.length>0&&l.jsxs("details",{className:"g7dt-details",children:[l.jsxs("summary",{className:"g7dt-summary",children:["평가 단계 (",f.steps.length,")"]}),l.jsx("div",{className:"g7dt-mt-1 g7dt-space-y-1 g7dt-pl-2 g7dt-border-l",children:f.steps.map((A,O)=>l.jsxs("div",{className:"g7dt-text-xxs",children:[l.jsx("span",{className:"g7dt-text-purple",children:A.step}),A.path&&l.jsx("span",{className:"g7dt-text-gray g7dt-ml-1",children:A.path}),A.fromCache&&l.jsx("span",{className:"g7dt-text-green g7dt-ml-1",children:"(cached)"}),A.error&&l.jsx("span",{className:"g7dt-text-red g7dt-ml-1",children:A.error})]},O))})]})]})]}),Object.keys(a.byWarning).length>0&&l.jsxs("div",{className:"g7dt-warning-box-light",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-yellow g7dt-mb-2",children:"경고 요약"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-2",children:Object.entries(a.byWarning).map(([A,O])=>l.jsxs("span",{className:"g7dt-warning-tag",children:[v(A),": ",O]},A))})]})]})},wk=({devTools:r})=>{const e=r.getHandlers(),[t,a]=j.useState(""),[i,o]=j.useState("all"),d={"built-in":e.filter(f=>f.category==="built-in"),custom:e.filter(f=>f.category==="custom"),module:e.filter(f=>f.category==="module"),plugin:e.filter(f=>f.category==="plugin")},g={all:e.length,"built-in":d["built-in"].length,custom:d.custom.length,module:d.module.length,plugin:d.plugin.length},h=e.filter(f=>i!=="all"&&f.category!==i?!1:t?f.name.toLowerCase().includes(t.toLowerCase())||f.description?.toLowerCase().includes(t.toLowerCase()):!0);return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsx("div",{className:"g7dt-flex g7dt-gap-2",children:["all","built-in","custom","module","plugin"].map(f=>l.jsxs("button",{onClick:()=>o(f),className:i===f?"g7dt-filter-btn g7dt-filter-active":"g7dt-filter-btn",children:[f==="all"?"전체":f," (",g[f],")"]},f))}),l.jsx("input",{type:"text",placeholder:"핸들러 이름 검색...",value:t,onChange:f=>a(f.target.value),className:"g7dt-input g7dt-w-full"}),l.jsx("div",{className:"g7dt-space-y-1 g7dt-handler-list",children:h.length===0?l.jsx("div",{className:"g7dt-empty-message g7dt-py-4",children:"등록된 핸들러가 없습니다"}):h.map(f=>l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsx("span",{className:"g7dt-font-mono g7dt-text-blue",children:f.name}),l.jsx("span",{className:f.category==="built-in"?"g7dt-mini-badge g7dt-badge-success":f.category==="module"?"g7dt-mini-badge g7dt-badge-purple":f.category==="plugin"?"g7dt-mini-badge g7dt-badge-info":"g7dt-mini-badge g7dt-badge-warning",children:f.category})]}),f.description&&l.jsx("div",{className:"g7dt-text-xs g7dt-text-gray g7dt-mt-1",children:f.description})]},f.name))}),l.jsxs("div",{className:"g7dt-text-xs g7dt-text-gray",children:["총 ",e.length,"개 핸들러 | 빌트인 ",g["built-in"]," | 커스텀 ",g.custom," | 모듈 ",g.module," | 플러그인 ",g.plugin]})]})},Sk=({devTools:r})=>{const[e,t]=j.useState(r.getComponentEventInfo()),[a,i]=j.useState(null),o=j.useCallback(()=>{t(r.getComponentEventInfo())},[r]);j.useEffect(()=>{o();const g=setInterval(o,2e3);return()=>clearInterval(g)},[o]);const d=a?e.emitHistory.filter(g=>g.eventName===a):e.emitHistory;return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-stats-grid-3",children:[l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value-lg g7dt-text-blue",children:e.subscriptions.length}),l.jsx("div",{className:"g7dt-stat-label",children:"이벤트 타입"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value-lg g7dt-text-green",children:e.totalSubscribers}),l.jsx("div",{className:"g7dt-stat-label",children:"총 구독자"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value-lg g7dt-text-purple",children:e.totalEmits}),l.jsx("div",{className:"g7dt-stat-label",children:"총 발행"})]})]}),l.jsxs("div",{children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"구독된 이벤트"}),l.jsxs("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-2",children:[l.jsx("button",{onClick:()=>i(null),className:a===null?"g7dt-filter-btn g7dt-filter-active":"g7dt-filter-btn",children:"전체"}),e.subscriptions.map(g=>l.jsxs("button",{onClick:()=>i(g.eventName),className:a===g.eventName?"g7dt-filter-btn g7dt-filter-active":"g7dt-filter-btn",children:[g.eventName," (",g.subscriberCount,")"]},g.eventName))]})]}),l.jsxs("div",{children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:["발행 이력 ",a&&`(${a})`]}),l.jsx("div",{className:"g7dt-space-y-1 g7dt-event-list",children:d.length===0?l.jsx("div",{className:"g7dt-empty-message g7dt-py-4",children:"이벤트 발행 이력이 없습니다"}):d.slice(-30).reverse().map(g=>l.jsxs("div",{className:`g7dt-card g7dt-text-xs ${g.hasError?"g7dt-card-error":""}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsx("span",{className:"g7dt-font-mono g7dt-text-green",children:g.eventName}),l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsxs("span",{className:"g7dt-text-gray",children:[g.listenerCount," listeners"]}),g.hasError&&l.jsx("span",{className:"g7dt-text-red g7dt-text-xxs",children:"에러"})]})]}),g.data!==void 0&&l.jsxs("details",{className:"g7dt-details g7dt-mt-1",children:[l.jsx("summary",{className:"g7dt-summary",children:"데이터"}),l.jsx("pre",{className:"g7dt-pre",children:JSON.stringify(g.data,null,2)})]}),g.hasError&&g.errorMessage&&l.jsx("div",{className:"g7dt-error-inline",children:g.errorMessage})]},g.id))})]}),l.jsx("button",{onClick:o,className:"g7dt-btn-secondary",children:"새로고침"})]})},Ck=({devTools:r})=>{const e=r.getDataSources(),[t,a]=j.useState("all"),[i,o]=j.useState(null),[d,g]=j.useState(!1),[h,f]=j.useState(null),p=j.useCallback(()=>{f(r.getDataPathTransformTrackingInfo())},[r]);j.useEffect(()=>{if(d){p();const k=setInterval(p,2e3);return()=>clearInterval(k)}},[d,p]);const y=k=>{switch(k){case"api_response":return"📥";case"extract_data":return"📄";case"apply_path":return"🔗";case"init_global":return"🌐";case"init_local":return"📌";default:return"❓"}},x=e.filter(k=>t==="all"?!0:k.status===t),S={all:e.length,idle:e.filter(k=>k.status==="idle").length,loading:e.filter(k=>k.status==="loading").length,loaded:e.filter(k=>k.status==="loaded").length,error:e.filter(k=>k.status==="error").length},v=k=>{switch(k){case"loaded":return"g7dt-badge-success";case"loading":return"g7dt-badge-warning";case"error":return"g7dt-badge-error";default:return"g7dt-badge-gray"}},w=i?e.find(k=>k.id===i):null;return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsx("div",{className:"g7dt-flex g7dt-gap-2",children:["all","idle","loading","loaded","error"].map(k=>l.jsxs("button",{onClick:()=>a(k),className:t===k?"g7dt-filter-btn g7dt-filter-active":"g7dt-filter-btn",children:[k==="all"?"전체":k," (",S[k],")"]},k))}),l.jsx("div",{className:"g7dt-ds-grid",children:x.length===0?l.jsx("div",{className:"g7dt-empty-message g7dt-col-span-2 g7dt-py-4",children:"데이터소스가 없습니다"}):x.map(k=>l.jsxs("div",{onClick:()=>o(k.id),className:`g7dt-ds-item ${i===k.id?"g7dt-ds-selected":""}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsx("span",{className:"g7dt-font-mono g7dt-text-blue g7dt-truncate",children:k.id}),l.jsx("span",{className:`g7dt-mini-badge ${v(k.status)}`,children:k.status})]}),l.jsx("div",{className:"g7dt-text-gray g7dt-mt-1 g7dt-truncate",children:k.endpoint||"(endpoint 없음)"}),k.itemCount!==void 0&&l.jsxs("div",{className:"g7dt-text-lightgray g7dt-mt-1",children:[k.itemCount,"개 항목"]})]},k.id))}),w&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:w.id}),l.jsx("button",{onClick:()=>o(null),className:"g7dt-btn-close",children:"✕"})]}),l.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"엔드포인트:"}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-green",children:w.endpoint||"-"})]}),w.dataPath&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"데이터 경로:"}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-yellow",children:w.dataPath})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"상태:"}),l.jsx("span",{className:`g7dt-ml-2 g7dt-mini-badge ${v(w.status)}`,children:w.status})]}),w.itemCount!==void 0&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"항목 수:"}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-blue",children:w.itemCount})]}),w.keys&&w.keys.length>0&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"키:"}),l.jsxs("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1",children:[w.keys.slice(0,10).map(k=>l.jsx("span",{className:"g7dt-key-tag",children:k},k)),w.keys.length>10&&l.jsxs("span",{className:"g7dt-text-gray",children:["+",w.keys.length-10,"개"]})]})]}),w.dependencies&&w.dependencies.length>0&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"의존성:"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1",children:w.dependencies.map(k=>l.jsx("span",{className:"g7dt-dep-tag",children:k},k))})]})]})]}),l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsxs("div",{className:"g7dt-text-xs g7dt-text-gray",children:["총 ",e.length,"개 데이터소스 | 로드됨 ",S.loaded," | 로딩중 ",S.loading," | 에러 ",S.error]}),l.jsx("button",{onClick:()=>g(!d),className:`g7dt-tab-button ${d?"g7dt-tab-active":""}`,children:"🔀 Path Transform"})]}),d&&h&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:["데이터 경로 변환 추적 (",h.transforms.length,"개)"]}),l.jsxs("div",{className:"g7dt-stats-grid-3 g7dt-mb-3",children:[l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-xl g7dt-font-bold g7dt-text-blue",children:h.stats.totalTransforms}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"총 변환"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-xl g7dt-font-bold g7dt-text-purple",children:Object.keys(h.stats.byDataSource).length}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"데이터소스"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-xl g7dt-font-bold g7dt-text-yellow",children:h.stats.warningsCount}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"경고"})]})]}),h.transforms.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"변환 기록이 없습니다"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:h.transforms.slice().reverse().slice(0,20).map((k,A)=>l.jsxs("div",{className:`g7dt-list-item ${k.warnings.length>0?"g7dt-border-yellow":""}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{className:"g7dt-text-xs g7dt-text-blue g7dt-font-mono",children:k.dataSourceId}),k.warnings.length>0&&l.jsxs("span",{className:"g7dt-badge g7dt-text-xs g7dt-text-yellow",children:["⚠️ ",k.warnings.length]})]}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1",children:k.transformSteps.map((O,N)=>l.jsxs("span",{className:"g7dt-badge g7dt-text-xs",title:`${O.inputPath} → ${O.outputPath}`,children:[y(O.step)," ",O.step]},N))}),k.finalBinding&&l.jsxs("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-1",children:["최종: ",l.jsx("span",{className:"g7dt-text-green",children:k.finalBinding.expression}),"→ ",l.jsx("span",{className:"g7dt-text-blue",children:k.finalBinding.resolvedPath})]}),k.warnings.length>0&&l.jsx("div",{className:"g7dt-text-xs g7dt-text-yellow g7dt-mt-1",children:k.warnings[0]})]},`${k.dataSourceId}-${A}`))}),h.stats.commonWarnings.length>0&&l.jsxs("div",{className:"g7dt-mt-3",children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-1",children:"자주 발생하는 경고"}),l.jsx("div",{className:"g7dt-space-y-1",children:h.stats.commonWarnings.slice(0,5).map((k,A)=>l.jsxs("div",{className:"g7dt-text-xs g7dt-text-yellow",children:[k.warning," (",k.count,"회)"]},A))})]})]})]})},jk=({devTools:r})=>{const[e,t]=j.useState(r.getStateRenderingInfo()),[a,i]=j.useState(null),[o,d]=j.useState(!1),[g,h]=j.useState(""),f=j.useCallback(()=>{t(r.getStateRenderingInfo())},[r]);j.useEffect(()=>{f();const v=setInterval(f,2e3);return()=>clearInterval(v)},[f]);const p=e.logs.filter(v=>!(o&&v.renderedComponents.length>0||g&&!v.statePath.toLowerCase().includes(g.toLowerCase()))),y=a?e.logs.find(v=>v.setStateId===a):null,x=e.stats,S=e.logs.filter(v=>v.renderedComponents.length===0).length;return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-stats-grid",children:[l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-blue",children:x.totalStateChanges}),l.jsx("div",{className:"g7dt-stat-label",children:"상태 변경"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-green",children:x.totalRenders}),l.jsx("div",{className:"g7dt-stat-label",children:"총 렌더링"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsxs("div",{className:"g7dt-stat-value g7dt-text-purple",children:[x.avgRenderDuration.toFixed(1),"ms"]}),l.jsx("div",{className:"g7dt-stat-label",children:"평균 렌더 시간"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:`g7dt-stat-value ${S>0?"g7dt-text-yellow":"g7dt-text-green"}`,children:S}),l.jsx("div",{className:"g7dt-stat-label",children:"렌더링 없음"})]})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsx("input",{type:"text",placeholder:"상태 경로 필터 (예: _global.user)",value:g,onChange:v=>h(v.target.value),className:"g7dt-input g7dt-flex-1"}),l.jsx("button",{onClick:()=>d(!o),className:o?"g7dt-filter-btn-active-yellow":"g7dt-filter-btn",children:"렌더링 없음만"})]}),l.jsx("div",{className:"g7dt-scroll-list",children:p.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"상태-렌더링 로그가 없습니다"}):p.slice(-30).reverse().map(v=>{const w=v.renderedComponents.length>0,k=w?"✅":"⚠️",A=new Date(v.timestamp).toLocaleTimeString();return l.jsxs("div",{onClick:()=>i(v.setStateId),className:`g7dt-render-log-item ${a===v.setStateId?"g7dt-selected":w?"":"g7dt-warning"}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsxs("span",{className:"g7dt-mono g7dt-text-blue",children:[k," ",v.statePath]}),l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[w?l.jsxs("span",{className:"g7dt-text-green",children:[v.renderedComponents.length,"개 렌더"]}):l.jsx("span",{className:"g7dt-text-yellow",children:"렌더링 없음"}),l.jsx("span",{className:"g7dt-text-muted",children:A})]})]}),v.triggeredBy?.handlerType&&l.jsxs("div",{className:"g7dt-text-muted g7dt-mt-1",children:["트리거: ",v.triggeredBy.handlerType]})]},v.setStateId)})}),y&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:y.statePath}),l.jsx("button",{onClick:()=>i(null),className:"g7dt-close-btn",children:"✕"})]}),l.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"setStateId:"}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-purple g7dt-mono",children:y.setStateId})]}),y.triggeredBy&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"트리거:"}),l.jsxs("span",{className:"g7dt-ml-2 g7dt-text-yellow",children:[y.triggeredBy.handlerType,y.triggeredBy.actionId&&` (${y.triggeredBy.actionId})`]})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"이전 값:"}),l.jsx("pre",{className:"g7dt-pre g7dt-text-red",children:JSON.stringify(y.oldValue,null,2)?.slice(0,200)})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"새 값:"}),l.jsx("pre",{className:"g7dt-pre g7dt-text-green",children:JSON.stringify(y.newValue,null,2)?.slice(0,200)})]}),y.renderedComponents.length>0?l.jsxs("div",{children:[l.jsxs("span",{className:"g7dt-text-muted",children:["렌더링된 컴포넌트 (",y.renderedComponents.length,"개):"]}),l.jsxs("div",{className:"g7dt-mt-1 g7dt-space-y-1",children:[y.renderedComponents.slice(0,10).map((v,w)=>l.jsxs("div",{className:"g7dt-render-comp-item",children:[l.jsx("span",{className:"g7dt-text-blue",children:v.componentName}),l.jsxs("span",{className:"g7dt-text-muted",children:[v.renderDuration.toFixed(2),"ms"]})]},w)),y.renderedComponents.length>10&&l.jsxs("div",{className:"g7dt-text-muted g7dt-text-center",children:["... 외 ",y.renderedComponents.length-10,"개"]})]}),l.jsxs("div",{className:"g7dt-mt-2 g7dt-text-muted",children:["총 렌더 시간: ",y.totalRenderDuration.toFixed(2),"ms"]})]}):l.jsxs("div",{className:"g7dt-warning-box",children:[l.jsx("span",{className:"g7dt-text-yellow",children:"⚠️ 렌더링이 발생하지 않았습니다"}),l.jsxs("div",{className:"g7dt-text-muted g7dt-mt-1 g7dt-text-xxs",children:["가능한 원인:",l.jsxs("ul",{className:"g7dt-list g7dt-mt-1",children:[l.jsx("li",{children:"해당 상태를 바인딩하는 컴포넌트가 없음"}),l.jsx("li",{children:"컴포넌트가 마운트되지 않은 상태"}),l.jsx("li",{children:"동일한 값으로 상태 설정"})]})]})]})]})]}),x.topRenderedComponents.length>0&&l.jsxs("div",{children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"가장 많이 렌더링된 컴포넌트"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-2",children:x.topRenderedComponents.slice(0,5).map((v,w)=>l.jsxs("span",{className:"g7dt-tag",children:[v.name,": ",l.jsx("span",{className:"g7dt-text-blue",children:v.count})]},w))})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsx("button",{onClick:f,className:"g7dt-btn-secondary",children:"새로고침"}),l.jsx("button",{onClick:()=>{r.clearStateRenderingLogs(),f()},className:"g7dt-btn-danger",children:"로그 초기화"})]})]})},kk=({devTools:r})=>{const[e,t]=j.useState(null),[a,i]=j.useState(null),[o,d]=j.useState("all"),g=j.useCallback(()=>{t(r.getStyleValidationInfo())},[r]);if(j.useEffect(()=>{g();const y=setInterval(g,2e3);return()=>clearInterval(y)},[g]),!e)return l.jsx("div",{className:"g7dt-empty-state",children:"로딩 중..."});const h=e.issues.filter(y=>o==="all"?!0:y.type===o),f=a?e.issues.find(y=>y.componentId===a):null,p=e.stats;return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-stats-grid",children:[l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-blue",children:p.totalComponents}),l.jsx("div",{className:"g7dt-stat-label",children:"총 컴포넌트"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:`g7dt-stat-value ${p.invisibleCount>0?"g7dt-text-red":"g7dt-text-green"}`,children:p.invisibleCount}),l.jsx("div",{className:"g7dt-stat-label",children:"숨겨진 요소"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:`g7dt-stat-value ${p.tailwindIssueCount>0?"g7dt-text-yellow":"g7dt-text-green"}`,children:p.tailwindIssueCount}),l.jsx("div",{className:"g7dt-stat-label",children:"Tailwind 이슈"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:`g7dt-stat-value ${p.darkModeIssueCount>0?"g7dt-text-purple":"g7dt-text-green"}`,children:p.darkModeIssueCount}),l.jsx("div",{className:"g7dt-stat-label",children:"다크모드 이슈"})]})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsxs("select",{value:o,onChange:y=>d(y.target.value),className:"g7dt-select",children:[l.jsx("option",{value:"all",children:"모든 이슈"}),l.jsx("option",{value:"invisible-element",children:"숨겨진 요소"}),l.jsx("option",{value:"tailwind-purging",children:"Tailwind 퍼징"}),l.jsx("option",{value:"dark-mode-missing",children:"다크모드 누락"})]}),l.jsx("button",{onClick:g,className:"g7dt-btn-secondary",children:"새로고침"})]}),l.jsx("div",{className:"g7dt-scroll-list",children:h.length===0?l.jsx("div",{className:"g7dt-empty-state",children:e.issues.length===0?"스타일 이슈가 없습니다 ✓":"필터에 맞는 이슈가 없습니다"}):h.map(y=>{const x=y.type==="invisible-element"?"👁️":y.type==="tailwind-purging"?"🎨":"🌙",S=y.severity==="error"?"g7dt-severity-error":y.severity==="warning"?"g7dt-severity-warning":"g7dt-severity-info";return l.jsxs("div",{onClick:()=>i(y.componentId),className:`g7dt-style-issue-item ${S} ${a===y.componentId?"g7dt-selected":""}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsxs("span",{className:"g7dt-mono g7dt-text-blue",children:[x," ",y.componentName]}),l.jsx("span",{className:y.severity==="error"?"g7dt-badge-error":y.severity==="warning"?"g7dt-badge-warning":"g7dt-badge-info",children:y.type})]}),l.jsx("div",{className:"g7dt-text-muted g7dt-mt-1 g7dt-truncate",children:y.description})]},y.componentId)})}),f&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:f.componentName}),l.jsx("button",{onClick:()=>i(null),className:"g7dt-close-btn",children:"✕"})]}),l.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"이슈 타입:"}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-yellow",children:f.type})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"설명:"}),l.jsx("div",{className:"g7dt-mt-1 g7dt-text-white",children:f.description})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"CSS 속성:"}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-purple",children:f.property}),l.jsxs("span",{className:"g7dt-ml-2 g7dt-text-muted",children:["= ",f.currentValue]}),f.expectedValue&&l.jsxs("span",{className:"g7dt-ml-2 g7dt-text-green",children:["(예상: ",f.expectedValue,")"]})]}),f.suggestion&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"해결 방법:"}),l.jsx("div",{className:"g7dt-mt-1 g7dt-text-green",children:f.suggestion})]})]})]}),e.componentStyles.length>0&&l.jsxs("div",{children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:["컴포넌트 스타일 (",e.componentStyles.length,")"]}),l.jsx("div",{className:"g7dt-scroll-list-sm",children:e.componentStyles.slice(0,20).map((y,x)=>l.jsxs("div",{className:"g7dt-list-item",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-blue",children:y.componentName}),l.jsxs("span",{className:"g7dt-text-muted",children:[y.classes.length," classes"]})]}),y.classes.length>0&&l.jsxs("div",{className:"g7dt-text-muted g7dt-mt-1 g7dt-truncate",children:[y.classes.slice(0,5).join(" "),y.classes.length>5&&"..."]})]},x))})]})]})},Nk=({devTools:r})=>{const[e,t]=j.useState(null),[a,i]=j.useState(null),[o,d]=j.useState("all"),g=j.useCallback(()=>{t(r.getAuthDebugInfo())},[r]);if(j.useEffect(()=>{g();const x=setInterval(g,2e3);return()=>clearInterval(x)},[g]),!e)return l.jsx("div",{className:"g7dt-empty-state",children:"로딩 중..."});const h=e.events.filter(x=>o==="all"?!0:x.type===o),f=a?e.events.find(x=>x.id===a):null,p=e.stats,y=e.state;return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-justify-between g7dt-mb-3",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:"현재 인증 상태"}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted",children:["소스: ",y.source||"unknown"]})]}),l.jsxs("div",{className:"g7dt-stats-grid-3 g7dt-mb-3",children:[l.jsx("div",{className:"g7dt-text-center",children:l.jsx("div",{className:`g7dt-text-lg g7dt-font-bold ${y.isAuthenticated?"g7dt-text-green":"g7dt-text-red"}`,children:y.isAuthenticated?"✓ 인증됨":"✕ 미인증"})}),l.jsx("div",{className:"g7dt-text-center",children:l.jsx("div",{className:`g7dt-text-lg g7dt-font-bold ${y.tokens.hasAccessToken?"g7dt-text-green":"g7dt-text-yellow"}`,children:y.tokens.hasAccessToken?"✓ 토큰 유효":"⚠ 토큰 없음"})}),l.jsx("div",{className:"g7dt-text-center",children:l.jsx("div",{className:"g7dt-text-lg g7dt-font-bold g7dt-text-blue",children:y.user?.name||y.user?.email||"익명"})})]}),y.user&&l.jsxs("div",{className:"g7dt-border-t g7dt-pt-3 g7dt-mt-3",children:[l.jsxs("div",{className:"g7dt-grid-2 g7dt-gap-2 g7dt-text-xs",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"ID:"}),l.jsx("span",{className:"g7dt-text-white g7dt-mono",children:y.user.id})]}),l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"이메일:"}),l.jsx("span",{className:"g7dt-text-white g7dt-truncate g7dt-ml-2",title:y.user.email,children:y.user.email})]}),y.user.name&&l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"이름:"}),l.jsx("span",{className:"g7dt-text-white",children:y.user.name})]}),y.user.nickname&&l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"닉네임:"}),l.jsx("span",{className:"g7dt-text-white",children:y.user.nickname})]}),y.user.phone&&l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"전화번호:"}),l.jsx("span",{className:"g7dt-text-white",children:y.user.phone})]}),y.user.status&&l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"상태:"}),l.jsx("span",{className:y.user.status==="active"?"g7dt-text-green":"g7dt-text-yellow",children:y.user.status})]}),y.user.locale&&l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"언어:"}),l.jsx("span",{className:"g7dt-text-white",children:y.user.locale})]})]}),y.user.roles&&y.user.roles.length>0&&l.jsxs("div",{className:"g7dt-mt-2",children:[l.jsx("span",{className:"g7dt-text-muted g7dt-text-xs",children:"역할: "}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1",children:y.user.roles.map((x,S)=>l.jsx("span",{className:"g7dt-role-tag",title:x.guard_name?`guard: ${x.guard_name}`:void 0,children:typeof x=="string"?x:x.name},S))})]}),y.user.permissions&&y.user.permissions.length>0&&l.jsxs("div",{className:"g7dt-mt-2",children:[l.jsx("span",{className:"g7dt-text-muted g7dt-text-xs",children:"권한: "}),l.jsxs("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1 g7dt-max-h-16 g7dt-overflow-auto",children:[y.user.permissions.slice(0,10).map((x,S)=>l.jsx("span",{className:"g7dt-perm-tag",title:x.guard_name?`guard: ${x.guard_name}`:void 0,children:typeof x=="string"?x:x.name},S)),y.user.permissions.length>10&&l.jsxs("span",{className:"g7dt-text-muted g7dt-text-xs",children:["+",y.user.permissions.length-10,"개"]})]})]}),l.jsxs("div",{className:"g7dt-mt-2 g7dt-grid-2 g7dt-gap-2 g7dt-text-xs",children:[y.user.created_at&&l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"가입일:"}),l.jsx("span",{className:"g7dt-text-muted",children:new Date(y.user.created_at).toLocaleDateString()})]}),y.user.last_login_at&&l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"마지막 로그인:"}),l.jsx("span",{className:"g7dt-text-muted",children:new Date(y.user.last_login_at).toLocaleString()})]}),y.user.email_verified_at&&l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"이메일 인증:"}),l.jsx("span",{className:"g7dt-text-green",children:"✓ 인증됨"})]})]})]}),l.jsx("div",{className:"g7dt-border-t g7dt-pt-3 g7dt-mt-3",children:l.jsxs("div",{className:"g7dt-grid-2 g7dt-gap-2 g7dt-text-xs",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"저장소:"}),l.jsx("span",{className:"g7dt-text-white",children:y.tokens.storage})]}),y.tokens.accessTokenPreview&&l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"토큰:"}),l.jsx("span",{className:"g7dt-text-muted g7dt-mono",children:y.tokens.accessTokenPreview})]})]})}),y.tokens.accessTokenExpiresAt&&l.jsxs("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-2 g7dt-text-center",children:["토큰 만료: ",new Date(y.tokens.accessTokenExpiresAt).toLocaleString()]})]}),l.jsxs("div",{className:"g7dt-stats-grid-5",children:[l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-blue",children:p.loginAttempts}),l.jsx("div",{className:"g7dt-stat-label",children:"로그인 시도"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-green",children:p.successfulLogins}),l.jsx("div",{className:"g7dt-stat-label",children:"성공"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:`g7dt-stat-value-sm ${p.failedLogins>0?"g7dt-text-red":"g7dt-text-muted"}`,children:p.failedLogins}),l.jsx("div",{className:"g7dt-stat-label",children:"실패"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-purple",children:p.tokenRefreshes}),l.jsx("div",{className:"g7dt-stat-label",children:"토큰 갱신"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:`g7dt-stat-value-sm ${p.unauthorizedResponses>0?"g7dt-text-red":"g7dt-text-muted"}`,children:p.unauthorizedResponses}),l.jsx("div",{className:"g7dt-stat-label",children:"401 응답"})]})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsxs("select",{value:o,onChange:x=>d(x.target.value),className:"g7dt-select",children:[l.jsx("option",{value:"all",children:"모든 이벤트"}),l.jsx("option",{value:"login",children:"로그인"}),l.jsx("option",{value:"logout",children:"로그아웃"}),l.jsx("option",{value:"token-refresh",children:"토큰 갱신"}),l.jsx("option",{value:"token-expired",children:"토큰 만료"}),l.jsx("option",{value:"api-unauthorized",children:"401 응답"})]}),l.jsx("button",{onClick:g,className:"g7dt-btn-secondary",children:"새로고침"})]}),l.jsx("div",{className:"g7dt-scroll-list-sm",children:h.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"인증 이벤트가 없습니다"}):h.slice(-20).reverse().map(x=>{const S=x.success?"✅":"❌",v=new Date(x.timestamp).toLocaleTimeString();return l.jsxs("div",{onClick:()=>i(x.id),className:`g7dt-auth-event-item ${a===x.id?"g7dt-selected":x.success?"":"g7dt-error"}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsxs("span",{className:"g7dt-mono",children:[S," ",x.type]}),l.jsx("span",{className:"g7dt-text-muted",children:v})]}),x.error&&l.jsx("div",{className:"g7dt-text-red g7dt-mt-1 g7dt-truncate",children:x.error})]},x.id)})}),f&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:f.type}),l.jsx("button",{onClick:()=>i(null),className:"g7dt-close-btn",children:"✕"})]}),l.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"결과:"}),l.jsx("span",{className:`g7dt-ml-2 ${f.success?"g7dt-text-green":"g7dt-text-red"}`,children:f.success?"성공":"실패"})]}),f.error&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"에러:"}),l.jsx("div",{className:"g7dt-mt-1 g7dt-text-red",children:f.error})]}),f.details&&Object.keys(f.details).length>0&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"상세:"}),l.jsx("pre",{className:"g7dt-pre g7dt-text-green",children:JSON.stringify(f.details,null,2)})]})]})]}),e.headerAnalysis.length>0&&l.jsxs("div",{children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"최근 API 인증 헤더"}),l.jsx("div",{className:"g7dt-scroll-list-xs",children:e.headerAnalysis.slice(-10).reverse().map((x,S)=>l.jsxs("div",{className:"g7dt-header-item",children:[l.jsx("span",{className:"g7dt-text-blue g7dt-truncate g7dt-flex-1",children:x.url}),l.jsx("span",{className:`g7dt-ml-2 ${x.hasAuthHeader?"g7dt-text-green":"g7dt-text-yellow"}`,children:x.hasAuthHeader?`✓ ${x.headerType}`:"✕ 헤더 없음"}),x.responseStatus&&l.jsx("span",{className:`g7dt-ml-2 ${x.responseStatus<400?"g7dt-text-muted":"g7dt-text-red"}`,children:x.responseStatus})]},S))})]})]})},Ek=({devTools:r})=>{const[e,t]=j.useState([]),[a,i]=j.useState(null),[o,d]=j.useState(null),[g,h]=j.useState("all"),[f,p]=j.useState(""),[y,x]=j.useState(""),S=j.useCallback(()=>{const N=r.getLogInfo();t(N.entries),i(N.stats)},[r]);j.useEffect(()=>{S();const N=setInterval(S,1e3);return()=>clearInterval(N)},[S]);const v=e.filter(N=>!(g!=="all"&&N.level!==g||f&&!N.prefix.toLowerCase().includes(f.toLowerCase())||y&&!N.message.toLowerCase().includes(y.toLowerCase()))),w=o?e.find(N=>N.id===o):null,k=()=>{r.clearLogs(),S(),d(null)},A=N=>{switch(N){case"error":return"g7dt-text-red";case"warn":return"g7dt-text-yellow";case"info":return"g7dt-text-blue";case"debug":return"g7dt-text-muted";default:return"g7dt-text-white"}},O=N=>{switch(N){case"error":return"g7dt-log-error";case"warn":return"g7dt-log-warn";case"info":return"g7dt-log-info";case"debug":return"g7dt-log-debug";default:return"g7dt-log-default"}};return l.jsxs("div",{className:"g7dt-space-y-4",children:[a&&l.jsxs("div",{className:"g7dt-stats-grid-6",children:[l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-white",children:a.totalLogs}),l.jsx("div",{className:"g7dt-stat-label",children:"전체"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-red",children:a.byLevel.error}),l.jsx("div",{className:"g7dt-stat-label",children:"에러"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-yellow",children:a.byLevel.warn}),l.jsx("div",{className:"g7dt-stat-label",children:"경고"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-blue",children:a.byLevel.info}),l.jsx("div",{className:"g7dt-stat-label",children:"정보"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:`g7dt-stat-value-sm ${a.recentErrors>0?"g7dt-text-red":"g7dt-text-green"}`,children:a.recentErrors}),l.jsx("div",{className:"g7dt-stat-label",children:"최근 에러"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:`g7dt-stat-value-sm ${a.recentWarnings>0?"g7dt-text-yellow":"g7dt-text-green"}`,children:a.recentWarnings}),l.jsx("div",{className:"g7dt-stat-label",children:"최근 경고"})]})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-flex-wrap",children:[l.jsxs("select",{value:g,onChange:N=>h(N.target.value),className:"g7dt-select",children:[l.jsx("option",{value:"all",children:"모든 레벨"}),l.jsx("option",{value:"error",children:"에러"}),l.jsx("option",{value:"warn",children:"경고"}),l.jsx("option",{value:"info",children:"정보"}),l.jsx("option",{value:"log",children:"로그"}),l.jsx("option",{value:"debug",children:"디버그"})]}),l.jsx("input",{type:"text",placeholder:"prefix 필터",value:f,onChange:N=>p(N.target.value),className:"g7dt-input g7dt-w-32"}),l.jsx("input",{type:"text",placeholder:"메시지 검색",value:y,onChange:N=>x(N.target.value),className:"g7dt-input g7dt-flex-1"}),l.jsx("button",{onClick:S,className:"g7dt-btn-secondary",children:"새로고침"}),l.jsx("button",{onClick:k,className:"g7dt-btn-danger",children:"초기화"})]}),l.jsx("div",{className:"g7dt-scroll-list-lg",children:v.length===0?l.jsx("div",{className:"g7dt-empty-state",children:e.length===0?"로그가 없습니다":"필터에 맞는 로그가 없습니다"}):v.slice(-50).reverse().map(N=>{const D=new Date(N.timestamp).toLocaleTimeString();return l.jsxs("div",{onClick:()=>d(N.id),className:`g7dt-log-item ${o===N.id?"g7dt-selected":O(N.level)}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{className:`g7dt-font-bold g7dt-uppercase ${A(N.level)}`,children:N.level}),l.jsxs("span",{className:"g7dt-text-purple",children:["[",N.prefix,"]"]})]}),l.jsx("span",{className:"g7dt-text-muted",children:D})]}),l.jsx("div",{className:"g7dt-text-white g7dt-mt-1 g7dt-truncate",children:N.message})]},N.id)})}),w&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold",children:[l.jsx("span",{className:A(w.level),children:w.level.toUpperCase()})," ",l.jsxs("span",{className:"g7dt-text-purple",children:["[",w.prefix,"]"]})]}),l.jsx("button",{onClick:()=>d(null),className:"g7dt-close-btn",children:"✕"})]}),l.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"시간:"}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-white",children:new Date(w.timestamp).toLocaleString()})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"메시지:"}),l.jsx("pre",{className:"g7dt-pre g7dt-text-white g7dt-whitespace-pre-wrap",children:w.message})]}),w.args.length>0&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"인수:"}),l.jsx("pre",{className:"g7dt-pre g7dt-text-green",children:JSON.stringify(w.args,null,2)})]}),w.stack&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"스택 트레이스:"}),l.jsx("pre",{className:"g7dt-pre-stack g7dt-text-red",children:w.stack})]})]})]}),a&&Object.keys(a.byPrefix).length>0&&l.jsxs("div",{children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"Prefix별 로그 수"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-2",children:Object.entries(a.byPrefix).sort((N,D)=>D[1]-N[1]).slice(0,10).map(([N,D])=>l.jsxs("button",{onClick:()=>p(N),className:f===N?"g7dt-prefix-btn-active":"g7dt-prefix-btn",children:[N,": ",l.jsx("span",{className:"g7dt-text-blue",children:D})]},N))})]})]})},_k=({devTools:r})=>{const[e,t]=j.useState(r.getLayoutDebugInfo()),[a,i]=j.useState(!1),[o,d]=j.useState(null),[g,h]=j.useState(!1),[f,p]=j.useState({});j.useEffect(()=>{const A=setInterval(()=>{t(r.getLayoutDebugInfo())},1e3);return()=>clearInterval(A)},[r]),j.useEffect(()=>{(async()=>{try{const O=await fetch("/api/admin/permissions",{headers:{Authorization:`Bearer ${localStorage.getItem("auth_token")}`,Accept:"application/json"}});if(O.ok){const N=await O.json(),D={},$=M=>{M.forEach(z=>{D[z.identifier]=z.name,z.children?.length&&$(z.children)})};Object.values(N.data?.permissions||{}).forEach(M=>{M.permissions&&$(M.permissions)}),p(D)}}catch(O){console.warn("[G7DevTools] 권한 목록 조회 실패:",O)}})()},[]);const y=e.current,x=y?.layoutJson,S=e.history,v=e.stats,w=x?[{key:"components",label:"컴포넌트",count:Array.isArray(x.components)?x.components.length:0},{key:"data_sources",label:"데이터소스",count:Array.isArray(x.data_sources)?x.data_sources.length:0},{key:"computed",label:"Computed",count:x.computed?Object.keys(x.computed).length:0},{key:"defines",label:"Defines",count:x.defines?Object.keys(x.defines).length:0},{key:"slots",label:"Slots",count:x.slots?Object.keys(x.slots).length:0},{key:"modals",label:"Modals",count:x.modals?Object.keys(x.modals).length:0},{key:"init_actions",label:"초기화 액션",count:Array.isArray(x.init_actions)?x.init_actions.length:0},{key:"scripts",label:"스크립트",count:Array.isArray(x.scripts)?x.scripts.length:0},{key:"meta",label:"메타데이터",count:x.meta?Object.keys(x.meta).length:0},{key:"errorHandling",label:"에러핸들링",count:x.errorHandling?Object.keys(x.errorHandling).length:0},{key:"permissions",label:"권한",count:Array.isArray(x.permissions)?x.permissions.length:0}]:[],k=A=>{navigator.clipboard.writeText(JSON.stringify(A,null,2))};return y?l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"📊 로드 통계"}),l.jsxs("div",{className:"g7dt-grid-3",children:[l.jsxs("div",{className:"g7dt-stat-item",children:[l.jsx("span",{className:"g7dt-text-muted",children:"총 로드:"}),l.jsx("span",{className:"g7dt-text-blue",children:v.totalLoads})]}),l.jsxs("div",{className:"g7dt-stat-item",children:[l.jsx("span",{className:"g7dt-text-muted",children:"캐시 히트:"}),l.jsx("span",{className:"g7dt-text-green",children:v.cacheHits})]}),l.jsxs("div",{className:"g7dt-stat-item",children:[l.jsx("span",{className:"g7dt-text-muted",children:"API 로드:"}),l.jsx("span",{className:"g7dt-text-yellow",children:v.apiLoads})]})]})]}),l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:"📋 현재 레이아웃"}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsx("button",{onClick:()=>k(x),className:"g7dt-btn-small",title:"전체 JSON 복사",children:"📋 복사"}),l.jsx("button",{onClick:()=>i(!a),className:"g7dt-btn-small",children:a?"요약 보기":"전체 보기"})]})]}),l.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[l.jsxs("div",{className:"g7dt-flex g7dt-gap-4",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"경로:"}),l.jsx("span",{className:"g7dt-ml-1 g7dt-text-white g7dt-font-mono",children:y.layoutPath})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"템플릿:"}),l.jsx("span",{className:"g7dt-ml-1 g7dt-text-blue",children:y.templateId})]})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-4",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"버전:"}),l.jsx("span",{className:"g7dt-ml-1 g7dt-text-white",children:y.version||"-"})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"소스:"}),l.jsx("span",{className:`g7dt-ml-1 ${y.source==="cache"?"g7dt-text-green":"g7dt-text-yellow"}`,children:y.source==="cache"?"💾 캐시":"🌐 API"})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"로드 시간:"}),l.jsx("span",{className:"g7dt-ml-1 g7dt-text-white",children:y.loadedAt?new Date(y.loadedAt).toLocaleTimeString():"-"})]})]}),l.jsx("div",{className:"g7dt-flex g7dt-gap-4 g7dt-mt-2",children:l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"권한:"}),x.permissions&&x.permissions.length>0?l.jsxs("span",{className:"g7dt-ml-1 g7dt-text-yellow",children:["🔒 ",x.permissions.map(A=>f[A]||A).join(", ")]}):x.permissions&&x.permissions.length===0?l.jsx("span",{className:"g7dt-ml-1 g7dt-text-green",children:"🌐 공개"}):l.jsx("span",{className:"g7dt-ml-1 g7dt-text-muted",children:"미정의 (부모 상속)"})]})})]})]}),!a&&l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"🏗️ 레이아웃 구조"}),l.jsx("div",{className:"g7dt-grid-2",children:w.map(A=>l.jsxs("button",{onClick:()=>d(o===A.key?null:A.key),className:`g7dt-section-btn ${o===A.key?"g7dt-selected":""}`,children:[l.jsx("span",{children:A.label}),l.jsxs("span",{className:"g7dt-text-blue",children:[A.count,"개"]})]},A.key))})]}),(a||o)&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:a?"📄 전체 레이아웃 JSON":`📎 ${o} 섹션`}),l.jsx("button",{onClick:()=>{a?k(x):o&&x&&k(x[o])},className:"g7dt-btn-small",children:"복사"})]}),o==="permissions"&&!a?l.jsx("div",{className:"g7dt-text-xs",children:x.permissions&&x.permissions.length>0?l.jsxs("table",{className:"g7dt-table g7dt-w-full",children:[l.jsx("thead",{children:l.jsxs("tr",{className:"g7dt-border-b g7dt-border-gray-700",children:[l.jsx("th",{className:"g7dt-text-left g7dt-p-2 g7dt-text-muted",children:"권한 ID"}),l.jsx("th",{className:"g7dt-text-left g7dt-p-2 g7dt-text-muted",children:"명칭"})]})}),l.jsx("tbody",{children:x.permissions.map(A=>l.jsxs("tr",{className:"g7dt-border-b g7dt-border-gray-800",children:[l.jsx("td",{className:"g7dt-p-2 g7dt-font-mono g7dt-text-blue",children:A}),l.jsx("td",{className:"g7dt-p-2 g7dt-text-white",children:f[A]||l.jsx("span",{className:"g7dt-text-muted",children:"-"})})]},A))})]}):x.permissions&&x.permissions.length===0?l.jsx("p",{className:"g7dt-text-muted g7dt-p-2",children:"🌐 공개 레이아웃 (permissions: [])"}):l.jsx("p",{className:"g7dt-text-muted g7dt-p-2",children:"권한 미정의 (부모 레이아웃 상속)"})}):l.jsx("pre",{className:"g7dt-pre g7dt-text-green g7dt-max-h-96 g7dt-overflow-auto",children:JSON.stringify(a?x:o&&x?x[o]:null,null,2)})]}),S.length>0&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-cursor-pointer",onClick:()=>h(!g),children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold",children:["📜 로드 이력 (",S.length,")"]}),l.jsx("span",{className:"g7dt-text-muted",children:g?"▼":"▶"})]}),g&&l.jsx("div",{className:"g7dt-mt-2 g7dt-space-y-1",children:S.slice(-20).reverse().map(A=>l.jsxs("div",{className:"g7dt-history-item",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsx("span",{className:"g7dt-font-mono g7dt-text-xs",children:A.layoutPath}),l.jsx("span",{className:`g7dt-text-xs ${A.source==="cache"?"g7dt-text-green":"g7dt-text-yellow"}`,children:A.source==="cache"?"💾":"🌐"})]}),l.jsxs("div",{className:"g7dt-text-xs g7dt-text-muted",children:[A.templateId," · ",A.loadedAt?new Date(A.loadedAt).toLocaleTimeString():"-"]})]},A.id))})]}),l.jsxs("div",{className:"g7dt-card g7dt-text-xs g7dt-text-muted",children:["💡 레이아웃 캐시 문제가 의심되면:",l.jsxs("ul",{className:"g7dt-ml-4 g7dt-list-disc",children:[l.jsx("li",{children:'"소스" 항목이 💾 캐시인지 🌐 API인지 확인'}),l.jsx("li",{children:"캐시에서 로드된 경우, JSON 내용이 최신인지 확인"}),l.jsxs("li",{children:["문제가 있으면 ",l.jsx("code",{className:"g7dt-code",children:"php artisan template:refresh-layout"})," 실행"]})]})]})]}):l.jsx("div",{className:"g7dt-space-y-4",children:l.jsxs("div",{className:"g7dt-empty-state",children:["현재 로드된 레이아웃이 없습니다.",l.jsx("br",{}),"페이지를 새로고침하거나 라우트를 변경해보세요."]})})},Ak=({devTools:r})=>{const[e,t]=j.useState(r.getChangeDetectionInfo()),[a,i]=j.useState(null),[o,d]=j.useState(!1),[g,h]=j.useState(new Set);j.useEffect(()=>{const N=setInterval(()=>{t(r.getChangeDetectionInfo())},500);return()=>clearInterval(N)},[r]);const{executionDetails:f,alerts:p,stats:y}=e,x=o?f.filter(N=>N.alerts.length>0||N.stateChanges.length===0):f,S=a?f.find(N=>N.executionId===a):null,v=N=>{h(D=>{const $=new Set(D);return $.has(N)?$.delete(N):$.add(N),$})},w=N=>{switch(N){case"normal":return"✅";case"early-return-condition":return"⏎";case"early-return-validation":return"❌";case"error":return"💥";default:return"❓"}},k=N=>{switch(N){case"no-state-change":return"⚠️";case"no-datasource-change":return"📊";case"expected-not-fulfilled":return"❗";case"object-reference-same":return"🔄";case"early-return-detected":return"⏎";case"async-timing-issue":return"⏱️";default:return"📢"}},A=N=>{switch(N){case"error":return"g7dt-text-red";case"warning":return"g7dt-text-yellow";case"info":return"g7dt-text-blue";default:return"g7dt-text-white"}},O=N=>new Date(N).toLocaleTimeString("ko-KR",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3});return l.jsxs("div",{className:"g7dt-space-y-4",children:[p.filter(N=>N.severity==="error"||N.severity==="warning").length>0&&l.jsx("div",{className:"g7dt-card",style:{backgroundColor:"#7f1d1d",borderColor:"#991b1b"},children:l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsxs("span",{className:"g7dt-font-bold",children:["⚠️ 변경 감지 알림: ",p.filter(N=>N.severity==="error").length,"개 에러,"," ",p.filter(N=>N.severity==="warning").length,"개 경고"]}),l.jsx("button",{onClick:()=>r.clearChangeDetectionData(),className:"g7dt-btn-small",children:"초기화"})]})}),l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"📊 변경 감지 통계"}),l.jsxs("div",{className:"g7dt-grid-3",children:[l.jsxs("div",{className:"g7dt-stat-item",children:[l.jsx("span",{className:"g7dt-text-muted",children:"총 실행:"}),l.jsx("span",{className:"g7dt-text-blue",children:y.totalExecutions})]}),l.jsxs("div",{className:"g7dt-stat-item",children:[l.jsx("span",{className:"g7dt-text-muted",children:"상태 변경 있음:"}),l.jsx("span",{className:"g7dt-text-green",children:y.executionsWithStateChange})]}),l.jsxs("div",{className:"g7dt-stat-item",children:[l.jsx("span",{className:"g7dt-text-muted",children:"상태 변경 없음:"}),l.jsx("span",{className:y.executionsWithoutStateChange>0?"g7dt-text-yellow":"g7dt-text-gray",children:y.executionsWithoutStateChange})]}),l.jsxs("div",{className:"g7dt-stat-item",children:[l.jsx("span",{className:"g7dt-text-muted",children:"Early Return:"}),l.jsx("span",{className:"g7dt-text-orange",children:y.earlyReturnCount})]}),l.jsxs("div",{className:"g7dt-stat-item",children:[l.jsx("span",{className:"g7dt-text-muted",children:"알림:"}),l.jsx("span",{className:y.alertCount>0?"g7dt-text-red":"g7dt-text-gray",children:y.alertCount})]})]})]}),p.length>0&&l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"🔔 최근 알림"}),l.jsx("div",{className:"g7dt-space-y-2",style:{maxHeight:"200px",overflowY:"auto"},children:p.slice(-10).reverse().map(N=>l.jsxs("div",{className:"g7dt-list-item",onClick:()=>v(N.id),style:{cursor:"pointer"},children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-start",children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{children:k(N.type)}),l.jsx("span",{className:`g7dt-text-xs ${A(N.severity)}`,children:N.message})]}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted",children:O(N.timestamp)})]}),g.has(N.id)&&l.jsxs("div",{className:"g7dt-mt-2 g7dt-text-xs g7dt-text-muted g7dt-pl-6",children:[l.jsx("p",{children:N.description}),N.statePath&&l.jsxs("p",{className:"g7dt-mt-1",children:[l.jsx("span",{className:"g7dt-text-cyan",children:"경로:"})," ",N.statePath]}),N.suggestion&&l.jsxs("p",{className:"g7dt-mt-1",children:[l.jsx("span",{className:"g7dt-text-green",children:"제안:"})," ",N.suggestion]}),N.docLink&&l.jsxs("p",{className:"g7dt-mt-1",children:[l.jsx("span",{className:"g7dt-text-blue",children:"문서:"})," ",l.jsx("code",{className:"g7dt-code",children:N.docLink})]})]})]},N.id))})]}),l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:"🔧 핸들러 실행 이력"}),l.jsxs("label",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-xs",children:[l.jsx("input",{type:"checkbox",checked:o,onChange:N=>d(N.target.checked)}),l.jsx("span",{children:"경고만 표시"})]})]}),x.length===0?l.jsxs("div",{className:"g7dt-empty-state",children:["핸들러 실행 이력이 없습니다.",l.jsx("br",{}),"액션을 실행하면 여기에 표시됩니다."]}):l.jsx("div",{className:"g7dt-space-y-1",style:{maxHeight:"300px",overflowY:"auto"},children:x.slice(-20).reverse().map(N=>l.jsxs("div",{className:`g7dt-list-item ${a===N.executionId?"g7dt-selected":""}`,onClick:()=>i(a===N.executionId?null:N.executionId),style:{cursor:"pointer"},children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{children:w(N.exitReason)}),l.jsx("span",{className:"g7dt-text-white g7dt-font-mono g7dt-text-xs",children:N.handlerName}),N.alerts.length>0&&l.jsx("span",{className:"g7dt-badge g7dt-badge-warning",children:N.alerts.length})]}),l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-xs",children:[l.jsxs("span",{className:"g7dt-text-muted",children:["상태: ",N.stateChanges.length]}),l.jsx("span",{className:"g7dt-text-muted",children:N.duration?`${N.duration}ms`:"-"}),l.jsx("span",{className:"g7dt-text-muted",children:O(N.startTime)})]})]}),a===N.executionId&&S&&l.jsxs("div",{className:"g7dt-mt-3 g7dt-pt-3 g7dt-border-t g7dt-border-gray-700",children:[l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted",children:"종료 사유: "}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-white",children:S.exitReason||"unknown"}),S.exitLocation&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-2",children:"위치: "}),l.jsx("code",{className:"g7dt-code g7dt-text-xs",children:S.exitLocation})]})]}),S.exitDescription&&l.jsx("div",{className:"g7dt-mb-2 g7dt-text-xs g7dt-text-muted",children:S.exitDescription}),S.stateChanges.length>0&&l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsxs("span",{className:"g7dt-text-xs g7dt-font-bold g7dt-text-green",children:["상태 변경 (",S.stateChanges.length,")"]}),l.jsx("div",{className:"g7dt-mt-1 g7dt-space-y-1",children:S.stateChanges.map(D=>l.jsxs("div",{className:"g7dt-text-xs g7dt-pl-2",children:[l.jsx("span",{className:"g7dt-text-cyan",children:D.path}),l.jsxs("span",{className:"g7dt-text-muted",children:[" (",D.changeType,")"]}),D.comparison.changedKeys&&l.jsxs("span",{className:"g7dt-text-muted g7dt-ml-1",children:["[변경: ",D.comparison.changedKeys.join(", "),"]"]})]},D.id))})]}),S.dataSourceChanges.length>0&&l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsxs("span",{className:"g7dt-text-xs g7dt-font-bold g7dt-text-blue",children:["데이터소스 변경 (",S.dataSourceChanges.length,")"]}),l.jsx("div",{className:"g7dt-mt-1 g7dt-space-y-1",children:S.dataSourceChanges.map((D,$)=>l.jsxs("div",{className:"g7dt-text-xs g7dt-pl-2",children:[l.jsx("span",{className:"g7dt-text-cyan",children:D.dataSourceId}),l.jsxs("span",{className:"g7dt-text-muted",children:[" ","(",D.changeType,": ",D.previousStatus," → ",D.newStatus,")"]})]},$))})]}),S.expectedChanges&&l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsx("span",{className:"g7dt-text-xs g7dt-font-bold g7dt-text-yellow",children:"기대 변경"}),l.jsxs("div",{className:"g7dt-mt-1 g7dt-text-xs g7dt-pl-2 g7dt-text-muted",children:["상태: ",S.expectedChanges.expectedStatePaths.join(", ")||"없음",l.jsx("br",{}),"데이터소스: ",S.expectedChanges.expectedDataSources.join(", ")||"없음"]})]}),S.alerts.length>0&&l.jsxs("div",{children:[l.jsxs("span",{className:"g7dt-text-xs g7dt-font-bold g7dt-text-red",children:["알림 (",S.alerts.length,")"]}),l.jsx("div",{className:"g7dt-mt-1 g7dt-space-y-1",children:S.alerts.map(D=>l.jsxs("div",{className:"g7dt-text-xs g7dt-pl-2",children:[l.jsx("span",{children:k(D.type)}),l.jsx("span",{className:`g7dt-ml-1 ${A(D.severity)}`,children:D.message})]},D.id))})]})]})]},N.executionId))})]}),l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"💡 변경 감지 가이드"}),l.jsxs("ul",{className:"g7dt-help-list",children:[l.jsx("li",{children:"핸들러 실행 후 상태 변경이 없으면 ⚠️ 경고가 표시됩니다"}),l.jsx("li",{children:"early return으로 종료된 경우 ⏎ 아이콘으로 표시됩니다"}),l.jsx("li",{children:"객체 변경 시 참조가 동일하면 🔄 경고가 발생합니다"}),l.jsx("li",{children:"문제 해결: exitLocation 확인 → 조건문 검토 → 불변성 확인"})]})]})]})},Tk=({devTools:r})=>{const[e,t]=j.useState(null),[a,i]=j.useState(null),[o,d]=j.useState("all"),g=j.useCallback(()=>{t(r.getStaleClosureTrackingInfo())},[r]);if(j.useEffect(()=>{g();const v=setInterval(g,2e3);return()=>clearInterval(v)},[g]),!e)return l.jsx("div",{className:"g7dt-empty-state",children:"로딩 중..."});const{warnings:h,stats:f}=e,p=h.filter(v=>o==="all"?!0:v.severity===o),y=a?h.find(v=>v.id===a):null,x=v=>{switch(v){case"error":return"❌";case"warning":return"⚠️";default:return"❓"}},S=v=>{switch(v){case"state-changed-during-async":return"⏳";case"captured-in-callback":return"📸";case"stale-in-handler":return"🔄";default:return"❓"}};return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"Stale Closure 통계"}),l.jsxs("div",{className:"g7dt-stats-grid-3",children:[l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-yellow",children:f.totalWarnings||0}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"총 경고"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-red",children:f.warningsBySeverity?.error||0}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"에러"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-orange",children:f.warningsBySeverity?.warning||0}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"경고"})]})]})]}),f.warningsByType&&Object.keys(f.warningsByType).length>0&&l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"타입별 분포"}),l.jsx("div",{className:"g7dt-space-y-2",children:Object.entries(f.warningsByType).map(([v,w])=>l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-text-xs",children:[l.jsxs("span",{className:"g7dt-text-muted",children:[S(v)," ",v]}),l.jsx("span",{className:"g7dt-text-white g7dt-font-mono",children:w})]},v))})]}),l.jsx("div",{className:"g7dt-card",children:l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted",children:"심각도:"}),l.jsxs("select",{value:o,onChange:v=>d(v.target.value),className:"g7dt-select",children:[l.jsx("option",{value:"all",children:"전체"}),l.jsx("option",{value:"error",children:"에러"}),l.jsx("option",{value:"warning",children:"경고"})]}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:[p.length,"개 표시"]})]})}),l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"Stale Closure 경고"}),p.length===0?l.jsx("div",{className:"g7dt-empty-state g7dt-text-green",children:"✅ Stale Closure 경고가 없습니다"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:p.slice().reverse().map(v=>l.jsxs("div",{className:`g7dt-list-item g7dt-cursor-pointer ${a===v.id?"g7dt-selected":""}`,onClick:()=>i(a===v.id?null:v.id),children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{children:x(v.severity)}),l.jsx("span",{children:S(v.type)}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-white g7dt-truncate",children:v.location}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:new Date(v.timestamp).toLocaleTimeString()})]}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-1 g7dt-truncate",children:v.statePath})]},v.id))})]}),y&&l.jsxs("div",{className:"g7dt-card g7dt-border-yellow",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:[x(y.severity)," 경고 상세"]}),l.jsxs("div",{className:"g7dt-space-y-3",children:[l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"위치"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-white g7dt-mono",children:y.location})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"타입"}),l.jsxs("div",{className:"g7dt-text-sm g7dt-text-white",children:[S(y.type)," ",y.type]})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"상태 경로"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-yellow g7dt-mono",children:y.statePath})]}),l.jsxs("div",{className:"g7dt-grid-2 g7dt-gap-3",children:[l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"캡처된 값"}),l.jsx("pre",{className:"g7dt-code-block g7dt-text-red",children:JSON.stringify(y.capturedValue,null,2)})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"현재 값"}),l.jsx("pre",{className:"g7dt-code-block g7dt-text-green",children:JSON.stringify(y.currentValue,null,2)})]})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"시간 차이"}),l.jsxs("div",{className:"g7dt-text-sm g7dt-text-white",children:[y.timeDiff,"ms"]})]}),y.suggestion&&l.jsxs("div",{className:"g7dt-bg-blue-dark g7dt-p-2 g7dt-rounded",children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-blue",children:"💡 제안"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-white g7dt-mt-1",children:y.suggestion})]})]})]})]})},Dk=({devTools:r})=>{const[e,t]=j.useState(null),[a,i]=j.useState(null),[o,d]=j.useState("all"),g=j.useCallback(()=>{t(r.getNestedContextTrackingInfo())},[r]);if(j.useEffect(()=>{g();const v=setInterval(g,2e3);return()=>clearInterval(v)},[g]),!e)return l.jsx("div",{className:"g7dt-empty-state",children:"로딩 중..."});const{contexts:h,stats:f}=e,p=h.filter(v=>o==="all"?!0:v.componentType===o),y=a?h.find(v=>v.id===a):null,x=v=>{switch(v){case"expandChildren":return"📂";case"cellChildren":return"📊";case"iteration":return"🔄";case"modal":return"🪟";case"slot":return"🔲";default:return"❓"}},S=v=>"│".repeat(Math.max(0,v-1))+(v>0?"├─":"");return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"Nested Context 통계"}),l.jsxs("div",{className:"g7dt-stats-grid-3",children:[l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-blue",children:f.totalContexts||0}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"총 컨텍스트"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-purple",children:f.maxDepth||0}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"최대 깊이"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-red",children:f.failedAccessCount||0}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"접근 오류"})]})]})]}),f.byType&&Object.keys(f.byType).length>0&&l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"타입별 분포"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-3",children:Object.entries(f.byType).map(([v,w])=>l.jsxs("div",{className:`g7dt-badge g7dt-cursor-pointer ${o===v?"g7dt-badge-selected":""}`,onClick:()=>d(o===v?"all":v),children:[x(v)," ",v,": ",w]},v))})]}),l.jsx("div",{className:"g7dt-card",children:l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted",children:"타입:"}),l.jsxs("select",{value:o,onChange:v=>d(v.target.value),className:"g7dt-select",children:[l.jsx("option",{value:"all",children:"전체"}),l.jsx("option",{value:"expandChildren",children:"expandChildren"}),l.jsx("option",{value:"cellChildren",children:"cellChildren"}),l.jsx("option",{value:"iteration",children:"iteration"}),l.jsx("option",{value:"modal",children:"modal"}),l.jsx("option",{value:"slot",children:"slot"})]}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:[p.length,"개 표시"]})]})}),l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"컨텍스트 목록"}),p.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"추적된 Nested Context가 없습니다"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:p.slice().reverse().map(v=>{const w=v.accessAttempts?.some(A=>!A.found),k=v.mergedContext?.all||[];return l.jsxs("div",{className:`g7dt-list-item g7dt-cursor-pointer ${a===v.id?"g7dt-selected":""} ${w?"g7dt-border-red":""}`,onClick:()=>i(a===v.id?null:v.id),children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{className:"g7dt-text-muted g7dt-mono g7dt-text-xs",children:S(v.depth)}),l.jsx("span",{children:x(v.componentType)}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-white",children:v.componentId||v.componentType}),w&&l.jsx("span",{className:"g7dt-text-red g7dt-text-xs",children:"⚠️ 오류"}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:["깊이: ",v.depth]})]}),l.jsxs("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-1",children:["변수: ",k.slice(0,5).join(", "),k.length>5&&"..."]})]},v.id)})})]}),y&&l.jsxs("div",{className:"g7dt-card g7dt-border-blue",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:[x(y.componentType)," 컨텍스트 상세"]}),l.jsxs("div",{className:"g7dt-space-y-3",children:[l.jsxs("div",{className:"g7dt-grid-2 g7dt-gap-3",children:[l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"타입"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-white",children:y.componentType})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"깊이"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-white",children:y.depth})]})]}),y.componentId&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"컴포넌트 ID"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-blue g7dt-mono",children:y.componentId})]}),y.parentId&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"부모 컨텍스트"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-purple g7dt-mono",children:y.parentId})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"사용 가능한 변수"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1",children:(y.mergedContext?.all||[]).map(v=>l.jsx("span",{className:"g7dt-badge g7dt-badge-blue g7dt-text-xs",children:v},v))})]}),y.ownContext?.added&&y.ownContext.added.length>0&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"추가된 변수 (이 컨텍스트에서)"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1",children:y.ownContext.added.map(v=>l.jsxs("span",{className:"g7dt-badge g7dt-badge-green g7dt-text-xs",children:["+ ",v]},v))})]}),y.accessAttempts&&y.accessAttempts.length>0&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"접근 시도"}),l.jsx("div",{className:"g7dt-space-y-1",children:y.accessAttempts.slice(0,10).map((v,w)=>l.jsxs("div",{className:`g7dt-flex g7dt-justify-between g7dt-text-xs ${v.found?"":"g7dt-text-red"}`,children:[l.jsx("span",{className:"g7dt-mono",children:v.path}),l.jsx("span",{children:v.found?"✓":"✕"})]},w))})]})]})]})]})},Rk=({devTools:r})=>{const[e,t]=j.useState(null),[a,i]=j.useState(null),[o,d]=j.useState(null),[g,h]=j.useState("modals"),f=j.useCallback(()=>{t(r.getModalStateScopeTrackingInfo())},[r]);if(j.useEffect(()=>{f();const D=setInterval(f,2e3);return()=>clearInterval(D)},[f]),!e)return l.jsx("div",{className:"g7dt-empty-state",children:"로딩 중..."});const{modals:p,issues:y,relations:x,changeLogs:S,stats:v}=e,w=a?p.find(D=>D.modalId===a):null,k=o?y.find(D=>D.id===o):null,A=D=>{switch(D){case"isolated":return"🔒";case"shared":return"🔓";case"inherited":return"📥";default:return"❓"}},O=D=>{switch(D){case"state-leakage":return"💧";case"isolation-violation":return"🔓";case"parent-mutation":return"👆";case"orphaned-state":return"👻";case"scope-mismatch":return"🔀";case"cleanup-failure":return"🧹";case"missing-definition":return"🚫";default:return"❓"}},N=D=>{switch(D){case"error":return"❌";case"warning":return"⚠️";default:return"❓"}};return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"모달 상태 스코프 통계"}),l.jsxs("div",{className:"g7dt-stats-grid-3",children:[l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-blue",children:v.totalModals}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"총 모달"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-green",children:v.openModals}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"열린 모달"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-red",children:v.totalIssues}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"이슈"})]})]})]}),l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"스코프별 / 이슈별"}),l.jsxs("div",{className:"g7dt-grid-2 g7dt-gap-4",children:[l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"스코프 타입"}),l.jsx("div",{className:"g7dt-space-y-1",children:Object.entries(v.byScope).map(([D,$])=>l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-text-xs",children:[l.jsxs("span",{children:[A(D)," ",D]}),l.jsx("span",{className:"g7dt-font-mono",children:$})]},D))})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"이슈 타입"}),l.jsxs("div",{className:"g7dt-space-y-1",children:[Object.entries(v.issuesByType).filter(([D,$])=>$>0).map(([D,$])=>l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-text-xs",children:[l.jsxs("span",{children:[O(D)," ",D]}),l.jsx("span",{className:"g7dt-font-mono g7dt-text-red",children:$})]},D)),Object.values(v.issuesByType).every(D=>D===0)&&l.jsx("div",{className:"g7dt-text-xs g7dt-text-green",children:"✅ 이슈 없음"})]})]})]})]}),l.jsx("div",{className:"g7dt-card",children:l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsxs("button",{className:`g7dt-tab-button ${g==="modals"?"g7dt-tab-active":""}`,onClick:()=>h("modals"),children:["🪟 모달 (",p.length,")"]}),l.jsxs("button",{className:`g7dt-tab-button ${g==="issues"?"g7dt-tab-active":""}`,onClick:()=>h("issues"),children:["⚠️ 이슈 (",y.length,")"]}),l.jsxs("button",{className:`g7dt-tab-button ${g==="logs"?"g7dt-tab-active":""}`,onClick:()=>h("logs"),children:["📝 로그 (",S.length,")"]})]})}),g==="modals"&&l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"모달 목록"}),p.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"추적된 모달이 없습니다"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:p.map(D=>{const $=y.some(M=>M.modalId===D.modalId);return l.jsx("div",{className:`g7dt-list-item g7dt-cursor-pointer ${a===D.modalId?"g7dt-selected":""} ${$?"g7dt-border-red":""}`,onClick:()=>i(a===D.modalId?null:D.modalId),children:l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{children:D.closedAt===null?"📭":"📪"}),l.jsx("span",{children:A(D.scopeType)}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-white",children:D.modalName}),$&&l.jsx("span",{className:"g7dt-text-red",children:"⚠️"}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:["변경: ",D.stateChangeCount]})]})},D.modalId)})})]}),g==="issues"&&l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"이슈 목록"}),y.length===0?l.jsx("div",{className:"g7dt-empty-state g7dt-text-green",children:"✅ 모달 상태 이슈가 없습니다"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:y.slice().reverse().map(D=>l.jsxs("div",{className:`g7dt-list-item g7dt-cursor-pointer ${o===D.id?"g7dt-selected":""}`,onClick:()=>d(o===D.id?null:D.id),children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{children:N(D.severity)}),l.jsx("span",{children:O(D.type)}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-white",children:D.modalName}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:new Date(D.timestamp).toLocaleTimeString()})]}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-1 g7dt-truncate",children:D.description})]},D.id))})]}),g==="logs"&&l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"상태 변경 로그"}),S.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"상태 변경 로그가 없습니다"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:S.slice().reverse().slice(0,50).map(D=>l.jsxs("div",{className:`g7dt-list-item ${D.violatesIsolation?"g7dt-border-red":""}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{className:"g7dt-text-xs g7dt-text-white",children:D.modalName}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-blue g7dt-mono",children:D.stateKey}),D.violatesIsolation&&l.jsx("span",{className:"g7dt-text-red",children:"⚠️ 격리 위반"}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:new Date(D.timestamp).toLocaleTimeString()})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-text-xs g7dt-mt-1",children:[l.jsx("span",{className:"g7dt-text-red g7dt-truncate",style:{maxWidth:"45%"},children:JSON.stringify(D.previousValue)}),l.jsx("span",{className:"g7dt-text-muted",children:"→"}),l.jsx("span",{className:"g7dt-text-green g7dt-truncate",style:{maxWidth:"45%"},children:JSON.stringify(D.newValue)})]})]},D.id))})]}),w&&g==="modals"&&l.jsxs("div",{className:"g7dt-card g7dt-border-blue",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:[A(w.scopeType)," 모달 상세: ",w.modalName]}),l.jsxs("div",{className:"g7dt-space-y-3",children:[l.jsxs("div",{className:"g7dt-grid-2 g7dt-gap-3",children:[l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"스코프"}),l.jsxs("div",{className:"g7dt-text-sm g7dt-text-white",children:[A(w.scopeType)," ",w.scopeType]})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"상태"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-white",children:w.closedAt===null?"📭 열림":"📪 닫힘"})]})]}),w.parentModalId&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"부모 모달"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-purple g7dt-mono",children:w.parentModalId})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"상태 변경 횟수"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-white",children:w.stateChangeCount})]}),w.isolatedStateKeys.length>0&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-1",children:"격리된 상태 키"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1",children:w.isolatedStateKeys.map(D=>l.jsxs("span",{className:"g7dt-badge g7dt-badge-red g7dt-text-xs",children:["🔒 ",D]},D))})]}),w.sharedStateKeys.length>0&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-1",children:"공유된 상태 키"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1",children:w.sharedStateKeys.map(D=>l.jsxs("span",{className:"g7dt-badge g7dt-badge-blue g7dt-text-xs",children:["🔓 ",D]},D))})]})]})]}),k&&g==="issues"&&l.jsxs("div",{className:"g7dt-card g7dt-border-red",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:[N(k.severity)," 이슈 상세"]}),l.jsxs("div",{className:"g7dt-space-y-3",children:[l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"타입"}),l.jsxs("div",{className:"g7dt-text-sm g7dt-text-white",children:[O(k.type)," ",k.type]})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"설명"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-white",children:k.description})]}),k.affectedStateKeys.length>0&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"영향 받는 상태 키"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1",children:k.affectedStateKeys.map(D=>l.jsx("span",{className:"g7dt-badge g7dt-text-xs",children:D},D))})]}),k.leakedValue!==void 0&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"유출된 값"}),l.jsx("pre",{className:"g7dt-code-block g7dt-text-red",children:JSON.stringify(k.leakedValue,null,2)})]})]})]}),x.length>0&&l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"모달 관계"}),l.jsx("div",{className:"g7dt-space-y-2",children:x.map((D,$)=>l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-xs",children:[l.jsx("span",{className:"g7dt-text-purple",children:D.parentModalId}),l.jsx("span",{className:"g7dt-text-muted",children:"→"}),l.jsx("span",{className:"g7dt-text-blue",children:D.childModalId}),l.jsx("span",{className:"g7dt-badge g7dt-text-xs g7dt-ml-auto",children:D.relationType})]},$))})]})]})},Ok=({devTools:r})=>{const[e,t]=j.useState("definitions"),[a,i]=j.useState(null),[o,d]=j.useState(""),g=j.useCallback(()=>{r&&i(r.getNamedActionTrackingInfo())},[r]);if(j.useEffect(()=>{g();const v=setInterval(g,2e3);return()=>clearInterval(v)},[g]),!a)return l.jsx("div",{className:"g7dt-empty-message g7dt-py-4",children:"데이터 로딩 중..."});const{definitions:h,refLogs:f,stats:p}=a,y=Object.keys(h),x=y.filter(v=>!o||v.toLowerCase().includes(o.toLowerCase())||h[v]?.handler?.toLowerCase().includes(o.toLowerCase())),S=f.filter(v=>!o||v.actionRefName.toLowerCase().includes(o.toLowerCase())||v.resolvedHandler.toLowerCase().includes(o.toLowerCase()));return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-grid g7dt-grid-cols-3 g7dt-gap-2",children:[l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value",children:p.totalDefinitions}),l.jsx("div",{className:"g7dt-stat-label",children:"정의"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value",children:p.totalRefs}),l.jsx("div",{className:"g7dt-stat-label",children:"참조"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value",style:{color:p.unusedDefinitions.length>0?"#f59e0b":"#10b981"},children:p.unusedDefinitions.length}),l.jsx("div",{className:"g7dt-stat-label",children:"미사용"})]})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsxs("button",{onClick:()=>t("definitions"),className:e==="definitions"?"g7dt-filter-btn g7dt-filter-active":"g7dt-filter-btn",children:["정의 목록 (",y.length,")"]}),l.jsxs("button",{onClick:()=>t("refs"),className:e==="refs"?"g7dt-filter-btn g7dt-filter-active":"g7dt-filter-btn",children:["참조 이력 (",f.length,")"]}),l.jsx("button",{onClick:g,className:"g7dt-filter-btn",title:"새로고침",children:"↻"})]}),l.jsx("input",{type:"text",placeholder:e==="definitions"?"액션 이름 검색...":"actionRef 검색...",value:o,onChange:v=>d(v.target.value),className:"g7dt-input g7dt-w-full"}),e==="definitions"&&l.jsx("div",{className:"g7dt-space-y-1",children:x.length===0?l.jsx("div",{className:"g7dt-empty-message g7dt-py-4",children:y.length===0?"정의된 named_actions가 없습니다":"검색 결과 없음"}):x.map(v=>{const w=h[v],k=p.refCountByName[v]||0,A=p.unusedDefinitions.includes(v);return l.jsxs("div",{className:"g7dt-card",style:{borderLeft:A?"3px solid #f59e0b":"3px solid #10b981"},children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-font-bold",children:v}),l.jsxs("span",{className:"g7dt-text-muted g7dt-ml-2",children:["→ ",w.handler]})]}),l.jsxs("span",{className:"g7dt-badge",title:"참조 횟수",children:[k,"회"]})]}),w.params&&l.jsxs("details",{className:"g7dt-mt-1",children:[l.jsx("summary",{className:"g7dt-text-xs g7dt-text-muted g7dt-cursor-pointer",children:"params"}),l.jsx("pre",{className:"g7dt-pre g7dt-text-xs g7dt-mt-1",style:{maxHeight:"200px",overflow:"auto"},children:JSON.stringify(w.params,null,2)})]}),A&&l.jsx("div",{className:"g7dt-text-xs",style:{color:"#f59e0b",marginTop:"4px"},children:"⚠ 미사용 정의"})]},v)})}),e==="refs"&&l.jsx("div",{className:"g7dt-space-y-1",children:S.length===0?l.jsx("div",{className:"g7dt-empty-message g7dt-py-4",children:f.length===0?"actionRef 해석 이력이 없습니다":"검색 결과 없음"}):[...S].reverse().map(v=>l.jsx("div",{className:"g7dt-card",children:l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-font-bold",children:v.actionRefName}),l.jsxs("span",{className:"g7dt-text-muted g7dt-ml-2",children:["→ ",v.resolvedHandler]})]}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted",children:new Date(v.timestamp).toLocaleTimeString()})]})},v.id))})]})},Lk=()=>{j.useEffect(()=>{ik()},[]);const r=j.useRef(ix()),[e,t]=j.useState(r.current.isOpen??!1),[a,i]=j.useState(!1),[o,d]=j.useState("state"),[g,h]=j.useState({_global:{},_local:{},_computed:{}}),[f,p]=j.useState([]),[y,x]=j.useState({hits:0,misses:0,entries:0,hitRate:0}),[S,v]=j.useState(!1),[w,k]=j.useState(r.current.position??{x:-1,y:-1}),[A,O]=j.useState(!1),N=j.useRef(null),D=j.useRef(null),[$,M]=j.useState(r.current.size??{width:ok,height:lk}),[z,K]=j.useState(!1),[pe,we]=j.useState(null),J=j.useRef(null),[be,le]=j.useState(!1),de=j.useRef(null),je=ka.getInstance(),W=tx();j.useEffect(()=>{if(w.x===-1&&w.y===-1){const U=window.innerWidth-$.width-16;k({x:U,y:16})}},[w,$.width]),j.useEffect(()=>{if(w.x===-1&&w.y===-1||A||z)return;const U=setTimeout(()=>{ox({position:w,size:$})},300);return()=>clearTimeout(U)},[w,$,A,z]),j.useEffect(()=>{ox({isOpen:e})},[e]);const ge=j.useCallback(U=>{U.target.tagName!=="BUTTON"&&(O(!0),N.current={x:U.clientX,y:U.clientY,posX:w.x,posY:w.y},U.preventDefault())},[w]);j.useEffect(()=>{if(!A)return;const U=ye=>{if(!N.current)return;const oe=ye.clientX-N.current.x,ke=ye.clientY-N.current.y;let Oe=N.current.posX+oe,Te=N.current.posY+ke;const qe=window.innerWidth-$.width,Ie=window.innerHeight-$.height;Oe=Math.max(0,Math.min(Oe,qe)),Te=Math.max(0,Math.min(Te,Ie)),k({x:Oe,y:Te})},re=()=>{O(!1),N.current=null};return document.addEventListener("mousemove",U),document.addEventListener("mouseup",re),()=>{document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",re)}},[A,$.width,$.height]);const ne=j.useCallback(U=>re=>{re.preventDefault(),re.stopPropagation(),K(!0),we(U),J.current={x:re.clientX,y:re.clientY,width:$.width,height:$.height,posX:w.x,posY:w.y}},[$,w]);j.useEffect(()=>{if(!z||!pe)return;const U=ye=>{if(!J.current)return;const oe=ye.clientX-J.current.x,ke=ye.clientY-J.current.y;let Oe=J.current.width,Te=J.current.height,qe=J.current.posX,Ie=J.current.posY;if(pe.includes("e")&&(Oe=Math.max(ax,J.current.width+oe)),pe.includes("w")){const Nt=Math.min(oe,J.current.width-ax);Oe=J.current.width-Nt,qe=J.current.posX+Nt}if(pe.includes("s")&&(Te=Math.max(sx,J.current.height+ke)),pe.includes("n")){const Nt=Math.min(ke,J.current.height-sx);Te=J.current.height-Nt,Ie=J.current.posY+Nt}Oe=Math.min(Oe,window.innerWidth-qe),Te=Math.min(Te,window.innerHeight-Ie),qe=Math.max(0,qe),Ie=Math.max(0,Ie),M({width:Oe,height:Te}),k({x:qe,y:Ie})},re=()=>{K(!1),we(null),J.current=null};return document.addEventListener("mousemove",U),document.addEventListener("mouseup",re),()=>{document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",re)}},[z,pe]);const X=j.useCallback(()=>{be?(de.current&&(k(de.current.position),M(de.current.size)),le(!1)):(de.current={position:w,size:$},k({x:0,y:0}),M({width:window.innerWidth,height:window.innerHeight}),le(!0))},[be,w,$]),ae=j.useCallback(()=>{je.isEnabled()&&(h(je.getState()),p(je.getActionHistory()),x(je.getCacheStats()),v(W.isConnected()))},[je,W]);j.useEffect(()=>{const U=re=>{re.ctrlKey&&re.shiftKey&&re.key==="G"&&(re.preventDefault(),t(ye=>!ye))};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[]),j.useEffect(()=>{if(!e||!je.isEnabled())return;ae();const U=je.watchState("*",()=>{h(je.getState())}),re=je.watchActions(()=>{p(je.getActionHistory()),x(je.getCacheStats())}),ye=setInterval(ae,5e3);return()=>{U(),re(),clearInterval(ye)}},[e,je,ae]);const R=async()=>{try{const U=await W.dumpState();console.log("[G7DevTools] 상태 덤프 완료:",U),v(!0)}catch(U){console.error("[G7DevTools] 상태 덤프 실패:",U),v(!1)}};return je.isEnabled()?e?a?l.jsx("div",{className:"g7dt-minimized",children:l.jsxs("div",{className:"g7dt-minimized-content",children:[l.jsx("span",{className:"g7dt-font-bold g7dt-text-sm",children:"G7 DevTools"}),l.jsx("button",{onClick:()=>i(!1),className:"g7dt-btn g7dt-text-xs",title:"확장",children:"▲"}),l.jsx("button",{onClick:()=>t(!1),className:"g7dt-btn g7dt-text-xs",children:"✕"})]})}):l.jsxs("div",{ref:D,className:`g7dt-panel ${be?"maximized":""} ${z?"g7dt-resizing":""}`,style:{left:`${w.x>=0?w.x:0}px`,top:`${w.y>=0?w.y:0}px`,width:`${$.width}px`,height:`${$.height}px`},children:[!be&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"g7dt-resize-handle g7dt-resize-corner g7dt-resize-nw",onMouseDown:ne("nw")}),l.jsx("div",{className:"g7dt-resize-handle g7dt-resize-corner g7dt-resize-ne",onMouseDown:ne("ne")}),l.jsx("div",{className:"g7dt-resize-handle g7dt-resize-corner g7dt-resize-sw",onMouseDown:ne("sw")}),l.jsx("div",{className:"g7dt-resize-handle g7dt-resize-corner g7dt-resize-se",onMouseDown:ne("se")}),l.jsx("div",{className:"g7dt-resize-handle g7dt-resize-edge-h g7dt-resize-n",onMouseDown:ne("n")}),l.jsx("div",{className:"g7dt-resize-handle g7dt-resize-edge-h g7dt-resize-s",onMouseDown:ne("s")}),l.jsx("div",{className:"g7dt-resize-handle g7dt-resize-edge-v g7dt-resize-w",onMouseDown:ne("w")}),l.jsx("div",{className:"g7dt-resize-handle g7dt-resize-edge-v g7dt-resize-e",onMouseDown:ne("e")})]}),l.jsxs("div",{className:`g7dt-header ${A?"dragging":""}`,onMouseDown:ge,children:[l.jsxs("div",{className:"g7dt-header-left",children:[l.jsx("span",{className:"g7dt-header-title",children:"G7 DevTools"}),l.jsx("span",{className:`g7dt-header-badge ${S?"connected":""}`,title:S?"서버 덤프 성공":"서버에 덤프되지 않음 (덤프 버튼 클릭)",children:S?"덤프 완료":"로컬 모드"})]}),l.jsxs("div",{className:"g7dt-header-right",children:[l.jsx("button",{onClick:R,className:"g7dt-btn g7dt-btn-primary",title:"서버로 상태 덤프",children:"덤프"}),l.jsx("button",{onClick:ae,className:"g7dt-btn",title:"새로고침",children:"↻"}),l.jsx("button",{onClick:X,className:"g7dt-btn",title:be?"복원":"최대화",children:be?"❐":"□"}),l.jsx("button",{onClick:()=>i(!0),className:"g7dt-btn",title:"최소화",children:"▼"}),l.jsx("button",{onClick:()=>t(!1),className:"g7dt-btn",children:"✕"})]})]}),l.jsx("div",{className:"g7dt-tabs",children:Object.keys(nx).map(U=>l.jsx("button",{onClick:()=>d(U),className:`g7dt-tab ${o===U?"active":""}`,children:nx[U]},U))}),l.jsxs("div",{className:"g7dt-content",children:[o==="state"&&l.jsx(uk,{state:g,devTools:je}),o==="actions"&&l.jsx(gk,{actions:f,devTools:je}),o==="cache"&&l.jsx(hk,{stats:y,devTools:je}),o==="diagnose"&&l.jsx(fk,{}),o==="performance"&&l.jsx(pk,{devTools:je}),o==="lifecycle"&&l.jsx(mk,{devTools:je}),o==="network"&&l.jsx(yk,{devTools:je}),o==="form"&&l.jsx(xk,{devTools:je}),o==="conditional"&&l.jsx(bk,{devTools:je}),o==="expression"&&l.jsx(vk,{devTools:je}),o==="handlers"&&l.jsx(wk,{devTools:je}),o==="events"&&l.jsx(Sk,{devTools:je}),o==="datasources"&&l.jsx(Ck,{devTools:je}),o==="renders"&&l.jsx(jk,{devTools:je}),o==="styles"&&l.jsx(kk,{devTools:je}),o==="auth"&&l.jsx(Nk,{devTools:je}),o==="logs"&&l.jsx(Ek,{devTools:je}),o==="layout"&&l.jsx(_k,{devTools:je}),o==="changedetection"&&l.jsx(Ak,{devTools:je}),o==="staleclosure"&&l.jsx(Tk,{devTools:je}),o==="nestedcontext"&&l.jsx(Dk,{devTools:je}),o==="modalscope"&&l.jsx(Rk,{devTools:je}),o==="namedactions"&&l.jsx(Ok,{devTools:je})]}),l.jsxs("div",{className:"g7dt-footer",children:[l.jsx("span",{children:"Ctrl+Shift+G 토글 | 헤더 드래그로 이동"}),l.jsxs("span",{children:["액션: ",f.length," | 캐시 히트율: ",(y.hitRate*100).toFixed(1),"%"]})]})]}):l.jsx("button",{onClick:()=>t(!0),className:"g7dt-floating-btn",title:"G7 DevTools (Ctrl+Shift+G)",children:l.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:[l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}):e?l.jsxs("div",{className:"g7dt-disabled-notice",children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-justify-between g7dt-mb-2",children:[l.jsx("span",{className:"g7dt-font-bold g7dt-text-yellow",children:"G7 DevTools"}),l.jsx("button",{onClick:()=>t(!1),className:"g7dt-btn",children:"✕"})]}),l.jsx("p",{className:"g7dt-text-sm g7dt-text-gray",children:"DevTools가 비활성화되어 있습니다."}),l.jsx("p",{className:"g7dt-text-xs g7dt-text-gray-dark g7dt-mt-2",children:"환경설정 > 고급 설정 > 디버그 모드를 켜세요."})]}):null},Mk=["display","visibility","opacity","position","zIndex","overflow","width","height","backgroundColor","color"],_r=class _r{constructor(){H(this,"enabled",!1);H(this,"trackedComponents",new Map);H(this,"mutationObserver",null);H(this,"scanInterval",null);H(this,"devTools");this.devTools=ka.getInstance()}static getInstance(){return _r.instance||(_r.instance=new _r),_r.instance}enable(){this.enabled||(this.enabled=!0,this.setupMutationObserver(),this.scanInterval=setInterval(()=>{this.scanVisibleComponents()},5e3),console.log("[StyleTracker] 스타일 추적 활성화됨"))}disable(){this.enabled&&(this.enabled=!1,this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.scanInterval&&(clearInterval(this.scanInterval),this.scanInterval=null),this.trackedComponents.clear(),console.log("[StyleTracker] 스타일 추적 비활성화됨"))}trackComponent(e,t,a){if(!this.enabled||!this.devTools.isEnabled()||!a)return;const i=this.extractClasses(a),o=this.getComputedStyles(a);this.devTools.trackComponentStyle(e,t,i,o),this.trackedComponents.set(e,{componentId:e,componentName:t,classes:i,computedStyles:o,element:new WeakRef(a),timestamp:Date.now()}),this.detectIssues(e,t,a,i,o)}untrackComponent(e){this.trackedComponents.delete(e)}scanVisibleComponents(){if(!this.enabled||!this.devTools.isEnabled())return;(this.devTools.getLifecycleInfo().mountedComponents||[]).forEach(i=>{const o=i.id,d=i.name;let g=null;if(o&&(g=document.getElementById(o)),!g&&o&&(g=document.querySelector(`[data-component-id="${o}"]`)),!g&&o&&(g=document.querySelector(`[data-editor-id="${o}"]`)),!g)return;const h=this.extractClasses(g),f=this.getComputedStyles(g);this.devTools.trackComponentStyle(o,d,h,f),this.detectIssues(o,d,g,h,f),this.trackedComponents.set(o,{componentId:o,componentName:d,classes:h,computedStyles:f,element:new WeakRef(g),timestamp:Date.now()})}),document.querySelectorAll('[data-editor-id], [id^="comp-"]').forEach(i=>{if(!(i instanceof HTMLElement))return;const o=i.getAttribute("data-editor-id")||i.id,d=i.getAttribute("data-editor-name")||i.tagName;if(!o||this.trackedComponents.has(o))return;const g=this.extractClasses(i),h=this.getComputedStyles(i);this.devTools.trackComponentStyle(o,d,g,h),this.detectIssues(o,d,i,g,h),this.trackedComponents.set(o,{componentId:o,componentName:d,classes:g,computedStyles:h,element:new WeakRef(i),timestamp:Date.now()})})}detectIssues(e,t,a,i,o){o.display==="none"&&this.addIssue({type:"invisible-element",componentId:e,componentName:t,property:"display",currentValue:"none",severity:"info",description:"요소가 display:none으로 숨겨져 있습니다",suggestion:"의도적인 숨김이 아니라면 조건부 렌더링(if)을 확인하세요"}),o.visibility==="hidden"&&this.addIssue({type:"invisible-element",componentId:e,componentName:t,property:"visibility",currentValue:"hidden",severity:"info",description:"요소가 visibility:hidden으로 숨겨져 있습니다",suggestion:"공간은 유지되지만 보이지 않습니다. 의도적인지 확인하세요"}),o.opacity==="0"&&this.addIssue({type:"invisible-element",componentId:e,componentName:t,property:"opacity",currentValue:"0",severity:"warning",description:"요소가 opacity:0으로 투명합니다",suggestion:"애니메이션 상태가 아니라면 스타일을 확인하세요"}),(o.width==="0px"||o.height==="0px")&&this.addIssue({type:"invisible-element",componentId:e,componentName:t,property:o.width==="0px"?"width":"height",currentValue:"0px",severity:"warning",description:"요소의 크기가 0입니다",suggestion:"컨텐츠가 있는데 크기가 0이라면 레이아웃 문제일 수 있습니다"}),o.overflow==="hidden"&&(a.scrollWidth>a.clientWidth||a.scrollHeight>a.clientHeight)&&this.addIssue({type:"overflow-hidden",componentId:e,componentName:t,property:"overflow",currentValue:"hidden",severity:"warning",description:"컨텐츠가 overflow:hidden으로 잘리고 있습니다",suggestion:"overflow-auto 또는 컨테이너 크기를 확인하세요"});const d=i.some(S=>S.startsWith("dark:"));i.some(S=>(S.startsWith("bg-white")||S.startsWith("bg-gray-"))&&!S.startsWith("dark:"))&&!d&&this.addIssue({type:"dark-mode-missing",componentId:e,componentName:t,property:"className",currentValue:i.filter(S=>S.startsWith("bg-")).join(" "),severity:"info",description:"다크 모드 변형 클래스가 누락되었을 수 있습니다",suggestion:"bg-white 사용 시 dark:bg-gray-800 등을 함께 지정하세요"});const h=parseInt(o.zIndex,10);!isNaN(h)&&h>50&&o.position!=="static"&&this.addIssue({type:"z-index-conflict",componentId:e,componentName:t,property:"z-index",currentValue:o.zIndex,severity:"info",description:`높은 z-index(${h})가 설정되어 있습니다`,suggestion:"z-index 충돌을 피하려면 10, 20, 30, 40, 50 단위를 사용하세요"});const f=i.some(S=>S.startsWith("sm:")||S.startsWith("md:")||S.startsWith("lg:")||S.startsWith("xl:")),p=i.includes("hidden"),y=i.includes("portable:block")||i.includes("portable:flex"),x=i.includes("desktop:block")||i.includes("desktop:flex");p&&!f&&!y&&!x&&this.addIssue({type:"responsive-issue",componentId:e,componentName:t,property:"className",currentValue:"hidden",severity:"info",description:"반응형 표시 클래스 없이 hidden이 설정되어 있습니다",suggestion:"조건에 따라 표시하려면 sm:block, desktop:flex 등을 추가하세요"})}addIssue(e){this.devTools.addStyleIssue(e)}extractClasses(e){return(e.getAttribute("class")||"").split(/\s+/).filter(Boolean)}getComputedStyles(e){const t=window.getComputedStyle(e),a={};for(const i of Mk)a[i]=t.getPropertyValue(i.replace(/([A-Z])/g,"-$1").toLowerCase());return a}setupMutationObserver(){typeof MutationObserver>"u"||(this.mutationObserver=new MutationObserver(e=>{let t=!1;for(const a of e){if(a.type==="childList"&&a.addedNodes.length>0){t=!0;break}if(a.type==="attributes"&&(a.attributeName==="class"||a.attributeName==="style")){t=!0;break}}t&&setTimeout(()=>this.scanVisibleComponents(),100)}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","style"]}))}fullScan(){return this.scanVisibleComponents(),this.devTools.getStyleValidationInfo().issues}getIssues(){return this.devTools.getStyleValidationInfo().issues}getIssuesForComponent(e){return this.getIssues().filter(t=>t.componentId===e)}clear(){this.trackedComponents.clear(),this.devTools.clearStyleValidationData()}};H(_r,"instance",null);let qg=_r;function $k(){return qg.getInstance()}function Ik(r={}){const{checked:e,value:t,name:a,type:i="checkbox"}=r,o={checked:e??!1,value:t??String(e??""),name:a??"",type:i};return{target:o,currentTarget:o,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new Event("change"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"change",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{}}}function zk(r={}){const{button:e=0,clientX:t=0,clientY:a=0}=r;return{button:e,clientX:t,clientY:a,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new MouseEvent("click"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"click",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("div"),currentTarget:document.createElement("div")}}function Hk(){return{preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new Event("submit"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"submit",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("form"),currentTarget:document.createElement("form")}}function Pk(r,e="keydown"){return{key:r,code:r.length===1?`Key${r.toUpperCase()}`:r,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new KeyboardEvent(e,{key:r}),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:e,isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("div"),currentTarget:document.createElement("div"),altKey:!1,ctrlKey:!1,metaKey:!1,shiftKey:!1,repeat:!1}}const Bk={justify:/^justify-(start|end|center|between|around|evenly)$/,items:/^items-(start|end|center|baseline|stretch)$/,content:/^content-(start|end|center|between|around|evenly|stretch)$/,self:/^self-(auto|start|end|center|stretch|baseline)$/,flex:/^flex-(row|row-reverse|col|col-reverse|wrap|wrap-reverse|nowrap|1|auto|initial|none)$/,grow:/^(grow|grow-0)$/,shrink:/^(shrink|shrink-0)$/,basis:/^basis-/,order:/^(order-|-)order-/,gap:/^gap(-x|-y)?-/,gridCols:/^grid-cols-/,gridRows:/^grid-rows-/,colSpan:/^col-(span-|start-|end-)/,rowSpan:/^row-(span-|start-|end-)/,display:/^(block|inline-block|inline|flex|inline-flex|table|inline-table|table-caption|table-cell|table-column|table-column-group|table-footer-group|table-header-group|table-row-group|table-row|flow-root|grid|inline-grid|contents|list-item|hidden)$/,position:/^(static|fixed|absolute|relative|sticky)$/,inset:/^(inset|top|right|bottom|left)-/,zIndex:/^z-/,width:/^w-/,minWidth:/^min-w-/,maxWidth:/^max-w-/,height:/^h-/,minHeight:/^min-h-/,maxHeight:/^max-h-/,padding:/^p[xytblr]?-/,margin:/^-?m[xytblr]?-/,space:/^space-(x|y)-/,fontSize:/^text-(xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl)$/,fontWeight:/^font-(thin|extralight|light|normal|medium|semibold|bold|extrabold|black)$/,fontStyle:/^(italic|not-italic)$/,fontFamily:/^font-(sans|serif|mono)/,textAlign:/^text-(left|center|right|justify|start|end)$/,textColor:/^text-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,textDecoration:/^(underline|overline|line-through|no-underline)$/,textTransform:/^(uppercase|lowercase|capitalize|normal-case)$/,lineHeight:/^leading-/,letterSpacing:/^tracking-/,textOverflow:/^(truncate|text-ellipsis|text-clip)$/,whitespace:/^whitespace-/,wordBreak:/^break-/,bgColor:/^bg-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,bgGradient:/^bg-gradient-/,bgSize:/^bg-(auto|cover|contain)$/,bgPosition:/^bg-(bottom|center|left|left-bottom|left-top|right|right-bottom|right-top|top)$/,bgRepeat:/^bg-(repeat|no-repeat|repeat-x|repeat-y|repeat-round|repeat-space)$/,bgAttachment:/^bg-(fixed|local|scroll)$/,bgClip:/^bg-clip-/,bgOrigin:/^bg-origin-/,borderWidth:/^border(-[xytblr])?(-0|-2|-4|-8)?$/,borderColor:/^border-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,borderStyle:/^border-(solid|dashed|dotted|double|hidden|none)$/,borderRadius:/^rounded(-[tblrse]{1,2})?(-none|-sm|-md|-lg|-xl|-2xl|-3xl|-full)?$/,ringWidth:/^ring(-0|-1|-2|-4|-8|-inset)?$/,ringColor:/^ring-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,ringOffset:/^ring-offset-/,shadow:/^shadow(-sm|-md|-lg|-xl|-2xl|-inner|-none)?$/,opacity:/^opacity-/,mixBlend:/^mix-blend-/,bgBlend:/^bg-blend-/,blur:/^blur(-none|-sm|-md|-lg|-xl|-2xl|-3xl)?$/,brightness:/^brightness-/,contrast:/^contrast-/,grayscale:/^grayscale(-0)?$/,hueRotate:/^-?hue-rotate-/,invert:/^invert(-0)?$/,saturate:/^saturate-/,sepia:/^sepia(-0)?$/,backdropBlur:/^backdrop-blur-/,backdropBrightness:/^backdrop-brightness-/,backdropContrast:/^backdrop-contrast-/,backdropGrayscale:/^backdrop-grayscale-/,backdropHueRotate:/^backdrop-hue-rotate-/,backdropInvert:/^backdrop-invert-/,backdropOpacity:/^backdrop-opacity-/,backdropSaturate:/^backdrop-saturate-/,backdropSepia:/^backdrop-sepia-/,scale:/^scale(-x|-y)?-/,rotate:/^-?rotate-/,translate:/^-?translate-[xy]-/,skew:/^-?skew-[xy]-/,transformOrigin:/^origin-/,transition:/^transition(-none|-all|-colors|-opacity|-shadow|-transform)?$/,duration:/^duration-/,ease:/^ease-(linear|in|out|in-out)$/,delay:/^delay-/,animate:/^animate-/,cursor:/^cursor-/,userSelect:/^select-/,pointerEvents:/^pointer-events-/,resize:/^resize(-none|-x|-y)?$/,scrollBehavior:/^scroll-(auto|smooth)$/,touchAction:/^touch-/,overflow:/^overflow(-x|-y)?-(auto|hidden|clip|visible|scroll)$/,overscroll:/^overscroll(-x|-y)?-(auto|contain|none)$/,visibility:/^(visible|invisible|collapse)$/,aspectRatio:/^aspect-/,columns:/^columns-/,breakAfter:/^break-after-/,breakBefore:/^break-before-/,breakInside:/^break-inside-/,boxDecorationBreak:/^box-decoration-/,boxSizing:/^box-(border|content)$/,float:/^float-(right|left|none)$/,clear:/^clear-(left|right|both|none)$/,isolation:/^(isolate|isolation-auto)$/,objectFit:/^object-(contain|cover|fill|none|scale-down)$/,objectPosition:/^object-/};function lx(r){const e=r.replace(/^(dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+/,"");for(const[t,a]of Object.entries(Bk))if(a.test(e))return t;return null}function cx(r){const e=r.match(/^((dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+)/);return e?e[1]:""}function Uk(r,e){if(!e||e.trim()==="")return r;if(!r||r.trim()==="")return e;const t=r.split(/\s+/).filter(Boolean),a=e.split(/\s+/).filter(Boolean),i=new Map;for(const d of a){const g=lx(d);if(g){const h=cx(d),f=`${g}:${h}`;i.set(f,d)}}return[...t.filter(d=>{const g=lx(d);if(!g)return!0;const h=cx(d),f=`${g}:${h}`;return!i.has(f)}),...a].join(" ")}function qk(r){return Object.entries(r).filter(([,e])=>e).map(([e])=>e).join(" ")}function Gk(...r){return r.filter(e=>typeof e=="string"&&e.length>0).join(" ")}const Ee=it("G7CoreGlobals");function Fk(){window.React=Ke,window.ReactDOM={...Hu,createPortal:Os.createPortal,unstable_batchedUpdates:r=>r()},window.ReactJSXRuntime=u7,Ee.log("전역 객체 window.React, window.ReactDOM, window.ReactJSXRuntime에 노출됨")}function Vk(r){const e=new Map,t=ka.getInstance();r.componentEvent={on:(a,i)=>(e.has(a)||e.set(a,new Set),e.get(a).add(i),t.trackEventSubscribe(a),()=>{e.get(a)?.delete(i),t.trackEventUnsubscribe(a)}),emit:async(a,i)=>{const o=e.get(a),d=o?.size??0;if(!o||o.size===0)return t.trackEventEmit(a,i,0),[];let g,h=[];try{h=await Promise.all(Array.from(o).map(async f=>{try{return await f(i)}catch(p){throw Ee.error(`componentEvent: Error in listener for "${a}":`,p),p}}))}catch(f){g=f instanceof Error?f:new Error(String(f))}if(t.trackEventEmit(a,i,d,h,g),g)throw g;return h},off:a=>{e.delete(a),t.trackEventOff(a)},clear:()=>{e.clear(),t.trackEventClear()}},Ee.log("전역 객체 window.G7Core.componentEvent에 노출됨")}function Kk(r,e){r.useTranslation=Tj,r.t=(t,a)=>{const i=e.getState();if(!i.translationEngine||!i.translationContext)return t;if(a){const o="|"+Object.entries(a).map(([d,g])=>`${d}=${g}`).join("|");return i.translationEngine.translate(t,i.translationContext,o)}return i.translationEngine.translate(t,i.translationContext)},Ee.log("전역 객체 window.G7Core.useTranslation에 노출됨")}function Wk(r,e){r.createChangeEvent=Ik,r.createClickEvent=zk,r.createSubmitEvent=Hk,r.createKeyboardEvent=Pk,r.uuid=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const a=Math.random()*16|0;return(t==="x"?a:a&3|8).toString(16)}),r.createLogger=it,Ee.log("전역 객체 window.G7Core.createLogger에 노출됨"),r.renderItemChildren=(t,a,i,o,d)=>{const g=e.getState(),p={_global:window.__templateApp?.getGlobalState?.()||{},_local:a._local||{},_computed:a._computed||{},...a},y=new Set,x=(v,w)=>{const k=p._global?._remountKeys;return v&&k?.[v]&&!y.has(v)?(y.add(v),`${v}-remount-${k[v]}`):v||w},S={translationContext:g.translationContext,translationEngine:g.translationEngine,bindingEngine:g.bindingEngine,actionDispatcher:g.actionDispatcher,getRemountKey:x,...d};return fo(t,p,i,o,S)},r.getComponentMap=()=>ba.getInstance().getComponentMap(),r.renderComponentLayout=(t,a,i)=>{if(!t||!Array.isArray(t)||t.length===0)return null;const o=ba.getInstance().getComponentMap(),d=e.getState(),h=window.__templateApp?.getGlobalState?.()||{},f={_global:h._global||{},_local:h._local||{},_computed:h._computed||{},...a},p=new Set,y=(x,S)=>{const v=f._global?._remountKeys;return x&&v?.[x]&&!p.has(x)?(p.add(x),`${x}-remount-${v[x]}`):x||S};return fo(t,f,o,i,{translationContext:d.translationContext,translationEngine:d.translationEngine,bindingEngine:d.bindingEngine,actionDispatcher:d.actionDispatcher,getRemountKey:y})},r.renderExpandContent=t=>{const{children:a,row:i,expandContext:o,componentContext:d,keyPrefix:g}=t;if(!a||!Array.isArray(a)||a.length===0)return null;const h=t.componentMap||ba.getInstance().getComponentMap(),f=e.getState(),p=r.state?.get?.()||{},y=d?.stateRef?.current??d?.state??{},x={...p._local||{},...y},S=d?.computedRef?.current??p._computed??{},v=f.bindingEngine??r.getDataBindingEngine?.(),w={...p,_local:x,_computed:S,row:i,item:i,$item:i};let k={};if(o&&typeof o=="object"&&v)try{for(const[D,$]of Object.entries(o))if(typeof $=="string"){const M=$.match(/^\{\{([^}]+)\}\}$/);if(M){const z=M[1].trim();try{k[D]=v.evaluateExpression(z,w,{skipCache:!0})}catch{k[D]=void 0}}else k[D]=v.resolveBindings($,w,{skipCache:!0})}else k[D]=$}catch(D){Ee.warn("renderExpandContent: expandContext 평가 오류:",D)}const A={row:i,item:i,$item:i,_local:x,_global:p._global||{},_computed:p._computed||{},...k},O=new Set,N=(D,$)=>{const M=A._global?._remountKeys;return D&&M?.[D]&&!O.has(D)?(O.add(D),`${D}-remount-${M[D]}`):D||$};return fo(a,A,h,g,{translationContext:f.translationContext,translationEngine:f.translationEngine??void 0,bindingEngine:f.bindingEngine??void 0,actionDispatcher:f.actionDispatcher,componentContext:d,getRemountKey:N})},r.$get=function(a,i,o=void 0){if(a==null)return o;const d=Array.isArray(i)?i:[i];if(d.length===0)return a;let g=a;for(const h of d){if(g==null||h==null)return o;g=g[h]}return g??o},Ee.log("전역 객체 window.G7Core.renderItemChildren에 노출됨"),Ee.log("전역 객체 window.G7Core.renderComponentLayout에 노출됨"),Ee.log("전역 객체 window.G7Core.renderExpandContent에 노출됨"),Ee.log("전역 객체 window.G7Core.$get에 노출됨")}function Yk(r){r.dispatch=async(e,t)=>{const a=window.__templateApp;if(!a)return Ee.warn("G7Core.dispatch: TemplateApp이 초기화되지 않았습니다."),{success:!1,error:new Error("TemplateApp이 초기화되지 않았습니다.")};const i=a.getActionDispatcher?.();if(!i)return Ee.warn("G7Core.dispatch: ActionDispatcher를 찾을 수 없습니다."),{success:!1,error:new Error("ActionDispatcher를 찾을 수 없습니다.")};const o=a.getRouter?.(),d=a.getGlobalState?.(),g=a.setGlobalState?.bind(a),f=t?.componentContext||window.__g7ActionContext,p=window.__g7PendingLocalState;let y=f?.state??d;p&&f&&(y=p,Ee.log("[dispatch] Using __g7PendingLocalState for context.state:",p));let x=f?.data??d;p&&f?.data?._local&&(x={...f.data,_local:p},Ee.log("[dispatch] Updated context.data._local with pendingLocalState"));const S={navigate:o?(v,w)=>o.navigate(v,w):void 0,setState:f?.setState??g,state:y,data:x,_isDispatchFallbackContext:!f?.setState};if(e.debounce){const v=e.debounceKey||`dispatch-${e.handler}`,w=typeof e.debounce=="number"?e.debounce:e.debounce.delay;return i.debouncedCall(v,w,()=>{const{debounce:k,debounceKey:A,...O}=e;i.dispatchAction(O,S)}),{success:!0,debounced:!0}}try{return await i.dispatchAction(e,S)}catch(v){return Ee.error("G7Core.dispatch: 액션 실행 오류:",v),{success:!1,error:v instanceof Error?v:new Error(String(v))}}},Ee.log("전역 객체 window.G7Core.dispatch에 노출됨")}function Hc(r){const e={};for(const[t,a]of Object.entries(r))if(t.includes(".")){const i=t.split(".");let o=e;for(let d=0;d0&&e.every(t=>/^\d+$/.test(t))}function dx(r,e){const t={...r};for(const a of Object.keys(e))a in t?t[a]!==null&&typeof t[a]=="object"&&!Array.isArray(t[a])&&e[a]!==null&&typeof e[a]=="object"&&!Array.isArray(e[a])&&(t[a]=dx(t[a],e[a])):t[a]=e[a];return t}function ia(r,e){if(Array.isArray(r)&&!Array.isArray(e)&&Jk(e)){const a=Object.keys(e).map(o=>parseInt(o,10));if(!((a.length>0?Math.max(...a):0)>=r.length+a.length+10)){const o=[...r];for(const[d,g]of Object.entries(e)){const h=parseInt(d,10);h>=0&&h=o.length&&(o[h]=g)}return o}}const t={...r};for(const[a,i]of Object.entries(e))i!==null&&typeof i=="object"&&!Array.isArray(i)?t[a]!==null&&typeof t[a]=="object"?t[a]=ia(t[a],i):t[a]={...i}:t[a]=i;return t}function Xk(r){r.state={get:()=>window.__templateApp?.getGlobalState?.()||{},set:(e,t)=>{const a=window.__templateApp;if(a?.setGlobalState&&a?.getGlobalState){const i=t?.merge||"deep",o=Hc(e);let d;if(i==="replace")d=o;else if(i==="shallow")d={...a.getGlobalState(),...o};else{const g=a.getGlobalState();d=ia(g,o)}a.setGlobalState(d,{render:t?.render})}else Ee.warn("G7Core.state.set: TemplateApp이 초기화되지 않았습니다.")},setLocal:(e,t)=>{const a=window.__templateApp;if(t?.debounce){const k=a?.getActionDispatcher?.();if(k){const A=t.debounceKey||`setLocal-${Object.keys(e).join(",")}`,{debounce:O,debounceKey:N,...D}=t;k.debouncedCall(A,t.debounce,()=>{r.state.setLocal(e,D)});return}}const i=t?.scope??"current",o=t?.merge||"deep",d=window.__g7ActionContext,g=Hc(e);if(i==="parent"||i==="root"){const k=window.__g7LayoutContextStack||[];if(k.length>0){const A=i==="parent"?k[k.length-1]:k[0];if(A?.setState){A.setState(O=>o==="replace"?g:o==="shallow"?{...O||{},...g}:ia(O||{},g)),Ee.log(`[setLocal] scope=${i}: 타겟 컨텍스트에 상태 업데이트 (mergeMode=${o})`,g);return}}Ee.warn(`[setLocal] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const h=window.__g7PendingLocalState,f=a?.getGlobalState?.()?._local||{},x=!((window.__g7LayoutContextStack||[]).length>0)&&d?.state?d.state:void 0,S=x?dx(f,x):f,v=h||S;let w;if(o==="replace"?w=g:o==="shallow"?w={...v,...g}:w=ia(v,g),a?.setGlobalState&&(a.setGlobalState({_local:w},{render:t?.render}),Ee.log(`[setLocal] globalLocal updated via setGlobalState (mergeMode=${o}, render=${t?.render??!0}):`,g)),window.__g7PendingLocalState=w,Ee.log("[setLocal] __g7PendingLocalState updated:",w),window.__g7SequenceLocalSync=w,window.__g7LastSetLocalSnapshot=w,o==="replace")window.__g7ForcedLocalFields=g;else{const k=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=ia(k,g)}if(Ee.log("[setLocal] __g7ForcedLocalFields updated:",g),o==="replace")window.__g7SetLocalOverrideKeys=g;else{const k=window.__g7SetLocalOverrideKeys||{};window.__g7SetLocalOverrideKeys=ia(k,g)}Ee.log("[setLocal] __g7SetLocalOverrideKeys updated:",g),d?.setState&&d.setState(k=>o==="replace"?g:o==="shallow"?{...k||{},...g}:ia(k||{},g)),a?.setGlobalState||Ee.warn("G7Core.state.setLocal: TemplateApp이 없습니다.")},getLocal:()=>{const a=(window.__templateApp?.getGlobalState?.()||{})._local||{},i=window.__g7PendingLocalState;if(i)return ia(a,i);const o=window.__g7LastSetLocalSnapshot;return o&&o!==a?ia(a,o):a},update:e=>{const t=window.__templateApp;if(t?.getGlobalState&&t?.setGlobalState){const a=t.getGlobalState(),i=e(a);t.setGlobalState(i)}else Ee.warn("G7Core.state.update: TemplateApp이 초기화되지 않았습니다.")},subscribe:e=>{const t=window.__templateApp;return t?.onGlobalStateChange?t.onGlobalStateChange(e):(Ee.warn("G7Core.state.subscribe: TemplateApp이 초기화되지 않았습니다."),()=>{})},getDataSource:e=>window.__templateApp?.getDataSource?.(e),getIsolated:e=>e?window.__g7IsolatedStates?.[e]?.state??null:window.__g7ActionContext?.isolatedContext?.state??null,setIsolated:(e,t,a)=>{let i,o,d;typeof e=="string"?(i=e,o=t||{},d=a):(o=e,d=t&&typeof t=="object"&&"merge"in t?t:a);const g=d?.merge||"deep",h=Hc(o);if(i){const y=window.__g7IsolatedStates?.[i];y?.mergeState?y.mergeState(h,g):Ee.warn(`G7Core.state.setIsolated: scopeId '${i}'를 찾을 수 없습니다.`);return}const f=window.__g7ActionContext;f?.isolatedContext?.mergeState?f.isolatedContext.mergeState(h,g):Ee.warn("G7Core.state.setIsolated: 액션 컨텍스트에 isolatedContext가 없습니다.")},getParent:()=>{const e=window.__g7LayoutContextStack||[];if(e.length===0)return Ee.log("[getParent] 레이아웃 컨텍스트 스택이 비어있습니다."),null;const t=e[e.length-1];if(!t)return null;const a=t.dataContext||{};return{_local:t.state||a._local||{},_global:a._global||r.state.get()||{},setState:t.setState}},setParentLocal:(e,t,a)=>{const i=window.__g7LayoutContextStack||[];if(i.length===0){Ee.warn("[setParentLocal] 레이아웃 컨텍스트 스택이 비어있습니다.");return}const o=i[i.length-1];if(!o?.setState){Ee.warn("[setParentLocal] 부모 컨텍스트에 setState가 없습니다.");return}let d,g;typeof e=="string"?(d={[e]:t},g=a):(d=e,g=t&&typeof t=="object"&&"merge"in t?t:a);const h=g?.merge||"deep",f=Hc(d),p=o.state?._local!==void 0,y=p?o.state._local:o.state||{};let x;h==="replace"?x=f:h==="shallow"?x={...y,...f}:x=ia(y,f),window.__g7PendingLocalState=x;const S=window.__templateApp;if(S?.setGlobalState&&S.setGlobalState({_local:x}),o.setState(x),p?o.state._local=x:o.state=x,o.dataContext&&(o.dataContext._local=x),h==="replace")window.__g7ForcedLocalFields=f;else{const v=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=ia(v,f)}dg()},setParentGlobal:(e,t)=>{let a;typeof e=="string"?a={[e]:t}:a=e,r.state.set(a),Ee.log("[setParentGlobal] 전역 상태 업데이트:",a)}},window.__g7IsolatedStates||(window.__g7IsolatedStates={}),r.state.getGlobal=r.state.get,r.state.setGlobal=r.state.set,Ee.log("전역 객체 window.G7Core.state에 노출됨")}function Qk(r){r.dataSource={get:e=>window.__templateApp?.getDataSource?.(e),set:(e,t,a)=>{const i=window.__templateApp;i?.setDataSource?i.setDataSource(e,t,a):Ee.warn("G7Core.dataSource.set: TemplateApp이 초기화되지 않았습니다.")},refetch:async(e,t)=>{const a=window.__templateApp;if(a?.refetchDataSource)return a.refetchDataSource(e,t);Ee.warn("G7Core.dataSource.refetch: TemplateApp이 초기화되지 않았습니다.")},updateItem:(e,t,a,i,o)=>{const d=window.__templateApp;return d?.updateDataSourceItem?d.updateDataSourceItem(e,t,a,i,o):(Ee.warn("G7Core.dataSource.updateItem: TemplateApp이 초기화되지 않았습니다."),!1)},updateData:(e,t,a,i="append")=>{const o=window.__templateApp;if(!o?.getDataSource||!o?.setDataSource)return Ee.warn("G7Core.dataSource.updateData: TemplateApp이 초기화되지 않았습니다."),!1;const d=o.getDataSource(e);if(!d)return Ee.warn(`G7Core.dataSource.updateData: 데이터 소스 '${e}'를 찾을 수 없습니다.`),!1;let g,h=d,f=null;if(t){const y=t.split(".");f=y.pop();for(const x of y)if(h&&typeof h=="object"&&x in h)h=h[x];else return Ee.warn(`G7Core.dataSource.updateData: 경로 '${t}'를 찾을 수 없습니다.`),!1;g=h[f]}else g=d;if(!Array.isArray(g))return Ee.warn("G7Core.dataSource.updateData: 대상 경로의 데이터가 배열이 아닙니다."),!1;if(!Array.isArray(a))return Ee.warn("G7Core.dataSource.updateData: newData가 배열이 아닙니다."),!1;const p=i==="prepend"?[...a,...g]:[...g,...a];return t&&f?(h[f]=p,o.setDataSource(e,d,{merge:!1})):o.setDataSource(e,p,{merge:!1}),Ee.log(`G7Core.dataSource.updateData: '${e}'에 ${a.length}개 항목 ${i==="prepend"?"앞에":"뒤에"} 추가됨`),!0}},Ee.log("전역 객체 window.G7Core.dataSource에 노출됨")}function Zk(r,e){r.locale={current:()=>window.__templateApp?.getLocale?.()||"ko",supported:()=>e.getState().templateMetadata?.locales||["ko","en"],change:async t=>{const a=window.__templateApp;a?.changeLocale?await a.changeLocale(t):Ee.warn("G7Core.locale.change: TemplateApp이 초기화되지 않았습니다.")}},Ee.log("전역 객체 window.G7Core.locale에 노출됨")}function eN(r){r.toast={show:(e,t)=>{r.dispatch({handler:"toast",params:{message:e,type:t?.type||"info",...t?.duration&&{duration:t.duration}}})},success:(e,t)=>{r.toast.show(e,{type:"success",duration:t})},error:(e,t)=>{r.toast.show(e,{type:"error",duration:t})},warning:(e,t)=>{r.toast.show(e,{type:"warning",duration:t})},info:(e,t)=>{r.toast.show(e,{type:"info",duration:t})}},Ee.log("전역 객체 window.G7Core.toast에 노출됨")}function tN(r){r.modal={open:e=>{r.dispatch({handler:"openModal",target:e})},close:e=>{r.dispatch({handler:"closeModal",...e&&{target:e}})},closeAll:()=>{r.dispatch({handler:"closeAllModals"})},isOpen:e=>{const t=r.state.get();return t._global?.activeModal===e||t._global?.modalStack?.includes(e)||!1},getStack:()=>r.state.get()._global?.modalStack||[]},Ee.log("전역 객체 window.G7Core.modal에 노출됨")}function nN(r){r.style={mergeClasses:Uk,conditionalClass:qk,joinClasses:Gk},Ee.log("전역 객체 window.G7Core.style에 노출됨")}function aN(r,e){const{webSocketManager:t}=e;r.websocket={manager:t,subscribe:(a,i,o,d)=>t.subscribe(a,i,o,d),unsubscribe:a=>t.unsubscribe(a),leaveChannel:a=>t.leaveChannel(a),disconnect:()=>t.disconnect(),isInitialized:()=>t.isInitialized(),getSubscriptionCount:()=>t.getSubscriptionCount()},Ee.log("전역 객체 window.G7Core.websocket에 노출됨")}function sN(r,e){const{transitionManager:t}=e;r.navigation={isPending:()=>t?.getIsPending?.()||!1,onComplete:a=>{if(!t)return a(),()=>{};let i=t.getIsPending();const o=t.subscribe(d=>{d?i=!0:i&&(a(),o())});return o}},Ee.log("전역 객체 window.G7Core.navigation에 노출됨")}function rN(r){r.plugin={getSettings:e=>window.G7Config?.plugins?.[e],get:(e,t,a)=>window.G7Config?.plugins?.[e]?.[t]??a,getAll:()=>window.G7Config?.plugins??{}},Ee.log("전역 객체 window.G7Core.plugin에 노출됨")}function iN(r){r.module={getSettings:e=>window.G7Config?.modules?.[e],get:(e,t,a)=>window.G7Config?.modules?.[e]?.[t]??a,getAll:()=>window.G7Config?.modules??{}},Ee.log("전역 객체 window.G7Core.module에 노출됨")}function oN(r,e){const{transitionManager:t,responsiveManager:a}=e;r.AuthManager=as,r.api=ns(),r.TransitionManager=t,r.useTransitionState=Wm,r.ResponsiveManager=a,r.useResponsive=Xm,r.useControllableState=y7,r.shallowArrayEqual=x7,r.shallowObjectEqual=Qm,r.updateQueryParams=async(i,o)=>{const d=window.__templateApp;if(d?.updateQueryParams)return d.updateQueryParams(i,o);Ee.warn("G7Core.updateQueryParams: TemplateApp이 초기화되지 않았습니다.")},Ee.log("전역 객체 window.G7Core.AuthManager에 노출됨"),Ee.log("전역 객체 window.G7Core.api에 노출됨"),Ee.log("전역 객체 window.G7Core.ResponsiveManager에 노출됨"),Ee.log("전역 객체 window.G7Core.useResponsive에 노출됨"),Ee.log("전역 객체 window.G7Core.useControllableState에 노출됨"),Ee.log("전역 객체 window.G7Core.updateQueryParams에 노출됨")}function lN(r,e){r.getSlotContext=()=>window.__slotContextValue??null,r.getDynamicRenderer=()=>window.__DynamicRenderer??null,r.getComponentRegistry=()=>e.getComponentRegistry?.()??ba.getInstance(),r.getDataBindingEngine=()=>e.getDataBindingEngine?.()??e.getState().bindingEngine,r.getTranslationEngine=()=>e.getTranslationEngine?.()??e.getState().translationEngine,r.getActionDispatcher=()=>e.getActionDispatcher?.()??e.getState().actionDispatcher,Ee.log("전역 객체 window.G7Core 슬롯 API에 노출됨 (getSlotContext, getDynamicRenderer 등)")}function cN(r){let e=!1,t=null,a=null;r.wysiwyg={isEditMode:()=>e,setEditMode:(i,o)=>{e=!0,t=i,a=o,Ee.log(`위지윅 편집 모드 활성화: ${i} (${o})`)},clearEditMode:()=>{e=!1,t=null,a=null,Ee.log("위지윅 편집 모드 비활성화")},getCurrentLayoutName:()=>t,getCurrentTemplateId:()=>a,isEditModeFromUrl:()=>typeof window>"u"?!1:new URLSearchParams(window.location.search).get("mode")==="edit",getEditModeUrl:(i,o)=>{const d=window.location.origin,g=i.startsWith("/")?i:`/${i}`;return`${d}${g}?mode=edit&template=${encodeURIComponent(o)}`},enterEditMode:(i,o)=>{if(typeof window>"u")return;const d=r.wysiwyg.getEditModeUrl(i,o);window.location.href=d},exitEditMode:()=>{if(typeof window>"u")return;const i=new URLSearchParams(window.location.search);i.delete("mode"),i.delete("template");const o=`${window.location.pathname}${i.toString()?"?"+i.toString():""}`;window.location.href=o},getVersion:()=>"1.0.0",getPhase:()=>1},Ee.log("전역 객체 window.G7Core 위지윅 편집기 API에 노출됨 (wysiwyg)")}function dN(r){if(typeof window>"u")return;Fk(),window.G7Core||(window.G7Core={});const e=window.G7Core;Vk(e),oN(e,r),Kk(e,r),Wk(e,r),Yk(e),Xk(e),Qk(e),Zk(e,r),eN(e),tN(e),nN(e),aN(e,r),sN(e,r),rN(e),iN(e),lN(e,r),cN(e),Ee.log("G7Core 전역 객체 초기화 완료")}function uN(){const r=window.G7Core;if(!r){Ee.warn("G7Core가 초기화되지 않았습니다.");return}const e=()=>ka.getInstance(),t={isEnabled:()=>{try{return e().isEnabled()}catch{return!1}},trackRender:a=>{try{e().isEnabled()&&e().trackRender(a)}catch{}},trackIteration:(a,i,o,d,g)=>{try{e().isEnabled()&&e().trackIteration(a,{source:i,itemVar:o,indexVar:d,sourceLength:g})}catch{}},trackIfCondition:(a,i,o,d)=>{try{e().isEnabled()&&e().trackIfCondition(a,i,o)}catch{}},trackMount:(a,i)=>{try{e().isEnabled()&&e().trackMount(a,{...i,id:a})}catch{}},trackUnmount:a=>{try{e().isEnabled()&&e().trackUnmount(a)}catch{}},trackExpressionEval:a=>{try{e().isEnabled()&&e().trackExpressionEval(a)}catch{}},trackBindingEval:a=>{try{e().isEnabled()&&e().trackBindingEval(a)}catch{}},recordCacheHit:()=>{try{e().isEnabled()&&e().recordCacheHit()}catch{}},recordCacheMiss:()=>{try{e().isEnabled()&&e().recordCacheMiss()}catch{}},trackHandlerRegistration:(a,i,o,d)=>{try{e().isEnabled()&&e().trackHandlerRegistration(a,i,o,d)}catch{}},trackHandlerUnregistration:a=>{try{e().isEnabled()&&e().trackHandlerUnregistration(a)}catch{}},logAction:a=>{try{e().isEnabled()&&e().logAction(a)}catch{}},trackRequest:(a,i)=>{try{return e().isEnabled()?e().trackRequest(a,i):""}catch{return""}},completeRequest:(a,i,o)=>{try{e().isEnabled()&&e().completeRequest(a,i,o)}catch{}},failRequest:(a,i)=>{try{e().isEnabled()&&e().failRequest(a,i)}catch{}},trackDataSourceDefinition:a=>{try{e().isEnabled()&&e().trackDataSourceDefinition(a)}catch{}},trackDataSourceLoading:a=>{try{e().isEnabled()&&e().trackDataSourceLoading(a)}catch{}},trackDataSourceLoaded:(a,i,o)=>{try{e().isEnabled()&&e().trackDataSourceLoaded(a,i,o)}catch{}},trackDataSourceError:(a,i)=>{try{e().isEnabled()&&e().trackDataSourceError(a,i)}catch{}},trackForm:(a,i,o)=>{try{e().isEnabled()&&e().trackForm(a,i,o)}catch{}},untrackForm:a=>{try{e().isEnabled()&&e().untrackForm(a)}catch{}},startStateChange:(a,i,o,d)=>{try{return e().isEnabled()?e().startStateChange(a,i,o,d):""}catch{return""}},completeStateChange:a=>{try{e().isEnabled()&&e().completeStateChange(a)}catch{}},trackComponentRender:(a,i,o,d,g,h)=>{try{e().isEnabled()&&e().trackComponentRender(a,i,o,d,g,h)}catch{}},updateLocalState:a=>{try{e().isEnabled()&&e().updateLocalState(a)}catch{}},updateComputedState:a=>{try{e().isEnabled()&&e().updateComputedState(a)}catch{}},updateParentContext:a=>{try{e().isEnabled()&&e().updateParentContext(a)}catch{}},trackComponentStateSource:(a,i,o,d)=>{try{e().isEnabled()&&e().trackComponentStateSource(a,i,o,d)}catch{}},trackDynamicState:(a,i)=>{try{e().isEnabled()&&e().trackDynamicState(a,i)}catch{}},trackContextFlow:(a,i,o,d,g,h)=>{try{e().isEnabled()&&e().trackContextFlow(a,i,o,d,g,h)}catch{}},trackComponentStyle:(a,i,o,d)=>{try{e().isEnabled()&&e().trackComponentStyle(a,i,o,d)}catch{}},trackAuthEvent:(a,i,o,d)=>{try{e().isEnabled()&&e().trackAuthEvent(a,i,o,d)}catch{}},trackAuthHeader:(a,i,o,d,g)=>{try{e().isEnabled()&&e().trackAuthHeader(a,i,o,d,g)}catch{}},trackLog:(a,i,o)=>{try{e().isEnabled()&&e().trackLog(a,i,o)}catch{}},trackAction:a=>{try{e().isEnabled()&&e().trackAction?.(a)}catch{}},trackDataSourceUpdate:a=>{try{e().isEnabled()&&e().trackDataSourceUpdate?.(a)}catch{}},startSequenceExecution:a=>{try{return e().isEnabled()?e().startSequenceExecution(a):""}catch{return""}},captureSequenceActionBefore:(a,i,o,d,g)=>{try{e().isEnabled()&&e().captureSequenceActionBefore(a,i,o,d,g)}catch{}},captureSequenceActionAfter:(a,i,o,d,g,h)=>{try{e().isEnabled()&&e().captureSequenceActionAfter(a,i,o,d,g,h)}catch{}},endSequenceExecution:(a,i)=>{try{e().isEnabled()&&e().endSequenceExecution(a,i)}catch{}},registerStateCaptureForHandler:(a,i,o)=>{try{e().isEnabled()&&e().registerStateCaptureForHandler(a,i,o)}catch{}},detectStaleClosure:(a,i,o,d,g)=>{try{return e().isEnabled()?e().detectStaleClosure(a,i,o,d,g):[]}catch{return[]}},trackStaleClosureWarning:a=>{try{e().isEnabled()&&e().trackStaleClosureWarning(a)}catch{}},trackModalOpen:a=>{try{e().isEnabled()&&e().trackModalOpen(a)}catch{}},trackModalClose:(a,i)=>{try{e().isEnabled()&&e().trackModalClose(a,i)}catch{}},trackModalStateChange:a=>{try{e().isEnabled()&&e().trackModalStateChange(a)}catch{}},trackNestedContext:a=>{try{return e().isEnabled()?e().trackNestedContext(a):""}catch{return""}},trackNestedContextAccess:(a,i)=>{try{e().isEnabled()&&e().trackNestedContextAccess(a,i)}catch{}},trackComputedProperty:(a,i,o,d,g,h,f)=>{try{e().isEnabled()&&e().trackComputedProperty(a,i,o,d,g,h,f)}catch{}},trackComputedRecalc:(a,i,o,d,g,h,f)=>{try{e().isEnabled()&&e().trackComputedRecalc(a,i,o,d,g,h,f)}catch{}},setNamedActionDefinitions:a=>{try{e().isEnabled()&&e().setNamedActionDefinitions(a)}catch{}},trackNamedActionRef:a=>{try{e().isEnabled()&&e().trackNamedActionRef(a)}catch{}}};r.devTools=t,Ee.log("G7Core.devTools 인터페이스 초기화 완료")}function gN(){const r=window.G7Core;if(!r){Ee.warn("G7Core가 초기화되지 않았습니다.");return}const e=ka.getInstance();if(e.initialize(),!e.isEnabled()){window.G7DevTools={isEnabled:()=>!1,enable:()=>{Ee.log("환경설정 > 고급 설정 > 디버그 모드를 켜세요")}},Hp(),Ee.log("G7DevTools 비활성화됨 (디버그 모드 꺼짐)");return}uN(),Hp();try{$k().enable(),Ee.log("StyleTracker 활성화됨")}catch(o){Ee.warn("StyleTracker 활성화 실패:",o)}const t=new ex,a=tx(),i={isEnabled:()=>e.isEnabled(),state:{get:()=>e.getState(),getHistory:()=>e.getStateHistory(),watch:(o,d)=>e.watchState(o,d)},actions:{getHistory:()=>e.getActionHistory(),watch:o=>e.watchActions(o),getMetrics:()=>e.getActionMetrics()},binding:{evaluate:o=>{const d=r.getDataBindingEngine?.();if(!d){Ee.warn("DataBindingEngine이 없습니다.");return}return d.evaluateExpression(o,e.getState())},getCacheStats:()=>e.getCacheStats(),clearStats:()=>{e.resetCacheStats(),Ee.log("캐시 통계 초기화됨")}},diagnose:{analyze:o=>t.analyze(o),suggestFix:o=>t.suggestFix(o),getCommonIssues:()=>t.getCommonIssues(),getRulesByCategory:o=>t.getRulesByCategory(o)},server:{dumpState:o=>a.dumpState(o),sendLog:o=>a.sendLog(o),sendError:(o,d)=>a.sendError(o,d),isConnected:()=>a.isConnected(),testConnection:()=>a.testConnection()},config:{isDebugMode:()=>e.isEnabled(),setLogLevel:o=>e.setLogLevel(o),setMaxHistory:o=>e.setMaxHistory(o)},lifecycle:{getMountedComponents:()=>e.getLifecycleInfo().mountedComponents,getOrphanedListeners:()=>e.getLifecycleInfo().orphanedListeners},performance:{getRenderCount:()=>e.getPerformanceInfo().renderCounts,getBindingEvalCount:()=>e.getPerformanceInfo().bindingEvalCount,getMemoryWarnings:()=>e.getPerformanceInfo().memoryWarnings,startProfiling:()=>e.startProfiling(),stopProfiling:()=>e.stopProfiling()},network:{getActiveRequests:()=>e.getNetworkInfo().activeRequests,getRequestHistory:()=>e.getNetworkInfo().requestHistory,getPendingDataSources:()=>e.getNetworkInfo().pendingDataSources},conditional:{getIfConditions:()=>e.getConditionalInfo().ifConditions,getIterations:()=>e.getConditionalInfo().iterations},form:{getForms:()=>e.getFormInfo()},websocket:{getInfo:()=>e.getWebSocketInfo()}};window.G7DevTools=i,r.devtools=i,Ee.log("G7DevTools 전역 객체 초기화 완료 (window.G7DevTools)"),hN()}function hN(){if(document.getElementById("g7-devtools-root")){Ee.log("DevToolsPanel 이미 렌더링됨");return}const r=document.createElement("div");r.id="g7-devtools-root",document.body.appendChild(r);try{Hu.createRoot(r).render(Ke.createElement(Lk)),Ee.log("DevToolsPanel UI 렌더링 완료")}catch(e){Ee.error("DevToolsPanel UI 렌더링 실패:",e)}}const et=it("TemplateEngine"),ue={templateId:null,locale:"ko",isInitialized:!1,reactRoot:null,containerId:null,currentLayoutJson:null,currentDataContext:{},translationContext:{templateId:"",locale:"ko"},registry:null,bindingEngine:null,translationEngine:null,actionDispatcher:null,templateMetadata:null};let Pc=!1;const Lo=[];async function fN(r){try{et.log("템플릿 메타데이터 로드 중...",r);const e=r.split("-").map(a=>a.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join("")).join(""),t=window[e];return t?.templateMetadata?(et.log("템플릿 메타데이터 로드 완료 (전역 변수)",t.templateMetadata),t.templateMetadata):(et.warn(`템플릿 번들에 메타데이터가 없습니다. 전역 변수: ${e}`),{identifier:r,locales:["ko","en"],name:{ko:r,en:r},description:{ko:"",en:""},version:"1.0.0",type:"admin"})}catch(e){return et.error("템플릿 메타데이터 로드 실패",e),{identifier:r,locales:["ko","en"],name:{ko:r,en:r},description:{ko:"",en:""},version:"1.0.0",type:"admin"}}}function ux(){return{$locale:ue.locale,$locales:ue.templateMetadata?.locales||["ko","en"],$templateId:ue.templateId}}async function Mo(r){try{if(et.log("템플릿 엔진 초기화 시작",r),ue.isInitialized)throw new Error("템플릿 엔진이 이미 초기화되었습니다. destroyTemplate()을 먼저 호출하세요.");if(!r.templateId)throw new Kj;Pc=r.debug??!1,typeof window<"u"&&(window.G7Config||(window.G7Config={}),window.G7Config.debug=Pc),gN(),ue.templateId=r.templateId,ue.locale=r.locale||"ko",et.log("엔진 인스턴스 생성 중..."),ue.registry=ba.getInstance(),ue.bindingEngine=new _n,ue.translationEngine=xr.getInstance(),r.cacheVersion!==void 0&&r.cacheVersion>0&&ue.translationEngine.setCacheVersion(r.cacheVersion),ue.translationContext={templateId:r.templateId,locale:ue.locale},ue.actionDispatcher=new So({},ue.translationEngine,ue.translationContext),f7(ue.actionDispatcher),et.log("다국어 파일 로드 중...",r.templateId,ue.locale);const e="en",t=[ue.translationEngine.loadTranslations(r.templateId,ue.locale).then(()=>{et.log(`다국어 파일 로드 완료: ${ue.locale}`)}).catch(a=>{et.warn(`다국어 파일 로드 실패 (${ue.locale}):`,a instanceof Error?a.message:a)})];ue.locale!==e&&t.push(ue.translationEngine.loadTranslations(r.templateId,e).then(()=>{et.log(`폴백 다국어 파일 로드 완료: ${e}`)}).catch(a=>{et.warn(`폴백 다국어 파일 로드 실패 (${e}):`,a instanceof Error?a.message:a)})),await Promise.allSettled(t),et.log("템플릿 메타데이터 로드 중...",r.templateId),ue.templateMetadata=await fN(r.templateId),ue.isInitialized=!0,et.log("템플릿 엔진 초기화 완료 (ComponentRegistry는 별도 로드)")}catch(e){throw et.error("템플릿 엔진 초기화 실패",e),ue.isInitialized=!1,ue.registry=null,ue.bindingEngine=null,ue.translationEngine=null,ue.actionDispatcher=null,e}}async function $o(r){try{if(et.log("템플릿 렌더링 시작",r),!ue.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다. initTemplateEngine()을 먼저 호출하세요.");if(!r.containerId)throw new Error("containerId는 필수입니다.");if(!r.layoutJson)throw new Error("layoutJson은 필수입니다.");const e=document.getElementById(r.containerId);if(!e)throw new Error(`컨테이너를 찾을 수 없습니다: #${r.containerId}`);const t=ux();ue.containerId=r.containerId,ue.currentLayoutJson=r.layoutJson,ue.currentDataContext={...t,...r.dataContext||{}},ue.translationContext=r.translationContext||{templateId:ue.templateId||"",locale:ue.locale},ue.reactRoot||(et.log("React Root 생성"),ue.reactRoot=Hu.createRoot(e));const a=hx();if(et.log("편집 모드:",a),a){await mN(r);return}const i=r.layoutJson.components||[];if(i.length===0){et.warn("렌더링할 컴포넌트가 없습니다.");return}const o=r.layoutJson.modals||[];if(et.log("modals 배열:",o),et.log("modals 개수:",o.length),et.log("DynamicRenderer로 렌더링 시작"),ue.reactRoot.render(Ke.createElement(Dc,{translationEngine:ue.translationEngine,translationContext:ue.translationContext},Ke.createElement(ug,null,Ke.createElement(gg,null,Ke.createElement(Og,null,[...i.map((d,g)=>{const h=ue.currentLayoutJson?.layout_name||"";return Ke.createElement(Ua,{key:h&&!d._fromBase?`${d.id}_${h}`:d.id,componentDef:d,dataContext:ue.currentDataContext,translationContext:ue.translationContext,registry:ue.registry,bindingEngine:ue.bindingEngine,translationEngine:ue.translationEngine,actionDispatcher:ue.actionDispatcher,isRootRenderer:g===0,layoutKey:h})}),Ke.createElement(qm,{key:"__modal_parent_context_provider"},o.map(d=>{const g=ue.currentDataContext._global?.modalStack||[],f=g.includes(d.id)||ue.currentDataContext._global?.activeModal===d.id,p=g.indexOf(d.id),y=p>=0?50+p:50,x=window.__g7LayoutContextStack||[],v=x[x.length-1]?.dataContext,w=Ke.createElement(Ua,{key:`modal_${d.id}_renderer`,componentDef:{...d,props:{...d.props,isOpen:f,style:{...d.props?.style,zIndex:y},onClose:ue.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},ue.currentDataContext)}},dataContext:ue.currentDataContext,translationContext:ue.translationContext,registry:ue.registry,bindingEngine:ue.bindingEngine,translationEngine:ue.translationEngine,actionDispatcher:ue.actionDispatcher,parentDataContext:v});return d.data_sources&&d.data_sources.length>0?Ke.createElement(Xy,{key:`modal_${d.id}`,isOpen:f,modalId:d.id,dataSources:d.data_sources,dataContext:ue.currentDataContext,globalStateUpdater:ue.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:ue.bindingEngine,debug:Pc,children:w}):w}))]))))),et.log("템플릿 렌더링 완료"),Lo.length>0){et.log(`대기 중인 데이터 업데이트 ${Lo.length}건 적용`);const d=[...Lo];Lo.length=0;for(const{data:g,options:h}of d)fi(g,h)}}catch(e){throw et.error("템플릿 렌더링 실패",e),e}}function fi(r,e){try{if(et.log("템플릿 데이터 업데이트 시작",Object.keys(r)),hx()){et.log("편집 모드에서는 updateTemplateData를 건너뜁니다.");return}if(!ue.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다.");if(!ue.reactRoot||!ue.currentLayoutJson){et.log("React 미준비 - 데이터 업데이트 큐잉:",Object.keys(r)),Lo.push({data:r,options:e});return}const t=ux(),a={...ue.currentDataContext._global||{},...r._global||{}};ue.currentDataContext={...t,...ue.currentDataContext,...r,_global:a},a._local!==void 0&&(ue.currentDataContext._local=a._local),a._computed!==void 0&&(ue.currentDataContext._computed=a._computed);const i=ue.currentLayoutJson.components||[],o=ue.currentLayoutJson.modals||[];et.log("updateTemplateData - modals 배열:",o),et.log("updateTemplateData - modals 개수:",o.length),et.log("updateTemplateData - activeModal:",ue.currentDataContext._global?.activeModal);const d=()=>{ue.reactRoot.render(Ke.createElement(Dc,{translationEngine:ue.translationEngine,translationContext:ue.translationContext},Ke.createElement(ug,null,Ke.createElement(gg,null,Ke.createElement(Og,null,[...i.map((g,h)=>{const f=ue.currentLayoutJson?.layout_name||"";return Ke.createElement(Ua,{key:f&&!g._fromBase?`${g.id}_${f}`:g.id,componentDef:g,dataContext:ue.currentDataContext,translationContext:ue.translationContext,registry:ue.registry,bindingEngine:ue.bindingEngine,translationEngine:ue.translationEngine,actionDispatcher:ue.actionDispatcher,isRootRenderer:h===0,layoutKey:f})}),Ke.createElement(qm,{key:"__modal_parent_context_provider_update"},o.map(g=>{const h=ue.currentDataContext._global?.modalStack||[],p=h.includes(g.id)||ue.currentDataContext._global?.activeModal===g.id,y=h.indexOf(g.id),x=y>=0?50+y:50,S=window.__g7LayoutContextStack||[],w=S[S.length-1]?.dataContext,k=Ke.createElement(Ua,{key:`modal_${g.id}_renderer`,componentDef:{...g,props:{...g.props,isOpen:p,style:{...g.props?.style,zIndex:x},onClose:ue.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},ue.currentDataContext)}},dataContext:ue.currentDataContext,translationContext:ue.translationContext,registry:ue.registry,bindingEngine:ue.bindingEngine,translationEngine:ue.translationEngine,actionDispatcher:ue.actionDispatcher,parentDataContext:w});return g.data_sources&&g.data_sources.length>0?Ke.createElement(Xy,{key:`modal_${g.id}`,isOpen:p,modalId:g.id,dataSources:g.data_sources,dataContext:ue.currentDataContext,globalStateUpdater:ue.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:ue.bindingEngine,debug:Pc,children:k}):k}))])))))};e?.sync?(et.log("재렌더링 시작 (sync mode - 즉시 렌더링)"),d()):(et.log("재렌더링 시작 (with startTransition)"),j.startTransition(()=>{d()})),et.log("템플릿 데이터 업데이트 완료")}catch(t){throw et.error("템플릿 데이터 업데이트 실패",t),t}}function Bc(){try{et.log("템플릿 정리 시작"),ue.reactRoot&&(et.log("React Root 언마운트"),ue.reactRoot.unmount(),ue.reactRoot=null),ue.templateId=null,ue.locale="ko",ue.isInitialized=!1,ue.containerId=null,ue.currentLayoutJson=null,ue.currentDataContext={},ue.translationContext={templateId:"",locale:"ko"},ue.registry=null,ue.bindingEngine=null,ue.translationEngine=null,ue.actionDispatcher=null,ue.templateMetadata=null,et.log("템플릿 정리 완료")}catch(r){throw et.error("템플릿 정리 실패",r),r}}function Is(){return Object.freeze({...ue})}function gx(){return ue.actionDispatcher}function hx(){if(typeof window>"u")return!1;const r=new URLSearchParams(window.location.search),e=r.get("mode"),t=r.get("template");return e==="edit"&&!!t}function pN(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("template")}async function mN(r){et.log("위지윅 편집기 렌더링 시작");try{const{WysiwygEditor:e}=await Promise.resolve().then(()=>t_),t=pN()||ue.templateId||"unknown",a=()=>{const o=new URLSearchParams(window.location.search);o.delete("mode"),o.delete("template");const d=`${window.location.pathname}${o.toString()?"?"+o.toString():""}`;window.location.href=d},i=o=>{et.log("레이아웃 저장 완료:",o)};et.log("WysiwygEditor 렌더링",{templateId:t,layoutName:r.layoutJson?.layout_name}),ue.reactRoot.render(Ke.createElement(Dc,{translationEngine:ue.translationEngine,translationContext:ue.translationContext},Ke.createElement(e,{layoutData:r.layoutJson,templateId:t,onClose:a,onSaveComplete:i,initialEditMode:"visual",readOnly:!1}))),et.log("위지윅 편집기 렌더링 완료")}catch(e){throw et.error("위지윅 편집기 로드 실패:",e),ue.reactRoot.render(Ke.createElement("div",{className:"flex items-center justify-center h-screen bg-gray-100 dark:bg-gray-900"},Ke.createElement("div",{className:"text-center p-8 bg-white dark:bg-gray-800 rounded-lg shadow-lg"},Ke.createElement("h1",{className:"text-xl font-bold text-red-600 dark:text-red-400 mb-4"},"위지윅 편집기 로드 실패"),Ke.createElement("p",{className:"text-gray-600 dark:text-gray-400 mb-4"},"편집기를 불러오는 중 오류가 발생했습니다."),Ke.createElement("button",{className:"px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700",onClick:()=>window.location.reload()},"새로고침")))),e}}const Io={initTemplateEngine:Mo,renderTemplate:$o,updateTemplateData:fi,destroyTemplate:Bc,getState:Is};typeof window<"u"&&(window.G7Core||(window.G7Core={}),window.G7Core.TemplateEngine=Io,dN({getState:()=>({translationEngine:ue.translationEngine,translationContext:ue.translationContext,bindingEngine:ue.bindingEngine,actionDispatcher:ue.actionDispatcher,templateMetadata:ue.templateMetadata}),transitionManager:Pa,responsiveManager:ei,webSocketManager:Lc}),et.log("전역 객체 window.G7Core.TemplateEngine에 노출됨"));const qa=Object.freeze(Object.defineProperty({__proto__:null,DataSourceManager:is,LayoutLoader:Rg,TemplateApp:Oo,TemplateEngine:Io,default:Io,destroyTemplate:Bc,getActionDispatcher:gx,getState:Is,initTemplateApp:Pg,initTemplateEngine:Mo,renderTemplate:$o,updateTemplateData:fi},Symbol.toStringTag,{value:"Module"})),fx=r=>{let e;const t=new Set,a=(f,p)=>{const y=typeof f=="function"?f(e):f;if(!Object.is(y,e)){const x=e;e=p??(typeof y!="object"||y===null)?y:Object.assign({},e,y),t.forEach(S=>S(e,x))}},i=()=>e,g={setState:a,getState:i,getInitialState:()=>h,subscribe:f=>(t.add(f),()=>t.delete(f))},h=e=r(a,i,g);return g},yN=(r=>r?fx(r):fx),xN=r=>r;function bN(r,e=xN){const t=Ke.useSyncExternalStore(r.subscribe,Ke.useCallback(()=>e(r.getState()),[r,e]),Ke.useCallback(()=>e(r.getInitialState()),[r,e]));return Ke.useDebugValue(t),t}const px=r=>{const e=yN(r),t=a=>bN(e,a);return Object.assign(t,e),t},vN=(r=>r?px(r):px);var mx=Symbol.for("immer-nothing"),yx=Symbol.for("immer-draftable"),An=Symbol.for("immer-state");function Na(r,...e){throw new Error(`[Immer] minified error nr: ${r}. Full error at: https://bit.ly/3cXEKWf`)}var Wn=Object,pi=Wn.getPrototypeOf,Uc="constructor",qc="prototype",Gg="configurable",Gc="enumerable",Fc="writable",zo="value",zs=r=>!!r&&!!r[An];function os(r){return r?bx(r)||Wc(r)||!!r[yx]||!!r[Uc]?.[yx]||Yc(r)||Jc(r):!1}var wN=Wn[qc][Uc].toString(),xx=new WeakMap;function bx(r){if(!r||!Vg(r))return!1;const e=pi(r);if(e===null||e===Wn[qc])return!0;const t=Wn.hasOwnProperty.call(e,Uc)&&e[Uc];if(t===Object)return!0;if(!mi(t))return!1;let a=xx.get(t);return a===void 0&&(a=Function.toString.call(t),xx.set(t,a)),a===wN}function Vc(r,e,t=!0){Ho(r)===0?(t?Reflect.ownKeys(r):Wn.keys(r)).forEach(i=>{e(i,r[i],r)}):r.forEach((a,i)=>e(i,a,r))}function Ho(r){const e=r[An];return e?e.type_:Wc(r)?1:Yc(r)?2:Jc(r)?3:0}var vx=(r,e,t=Ho(r))=>t===2?r.has(e):Wn[qc].hasOwnProperty.call(r,e),Fg=(r,e,t=Ho(r))=>t===2?r.get(e):r[e],Kc=(r,e,t,a=Ho(r))=>{a===2?r.set(e,t):a===3?r.add(t):r[e]=t};function SN(r,e){return r===e?r!==0||1/r===1/e:r!==r&&e!==e}var Wc=Array.isArray,Yc=r=>r instanceof Map,Jc=r=>r instanceof Set,Vg=r=>typeof r=="object",mi=r=>typeof r=="function",Kg=r=>typeof r=="boolean";function CN(r){const e=+r;return Number.isInteger(e)&&String(e)===r}var ls=r=>r.copy_||r.base_,Wg=r=>r.modified_?r.copy_:r.base_;function Yg(r,e){if(Yc(r))return new Map(r);if(Jc(r))return new Set(r);if(Wc(r))return Array[qc].slice.call(r);const t=bx(r);if(e===!0||e==="class_only"&&!t){const a=Wn.getOwnPropertyDescriptors(r);delete a[An];let i=Reflect.ownKeys(a);for(let o=0;o1&&Wn.defineProperties(r,{set:Xc,add:Xc,clear:Xc,delete:Xc}),Wn.freeze(r),e&&Vc(r,(t,a)=>{Jg(a,!0)},!1)),r}function jN(){Na(2)}var Xc={[zo]:jN};function Qc(r){return r===null||!Vg(r)?!0:Wn.isFrozen(r)}var Zc="MapSet",Xg="Patches",wx="ArrayMethods",Sx={};function Cr(r){const e=Sx[r];return e||Na(0,r),e}var Cx=r=>!!Sx[r],Po,jx=()=>Po,kN=(r,e)=>({drafts_:[],parent_:r,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:Cx(Zc)?Cr(Zc):void 0,arrayMethodsPlugin_:Cx(wx)?Cr(wx):void 0});function kx(r,e){e&&(r.patchPlugin_=Cr(Xg),r.patches_=[],r.inversePatches_=[],r.patchListener_=e)}function Qg(r){Zg(r),r.drafts_.forEach(NN),r.drafts_=null}function Zg(r){r===Po&&(Po=r.parent_)}var Nx=r=>Po=kN(Po,r);function NN(r){const e=r[An];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function Ex(r,e){e.unfinalizedDrafts_=e.drafts_.length;const t=e.drafts_[0];if(r!==void 0&&r!==t){t[An].modified_&&(Qg(e),Na(4)),os(r)&&(r=_x(e,r));const{patchPlugin_:i}=e;i&&i.generateReplacementPatches_(t[An].base_,r,e)}else r=_x(e,t);return EN(e,r,!0),Qg(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),r!==mx?r:void 0}function _x(r,e){if(Qc(e))return e;const t=e[An];if(!t)return td(e,r.handledSet_,r);if(!ed(t,r))return e;if(!t.modified_)return t.base_;if(!t.finalized_){const{callbacks_:a}=t;if(a)for(;a.length>0;)a.pop()(r);Dx(t,r)}return t.copy_}function EN(r,e,t=!1){!r.parent_&&r.immer_.autoFreeze_&&r.canAutoFreeze_&&Jg(e,t)}function Ax(r){r.finalized_=!0,r.scope_.unfinalizedDrafts_--}var ed=(r,e)=>r.scope_===e,_N=[];function Tx(r,e,t,a){const i=ls(r),o=r.type_;if(a!==void 0&&Fg(i,a,o)===e){Kc(i,a,t,o);return}if(!r.draftLocations_){const g=r.draftLocations_=new Map;Vc(i,(h,f)=>{if(zs(f)){const p=g.get(f)||[];p.push(h),g.set(f,p)}})}const d=r.draftLocations_.get(e)??_N;for(const g of d)Kc(i,g,t,o)}function AN(r,e,t){r.callbacks_.push(function(i){const o=e;if(!o||!ed(o,i))return;i.mapSetPlugin_?.fixSetContents(o);const d=Wg(o);Tx(r,o.draft_??o,d,t),Dx(o,i)})}function Dx(r,e){if(r.modified_&&!r.finalized_&&(r.type_===3||r.type_===1&&r.allIndicesReassigned_||(r.assigned_?.size??0)>0)){const{patchPlugin_:a}=e;if(a){const i=a.getPath(r);i&&a.generatePatches_(r,i,e)}Ax(r)}}function TN(r,e,t){const{scope_:a}=r;if(zs(t)){const i=t[An];ed(i,a)&&i.callbacks_.push(function(){ad(r);const d=Wg(i);Tx(r,t,d,e)})}else os(t)&&r.callbacks_.push(function(){const o=ls(r);r.type_===3?o.has(t)&&td(t,a.handledSet_,a):Fg(o,e,r.type_)===t&&a.drafts_.length>1&&(r.assigned_.get(e)??!1)===!0&&r.copy_&&td(Fg(r.copy_,e,r.type_),a.handledSet_,a)})}function td(r,e,t){return!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1||zs(r)||e.has(r)||!os(r)||Qc(r)||(e.add(r),Vc(r,(a,i)=>{if(zs(i)){const o=i[An];if(ed(o,t)){const d=Wg(o);Kc(r,a,d,r.type_),Ax(o)}}else os(i)&&td(i,e,t)})),r}function DN(r,e){const t=Wc(r),a={type_:t?1:0,scope_:e?e.scope_:jx(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:e,base_:r,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let i=a,o=nd;t&&(i=[a],o=Bo);const{revoke:d,proxy:g}=Proxy.revocable(i,o);return a.draft_=g,a.revoke_=d,[g,a]}var nd={get(r,e){if(e===An)return r;let t=r.scope_.arrayMethodsPlugin_;const a=r.type_===1&&typeof e=="string";if(a&&t?.isArrayOperationMethod(e))return t.createMethodInterceptor(r,e);const i=ls(r);if(!vx(i,e,r.type_))return RN(r,i,e);const o=i[e];if(r.finalized_||!os(o)||a&&r.operationMethod&&t?.isMutatingArrayMethod(r.operationMethod)&&CN(e))return o;if(o===eh(r.base_,e)){ad(r);const d=r.type_===1?+e:e,g=nh(r.scope_,o,r,d);return r.copy_[d]=g}return o},has(r,e){return e in ls(r)},ownKeys(r){return Reflect.ownKeys(ls(r))},set(r,e,t){const a=Rx(ls(r),e);if(a?.set)return a.set.call(r.draft_,t),!0;if(!r.modified_){const i=eh(ls(r),e),o=i?.[An];if(o&&o.base_===t)return r.copy_[e]=t,r.assigned_.set(e,!1),!0;if(SN(t,i)&&(t!==void 0||vx(r.base_,e,r.type_)))return!0;ad(r),th(r)}return r.copy_[e]===t&&(t!==void 0||e in r.copy_)||Number.isNaN(t)&&Number.isNaN(r.copy_[e])||(r.copy_[e]=t,r.assigned_.set(e,!0),TN(r,e,t)),!0},deleteProperty(r,e){return ad(r),eh(r.base_,e)!==void 0||e in r.base_?(r.assigned_.set(e,!1),th(r)):r.assigned_.delete(e),r.copy_&&delete r.copy_[e],!0},getOwnPropertyDescriptor(r,e){const t=ls(r),a=Reflect.getOwnPropertyDescriptor(t,e);return a&&{[Fc]:!0,[Gg]:r.type_!==1||e!=="length",[Gc]:a[Gc],[zo]:t[e]}},defineProperty(){Na(11)},getPrototypeOf(r){return pi(r.base_)},setPrototypeOf(){Na(12)}},Bo={};for(let r in nd){let e=nd[r];Bo[r]=function(){const t=arguments;return t[0]=t[0][0],e.apply(this,t)}}Bo.deleteProperty=function(r,e){return Bo.set.call(this,r,e,void 0)},Bo.set=function(r,e,t){return nd.set.call(this,r[0],e,t,r[0])};function eh(r,e){const t=r[An];return(t?ls(t):r)[e]}function RN(r,e,t){const a=Rx(e,t);return a?zo in a?a[zo]:a.get?.call(r.draft_):void 0}function Rx(r,e){if(!(e in r))return;let t=pi(r);for(;t;){const a=Object.getOwnPropertyDescriptor(t,e);if(a)return a;t=pi(t)}}function th(r){r.modified_||(r.modified_=!0,r.parent_&&th(r.parent_))}function ad(r){r.copy_||(r.assigned_=new Map,r.copy_=Yg(r.base_,r.scope_.immer_.useStrictShallowCopy_))}var ON=class{constructor(r){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,a)=>{if(mi(e)&&!mi(t)){const o=t;t=e;const d=this;return function(h=o,...f){return d.produce(h,p=>t.call(this,p,...f))}}mi(t)||Na(6),a!==void 0&&!mi(a)&&Na(7);let i;if(os(e)){const o=Nx(this),d=nh(o,e,void 0);let g=!0;try{i=t(d),g=!1}finally{g?Qg(o):Zg(o)}return kx(o,a),Ex(i,o)}else if(!e||!Vg(e)){if(i=t(e),i===void 0&&(i=e),i===mx&&(i=void 0),this.autoFreeze_&&Jg(i,!0),a){const o=[],d=[];Cr(Xg).generateReplacementPatches_(e,i,{patches_:o,inversePatches_:d}),a(o,d)}return i}else Na(1,e)},this.produceWithPatches=(e,t)=>{if(mi(e))return(d,...g)=>this.produceWithPatches(d,h=>e(h,...g));let a,i;return[this.produce(e,t,(d,g)=>{a=d,i=g}),a,i]},Kg(r?.autoFreeze)&&this.setAutoFreeze(r.autoFreeze),Kg(r?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(r.useStrictShallowCopy),Kg(r?.useStrictIteration)&&this.setUseStrictIteration(r.useStrictIteration)}createDraft(r){os(r)||Na(8),zs(r)&&(r=LN(r));const e=Nx(this),t=nh(e,r,void 0);return t[An].isManual_=!0,Zg(e),t}finishDraft(r,e){const t=r&&r[An];(!t||!t.isManual_)&&Na(9);const{scope_:a}=t;return kx(a,e),Ex(void 0,a)}setAutoFreeze(r){this.autoFreeze_=r}setUseStrictShallowCopy(r){this.useStrictShallowCopy_=r}setUseStrictIteration(r){this.useStrictIteration_=r}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(r,e){let t;for(t=e.length-1;t>=0;t--){const i=e[t];if(i.path.length===0&&i.op==="replace"){r=i.value;break}}t>-1&&(e=e.slice(t+1));const a=Cr(Xg).applyPatches_;return zs(r)?a(r,e):this.produce(r,i=>a(i,e))}};function nh(r,e,t,a){const[i,o]=Yc(e)?Cr(Zc).proxyMap_(e,t):Jc(e)?Cr(Zc).proxySet_(e,t):DN(e,t);return(t?.scope_??jx()).drafts_.push(i),o.callbacks_=t?.callbacks_??[],o.key_=a,t&&a!==void 0?AN(t,o,a):o.callbacks_.push(function(h){h.mapSetPlugin_?.fixSetContents(o);const{patchPlugin_:f}=h;o.modified_&&f&&f.generatePatches_(o,[],h)}),i}function LN(r){return zs(r)||Na(10,r),Ox(r)}function Ox(r){if(!os(r)||Qc(r))return r;const e=r[An];let t,a=!0;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,t=Yg(r,e.scope_.immer_.useStrictShallowCopy_),a=e.scope_.immer_.shouldUseStrictIteration()}else t=Yg(r,!0);return Vc(t,(i,o)=>{Kc(t,i,Ox(o))},a),e&&(e.finalized_=!1),t}var MN=new ON,$N=MN.produce;const IN=r=>(e,t,a)=>(a.setState=(i,o,...d)=>{const g=typeof i=="function"?$N(i):i;return e(g,o,...d)},r(a.setState,t,a)),Lx={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_NAME:"그누보드7",VITE_REVERB_APP_KEY:"",VITE_REVERB_HOST:"localhost",VITE_REVERB_PORT:"8080",VITE_REVERB_SCHEME:"https"},Uo=new Map,sd=r=>{const e=Uo.get(r);return e?Object.fromEntries(Object.entries(e.stores).map(([t,a])=>[t,a.getState()])):{}},zN=(r,e,t)=>{if(r===void 0)return{type:"untracked",connection:e.connect(t)};const a=Uo.get(t.name);if(a)return{type:"tracked",store:r,...a};const i={connection:e.connect(t),stores:{}};return Uo.set(t.name,i),{type:"tracked",store:r,...i}},HN=(r,e)=>{if(e===void 0)return;const t=Uo.get(r);t&&(delete t.stores[e],Object.keys(t.stores).length===0&&Uo.delete(r))},PN=r=>{var e,t;if(!r)return;const a=r.split(` -`),i=a.findIndex(d=>d.includes("api.setState"));if(i<0)return;const o=((e=a[i+1])==null?void 0:e.trim())||"";return(t=/.+ (.+) .+/.exec(o))==null?void 0:t[1]},BN=(r,e={})=>(t,a,i)=>{const{enabled:o,anonymousActionType:d,store:g,...h}=e;let f;try{f=(o??(Lx?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!f)return r(t,a,i);const{connection:p,...y}=zN(g,f,h);let x=!0;i.setState=((w,k,A)=>{const O=t(w,k);if(!x)return O;const N=A===void 0?{type:d||PN(new Error().stack)||"anonymous"}:typeof A=="string"?{type:A}:A;return g===void 0?(p?.send(N,a()),O):(p?.send({...N,type:`${g}/${N.type}`},{...sd(h.name),[g]:i.getState()}),O)}),i.devtools={cleanup:()=>{p&&typeof p.unsubscribe=="function"&&p.unsubscribe(),HN(h.name,g)}};const S=(...w)=>{const k=x;x=!1,t(...w),x=k},v=r(i.setState,a,i);if(y.type==="untracked"?p?.init(v):(y.stores[y.store]=i,p?.init(Object.fromEntries(Object.entries(y.stores).map(([w,k])=>[w,w===y.store?v:k.getState()])))),i.dispatchFromDevtools&&typeof i.dispatch=="function"){let w=!1;const k=i.dispatch;i.dispatch=(...A)=>{(Lx?"production":void 0)!=="production"&&A[0].type==="__setState"&&!w&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),w=!0),k(...A)}}return p.subscribe(w=>{var k;switch(w.type){case"ACTION":if(typeof w.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return ah(w.payload,A=>{if(A.type==="__setState"){if(g===void 0){S(A.state);return}Object.keys(A.state).length!==1&&console.error(` +`,ok=()=>{const r="g7-devtools-styles";if(document.getElementById(r))return;const e=document.createElement("style");e.id=r,e.textContent=ik,document.head.appendChild(e)},nx={state:"상태",actions:"액션",cache:"캐시",diagnose:"진단",performance:"성능",lifecycle:"라이프사이클",network:"네트워크",form:"Form",conditional:"조건부",expression:"표현식",handlers:"핸들러",events:"이벤트",datasources:"데이터소스",renders:"렌더링",styles:"스타일",auth:"인증",logs:"로그",layout:"레이아웃",changedetection:"변경감지",staleclosure:"Stale Closure",nestedcontext:"Context",modalscope:"모달스코프",namedactions:"Named Actions"},lk=700,ck=500,ax=400,sx=300,rx="g7-devtools-panel",Ug=r=>r===null||r===void 0?"g7dt-text-gray":typeof r=="string"?"g7dt-text-yellow":typeof r=="number"?"g7dt-text-cyan":typeof r=="boolean"?"g7dt-text-pink":Array.isArray(r)?"g7dt-text-orange":typeof r=="object"?"g7dt-text-blue":"g7dt-text-white",dk=r=>r===null?"null":r===void 0?"undefined":Array.isArray(r)?`Array(${r.length})`:typeof r=="object"?`Object(${Object.keys(r).length})`:typeof r,uk=r=>r===null?"null":r===void 0?"undefined":typeof r=="string"?r.length>50?`"${r.substring(0,50)}..."`:`"${r}"`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):"",ix=()=>{try{const r=localStorage.getItem(rx);if(r)return JSON.parse(r)}catch(r){console.warn("[G7DevTools] 설정 로드 실패:",r)}return{}},ox=r=>{try{const t={...ix(),...r};localStorage.setItem(rx,JSON.stringify(t))}catch(e){console.warn("[G7DevTools] 설정 저장 실패:",e)}},hi=({keyName:r,value:e,path:t,expandedPaths:a,onToggle:i,searchTerm:o,depth:d=0})=>{const g=e!==null&&typeof e=="object",h=a.has(t),f=Array.isArray(e),p=o&&(r.toLowerCase().includes(o.toLowerCase())||typeof e=="string"&&e.toLowerCase().includes(o.toLowerCase())||typeof e=="number"&&String(e).includes(o)),y=S=>{S.stopPropagation(),g&&i(t)},x=g?Object.entries(e):[];return l.jsxs("div",{style:{marginLeft:d>0?"16px":"0"},children:[l.jsxs("div",{className:`g7dt-tree-node g7dt-flex g7dt-items-center g7dt-gap-1 ${p?"g7dt-ring-highlight":""}`,onClick:y,children:[g?l.jsx("span",{className:"g7dt-text-gray g7dt-w-4 g7dt-text-xs g7dt-select-none",style:{textAlign:"center"},children:h?"▼":"▶"}):l.jsx("span",{className:"g7dt-w-4"}),l.jsx("span",{className:"g7dt-text-purple g7dt-text-xs",children:r}),l.jsx("span",{className:"g7dt-text-gray-dark g7dt-text-xs",children:":"}),g?l.jsxs("span",{className:`g7dt-text-xs ${Ug(e)}`,children:[f?"[":"{",!h&&l.jsx("span",{className:"g7dt-text-gray",style:{margin:"0 4px"},children:dk(e)}),!h&&(f?"]":"}")]}):l.jsx("span",{className:`g7dt-text-xs ${Ug(e)}`,children:uk(e)}),!g&&l.jsxs("span",{className:"g7dt-text-gray-dark g7dt-text-xs g7dt-ml-1",children:["(",typeof e,")"]})]}),g&&h&&l.jsxs("div",{className:"g7dt-border-l",style:{marginLeft:"8px"},children:[x.map(([S,v])=>l.jsx(hi,{keyName:f?`[${S}]`:S,value:v,path:`${t}.${S}`,expandedPaths:a,onToggle:i,searchTerm:o,depth:d+1},`${t}.${S}`)),l.jsx("div",{className:"g7dt-ml-4 g7dt-text-xs",children:l.jsx("span",{className:Ug(e),children:f?"]":"}"})})]})]})},gk=({state:r,devTools:e})=>{const[t,a]=j.useState(new Set(["_global","_local","_computed","_isolated","$parent"])),[i,o]=j.useState(""),[d,g]=j.useState(!1),[h,f]=j.useState(!1),[p,y]=j.useState(null),x=j.useCallback(()=>{e&&y(e.getComputedDependencyTrackingInfo())},[e]);j.useEffect(()=>{if(h&&e){x();const M=setInterval(x,2e3);return()=>clearInterval(M)}},[h,e,x]);const S=M=>{switch(M){case"state-change":return"📊";case"prop-change":return"📥";case"dependency-change":return"🔗";case"manual":return"👆";case"initial":return"🚀";default:return"❓"}},v=j.useCallback(M=>{a(z=>{const K=new Set(z);return K.has(M)?K.delete(M):K.add(M),K})},[]),w=j.useCallback((M,z)=>{const K=[z];if(M!==null&&typeof M=="object")for(const[ye,we]of Object.entries(M))K.push(...w(we,`${z}.${ye}`));return K},[]),k=j.useCallback(()=>{if(d)a(new Set(["_global","_local","_computed","_isolated","$parent"]));else{const M=new Set;w(r._global,"_global").forEach(z=>M.add(z)),w(r._local,"_local").forEach(z=>M.add(z)),w(r._computed,"_computed").forEach(z=>M.add(z)),w(r._isolated,"_isolated").forEach(z=>M.add(z)),r.$parent&&w(r.$parent,"$parent").forEach(z=>M.add(z)),a(M)}g(!d)},[d,r,w]),A=Object.keys(r._global||{}).length,O=Object.keys(r._local||{}).length,N=Object.keys(r._computed||{}).length,D=Object.keys(r._isolated||{}).length,$=Object.keys(r.$parent||{}).length;return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-items-center g7dt-flex-shrink-0",children:[l.jsx("input",{type:"text",placeholder:"키 또는 값 검색...",value:i,onChange:M=>o(M.target.value),className:"g7dt-input g7dt-flex-1"}),l.jsx("button",{onClick:k,className:"g7dt-btn g7dt-bg-gray-700",children:d?"모두 접기":"모두 펼치기"})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-3 g7dt-text-xs g7dt-text-gray g7dt-flex-wrap g7dt-flex-shrink-0",children:[l.jsxs("span",{children:[l.jsx("span",{className:"g7dt-text-yellow",children:"●"})," string"]}),l.jsxs("span",{children:[l.jsx("span",{className:"g7dt-text-cyan",children:"●"})," number"]}),l.jsxs("span",{children:[l.jsx("span",{className:"g7dt-text-pink",children:"●"})," boolean"]}),l.jsxs("span",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"●"})," null"]}),l.jsxs("span",{children:[l.jsx("span",{className:"g7dt-text-orange",children:"●"})," array"]}),l.jsxs("span",{children:[l.jsx("span",{className:"g7dt-text-blue",children:"●"})," object"]})]}),l.jsxs("div",{className:"g7dt-bg-gray-800 g7dt-rounded g7dt-p-2 g7dt-overflow-auto g7dt-border",style:{flex:1,minHeight:0},children:[l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-green g7dt-mb-1 g7dt-cursor-pointer",onClick:()=>v("_global"),children:[l.jsx("span",{children:t.has("_global")?"▼":"▶"}),l.jsx("span",{children:"_global"}),l.jsxs("span",{className:"g7dt-text-gray g7dt-text-xs",style:{fontWeight:"normal"},children:["(",A,"개 키)"]})]}),t.has("_global")&&l.jsx("div",{className:"g7dt-ml-2 g7dt-border-l",children:Object.entries(r._global||{}).map(([M,z])=>l.jsx(hi,{keyName:M,value:z,path:`_global.${M}`,expandedPaths:t,onToggle:v,searchTerm:i},`_global.${M}`))})]}),l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-blue g7dt-mb-1 g7dt-cursor-pointer",onClick:()=>v("_local"),children:[l.jsx("span",{children:t.has("_local")?"▼":"▶"}),l.jsx("span",{children:"_local"}),l.jsxs("span",{className:"g7dt-text-gray g7dt-text-xs",style:{fontWeight:"normal"},children:["(",O,"개 키)"]})]}),t.has("_local")&&l.jsx("div",{className:"g7dt-ml-2 g7dt-border-l",children:Object.entries(r._local||{}).map(([M,z])=>l.jsx(hi,{keyName:M,value:z,path:`_local.${M}`,expandedPaths:t,onToggle:v,searchTerm:i},`_local.${M}`))})]}),l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-purple g7dt-mb-1 g7dt-cursor-pointer",onClick:()=>v("_computed"),children:[l.jsx("span",{children:t.has("_computed")?"▼":"▶"}),l.jsx("span",{children:"_computed"}),l.jsxs("span",{className:"g7dt-text-gray g7dt-text-xs",style:{fontWeight:"normal"},children:["(",N,"개 키)"]})]}),t.has("_computed")&&l.jsx("div",{className:"g7dt-ml-2 g7dt-border-l",children:Object.entries(r._computed||{}).map(([M,z])=>l.jsx(hi,{keyName:M,value:z,path:`_computed.${M}`,expandedPaths:t,onToggle:v,searchTerm:i},`_computed.${M}`))})]}),D>0&&l.jsxs("div",{children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-orange g7dt-mb-1 g7dt-cursor-pointer",onClick:()=>v("_isolated"),children:[l.jsx("span",{children:t.has("_isolated")?"▼":"▶"}),l.jsx("span",{children:"_isolated"}),l.jsxs("span",{className:"g7dt-text-gray g7dt-text-xs",style:{fontWeight:"normal"},children:["(",D,"개 스코프)"]})]}),t.has("_isolated")&&l.jsx("div",{className:"g7dt-ml-2 g7dt-border-l",children:Object.entries(r._isolated||{}).map(([M,z])=>l.jsx(hi,{keyName:M,value:z,path:`_isolated.${M}`,expandedPaths:t,onToggle:v,searchTerm:i},`_isolated.${M}`))})]}),$>0&&l.jsxs("div",{children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-cyan g7dt-mb-1 g7dt-cursor-pointer",onClick:()=>v("$parent"),children:[l.jsx("span",{children:t.has("$parent")?"▼":"▶"}),l.jsx("span",{children:"$parent"}),l.jsxs("span",{className:"g7dt-text-gray g7dt-text-xs",style:{fontWeight:"normal"},children:["(",$,"개 키)"]})]}),t.has("$parent")&&l.jsx("div",{className:"g7dt-ml-2 g7dt-border-l",children:Object.entries(r.$parent||{}).map(([M,z])=>l.jsx(hi,{keyName:M,value:z,path:`$parent.${M}`,expandedPaths:t,onToggle:v,searchTerm:i},`$parent.${M}`))})]})]}),e&&l.jsx("div",{className:"g7dt-flex g7dt-justify-end g7dt-mt-2",children:l.jsx("button",{onClick:()=>f(!h),className:`g7dt-tab-button ${h?"g7dt-tab-active":""}`,children:"🧮 Computed 추적"})}),h&&p&&l.jsxs("div",{className:"g7dt-card g7dt-mt-2",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:["Computed 의존성 추적 (",p.properties.length,"개)"]}),l.jsxs("div",{className:"g7dt-stats-grid g7dt-mb-3",children:[l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-purple",children:p.stats.totalComputed}),l.jsx("div",{className:"g7dt-stat-label",children:"Computed"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-blue",children:p.stats.totalRecalculations}),l.jsx("div",{className:"g7dt-stat-label",children:"재계산"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-yellow",children:p.stats.unnecessaryRecalculations}),l.jsx("div",{className:"g7dt-stat-label",children:"불필요"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsxs("div",{className:"g7dt-stat-value g7dt-text-green",children:[p.stats.avgComputationTime.toFixed(1),"ms"]}),l.jsx("div",{className:"g7dt-stat-label",children:"평균시간"})]})]}),p.stats.cycleDetectionCount>0&&l.jsxs("div",{className:"g7dt-text-xs g7dt-text-red g7dt-mb-3 g7dt-p-2 g7dt-bg-red-900 g7dt-rounded",children:["⚠️ 순환 의존성 감지: ",p.stats.cycleDetectionCount,"건"]}),p.stats.topRecalculated.length>0&&l.jsxs("div",{className:"g7dt-mb-3",children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"자주 재계산되는 속성"}),l.jsx("div",{className:"g7dt-space-y-1",children:p.stats.topRecalculated.slice(0,3).map((M,z)=>l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-text-xs",children:[l.jsx("span",{className:"g7dt-text-purple g7dt-font-mono",children:M.name}),l.jsxs("span",{className:"g7dt-text-muted",children:[M.count,"회"]})]},z))})]}),p.recalcLogs.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"재계산 로그가 없습니다"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-40 g7dt-overflow-y-auto",children:p.recalcLogs.slice().reverse().slice(0,20).map(M=>l.jsxs("div",{className:`g7dt-list-item ${M.valueChanged?"":"g7dt-border-yellow"}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{children:S(M.trigger)}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-purple g7dt-font-mono",children:M.computedName}),!M.valueChanged&&l.jsx("span",{className:"g7dt-badge g7dt-text-xs g7dt-text-yellow",children:"값 변경 없음"}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:[M.computationTime.toFixed(1),"ms"]})]}),M.triggeredBy&&l.jsxs("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-1",children:["트리거: ",l.jsx("span",{className:"g7dt-text-blue",children:M.triggeredBy.path})]})]},M.id))})]})]})},hk=({actions:r,devTools:e})=>{const[t,a]=j.useState(""),[i,o]=j.useState("actions"),[d,g]=j.useState(null),[h,f]=j.useState(null),p=j.useCallback(()=>{e&&g(e.getSequenceTrackingInfo())},[e]);j.useEffect(()=>{if(i==="sequences"&&e){p();const w=setInterval(p,2e3);return()=>clearInterval(w)}},[i,e,p]);const y=t?r.filter(w=>w.type.toLowerCase().includes(t.toLowerCase())||w.status===t):r,x=w=>{switch(w){case"success":return"g7dt-status-success";case"error":return"g7dt-status-error";case"started":return"g7dt-status-started";default:return"g7dt-status-default"}},S=w=>{switch(w){case"success":return"g7dt-badge-success";case"error":return"g7dt-badge-error";default:return"g7dt-badge-warning"}},v=h&&d?d.executions.find(w=>w.id===h):null;return l.jsxs("div",{className:"g7dt-space-y-4",children:[e&&l.jsx("div",{className:"g7dt-card",children:l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsxs("button",{className:`g7dt-tab-button ${i==="actions"?"g7dt-tab-active":""}`,onClick:()=>o("actions"),children:["📋 액션 (",r.length,")"]}),l.jsxs("button",{className:`g7dt-tab-button ${i==="sequences"?"g7dt-tab-active":""}`,onClick:()=>o("sequences"),children:["🔗 Sequence (",d?.executions.length||0,")"]})]})}),i==="actions"&&l.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-flex-shrink-0",children:[l.jsx("input",{type:"text",placeholder:"액션 타입 또는 상태로 필터...",value:t,onChange:w=>a(w.target.value),className:"g7dt-input g7dt-flex-1"}),l.jsx("button",{onClick:()=>a(""),className:"g7dt-btn-text",children:"초기화"})]}),i==="sequences"&&d&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"Sequence 통계"}),l.jsxs("div",{className:"g7dt-stats-grid-3",children:[l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-blue",children:d.stats.totalSequences}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"총 실행"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-green",children:d.stats.successCount}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"성공"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-red",children:d.stats.errorCount}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"실패"})]})]})]}),l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"Sequence 실행 목록"}),d.executions.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"실행된 Sequence가 없습니다"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-40 g7dt-overflow-y-auto",children:d.executions.slice().reverse().map(w=>l.jsx("div",{className:`g7dt-list-item g7dt-cursor-pointer ${h===w.id?"g7dt-selected":""} ${w.status==="error"?"g7dt-border-red":""}`,onClick:()=>f(h===w.id?null:w.id),children:l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{children:w.status==="completed"?"✅":w.status==="error"?"❌":"⏳"}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-white",children:[w.actions.length,"개 액션"]}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:[w.totalDuration.toFixed(0),"ms"]})]})},w.id))})]}),v&&l.jsxs("div",{className:"g7dt-card g7dt-border-blue",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:["🔗 Sequence 상세 (",v.actions.length,"개 액션)"]}),l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:v.actions.map((w,k)=>l.jsxs("div",{className:`g7dt-list-item ${w.status==="error"?"g7dt-border-red":""}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted",children:["#",w.index+1]}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-white g7dt-font-mono",children:w.handler}),l.jsx("span",{className:`g7dt-text-xs ${w.status==="success"?"g7dt-text-green":"g7dt-text-red"}`,children:w.status==="success"?"✓":"✕"}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:[w.duration.toFixed(0),"ms"]})]}),w.stateChanges&&w.stateChanges.length>0&&l.jsxs("div",{className:"g7dt-mt-1",children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"상태 변경:"}),w.stateChanges.slice(0,3).map((A,O)=>l.jsx("div",{className:"g7dt-text-xs g7dt-text-yellow g7dt-ml-2",children:A.path},O)),w.stateChanges.length>3&&l.jsxs("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-2",children:["...외 ",w.stateChanges.length-3,"개"]})]})]},k))})]})]}),i==="actions"&&l.jsx("div",{className:"g7dt-section",children:l.jsx("div",{className:"g7dt-scroll-list g7dt-space-y-2-flat g7dt-action-list",children:y.length===0?l.jsx("div",{className:"g7dt-empty-message",children:"액션 이력이 없습니다"}):y.slice(-30).reverse().map((w,k)=>l.jsxs("div",{className:`g7dt-action-item ${x(w.status)}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-start",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-font-mono g7dt-font-bold",children:w.type}),l.jsx("span",{className:`g7dt-status-badge ${S(w.status)}`,children:w.status})]}),l.jsx("span",{className:"g7dt-text-gray",children:w.duration?`${w.duration.toFixed(2)}ms`:"-"})]}),w.error&&l.jsx("div",{className:"g7dt-error-box",children:w.error.message}),w.params&&Object.keys(w.params).length>0&&l.jsxs("details",{className:"g7dt-details",children:[l.jsx("summary",{className:"g7dt-summary",children:"파라미터"}),l.jsx("pre",{className:"g7dt-pre",children:JSON.stringify(w.params,null,2)})]})]},`${w.id}-${k}`))})})]})},fk=({stats:r,devTools:e})=>{const[t,a]=j.useState(null),[i,o]=j.useState(!1),d=j.useCallback(()=>{a(e.getCacheDecisionTrackingInfo())},[e]);j.useEffect(()=>{if(i){d();const f=setInterval(d,2e3);return()=>clearInterval(f)}},[i,d]);const g=()=>{e.resetCacheStats(),console.log("[G7DevTools] 캐시 통계 초기화")},h=f=>{switch(f){case"use_cache":return"✅";case"skip_cache":return"⏭️";case"invalidate":return"🗑️";default:return"❓"}};return l.jsxs("div",{className:"g7dt-space-y-6",children:[l.jsxs("div",{className:"g7dt-stats-grid",children:[l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-green",children:r.hits}),l.jsx("div",{className:"g7dt-stat-label",children:"Cache Hits"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-red",children:r.misses}),l.jsx("div",{className:"g7dt-stat-label",children:"Cache Misses"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-blue",children:r.entries}),l.jsx("div",{className:"g7dt-stat-label",children:"Entries"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsxs("div",{className:"g7dt-stat-value g7dt-text-purple",children:[(r.hitRate*100).toFixed(1),"%"]}),l.jsx("div",{className:"g7dt-stat-label",children:"Hit Rate"})]})]}),l.jsxs("div",{className:"g7dt-space-y-2",children:[l.jsx("div",{className:"g7dt-text-sm g7dt-text-gray",children:"캐시 히트율"}),l.jsx("div",{className:"g7dt-progress-bar",children:l.jsx("div",{className:"g7dt-progress-fill",style:{width:`${r.hitRate*100}%`}})})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsx("button",{onClick:g,className:"g7dt-btn-danger",children:"캐시 통계 초기화"}),l.jsx("button",{onClick:()=>o(!i),className:`g7dt-tab-button ${i?"g7dt-tab-active":""}`,children:"📋 Decision Log"})]}),i&&t&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:["캐시 결정 로그 (",t.decisions.length,"개)"]}),t.decisions.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"캐시 결정 기록이 없습니다"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:t.decisions.slice().reverse().slice(0,50).map(f=>l.jsxs("div",{className:`g7dt-list-item ${f.decision==="skip_cache"?"g7dt-border-yellow":f.decision==="invalidate"?"g7dt-border-red":""}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{children:h(f.decision)}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-white g7dt-font-mono g7dt-truncate",style:{maxWidth:"200px"},children:f.expression}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:f.decision})]}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-1",children:f.reason}),f.context&&l.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-mt-1",children:[f.context.isInIteration&&l.jsx("span",{className:"g7dt-badge g7dt-text-xs",children:"🔄 iteration"}),f.context.isInAction&&l.jsx("span",{className:"g7dt-badge g7dt-text-xs",children:"⚡ action"})]})]},f.id))})]})]})},pk=()=>{const[r,e]=j.useState([]),[t,a]=j.useState([]),[i,o]=j.useState(""),d=["이전 값이 전송됨","모든 행이 같은 값","상태가 업데이트 안됨","API 호출이 안됨","초기값이 없음","무한 로딩","Form 값이 저장 안됨","iteration 데이터 중복"],g=p=>{e(y=>y.includes(p)?y.filter(x=>x!==p):[...y,p])},h=()=>{i&&!r.includes(i)&&(e(p=>[...p,i]),o(""))},f=async()=>{const{DiagnosticEngine:p}=await Promise.resolve().then(()=>ak),x=new p().analyze(r);a(x)};return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"증상 선택"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-2",children:d.map(p=>l.jsx("button",{onClick:()=>g(p),className:r.includes(p)?"g7dt-symptom-btn g7dt-symptom-active":"g7dt-symptom-btn",children:p},p))})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsx("input",{type:"text",placeholder:"직접 증상 입력...",value:i,onChange:p=>o(p.target.value),onKeyDown:p=>p.key==="Enter"&&h(),className:"g7dt-input g7dt-flex-1"}),l.jsx("button",{onClick:h,className:"g7dt-btn-secondary",children:"추가"})]}),l.jsxs("button",{onClick:f,disabled:r.length===0,className:r.length===0?"g7dt-btn-primary g7dt-btn-disabled g7dt-w-full":"g7dt-btn-primary g7dt-w-full",children:["진단 실행 (",r.length,"개 증상)"]}),t.length>0&&l.jsxs("div",{className:"g7dt-space-y-3",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:"진단 결과"}),t.slice(0,5).map((p,y)=>l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("span",{className:"g7dt-font-bold g7dt-text-yellow",children:p.rule.name}),l.jsxs("span",{className:"g7dt-confidence-badge",children:[(p.confidence*100).toFixed(0),"%"]})]}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-lightgray",children:p.rule.solution}),p.rule.codeExample&&l.jsx("pre",{className:"g7dt-pre g7dt-mt-2",children:p.rule.codeExample})]},y))]})]})},mk=({devTools:r})=>{const e=r.getPerformanceInfo();return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-stats-grid-2",children:[l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-blue",children:e.bindingEvalCount}),l.jsx("div",{className:"g7dt-stat-label",children:"바인딩 평가 횟수"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-purple",children:e.renderCounts.size}),l.jsx("div",{className:"g7dt-stat-label",children:"렌더링된 컴포넌트"})]})]}),e.memoryWarnings.length>0&&l.jsxs("div",{children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-red g7dt-mb-2",children:"메모리 경고"}),l.jsx("div",{className:"g7dt-space-y-2",children:e.memoryWarnings.map((t,a)=>l.jsxs("div",{className:"g7dt-warning-card",children:[l.jsx("div",{className:"g7dt-font-bold",children:t.type}),l.jsx("div",{className:"g7dt-text-lightgray",children:t.message}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-gray g7dt-mt-1",children:t.suggestion})]},a))})]}),e.renderCounts.size>0&&l.jsxs("div",{children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"컴포넌트별 렌더링"}),l.jsx("div",{className:"g7dt-space-y-1 g7dt-scroll-list",children:Array.from(e.renderCounts.entries()).sort((t,a)=>a[1]-t[1]).slice(0,10).map(([t,a])=>l.jsxs("div",{className:"g7dt-list-item",children:[l.jsx("span",{className:"g7dt-text-lightgray g7dt-truncate",children:t}),l.jsxs("span",{className:a>50?"g7dt-text-red":"g7dt-text-gray",children:[a,"회"]})]},t))})]})]})},yk=({devTools:r})=>{const e=r.getLifecycleInfo();return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-section",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-green g7dt-mb-2 g7dt-flex-shrink-0",children:["마운트된 컴포넌트 (",e.mountedComponents.length,")"]}),l.jsx("div",{className:"g7dt-scroll-list",children:e.mountedComponents.length===0?l.jsx("div",{className:"g7dt-empty-message",children:"추적된 컴포넌트 없음"}):e.mountedComponents.map(t=>l.jsxs("div",{className:"g7dt-list-item g7dt-text-xs",children:[l.jsx("span",{className:"g7dt-text-lightgray",children:t.name}),l.jsx("span",{className:"g7dt-text-gray",children:t.id})]},t.id))})]}),e.orphanedListeners.length>0&&l.jsxs("div",{className:"g7dt-section",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-red g7dt-mb-2 g7dt-flex-shrink-0",children:["정리되지 않은 리스너 (",e.orphanedListeners.length,")"]}),l.jsx("div",{className:"g7dt-scroll-list",children:e.orphanedListeners.map((t,a)=>l.jsxs("div",{className:"g7dt-warning-card g7dt-text-xs",children:[l.jsx("span",{className:"g7dt-text-lightgray",children:t.type}),l.jsxs("span",{className:"g7dt-text-gray g7dt-ml-2",children:["on ",t.target]})]},a))})]})]})},xk=({devTools:r})=>{const e=r.getNetworkInfo(),t=d=>{switch(d){case"success":return"g7dt-text-green";case"error":return"g7dt-text-red";case"pending":return"g7dt-text-yellow";default:return"g7dt-text-gray"}},a=d=>d.queryParams&&Object.keys(d.queryParams).length>0,i=d=>Object.entries(d).map(([g,h])=>l.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-text-xs",children:[l.jsxs("span",{className:"g7dt-text-purple",children:[g,":"]}),l.jsx("span",{className:"g7dt-text-lightgray",children:Array.isArray(h)?JSON.stringify(h):h})]},g)),o=(d,g=5e3)=>{try{const h=JSON.stringify(d,null,2);return h.length>g?h.substring(0,g)+` +... (truncated)`:h}catch{return"(직렬화 불가)"}};return l.jsxs("div",{className:"g7dt-space-y-4",children:[e.activeRequests.length>0&&l.jsxs("div",{children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-yellow g7dt-mb-2",children:["진행 중 (",e.activeRequests.length,")"]}),l.jsx("div",{className:"g7dt-space-y-1",children:e.activeRequests.map(d=>l.jsxs("details",{className:"g7dt-details",children:[l.jsxs("summary",{className:"g7dt-summary g7dt-pending-request",children:[l.jsx("span",{className:"g7dt-font-bold",children:d.method}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-lightgray g7dt-truncate",children:d.fullUrl||d.url})]}),l.jsxs("div",{className:"g7dt-card g7dt-mt-1 g7dt-text-xs",children:[a(d)&&l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsx("div",{className:"g7dt-text-blue g7dt-font-bold g7dt-mb-1",children:"쿼리 파라미터"}),l.jsx("div",{className:"g7dt-pl-2 g7dt-border-l-2 g7dt-border-blue",children:i(d.queryParams)})]}),d.requestBody&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-orange g7dt-font-bold g7dt-mb-1",children:"요청 본문"}),l.jsx("pre",{className:"g7dt-pre g7dt-text-xs",children:o(d.requestBody,2e3)})]})]})]},d.id))})]}),l.jsxs("div",{children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"요청 이력"}),l.jsx("div",{className:"g7dt-space-y-1 g7dt-scroll-list-lg",children:e.requestHistory.length===0?l.jsx("div",{className:"g7dt-empty-message",children:"요청 이력 없음"}):e.requestHistory.slice(-20).reverse().map(d=>l.jsxs("details",{className:"g7dt-details",children:[l.jsxs("summary",{className:"g7dt-summary g7dt-card g7dt-text-xs",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-w-full",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-font-bold",children:d.method}),l.jsx("span",{className:`g7dt-ml-2 ${t(d.status)}`,children:d.statusCode||d.status})]}),l.jsxs("span",{className:"g7dt-text-gray",children:[d.duration,"ms"]})]}),l.jsx("div",{className:"g7dt-text-gray g7dt-truncate g7dt-mt-1",children:d.fullUrl||d.url})]}),l.jsxs("div",{className:"g7dt-card g7dt-mt-1 g7dt-text-xs g7dt-ml-2 g7dt-border-l-2 g7dt-border-gray",children:[l.jsx("div",{className:"g7dt-mb-2",children:l.jsxs("div",{className:"g7dt-text-xs g7dt-space-y-1",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"URL:"})," ",l.jsx("span",{className:"g7dt-text-lightgray",children:d.fullUrl||d.url})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"상태:"})," ",l.jsx("span",{className:t(d.status),children:d.statusCode||d.status})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"소요시간:"})," ",l.jsxs("span",{className:"g7dt-text-lightgray",children:[d.duration,"ms"]})]}),d.dataSourceId&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"데이터소스:"})," ",l.jsx("span",{className:"g7dt-text-blue",children:d.dataSourceId})]}),d.error&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"에러:"})," ",l.jsx("span",{className:"g7dt-text-red",children:d.error})]})]})}),a(d)&&l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsx("div",{className:"g7dt-text-blue g7dt-font-bold g7dt-mb-1",children:"쿼리 파라미터"}),l.jsx("div",{className:"g7dt-pl-2 g7dt-border-l-2 g7dt-border-blue",children:i(d.queryParams)})]}),d.requestBody&&l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsx("div",{className:"g7dt-text-orange g7dt-font-bold g7dt-mb-1",children:"요청 본문"}),l.jsx("pre",{className:"g7dt-pre g7dt-text-xs g7dt-max-h-40 g7dt-overflow-auto",children:o(d.requestBody,2e3)})]}),d.response!==void 0&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-green g7dt-font-bold g7dt-mb-1",children:"응답 내용"}),l.jsx("pre",{className:"g7dt-pre g7dt-text-xs g7dt-max-h-60 g7dt-overflow-auto",children:o(d.response,5e3)})]})]})]},d.id))})]}),e.pendingDataSources.length>0&&l.jsxs("div",{children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-blue g7dt-mb-2",children:["대기 중인 데이터소스 (",e.pendingDataSources.length,")"]}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-2",children:e.pendingDataSources.map(d=>l.jsx("span",{className:"g7dt-tag-blue",children:d},d))})]})]})},bk=({devTools:r})=>{const e=r.getFormInfo(),[t,a]=j.useState(!1),[i,o]=j.useState(null),d=j.useCallback(()=>{o(r.getFormBindingValidationTrackingInfo())},[r]);j.useEffect(()=>{if(t){d();const f=setInterval(d,2e3);return()=>clearInterval(f)}},[t,d]);const g=f=>{switch(f){case"missing-datakey":return"🔑";case"missing-input-name":return"📝";case"context-not-propagated":return"🔗";case"sortable-context-break":return"📊";case"modal-context-isolation":return"🪟";case"duplicate-input-name":return"👯";case"value-type-mismatch":return"⚠️";case"binding-path-invalid":return"❌";default:return"❓"}},h=f=>{switch(f){case"error":return"g7dt-text-red";case"warning":return"g7dt-text-yellow";case"info":return"g7dt-text-blue";default:return"g7dt-text-gray"}};return l.jsxs("div",{className:"g7dt-space-y-4",children:[e.length===0?l.jsx("div",{className:"g7dt-empty-message g7dt-py-8",children:"추적된 Form이 없습니다"}):e.map(f=>l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("span",{className:"g7dt-font-bold g7dt-text-blue",children:f.dataKey||"(no dataKey)"}),!f.dataKey&&l.jsx("span",{className:"g7dt-text-red g7dt-text-xs",children:"dataKey 필요"})]}),l.jsx("div",{className:"g7dt-space-y-1 g7dt-mb-2",children:f.inputs.map((p,y)=>l.jsxs("div",{className:"g7dt-text-xs g7dt-flex g7dt-justify-between",children:[l.jsx("span",{children:p.name||l.jsx("span",{className:"g7dt-text-red",children:"name 없음"})}),l.jsx("span",{className:"g7dt-text-gray",children:p.type})]},y))}),l.jsxs("details",{className:"g7dt-details",children:[l.jsx("summary",{className:"g7dt-summary",children:"현재 값 보기"}),l.jsx("pre",{className:"g7dt-pre",children:JSON.stringify(f,null,2)})]})]},f.id)),l.jsx("div",{className:"g7dt-flex g7dt-justify-end",children:l.jsx("button",{onClick:()=>a(!t),className:`g7dt-tab-button ${t?"g7dt-tab-active":""}`,children:"🔍 Auto-Binding Check"})}),t&&i&&l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"Form 바인딩 검증 결과"}),l.jsxs("div",{className:"g7dt-stats-grid g7dt-mb-3",children:[l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-blue",children:i.stats.totalFormsValidated}),l.jsx("div",{className:"g7dt-stat-label",children:"검증된 Form"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-green",children:i.stats.validForms}),l.jsx("div",{className:"g7dt-stat-label",children:"유효"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-red",children:i.stats.formsWithIssues}),l.jsx("div",{className:"g7dt-stat-label",children:"문제 있음"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-yellow",children:i.stats.totalIssues}),l.jsx("div",{className:"g7dt-stat-label",children:"총 이슈"})]})]}),i.stats.topIssues.length>0&&l.jsxs("div",{className:"g7dt-mb-3",children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"자주 발생하는 이슈"}),l.jsx("div",{className:"g7dt-space-y-1",children:i.stats.topIssues.slice(0,3).map((f,p)=>l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-xs",children:[l.jsx("span",{children:g(f.type)}),l.jsx("span",{className:"g7dt-text-white",children:f.description}),l.jsxs("span",{className:"g7dt-text-muted",children:["(",f.count,")"]})]},p))})]}),i.issues.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"바인딩 이슈가 없습니다 ✅"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:i.issues.slice().reverse().slice(0,30).map(f=>l.jsxs("div",{className:`g7dt-list-item ${f.severity==="error"?"g7dt-border-red":f.severity==="warning"?"g7dt-border-yellow":""}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{children:g(f.type)}),l.jsx("span",{className:`g7dt-text-xs g7dt-font-bold ${h(f.severity)}`,children:f.type}),f.formDataKey&&l.jsx("span",{className:"g7dt-text-xs g7dt-text-blue g7dt-font-mono",children:f.formDataKey})]}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-white g7dt-mt-1",children:f.description}),l.jsxs("div",{className:"g7dt-text-xs g7dt-text-green g7dt-mt-1",children:["💡 ",f.suggestion]}),f.contextInfo&&l.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-mt-1",children:[f.contextInfo.isInsideModal&&l.jsx("span",{className:"g7dt-badge g7dt-text-xs",children:"🪟 modal"}),f.contextInfo.isInsideSortable&&l.jsx("span",{className:"g7dt-badge g7dt-text-xs",children:"📊 sortable"}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted",children:["depth: ",f.contextInfo.depth]})]})]},f.id))})]})]})},vk=({devTools:r})=>{const e=r.getConditionalInfo();return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-purple g7dt-mb-2",children:["if 조건 (",e.ifConditions.length,")"]}),l.jsx("div",{className:"g7dt-space-y-1 g7dt-scroll-list",children:e.ifConditions.length===0?l.jsx("div",{className:"g7dt-empty-message",children:"추적된 if 조건 없음"}):e.ifConditions.map(t=>l.jsx("div",{className:`g7dt-condition-item ${t.evaluatedValue?"g7dt-condition-true":"g7dt-condition-false"}`,children:l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsx("span",{className:"g7dt-font-mono g7dt-text-lightgray g7dt-truncate-60",children:t.expression}),l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{className:t.evaluatedValue?"g7dt-badge-success":"g7dt-badge-error",children:t.evaluatedValue?"true":"false"}),l.jsxs("span",{className:"g7dt-text-gray",children:[t.evaluationCount,"회"]})]})]})},t.id))})]}),l.jsxs("div",{children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-cyan g7dt-mb-2",children:["iteration (",e.iterations.length,")"]}),l.jsx("div",{className:"g7dt-space-y-1 g7dt-scroll-list",children:e.iterations.length===0?l.jsx("div",{className:"g7dt-empty-message",children:"추적된 iteration 없음"}):e.iterations.map(t=>l.jsxs("div",{className:"g7dt-card g7dt-text-xs",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-1",children:[l.jsx("span",{className:"g7dt-font-mono g7dt-text-lightgray g7dt-truncate-60",children:t.source}),l.jsxs("span",{className:t.sourceLength>0?"g7dt-badge-blue":"g7dt-badge-warning",children:[t.sourceLength,"개 항목"]})]}),l.jsxs("div",{className:"g7dt-text-gray",children:[l.jsxs("span",{className:"g7dt-mr-2",children:["item_var: ",t.itemVar]}),t.indexVar&&l.jsxs("span",{children:["index_var: ",t.indexVar]})]})]},t.id))})]}),(e.ifConditions.some(t=>t.evaluatedValue===!1&&t.evaluationCount>5)||e.iterations.some(t=>t.sourceLength===0))&&l.jsxs("div",{className:"g7dt-warning-box",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-yellow g7dt-mb-2",children:"잠재적 문제"}),l.jsxs("div",{className:"g7dt-space-y-1 g7dt-text-xs",children:[e.ifConditions.filter(t=>t.evaluatedValue===!1&&t.evaluationCount>5).map(t=>l.jsxs("div",{className:"g7dt-text-lightgray",children:["⚠️ if 조건 항상 false: ",t.expression]},t.id)),e.iterations.filter(t=>t.sourceLength===0).map(t=>l.jsxs("div",{className:"g7dt-text-lightgray",children:["⚠️ iteration 소스 비어있음: ",t.source]},t.id))]})]})]})},wk=({devTools:r})=>{const[e,t]=j.useState([]),[a,i]=j.useState({totalEvaluations:0,uniqueExpressions:0,warningCount:0,cacheHitRate:0,averageDuration:0,byType:{},byWarning:{}}),[o,d]=j.useState(""),[g,h]=j.useState(!1),[f,p]=j.useState(null),y=j.useCallback(()=>{const A=r.getExpressionInfo();t(A.expressions),i(A.stats)},[r]);j.useEffect(()=>{y();const A=r.watchExpressions(()=>{y()}),O=setInterval(y,2e3);return()=>{A(),clearInterval(O)}},[r,y]);const x=e.filter(A=>{if(g&&!A.warning)return!1;if(o){const O=o.toLowerCase();return A.expression.toLowerCase().includes(O)||A.componentName?.toLowerCase().includes(O)||A.propName?.toLowerCase().includes(O)||A.resultType.toLowerCase().includes(O)}return!0}),S=A=>{switch(A){case"string":return"g7dt-text-green";case"number":return"g7dt-text-blue";case"boolean":return"g7dt-text-purple";case"array":return"g7dt-text-cyan";case"object":return"g7dt-text-yellow";case"undefined":case"null":return"g7dt-text-red";default:return"g7dt-text-gray"}},v=A=>{switch(A){case"undefined-result":return"undefined 결과";case"null-result":return"null 결과";case"array-to-string":return"배열→문자열";case"object-to-string":return"객체→문자열";case"missing-optional-chain":return"?. 누락 의심";case"wrong-iteration-var":return"잘못된 반복 변수";case"type-mismatch":return"타입 불일치";case"cache-stale":return"캐시 오래됨";case"slow-evaluation":return"느린 평가";default:return A}},w=(A,O)=>O==="undefined"?"undefined":O==="null"?"null":O==="string"?`"${String(A).substring(0,50)}${String(A).length>50?"...":""}"`:O==="array"?`Array(${Array.isArray(A)?A.length:"?"})`:O==="object"?"Object{...}":String(A),k=()=>{r.clearExpressions(),t([]),p(null)};return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-stats-grid-5",children:[l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-lg g7dt-text-blue",children:a.totalEvaluations}),l.jsx("div",{className:"g7dt-stat-label-xs",children:"총 평가"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-lg g7dt-text-green",children:a.uniqueExpressions}),l.jsx("div",{className:"g7dt-stat-label-xs",children:"고유 표현식"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-lg g7dt-text-yellow",children:a.warningCount}),l.jsx("div",{className:"g7dt-stat-label-xs",children:"경고"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsxs("div",{className:"g7dt-stat-value-lg g7dt-text-purple",children:[(a.cacheHitRate*100).toFixed(0),"%"]}),l.jsx("div",{className:"g7dt-stat-label-xs",children:"캐시 히트"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsxs("div",{className:"g7dt-stat-value-lg g7dt-text-cyan",children:[a.averageDuration.toFixed(1),"ms"]}),l.jsx("div",{className:"g7dt-stat-label-xs",children:"평균 시간"})]})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-items-center",children:[l.jsx("input",{type:"text",placeholder:"표현식, 컴포넌트, prop 검색...",value:o,onChange:A=>d(A.target.value),className:"g7dt-input g7dt-flex-1"}),l.jsxs("label",{className:"g7dt-checkbox-label",children:[l.jsx("input",{type:"checkbox",checked:g,onChange:A=>h(A.target.checked),className:"g7dt-checkbox"}),"경고만"]}),l.jsx("button",{onClick:k,className:"g7dt-btn-danger-sm",children:"초기화"})]}),Object.keys(a.byType).length>0&&l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1",children:Object.entries(a.byType).map(([A,O])=>l.jsxs("span",{className:`g7dt-type-tag ${S(A)}`,children:[A,": ",O]},A))}),l.jsx("div",{className:"g7dt-space-y-1 g7dt-expr-list",children:x.length===0?l.jsx("div",{className:"g7dt-empty-message g7dt-py-4",children:o||g?"조건에 맞는 표현식이 없습니다":"추적된 표현식이 없습니다"}):x.slice(-50).reverse().map(A=>l.jsx("div",{onClick:()=>p(A),className:`g7dt-expr-item ${f?.id===A.id?"g7dt-expr-selected":A.warning?"g7dt-expr-warning":""}`,children:l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-start g7dt-gap-2",children:[l.jsxs("div",{className:"g7dt-flex-1 g7dt-min-w-0",children:[l.jsx("div",{className:"g7dt-font-mono g7dt-text-white g7dt-truncate",title:A.expression,children:A.expression}),l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-mt-1 g7dt-text-xxs",children:[A.componentName&&l.jsxs("span",{className:"g7dt-text-gray",children:[A.componentName,A.propName&&`.${A.propName}`]}),l.jsx("span",{className:S(A.resultType),children:w(A.result,A.resultType)})]})]}),l.jsxs("div",{className:"g7dt-flex g7dt-flex-col g7dt-items-end g7dt-gap-1",children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-1",children:[A.fromCache&&l.jsx("span",{className:"g7dt-mini-badge g7dt-badge-success",children:"캐시"}),A.warning&&l.jsx("span",{className:"g7dt-mini-badge g7dt-badge-warning",children:v(A.warning.type)})]}),A.duration!==void 0&&l.jsxs("span",{className:"g7dt-text-xxs g7dt-text-gray",children:[A.duration.toFixed(2),"ms"]})]})]})},A.id))}),f&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:"표현식 상세"}),l.jsx("button",{onClick:()=>p(null),className:"g7dt-btn-close",children:"✕"})]}),l.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"표현식:"}),l.jsx("code",{className:"g7dt-code g7dt-text-green",children:f.expression})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"결과:"}),l.jsx("span",{className:`g7dt-ml-2 ${S(f.resultType)}`,children:JSON.stringify(f.result,null,2)?.substring(0,200)}),l.jsxs("span",{className:"g7dt-ml-2 g7dt-text-darkgray",children:["(",f.resultType,")"]})]}),f.componentName&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"컴포넌트:"}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-blue",children:f.componentName}),f.propName&&l.jsxs("span",{className:"g7dt-text-gray",children:[".",f.propName]})]}),f.method&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"메서드:"}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-purple",children:f.method})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"캐시:"}),l.jsxs("span",{className:`g7dt-ml-2 ${f.fromCache?"g7dt-text-green":"g7dt-text-gray"}`,children:[f.fromCache?"캐시에서 로드":"새로 평가",f.skipCache&&" (skipCache)"]})]}),f.duration!==void 0&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"소요 시간:"}),l.jsxs("span",{className:`g7dt-ml-2 ${f.duration>10?"g7dt-text-red":"g7dt-text-lightgray"}`,children:[f.duration.toFixed(3),"ms"]})]}),f.warning&&l.jsxs("div",{className:"g7dt-warning-box-light",children:[l.jsxs("div",{className:"g7dt-text-yellow g7dt-font-bold",children:["⚠️ ",v(f.warning.type)]}),l.jsx("div",{className:"g7dt-text-lightgray g7dt-mt-1",children:f.warning.message}),f.warning.suggestion&&l.jsxs("div",{className:"g7dt-text-gray g7dt-mt-1 g7dt-text-xxs",children:["💡 ",f.warning.suggestion]})]}),f.steps&&f.steps.length>0&&l.jsxs("details",{className:"g7dt-details",children:[l.jsxs("summary",{className:"g7dt-summary",children:["평가 단계 (",f.steps.length,")"]}),l.jsx("div",{className:"g7dt-mt-1 g7dt-space-y-1 g7dt-pl-2 g7dt-border-l",children:f.steps.map((A,O)=>l.jsxs("div",{className:"g7dt-text-xxs",children:[l.jsx("span",{className:"g7dt-text-purple",children:A.step}),A.path&&l.jsx("span",{className:"g7dt-text-gray g7dt-ml-1",children:A.path}),A.fromCache&&l.jsx("span",{className:"g7dt-text-green g7dt-ml-1",children:"(cached)"}),A.error&&l.jsx("span",{className:"g7dt-text-red g7dt-ml-1",children:A.error})]},O))})]})]})]}),Object.keys(a.byWarning).length>0&&l.jsxs("div",{className:"g7dt-warning-box-light",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-yellow g7dt-mb-2",children:"경고 요약"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-2",children:Object.entries(a.byWarning).map(([A,O])=>l.jsxs("span",{className:"g7dt-warning-tag",children:[v(A),": ",O]},A))})]})]})},Sk=({devTools:r})=>{const e=r.getHandlers(),[t,a]=j.useState(""),[i,o]=j.useState("all"),d={"built-in":e.filter(f=>f.category==="built-in"),custom:e.filter(f=>f.category==="custom"),module:e.filter(f=>f.category==="module"),plugin:e.filter(f=>f.category==="plugin")},g={all:e.length,"built-in":d["built-in"].length,custom:d.custom.length,module:d.module.length,plugin:d.plugin.length},h=e.filter(f=>i!=="all"&&f.category!==i?!1:t?f.name.toLowerCase().includes(t.toLowerCase())||f.description?.toLowerCase().includes(t.toLowerCase()):!0);return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsx("div",{className:"g7dt-flex g7dt-gap-2",children:["all","built-in","custom","module","plugin"].map(f=>l.jsxs("button",{onClick:()=>o(f),className:i===f?"g7dt-filter-btn g7dt-filter-active":"g7dt-filter-btn",children:[f==="all"?"전체":f," (",g[f],")"]},f))}),l.jsx("input",{type:"text",placeholder:"핸들러 이름 검색...",value:t,onChange:f=>a(f.target.value),className:"g7dt-input g7dt-w-full"}),l.jsx("div",{className:"g7dt-space-y-1 g7dt-handler-list",children:h.length===0?l.jsx("div",{className:"g7dt-empty-message g7dt-py-4",children:"등록된 핸들러가 없습니다"}):h.map(f=>l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsx("span",{className:"g7dt-font-mono g7dt-text-blue",children:f.name}),l.jsx("span",{className:f.category==="built-in"?"g7dt-mini-badge g7dt-badge-success":f.category==="module"?"g7dt-mini-badge g7dt-badge-purple":f.category==="plugin"?"g7dt-mini-badge g7dt-badge-info":"g7dt-mini-badge g7dt-badge-warning",children:f.category})]}),f.description&&l.jsx("div",{className:"g7dt-text-xs g7dt-text-gray g7dt-mt-1",children:f.description})]},f.name))}),l.jsxs("div",{className:"g7dt-text-xs g7dt-text-gray",children:["총 ",e.length,"개 핸들러 | 빌트인 ",g["built-in"]," | 커스텀 ",g.custom," | 모듈 ",g.module," | 플러그인 ",g.plugin]})]})},Ck=({devTools:r})=>{const[e,t]=j.useState(r.getComponentEventInfo()),[a,i]=j.useState(null),o=j.useCallback(()=>{t(r.getComponentEventInfo())},[r]);j.useEffect(()=>{o();const g=setInterval(o,2e3);return()=>clearInterval(g)},[o]);const d=a?e.emitHistory.filter(g=>g.eventName===a):e.emitHistory;return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-stats-grid-3",children:[l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value-lg g7dt-text-blue",children:e.subscriptions.length}),l.jsx("div",{className:"g7dt-stat-label",children:"이벤트 타입"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value-lg g7dt-text-green",children:e.totalSubscribers}),l.jsx("div",{className:"g7dt-stat-label",children:"총 구독자"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value-lg g7dt-text-purple",children:e.totalEmits}),l.jsx("div",{className:"g7dt-stat-label",children:"총 발행"})]})]}),l.jsxs("div",{children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"구독된 이벤트"}),l.jsxs("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-2",children:[l.jsx("button",{onClick:()=>i(null),className:a===null?"g7dt-filter-btn g7dt-filter-active":"g7dt-filter-btn",children:"전체"}),e.subscriptions.map(g=>l.jsxs("button",{onClick:()=>i(g.eventName),className:a===g.eventName?"g7dt-filter-btn g7dt-filter-active":"g7dt-filter-btn",children:[g.eventName," (",g.subscriberCount,")"]},g.eventName))]})]}),l.jsxs("div",{children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:["발행 이력 ",a&&`(${a})`]}),l.jsx("div",{className:"g7dt-space-y-1 g7dt-event-list",children:d.length===0?l.jsx("div",{className:"g7dt-empty-message g7dt-py-4",children:"이벤트 발행 이력이 없습니다"}):d.slice(-30).reverse().map(g=>l.jsxs("div",{className:`g7dt-card g7dt-text-xs ${g.hasError?"g7dt-card-error":""}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsx("span",{className:"g7dt-font-mono g7dt-text-green",children:g.eventName}),l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsxs("span",{className:"g7dt-text-gray",children:[g.listenerCount," listeners"]}),g.hasError&&l.jsx("span",{className:"g7dt-text-red g7dt-text-xxs",children:"에러"})]})]}),g.data!==void 0&&l.jsxs("details",{className:"g7dt-details g7dt-mt-1",children:[l.jsx("summary",{className:"g7dt-summary",children:"데이터"}),l.jsx("pre",{className:"g7dt-pre",children:JSON.stringify(g.data,null,2)})]}),g.hasError&&g.errorMessage&&l.jsx("div",{className:"g7dt-error-inline",children:g.errorMessage})]},g.id))})]}),l.jsx("button",{onClick:o,className:"g7dt-btn-secondary",children:"새로고침"})]})},jk=({devTools:r})=>{const e=r.getDataSources(),[t,a]=j.useState("all"),[i,o]=j.useState(null),[d,g]=j.useState(!1),[h,f]=j.useState(null),p=j.useCallback(()=>{f(r.getDataPathTransformTrackingInfo())},[r]);j.useEffect(()=>{if(d){p();const k=setInterval(p,2e3);return()=>clearInterval(k)}},[d,p]);const y=k=>{switch(k){case"api_response":return"📥";case"extract_data":return"📄";case"apply_path":return"🔗";case"init_global":return"🌐";case"init_local":return"📌";default:return"❓"}},x=e.filter(k=>t==="all"?!0:k.status===t),S={all:e.length,idle:e.filter(k=>k.status==="idle").length,loading:e.filter(k=>k.status==="loading").length,loaded:e.filter(k=>k.status==="loaded").length,error:e.filter(k=>k.status==="error").length},v=k=>{switch(k){case"loaded":return"g7dt-badge-success";case"loading":return"g7dt-badge-warning";case"error":return"g7dt-badge-error";default:return"g7dt-badge-gray"}},w=i?e.find(k=>k.id===i):null;return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsx("div",{className:"g7dt-flex g7dt-gap-2",children:["all","idle","loading","loaded","error"].map(k=>l.jsxs("button",{onClick:()=>a(k),className:t===k?"g7dt-filter-btn g7dt-filter-active":"g7dt-filter-btn",children:[k==="all"?"전체":k," (",S[k],")"]},k))}),l.jsx("div",{className:"g7dt-ds-grid",children:x.length===0?l.jsx("div",{className:"g7dt-empty-message g7dt-col-span-2 g7dt-py-4",children:"데이터소스가 없습니다"}):x.map(k=>l.jsxs("div",{onClick:()=>o(k.id),className:`g7dt-ds-item ${i===k.id?"g7dt-ds-selected":""}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsx("span",{className:"g7dt-font-mono g7dt-text-blue g7dt-truncate",children:k.id}),l.jsx("span",{className:`g7dt-mini-badge ${v(k.status)}`,children:k.status})]}),l.jsx("div",{className:"g7dt-text-gray g7dt-mt-1 g7dt-truncate",children:k.endpoint||"(endpoint 없음)"}),k.itemCount!==void 0&&l.jsxs("div",{className:"g7dt-text-lightgray g7dt-mt-1",children:[k.itemCount,"개 항목"]})]},k.id))}),w&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:w.id}),l.jsx("button",{onClick:()=>o(null),className:"g7dt-btn-close",children:"✕"})]}),l.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"엔드포인트:"}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-green",children:w.endpoint||"-"})]}),w.dataPath&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"데이터 경로:"}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-yellow",children:w.dataPath})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"상태:"}),l.jsx("span",{className:`g7dt-ml-2 g7dt-mini-badge ${v(w.status)}`,children:w.status})]}),w.itemCount!==void 0&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"항목 수:"}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-blue",children:w.itemCount})]}),w.keys&&w.keys.length>0&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"키:"}),l.jsxs("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1",children:[w.keys.slice(0,10).map(k=>l.jsx("span",{className:"g7dt-key-tag",children:k},k)),w.keys.length>10&&l.jsxs("span",{className:"g7dt-text-gray",children:["+",w.keys.length-10,"개"]})]})]}),w.dependencies&&w.dependencies.length>0&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-gray",children:"의존성:"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1",children:w.dependencies.map(k=>l.jsx("span",{className:"g7dt-dep-tag",children:k},k))})]})]})]}),l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsxs("div",{className:"g7dt-text-xs g7dt-text-gray",children:["총 ",e.length,"개 데이터소스 | 로드됨 ",S.loaded," | 로딩중 ",S.loading," | 에러 ",S.error]}),l.jsx("button",{onClick:()=>g(!d),className:`g7dt-tab-button ${d?"g7dt-tab-active":""}`,children:"🔀 Path Transform"})]}),d&&h&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:["데이터 경로 변환 추적 (",h.transforms.length,"개)"]}),l.jsxs("div",{className:"g7dt-stats-grid-3 g7dt-mb-3",children:[l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-xl g7dt-font-bold g7dt-text-blue",children:h.stats.totalTransforms}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"총 변환"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-xl g7dt-font-bold g7dt-text-purple",children:Object.keys(h.stats.byDataSource).length}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"데이터소스"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-xl g7dt-font-bold g7dt-text-yellow",children:h.stats.warningsCount}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"경고"})]})]}),h.transforms.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"변환 기록이 없습니다"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:h.transforms.slice().reverse().slice(0,20).map((k,A)=>l.jsxs("div",{className:`g7dt-list-item ${k.warnings.length>0?"g7dt-border-yellow":""}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{className:"g7dt-text-xs g7dt-text-blue g7dt-font-mono",children:k.dataSourceId}),k.warnings.length>0&&l.jsxs("span",{className:"g7dt-badge g7dt-text-xs g7dt-text-yellow",children:["⚠️ ",k.warnings.length]})]}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1",children:k.transformSteps.map((O,N)=>l.jsxs("span",{className:"g7dt-badge g7dt-text-xs",title:`${O.inputPath} → ${O.outputPath}`,children:[y(O.step)," ",O.step]},N))}),k.finalBinding&&l.jsxs("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-1",children:["최종: ",l.jsx("span",{className:"g7dt-text-green",children:k.finalBinding.expression}),"→ ",l.jsx("span",{className:"g7dt-text-blue",children:k.finalBinding.resolvedPath})]}),k.warnings.length>0&&l.jsx("div",{className:"g7dt-text-xs g7dt-text-yellow g7dt-mt-1",children:k.warnings[0]})]},`${k.dataSourceId}-${A}`))}),h.stats.commonWarnings.length>0&&l.jsxs("div",{className:"g7dt-mt-3",children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-1",children:"자주 발생하는 경고"}),l.jsx("div",{className:"g7dt-space-y-1",children:h.stats.commonWarnings.slice(0,5).map((k,A)=>l.jsxs("div",{className:"g7dt-text-xs g7dt-text-yellow",children:[k.warning," (",k.count,"회)"]},A))})]})]})]})},kk=({devTools:r})=>{const[e,t]=j.useState(r.getStateRenderingInfo()),[a,i]=j.useState(null),[o,d]=j.useState(!1),[g,h]=j.useState(""),f=j.useCallback(()=>{t(r.getStateRenderingInfo())},[r]);j.useEffect(()=>{f();const v=setInterval(f,2e3);return()=>clearInterval(v)},[f]);const p=e.logs.filter(v=>!(o&&v.renderedComponents.length>0||g&&!v.statePath.toLowerCase().includes(g.toLowerCase()))),y=a?e.logs.find(v=>v.setStateId===a):null,x=e.stats,S=e.logs.filter(v=>v.renderedComponents.length===0).length;return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-stats-grid",children:[l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-blue",children:x.totalStateChanges}),l.jsx("div",{className:"g7dt-stat-label",children:"상태 변경"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-green",children:x.totalRenders}),l.jsx("div",{className:"g7dt-stat-label",children:"총 렌더링"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsxs("div",{className:"g7dt-stat-value g7dt-text-purple",children:[x.avgRenderDuration.toFixed(1),"ms"]}),l.jsx("div",{className:"g7dt-stat-label",children:"평균 렌더 시간"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:`g7dt-stat-value ${S>0?"g7dt-text-yellow":"g7dt-text-green"}`,children:S}),l.jsx("div",{className:"g7dt-stat-label",children:"렌더링 없음"})]})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsx("input",{type:"text",placeholder:"상태 경로 필터 (예: _global.user)",value:g,onChange:v=>h(v.target.value),className:"g7dt-input g7dt-flex-1"}),l.jsx("button",{onClick:()=>d(!o),className:o?"g7dt-filter-btn-active-yellow":"g7dt-filter-btn",children:"렌더링 없음만"})]}),l.jsx("div",{className:"g7dt-scroll-list",children:p.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"상태-렌더링 로그가 없습니다"}):p.slice(-30).reverse().map(v=>{const w=v.renderedComponents.length>0,k=w?"✅":"⚠️",A=new Date(v.timestamp).toLocaleTimeString();return l.jsxs("div",{onClick:()=>i(v.setStateId),className:`g7dt-render-log-item ${a===v.setStateId?"g7dt-selected":w?"":"g7dt-warning"}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsxs("span",{className:"g7dt-mono g7dt-text-blue",children:[k," ",v.statePath]}),l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[w?l.jsxs("span",{className:"g7dt-text-green",children:[v.renderedComponents.length,"개 렌더"]}):l.jsx("span",{className:"g7dt-text-yellow",children:"렌더링 없음"}),l.jsx("span",{className:"g7dt-text-muted",children:A})]})]}),v.triggeredBy?.handlerType&&l.jsxs("div",{className:"g7dt-text-muted g7dt-mt-1",children:["트리거: ",v.triggeredBy.handlerType]})]},v.setStateId)})}),y&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:y.statePath}),l.jsx("button",{onClick:()=>i(null),className:"g7dt-close-btn",children:"✕"})]}),l.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"setStateId:"}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-purple g7dt-mono",children:y.setStateId})]}),y.triggeredBy&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"트리거:"}),l.jsxs("span",{className:"g7dt-ml-2 g7dt-text-yellow",children:[y.triggeredBy.handlerType,y.triggeredBy.actionId&&` (${y.triggeredBy.actionId})`]})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"이전 값:"}),l.jsx("pre",{className:"g7dt-pre g7dt-text-red",children:JSON.stringify(y.oldValue,null,2)?.slice(0,200)})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"새 값:"}),l.jsx("pre",{className:"g7dt-pre g7dt-text-green",children:JSON.stringify(y.newValue,null,2)?.slice(0,200)})]}),y.renderedComponents.length>0?l.jsxs("div",{children:[l.jsxs("span",{className:"g7dt-text-muted",children:["렌더링된 컴포넌트 (",y.renderedComponents.length,"개):"]}),l.jsxs("div",{className:"g7dt-mt-1 g7dt-space-y-1",children:[y.renderedComponents.slice(0,10).map((v,w)=>l.jsxs("div",{className:"g7dt-render-comp-item",children:[l.jsx("span",{className:"g7dt-text-blue",children:v.componentName}),l.jsxs("span",{className:"g7dt-text-muted",children:[v.renderDuration.toFixed(2),"ms"]})]},w)),y.renderedComponents.length>10&&l.jsxs("div",{className:"g7dt-text-muted g7dt-text-center",children:["... 외 ",y.renderedComponents.length-10,"개"]})]}),l.jsxs("div",{className:"g7dt-mt-2 g7dt-text-muted",children:["총 렌더 시간: ",y.totalRenderDuration.toFixed(2),"ms"]})]}):l.jsxs("div",{className:"g7dt-warning-box",children:[l.jsx("span",{className:"g7dt-text-yellow",children:"⚠️ 렌더링이 발생하지 않았습니다"}),l.jsxs("div",{className:"g7dt-text-muted g7dt-mt-1 g7dt-text-xxs",children:["가능한 원인:",l.jsxs("ul",{className:"g7dt-list g7dt-mt-1",children:[l.jsx("li",{children:"해당 상태를 바인딩하는 컴포넌트가 없음"}),l.jsx("li",{children:"컴포넌트가 마운트되지 않은 상태"}),l.jsx("li",{children:"동일한 값으로 상태 설정"})]})]})]})]})]}),x.topRenderedComponents.length>0&&l.jsxs("div",{children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"가장 많이 렌더링된 컴포넌트"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-2",children:x.topRenderedComponents.slice(0,5).map((v,w)=>l.jsxs("span",{className:"g7dt-tag",children:[v.name,": ",l.jsx("span",{className:"g7dt-text-blue",children:v.count})]},w))})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsx("button",{onClick:f,className:"g7dt-btn-secondary",children:"새로고침"}),l.jsx("button",{onClick:()=>{r.clearStateRenderingLogs(),f()},className:"g7dt-btn-danger",children:"로그 초기화"})]})]})},Nk=({devTools:r})=>{const[e,t]=j.useState(null),[a,i]=j.useState(null),[o,d]=j.useState("all"),g=j.useCallback(()=>{t(r.getStyleValidationInfo())},[r]);if(j.useEffect(()=>{g();const y=setInterval(g,2e3);return()=>clearInterval(y)},[g]),!e)return l.jsx("div",{className:"g7dt-empty-state",children:"로딩 중..."});const h=e.issues.filter(y=>o==="all"?!0:y.type===o),f=a?e.issues.find(y=>y.componentId===a):null,p=e.stats;return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-stats-grid",children:[l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value g7dt-text-blue",children:p.totalComponents}),l.jsx("div",{className:"g7dt-stat-label",children:"총 컴포넌트"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:`g7dt-stat-value ${p.invisibleCount>0?"g7dt-text-red":"g7dt-text-green"}`,children:p.invisibleCount}),l.jsx("div",{className:"g7dt-stat-label",children:"숨겨진 요소"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:`g7dt-stat-value ${p.tailwindIssueCount>0?"g7dt-text-yellow":"g7dt-text-green"}`,children:p.tailwindIssueCount}),l.jsx("div",{className:"g7dt-stat-label",children:"Tailwind 이슈"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:`g7dt-stat-value ${p.darkModeIssueCount>0?"g7dt-text-purple":"g7dt-text-green"}`,children:p.darkModeIssueCount}),l.jsx("div",{className:"g7dt-stat-label",children:"다크모드 이슈"})]})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsxs("select",{value:o,onChange:y=>d(y.target.value),className:"g7dt-select",children:[l.jsx("option",{value:"all",children:"모든 이슈"}),l.jsx("option",{value:"invisible-element",children:"숨겨진 요소"}),l.jsx("option",{value:"tailwind-purging",children:"Tailwind 퍼징"}),l.jsx("option",{value:"dark-mode-missing",children:"다크모드 누락"})]}),l.jsx("button",{onClick:g,className:"g7dt-btn-secondary",children:"새로고침"})]}),l.jsx("div",{className:"g7dt-scroll-list",children:h.length===0?l.jsx("div",{className:"g7dt-empty-state",children:e.issues.length===0?"스타일 이슈가 없습니다 ✓":"필터에 맞는 이슈가 없습니다"}):h.map(y=>{const x=y.type==="invisible-element"?"👁️":y.type==="tailwind-purging"?"🎨":"🌙",S=y.severity==="error"?"g7dt-severity-error":y.severity==="warning"?"g7dt-severity-warning":"g7dt-severity-info";return l.jsxs("div",{onClick:()=>i(y.componentId),className:`g7dt-style-issue-item ${S} ${a===y.componentId?"g7dt-selected":""}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsxs("span",{className:"g7dt-mono g7dt-text-blue",children:[x," ",y.componentName]}),l.jsx("span",{className:y.severity==="error"?"g7dt-badge-error":y.severity==="warning"?"g7dt-badge-warning":"g7dt-badge-info",children:y.type})]}),l.jsx("div",{className:"g7dt-text-muted g7dt-mt-1 g7dt-truncate",children:y.description})]},y.componentId)})}),f&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:f.componentName}),l.jsx("button",{onClick:()=>i(null),className:"g7dt-close-btn",children:"✕"})]}),l.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"이슈 타입:"}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-yellow",children:f.type})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"설명:"}),l.jsx("div",{className:"g7dt-mt-1 g7dt-text-white",children:f.description})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"CSS 속성:"}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-purple",children:f.property}),l.jsxs("span",{className:"g7dt-ml-2 g7dt-text-muted",children:["= ",f.currentValue]}),f.expectedValue&&l.jsxs("span",{className:"g7dt-ml-2 g7dt-text-green",children:["(예상: ",f.expectedValue,")"]})]}),f.suggestion&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"해결 방법:"}),l.jsx("div",{className:"g7dt-mt-1 g7dt-text-green",children:f.suggestion})]})]})]}),e.componentStyles.length>0&&l.jsxs("div",{children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:["컴포넌트 스타일 (",e.componentStyles.length,")"]}),l.jsx("div",{className:"g7dt-scroll-list-sm",children:e.componentStyles.slice(0,20).map((y,x)=>l.jsxs("div",{className:"g7dt-list-item",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-blue",children:y.componentName}),l.jsxs("span",{className:"g7dt-text-muted",children:[y.classes.length," classes"]})]}),y.classes.length>0&&l.jsxs("div",{className:"g7dt-text-muted g7dt-mt-1 g7dt-truncate",children:[y.classes.slice(0,5).join(" "),y.classes.length>5&&"..."]})]},x))})]})]})},Ek=({devTools:r})=>{const[e,t]=j.useState(null),[a,i]=j.useState(null),[o,d]=j.useState("all"),g=j.useCallback(()=>{t(r.getAuthDebugInfo())},[r]);if(j.useEffect(()=>{g();const x=setInterval(g,2e3);return()=>clearInterval(x)},[g]),!e)return l.jsx("div",{className:"g7dt-empty-state",children:"로딩 중..."});const h=e.events.filter(x=>o==="all"?!0:x.type===o),f=a?e.events.find(x=>x.id===a):null,p=e.stats,y=e.state;return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-justify-between g7dt-mb-3",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:"현재 인증 상태"}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted",children:["소스: ",y.source||"unknown"]})]}),l.jsxs("div",{className:"g7dt-stats-grid-3 g7dt-mb-3",children:[l.jsx("div",{className:"g7dt-text-center",children:l.jsx("div",{className:`g7dt-text-lg g7dt-font-bold ${y.isAuthenticated?"g7dt-text-green":"g7dt-text-red"}`,children:y.isAuthenticated?"✓ 인증됨":"✕ 미인증"})}),l.jsx("div",{className:"g7dt-text-center",children:l.jsx("div",{className:`g7dt-text-lg g7dt-font-bold ${y.tokens.hasAccessToken?"g7dt-text-green":"g7dt-text-yellow"}`,children:y.tokens.hasAccessToken?"✓ 토큰 유효":"⚠ 토큰 없음"})}),l.jsx("div",{className:"g7dt-text-center",children:l.jsx("div",{className:"g7dt-text-lg g7dt-font-bold g7dt-text-blue",children:y.user?.name||y.user?.email||"익명"})})]}),y.user&&l.jsxs("div",{className:"g7dt-border-t g7dt-pt-3 g7dt-mt-3",children:[l.jsxs("div",{className:"g7dt-grid-2 g7dt-gap-2 g7dt-text-xs",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"ID:"}),l.jsx("span",{className:"g7dt-text-white g7dt-mono",children:y.user.id})]}),l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"이메일:"}),l.jsx("span",{className:"g7dt-text-white g7dt-truncate g7dt-ml-2",title:y.user.email,children:y.user.email})]}),y.user.name&&l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"이름:"}),l.jsx("span",{className:"g7dt-text-white",children:y.user.name})]}),y.user.nickname&&l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"닉네임:"}),l.jsx("span",{className:"g7dt-text-white",children:y.user.nickname})]}),y.user.phone&&l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"전화번호:"}),l.jsx("span",{className:"g7dt-text-white",children:y.user.phone})]}),y.user.status&&l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"상태:"}),l.jsx("span",{className:y.user.status==="active"?"g7dt-text-green":"g7dt-text-yellow",children:y.user.status})]}),y.user.locale&&l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"언어:"}),l.jsx("span",{className:"g7dt-text-white",children:y.user.locale})]})]}),y.user.roles&&y.user.roles.length>0&&l.jsxs("div",{className:"g7dt-mt-2",children:[l.jsx("span",{className:"g7dt-text-muted g7dt-text-xs",children:"역할: "}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1",children:y.user.roles.map((x,S)=>l.jsx("span",{className:"g7dt-role-tag",title:x.guard_name?`guard: ${x.guard_name}`:void 0,children:typeof x=="string"?x:x.name},S))})]}),y.user.permissions&&y.user.permissions.length>0&&l.jsxs("div",{className:"g7dt-mt-2",children:[l.jsx("span",{className:"g7dt-text-muted g7dt-text-xs",children:"권한: "}),l.jsxs("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1 g7dt-max-h-16 g7dt-overflow-auto",children:[y.user.permissions.slice(0,10).map((x,S)=>l.jsx("span",{className:"g7dt-perm-tag",title:x.guard_name?`guard: ${x.guard_name}`:void 0,children:typeof x=="string"?x:x.name},S)),y.user.permissions.length>10&&l.jsxs("span",{className:"g7dt-text-muted g7dt-text-xs",children:["+",y.user.permissions.length-10,"개"]})]})]}),l.jsxs("div",{className:"g7dt-mt-2 g7dt-grid-2 g7dt-gap-2 g7dt-text-xs",children:[y.user.created_at&&l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"가입일:"}),l.jsx("span",{className:"g7dt-text-muted",children:new Date(y.user.created_at).toLocaleDateString()})]}),y.user.last_login_at&&l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"마지막 로그인:"}),l.jsx("span",{className:"g7dt-text-muted",children:new Date(y.user.last_login_at).toLocaleString()})]}),y.user.email_verified_at&&l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"이메일 인증:"}),l.jsx("span",{className:"g7dt-text-green",children:"✓ 인증됨"})]})]})]}),l.jsx("div",{className:"g7dt-border-t g7dt-pt-3 g7dt-mt-3",children:l.jsxs("div",{className:"g7dt-grid-2 g7dt-gap-2 g7dt-text-xs",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"저장소:"}),l.jsx("span",{className:"g7dt-text-white",children:y.tokens.storage})]}),y.tokens.accessTokenPreview&&l.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[l.jsx("span",{className:"g7dt-text-muted",children:"토큰:"}),l.jsx("span",{className:"g7dt-text-muted g7dt-mono",children:y.tokens.accessTokenPreview})]})]})}),y.tokens.accessTokenExpiresAt&&l.jsxs("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-2 g7dt-text-center",children:["토큰 만료: ",new Date(y.tokens.accessTokenExpiresAt).toLocaleString()]})]}),l.jsxs("div",{className:"g7dt-stats-grid-5",children:[l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-blue",children:p.loginAttempts}),l.jsx("div",{className:"g7dt-stat-label",children:"로그인 시도"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-green",children:p.successfulLogins}),l.jsx("div",{className:"g7dt-stat-label",children:"성공"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:`g7dt-stat-value-sm ${p.failedLogins>0?"g7dt-text-red":"g7dt-text-muted"}`,children:p.failedLogins}),l.jsx("div",{className:"g7dt-stat-label",children:"실패"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-purple",children:p.tokenRefreshes}),l.jsx("div",{className:"g7dt-stat-label",children:"토큰 갱신"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:`g7dt-stat-value-sm ${p.unauthorizedResponses>0?"g7dt-text-red":"g7dt-text-muted"}`,children:p.unauthorizedResponses}),l.jsx("div",{className:"g7dt-stat-label",children:"401 응답"})]})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsxs("select",{value:o,onChange:x=>d(x.target.value),className:"g7dt-select",children:[l.jsx("option",{value:"all",children:"모든 이벤트"}),l.jsx("option",{value:"login",children:"로그인"}),l.jsx("option",{value:"logout",children:"로그아웃"}),l.jsx("option",{value:"token-refresh",children:"토큰 갱신"}),l.jsx("option",{value:"token-expired",children:"토큰 만료"}),l.jsx("option",{value:"api-unauthorized",children:"401 응답"})]}),l.jsx("button",{onClick:g,className:"g7dt-btn-secondary",children:"새로고침"})]}),l.jsx("div",{className:"g7dt-scroll-list-sm",children:h.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"인증 이벤트가 없습니다"}):h.slice(-20).reverse().map(x=>{const S=x.success?"✅":"❌",v=new Date(x.timestamp).toLocaleTimeString();return l.jsxs("div",{onClick:()=>i(x.id),className:`g7dt-auth-event-item ${a===x.id?"g7dt-selected":x.success?"":"g7dt-error"}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsxs("span",{className:"g7dt-mono",children:[S," ",x.type]}),l.jsx("span",{className:"g7dt-text-muted",children:v})]}),x.error&&l.jsx("div",{className:"g7dt-text-red g7dt-mt-1 g7dt-truncate",children:x.error})]},x.id)})}),f&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:f.type}),l.jsx("button",{onClick:()=>i(null),className:"g7dt-close-btn",children:"✕"})]}),l.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"결과:"}),l.jsx("span",{className:`g7dt-ml-2 ${f.success?"g7dt-text-green":"g7dt-text-red"}`,children:f.success?"성공":"실패"})]}),f.error&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"에러:"}),l.jsx("div",{className:"g7dt-mt-1 g7dt-text-red",children:f.error})]}),f.details&&Object.keys(f.details).length>0&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"상세:"}),l.jsx("pre",{className:"g7dt-pre g7dt-text-green",children:JSON.stringify(f.details,null,2)})]})]})]}),e.headerAnalysis.length>0&&l.jsxs("div",{children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"최근 API 인증 헤더"}),l.jsx("div",{className:"g7dt-scroll-list-xs",children:e.headerAnalysis.slice(-10).reverse().map((x,S)=>l.jsxs("div",{className:"g7dt-header-item",children:[l.jsx("span",{className:"g7dt-text-blue g7dt-truncate g7dt-flex-1",children:x.url}),l.jsx("span",{className:`g7dt-ml-2 ${x.hasAuthHeader?"g7dt-text-green":"g7dt-text-yellow"}`,children:x.hasAuthHeader?`✓ ${x.headerType}`:"✕ 헤더 없음"}),x.responseStatus&&l.jsx("span",{className:`g7dt-ml-2 ${x.responseStatus<400?"g7dt-text-muted":"g7dt-text-red"}`,children:x.responseStatus})]},S))})]})]})},_k=({devTools:r})=>{const[e,t]=j.useState([]),[a,i]=j.useState(null),[o,d]=j.useState(null),[g,h]=j.useState("all"),[f,p]=j.useState(""),[y,x]=j.useState(""),S=j.useCallback(()=>{const N=r.getLogInfo();t(N.entries),i(N.stats)},[r]);j.useEffect(()=>{S();const N=setInterval(S,1e3);return()=>clearInterval(N)},[S]);const v=e.filter(N=>!(g!=="all"&&N.level!==g||f&&!N.prefix.toLowerCase().includes(f.toLowerCase())||y&&!N.message.toLowerCase().includes(y.toLowerCase()))),w=o?e.find(N=>N.id===o):null,k=()=>{r.clearLogs(),S(),d(null)},A=N=>{switch(N){case"error":return"g7dt-text-red";case"warn":return"g7dt-text-yellow";case"info":return"g7dt-text-blue";case"debug":return"g7dt-text-muted";default:return"g7dt-text-white"}},O=N=>{switch(N){case"error":return"g7dt-log-error";case"warn":return"g7dt-log-warn";case"info":return"g7dt-log-info";case"debug":return"g7dt-log-debug";default:return"g7dt-log-default"}};return l.jsxs("div",{className:"g7dt-space-y-4",children:[a&&l.jsxs("div",{className:"g7dt-stats-grid-6",children:[l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-white",children:a.totalLogs}),l.jsx("div",{className:"g7dt-stat-label",children:"전체"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-red",children:a.byLevel.error}),l.jsx("div",{className:"g7dt-stat-label",children:"에러"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-yellow",children:a.byLevel.warn}),l.jsx("div",{className:"g7dt-stat-label",children:"경고"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-blue",children:a.byLevel.info}),l.jsx("div",{className:"g7dt-stat-label",children:"정보"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:`g7dt-stat-value-sm ${a.recentErrors>0?"g7dt-text-red":"g7dt-text-green"}`,children:a.recentErrors}),l.jsx("div",{className:"g7dt-stat-label",children:"최근 에러"})]}),l.jsxs("div",{className:"g7dt-stat-card-sm",children:[l.jsx("div",{className:`g7dt-stat-value-sm ${a.recentWarnings>0?"g7dt-text-yellow":"g7dt-text-green"}`,children:a.recentWarnings}),l.jsx("div",{className:"g7dt-stat-label",children:"최근 경고"})]})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-flex-wrap",children:[l.jsxs("select",{value:g,onChange:N=>h(N.target.value),className:"g7dt-select",children:[l.jsx("option",{value:"all",children:"모든 레벨"}),l.jsx("option",{value:"error",children:"에러"}),l.jsx("option",{value:"warn",children:"경고"}),l.jsx("option",{value:"info",children:"정보"}),l.jsx("option",{value:"log",children:"로그"}),l.jsx("option",{value:"debug",children:"디버그"})]}),l.jsx("input",{type:"text",placeholder:"prefix 필터",value:f,onChange:N=>p(N.target.value),className:"g7dt-input g7dt-w-32"}),l.jsx("input",{type:"text",placeholder:"메시지 검색",value:y,onChange:N=>x(N.target.value),className:"g7dt-input g7dt-flex-1"}),l.jsx("button",{onClick:S,className:"g7dt-btn-secondary",children:"새로고침"}),l.jsx("button",{onClick:k,className:"g7dt-btn-danger",children:"초기화"})]}),l.jsx("div",{className:"g7dt-scroll-list-lg",children:v.length===0?l.jsx("div",{className:"g7dt-empty-state",children:e.length===0?"로그가 없습니다":"필터에 맞는 로그가 없습니다"}):v.slice(-50).reverse().map(N=>{const D=new Date(N.timestamp).toLocaleTimeString();return l.jsxs("div",{onClick:()=>d(N.id),className:`g7dt-log-item ${o===N.id?"g7dt-selected":O(N.level)}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{className:`g7dt-font-bold g7dt-uppercase ${A(N.level)}`,children:N.level}),l.jsxs("span",{className:"g7dt-text-purple",children:["[",N.prefix,"]"]})]}),l.jsx("span",{className:"g7dt-text-muted",children:D})]}),l.jsx("div",{className:"g7dt-text-white g7dt-mt-1 g7dt-truncate",children:N.message})]},N.id)})}),w&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold",children:[l.jsx("span",{className:A(w.level),children:w.level.toUpperCase()})," ",l.jsxs("span",{className:"g7dt-text-purple",children:["[",w.prefix,"]"]})]}),l.jsx("button",{onClick:()=>d(null),className:"g7dt-close-btn",children:"✕"})]}),l.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"시간:"}),l.jsx("span",{className:"g7dt-ml-2 g7dt-text-white",children:new Date(w.timestamp).toLocaleString()})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"메시지:"}),l.jsx("pre",{className:"g7dt-pre g7dt-text-white g7dt-whitespace-pre-wrap",children:w.message})]}),w.args.length>0&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"인수:"}),l.jsx("pre",{className:"g7dt-pre g7dt-text-green",children:JSON.stringify(w.args,null,2)})]}),w.stack&&l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"스택 트레이스:"}),l.jsx("pre",{className:"g7dt-pre-stack g7dt-text-red",children:w.stack})]})]})]}),a&&Object.keys(a.byPrefix).length>0&&l.jsxs("div",{children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"Prefix별 로그 수"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-2",children:Object.entries(a.byPrefix).sort((N,D)=>D[1]-N[1]).slice(0,10).map(([N,D])=>l.jsxs("button",{onClick:()=>p(N),className:f===N?"g7dt-prefix-btn-active":"g7dt-prefix-btn",children:[N,": ",l.jsx("span",{className:"g7dt-text-blue",children:D})]},N))})]})]})},Ak=({devTools:r})=>{const[e,t]=j.useState(r.getLayoutDebugInfo()),[a,i]=j.useState(!1),[o,d]=j.useState(null),[g,h]=j.useState(!1),[f,p]=j.useState({});j.useEffect(()=>{const A=setInterval(()=>{t(r.getLayoutDebugInfo())},1e3);return()=>clearInterval(A)},[r]),j.useEffect(()=>{(async()=>{try{const O=await fetch("/api/admin/permissions",{headers:{Authorization:`Bearer ${localStorage.getItem("auth_token")}`,Accept:"application/json"}});if(O.ok){const N=await O.json(),D={},$=M=>{M.forEach(z=>{D[z.identifier]=z.name,z.children?.length&&$(z.children)})};Object.values(N.data?.permissions||{}).forEach(M=>{M.permissions&&$(M.permissions)}),p(D)}}catch(O){console.warn("[G7DevTools] 권한 목록 조회 실패:",O)}})()},[]);const y=e.current,x=y?.layoutJson,S=e.history,v=e.stats,w=x?[{key:"components",label:"컴포넌트",count:Array.isArray(x.components)?x.components.length:0},{key:"data_sources",label:"데이터소스",count:Array.isArray(x.data_sources)?x.data_sources.length:0},{key:"computed",label:"Computed",count:x.computed?Object.keys(x.computed).length:0},{key:"defines",label:"Defines",count:x.defines?Object.keys(x.defines).length:0},{key:"slots",label:"Slots",count:x.slots?Object.keys(x.slots).length:0},{key:"modals",label:"Modals",count:x.modals?Object.keys(x.modals).length:0},{key:"init_actions",label:"초기화 액션",count:Array.isArray(x.init_actions)?x.init_actions.length:0},{key:"scripts",label:"스크립트",count:Array.isArray(x.scripts)?x.scripts.length:0},{key:"meta",label:"메타데이터",count:x.meta?Object.keys(x.meta).length:0},{key:"errorHandling",label:"에러핸들링",count:x.errorHandling?Object.keys(x.errorHandling).length:0},{key:"permissions",label:"권한",count:Array.isArray(x.permissions)?x.permissions.length:0}]:[],k=A=>{navigator.clipboard.writeText(JSON.stringify(A,null,2))};return y?l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"📊 로드 통계"}),l.jsxs("div",{className:"g7dt-grid-3",children:[l.jsxs("div",{className:"g7dt-stat-item",children:[l.jsx("span",{className:"g7dt-text-muted",children:"총 로드:"}),l.jsx("span",{className:"g7dt-text-blue",children:v.totalLoads})]}),l.jsxs("div",{className:"g7dt-stat-item",children:[l.jsx("span",{className:"g7dt-text-muted",children:"캐시 히트:"}),l.jsx("span",{className:"g7dt-text-green",children:v.cacheHits})]}),l.jsxs("div",{className:"g7dt-stat-item",children:[l.jsx("span",{className:"g7dt-text-muted",children:"API 로드:"}),l.jsx("span",{className:"g7dt-text-yellow",children:v.apiLoads})]})]})]}),l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:"📋 현재 레이아웃"}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsx("button",{onClick:()=>k(x),className:"g7dt-btn-small",title:"전체 JSON 복사",children:"📋 복사"}),l.jsx("button",{onClick:()=>i(!a),className:"g7dt-btn-small",children:a?"요약 보기":"전체 보기"})]})]}),l.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[l.jsxs("div",{className:"g7dt-flex g7dt-gap-4",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"경로:"}),l.jsx("span",{className:"g7dt-ml-1 g7dt-text-white g7dt-font-mono",children:y.layoutPath})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"템플릿:"}),l.jsx("span",{className:"g7dt-ml-1 g7dt-text-blue",children:y.templateId})]})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-4",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"버전:"}),l.jsx("span",{className:"g7dt-ml-1 g7dt-text-white",children:y.version||"-"})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"소스:"}),l.jsx("span",{className:`g7dt-ml-1 ${y.source==="cache"?"g7dt-text-green":"g7dt-text-yellow"}`,children:y.source==="cache"?"💾 캐시":"🌐 API"})]}),l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"로드 시간:"}),l.jsx("span",{className:"g7dt-ml-1 g7dt-text-white",children:y.loadedAt?new Date(y.loadedAt).toLocaleTimeString():"-"})]})]}),l.jsx("div",{className:"g7dt-flex g7dt-gap-4 g7dt-mt-2",children:l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-text-muted",children:"권한:"}),x.permissions&&x.permissions.length>0?l.jsxs("span",{className:"g7dt-ml-1 g7dt-text-yellow",children:["🔒 ",x.permissions.map(A=>f[A]||A).join(", ")]}):x.permissions&&x.permissions.length===0?l.jsx("span",{className:"g7dt-ml-1 g7dt-text-green",children:"🌐 공개"}):l.jsx("span",{className:"g7dt-ml-1 g7dt-text-muted",children:"미정의 (부모 상속)"})]})})]})]}),!a&&l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"🏗️ 레이아웃 구조"}),l.jsx("div",{className:"g7dt-grid-2",children:w.map(A=>l.jsxs("button",{onClick:()=>d(o===A.key?null:A.key),className:`g7dt-section-btn ${o===A.key?"g7dt-selected":""}`,children:[l.jsx("span",{children:A.label}),l.jsxs("span",{className:"g7dt-text-blue",children:[A.count,"개"]})]},A.key))})]}),(a||o)&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:a?"📄 전체 레이아웃 JSON":`📎 ${o} 섹션`}),l.jsx("button",{onClick:()=>{a?k(x):o&&x&&k(x[o])},className:"g7dt-btn-small",children:"복사"})]}),o==="permissions"&&!a?l.jsx("div",{className:"g7dt-text-xs",children:x.permissions&&x.permissions.length>0?l.jsxs("table",{className:"g7dt-table g7dt-w-full",children:[l.jsx("thead",{children:l.jsxs("tr",{className:"g7dt-border-b g7dt-border-gray-700",children:[l.jsx("th",{className:"g7dt-text-left g7dt-p-2 g7dt-text-muted",children:"권한 ID"}),l.jsx("th",{className:"g7dt-text-left g7dt-p-2 g7dt-text-muted",children:"명칭"})]})}),l.jsx("tbody",{children:x.permissions.map(A=>l.jsxs("tr",{className:"g7dt-border-b g7dt-border-gray-800",children:[l.jsx("td",{className:"g7dt-p-2 g7dt-font-mono g7dt-text-blue",children:A}),l.jsx("td",{className:"g7dt-p-2 g7dt-text-white",children:f[A]||l.jsx("span",{className:"g7dt-text-muted",children:"-"})})]},A))})]}):x.permissions&&x.permissions.length===0?l.jsx("p",{className:"g7dt-text-muted g7dt-p-2",children:"🌐 공개 레이아웃 (permissions: [])"}):l.jsx("p",{className:"g7dt-text-muted g7dt-p-2",children:"권한 미정의 (부모 레이아웃 상속)"})}):l.jsx("pre",{className:"g7dt-pre g7dt-text-green g7dt-max-h-96 g7dt-overflow-auto",children:JSON.stringify(a?x:o&&x?x[o]:null,null,2)})]}),S.length>0&&l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-cursor-pointer",onClick:()=>h(!g),children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold",children:["📜 로드 이력 (",S.length,")"]}),l.jsx("span",{className:"g7dt-text-muted",children:g?"▼":"▶"})]}),g&&l.jsx("div",{className:"g7dt-mt-2 g7dt-space-y-1",children:S.slice(-20).reverse().map(A=>l.jsxs("div",{className:"g7dt-history-item",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsx("span",{className:"g7dt-font-mono g7dt-text-xs",children:A.layoutPath}),l.jsx("span",{className:`g7dt-text-xs ${A.source==="cache"?"g7dt-text-green":"g7dt-text-yellow"}`,children:A.source==="cache"?"💾":"🌐"})]}),l.jsxs("div",{className:"g7dt-text-xs g7dt-text-muted",children:[A.templateId," · ",A.loadedAt?new Date(A.loadedAt).toLocaleTimeString():"-"]})]},A.id))})]}),l.jsxs("div",{className:"g7dt-card g7dt-text-xs g7dt-text-muted",children:["💡 레이아웃 캐시 문제가 의심되면:",l.jsxs("ul",{className:"g7dt-ml-4 g7dt-list-disc",children:[l.jsx("li",{children:'"소스" 항목이 💾 캐시인지 🌐 API인지 확인'}),l.jsx("li",{children:"캐시에서 로드된 경우, JSON 내용이 최신인지 확인"}),l.jsxs("li",{children:["문제가 있으면 ",l.jsx("code",{className:"g7dt-code",children:"php artisan template:refresh-layout"})," 실행"]})]})]})]}):l.jsx("div",{className:"g7dt-space-y-4",children:l.jsxs("div",{className:"g7dt-empty-state",children:["현재 로드된 레이아웃이 없습니다.",l.jsx("br",{}),"페이지를 새로고침하거나 라우트를 변경해보세요."]})})},Tk=({devTools:r})=>{const[e,t]=j.useState(r.getChangeDetectionInfo()),[a,i]=j.useState(null),[o,d]=j.useState(!1),[g,h]=j.useState(new Set);j.useEffect(()=>{const N=setInterval(()=>{t(r.getChangeDetectionInfo())},500);return()=>clearInterval(N)},[r]);const{executionDetails:f,alerts:p,stats:y}=e,x=o?f.filter(N=>N.alerts.length>0||N.stateChanges.length===0):f,S=a?f.find(N=>N.executionId===a):null,v=N=>{h(D=>{const $=new Set(D);return $.has(N)?$.delete(N):$.add(N),$})},w=N=>{switch(N){case"normal":return"✅";case"early-return-condition":return"⏎";case"early-return-validation":return"❌";case"error":return"💥";default:return"❓"}},k=N=>{switch(N){case"no-state-change":return"⚠️";case"no-datasource-change":return"📊";case"expected-not-fulfilled":return"❗";case"object-reference-same":return"🔄";case"early-return-detected":return"⏎";case"async-timing-issue":return"⏱️";default:return"📢"}},A=N=>{switch(N){case"error":return"g7dt-text-red";case"warning":return"g7dt-text-yellow";case"info":return"g7dt-text-blue";default:return"g7dt-text-white"}},O=N=>new Date(N).toLocaleTimeString("ko-KR",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3});return l.jsxs("div",{className:"g7dt-space-y-4",children:[p.filter(N=>N.severity==="error"||N.severity==="warning").length>0&&l.jsx("div",{className:"g7dt-card",style:{backgroundColor:"#7f1d1d",borderColor:"#991b1b"},children:l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsxs("span",{className:"g7dt-font-bold",children:["⚠️ 변경 감지 알림: ",p.filter(N=>N.severity==="error").length,"개 에러,"," ",p.filter(N=>N.severity==="warning").length,"개 경고"]}),l.jsx("button",{onClick:()=>r.clearChangeDetectionData(),className:"g7dt-btn-small",children:"초기화"})]})}),l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"📊 변경 감지 통계"}),l.jsxs("div",{className:"g7dt-grid-3",children:[l.jsxs("div",{className:"g7dt-stat-item",children:[l.jsx("span",{className:"g7dt-text-muted",children:"총 실행:"}),l.jsx("span",{className:"g7dt-text-blue",children:y.totalExecutions})]}),l.jsxs("div",{className:"g7dt-stat-item",children:[l.jsx("span",{className:"g7dt-text-muted",children:"상태 변경 있음:"}),l.jsx("span",{className:"g7dt-text-green",children:y.executionsWithStateChange})]}),l.jsxs("div",{className:"g7dt-stat-item",children:[l.jsx("span",{className:"g7dt-text-muted",children:"상태 변경 없음:"}),l.jsx("span",{className:y.executionsWithoutStateChange>0?"g7dt-text-yellow":"g7dt-text-gray",children:y.executionsWithoutStateChange})]}),l.jsxs("div",{className:"g7dt-stat-item",children:[l.jsx("span",{className:"g7dt-text-muted",children:"Early Return:"}),l.jsx("span",{className:"g7dt-text-orange",children:y.earlyReturnCount})]}),l.jsxs("div",{className:"g7dt-stat-item",children:[l.jsx("span",{className:"g7dt-text-muted",children:"알림:"}),l.jsx("span",{className:y.alertCount>0?"g7dt-text-red":"g7dt-text-gray",children:y.alertCount})]})]})]}),p.length>0&&l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"🔔 최근 알림"}),l.jsx("div",{className:"g7dt-space-y-2",style:{maxHeight:"200px",overflowY:"auto"},children:p.slice(-10).reverse().map(N=>l.jsxs("div",{className:"g7dt-list-item",onClick:()=>v(N.id),style:{cursor:"pointer"},children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-start",children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{children:k(N.type)}),l.jsx("span",{className:`g7dt-text-xs ${A(N.severity)}`,children:N.message})]}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted",children:O(N.timestamp)})]}),g.has(N.id)&&l.jsxs("div",{className:"g7dt-mt-2 g7dt-text-xs g7dt-text-muted g7dt-pl-6",children:[l.jsx("p",{children:N.description}),N.statePath&&l.jsxs("p",{className:"g7dt-mt-1",children:[l.jsx("span",{className:"g7dt-text-cyan",children:"경로:"})," ",N.statePath]}),N.suggestion&&l.jsxs("p",{className:"g7dt-mt-1",children:[l.jsx("span",{className:"g7dt-text-green",children:"제안:"})," ",N.suggestion]}),N.docLink&&l.jsxs("p",{className:"g7dt-mt-1",children:[l.jsx("span",{className:"g7dt-text-blue",children:"문서:"})," ",l.jsx("code",{className:"g7dt-code",children:N.docLink})]})]})]},N.id))})]}),l.jsxs("div",{className:"g7dt-card",children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:"🔧 핸들러 실행 이력"}),l.jsxs("label",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-xs",children:[l.jsx("input",{type:"checkbox",checked:o,onChange:N=>d(N.target.checked)}),l.jsx("span",{children:"경고만 표시"})]})]}),x.length===0?l.jsxs("div",{className:"g7dt-empty-state",children:["핸들러 실행 이력이 없습니다.",l.jsx("br",{}),"액션을 실행하면 여기에 표시됩니다."]}):l.jsx("div",{className:"g7dt-space-y-1",style:{maxHeight:"300px",overflowY:"auto"},children:x.slice(-20).reverse().map(N=>l.jsxs("div",{className:`g7dt-list-item ${a===N.executionId?"g7dt-selected":""}`,onClick:()=>i(a===N.executionId?null:N.executionId),style:{cursor:"pointer"},children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{children:w(N.exitReason)}),l.jsx("span",{className:"g7dt-text-white g7dt-font-mono g7dt-text-xs",children:N.handlerName}),N.alerts.length>0&&l.jsx("span",{className:"g7dt-badge g7dt-badge-warning",children:N.alerts.length})]}),l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-xs",children:[l.jsxs("span",{className:"g7dt-text-muted",children:["상태: ",N.stateChanges.length]}),l.jsx("span",{className:"g7dt-text-muted",children:N.duration?`${N.duration}ms`:"-"}),l.jsx("span",{className:"g7dt-text-muted",children:O(N.startTime)})]})]}),a===N.executionId&&S&&l.jsxs("div",{className:"g7dt-mt-3 g7dt-pt-3 g7dt-border-t g7dt-border-gray-700",children:[l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted",children:"종료 사유: "}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-white",children:S.exitReason||"unknown"}),S.exitLocation&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-2",children:"위치: "}),l.jsx("code",{className:"g7dt-code g7dt-text-xs",children:S.exitLocation})]})]}),S.exitDescription&&l.jsx("div",{className:"g7dt-mb-2 g7dt-text-xs g7dt-text-muted",children:S.exitDescription}),S.stateChanges.length>0&&l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsxs("span",{className:"g7dt-text-xs g7dt-font-bold g7dt-text-green",children:["상태 변경 (",S.stateChanges.length,")"]}),l.jsx("div",{className:"g7dt-mt-1 g7dt-space-y-1",children:S.stateChanges.map(D=>l.jsxs("div",{className:"g7dt-text-xs g7dt-pl-2",children:[l.jsx("span",{className:"g7dt-text-cyan",children:D.path}),l.jsxs("span",{className:"g7dt-text-muted",children:[" (",D.changeType,")"]}),D.comparison.changedKeys&&l.jsxs("span",{className:"g7dt-text-muted g7dt-ml-1",children:["[변경: ",D.comparison.changedKeys.join(", "),"]"]})]},D.id))})]}),S.dataSourceChanges.length>0&&l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsxs("span",{className:"g7dt-text-xs g7dt-font-bold g7dt-text-blue",children:["데이터소스 변경 (",S.dataSourceChanges.length,")"]}),l.jsx("div",{className:"g7dt-mt-1 g7dt-space-y-1",children:S.dataSourceChanges.map((D,$)=>l.jsxs("div",{className:"g7dt-text-xs g7dt-pl-2",children:[l.jsx("span",{className:"g7dt-text-cyan",children:D.dataSourceId}),l.jsxs("span",{className:"g7dt-text-muted",children:[" ","(",D.changeType,": ",D.previousStatus," → ",D.newStatus,")"]})]},$))})]}),S.expectedChanges&&l.jsxs("div",{className:"g7dt-mb-2",children:[l.jsx("span",{className:"g7dt-text-xs g7dt-font-bold g7dt-text-yellow",children:"기대 변경"}),l.jsxs("div",{className:"g7dt-mt-1 g7dt-text-xs g7dt-pl-2 g7dt-text-muted",children:["상태: ",S.expectedChanges.expectedStatePaths.join(", ")||"없음",l.jsx("br",{}),"데이터소스: ",S.expectedChanges.expectedDataSources.join(", ")||"없음"]})]}),S.alerts.length>0&&l.jsxs("div",{children:[l.jsxs("span",{className:"g7dt-text-xs g7dt-font-bold g7dt-text-red",children:["알림 (",S.alerts.length,")"]}),l.jsx("div",{className:"g7dt-mt-1 g7dt-space-y-1",children:S.alerts.map(D=>l.jsxs("div",{className:"g7dt-text-xs g7dt-pl-2",children:[l.jsx("span",{children:k(D.type)}),l.jsx("span",{className:`g7dt-ml-1 ${A(D.severity)}`,children:D.message})]},D.id))})]})]})]},N.executionId))})]}),l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"💡 변경 감지 가이드"}),l.jsxs("ul",{className:"g7dt-help-list",children:[l.jsx("li",{children:"핸들러 실행 후 상태 변경이 없으면 ⚠️ 경고가 표시됩니다"}),l.jsx("li",{children:"early return으로 종료된 경우 ⏎ 아이콘으로 표시됩니다"}),l.jsx("li",{children:"객체 변경 시 참조가 동일하면 🔄 경고가 발생합니다"}),l.jsx("li",{children:"문제 해결: exitLocation 확인 → 조건문 검토 → 불변성 확인"})]})]})]})},Dk=({devTools:r})=>{const[e,t]=j.useState(null),[a,i]=j.useState(null),[o,d]=j.useState("all"),g=j.useCallback(()=>{t(r.getStaleClosureTrackingInfo())},[r]);if(j.useEffect(()=>{g();const v=setInterval(g,2e3);return()=>clearInterval(v)},[g]),!e)return l.jsx("div",{className:"g7dt-empty-state",children:"로딩 중..."});const{warnings:h,stats:f}=e,p=h.filter(v=>o==="all"?!0:v.severity===o),y=a?h.find(v=>v.id===a):null,x=v=>{switch(v){case"error":return"❌";case"warning":return"⚠️";default:return"❓"}},S=v=>{switch(v){case"state-changed-during-async":return"⏳";case"captured-in-callback":return"📸";case"stale-in-handler":return"🔄";default:return"❓"}};return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"Stale Closure 통계"}),l.jsxs("div",{className:"g7dt-stats-grid-3",children:[l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-yellow",children:f.totalWarnings||0}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"총 경고"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-red",children:f.warningsBySeverity?.error||0}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"에러"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-orange",children:f.warningsBySeverity?.warning||0}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"경고"})]})]})]}),f.warningsByType&&Object.keys(f.warningsByType).length>0&&l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"타입별 분포"}),l.jsx("div",{className:"g7dt-space-y-2",children:Object.entries(f.warningsByType).map(([v,w])=>l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-text-xs",children:[l.jsxs("span",{className:"g7dt-text-muted",children:[S(v)," ",v]}),l.jsx("span",{className:"g7dt-text-white g7dt-font-mono",children:w})]},v))})]}),l.jsx("div",{className:"g7dt-card",children:l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted",children:"심각도:"}),l.jsxs("select",{value:o,onChange:v=>d(v.target.value),className:"g7dt-select",children:[l.jsx("option",{value:"all",children:"전체"}),l.jsx("option",{value:"error",children:"에러"}),l.jsx("option",{value:"warning",children:"경고"})]}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:[p.length,"개 표시"]})]})}),l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"Stale Closure 경고"}),p.length===0?l.jsx("div",{className:"g7dt-empty-state g7dt-text-green",children:"✅ Stale Closure 경고가 없습니다"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:p.slice().reverse().map(v=>l.jsxs("div",{className:`g7dt-list-item g7dt-cursor-pointer ${a===v.id?"g7dt-selected":""}`,onClick:()=>i(a===v.id?null:v.id),children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{children:x(v.severity)}),l.jsx("span",{children:S(v.type)}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-white g7dt-truncate",children:v.location}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:new Date(v.timestamp).toLocaleTimeString()})]}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-1 g7dt-truncate",children:v.statePath})]},v.id))})]}),y&&l.jsxs("div",{className:"g7dt-card g7dt-border-yellow",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:[x(y.severity)," 경고 상세"]}),l.jsxs("div",{className:"g7dt-space-y-3",children:[l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"위치"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-white g7dt-mono",children:y.location})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"타입"}),l.jsxs("div",{className:"g7dt-text-sm g7dt-text-white",children:[S(y.type)," ",y.type]})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"상태 경로"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-yellow g7dt-mono",children:y.statePath})]}),l.jsxs("div",{className:"g7dt-grid-2 g7dt-gap-3",children:[l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"캡처된 값"}),l.jsx("pre",{className:"g7dt-code-block g7dt-text-red",children:JSON.stringify(y.capturedValue,null,2)})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"현재 값"}),l.jsx("pre",{className:"g7dt-code-block g7dt-text-green",children:JSON.stringify(y.currentValue,null,2)})]})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"시간 차이"}),l.jsxs("div",{className:"g7dt-text-sm g7dt-text-white",children:[y.timeDiff,"ms"]})]}),y.suggestion&&l.jsxs("div",{className:"g7dt-bg-blue-dark g7dt-p-2 g7dt-rounded",children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-blue",children:"💡 제안"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-white g7dt-mt-1",children:y.suggestion})]})]})]})]})},Rk=({devTools:r})=>{const[e,t]=j.useState(null),[a,i]=j.useState(null),[o,d]=j.useState("all"),g=j.useCallback(()=>{t(r.getNestedContextTrackingInfo())},[r]);if(j.useEffect(()=>{g();const v=setInterval(g,2e3);return()=>clearInterval(v)},[g]),!e)return l.jsx("div",{className:"g7dt-empty-state",children:"로딩 중..."});const{contexts:h,stats:f}=e,p=h.filter(v=>o==="all"?!0:v.componentType===o),y=a?h.find(v=>v.id===a):null,x=v=>{switch(v){case"expandChildren":return"📂";case"cellChildren":return"📊";case"iteration":return"🔄";case"modal":return"🪟";case"slot":return"🔲";default:return"❓"}},S=v=>"│".repeat(Math.max(0,v-1))+(v>0?"├─":"");return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"Nested Context 통계"}),l.jsxs("div",{className:"g7dt-stats-grid-3",children:[l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-blue",children:f.totalContexts||0}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"총 컨텍스트"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-purple",children:f.maxDepth||0}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"최대 깊이"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-red",children:f.failedAccessCount||0}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"접근 오류"})]})]})]}),f.byType&&Object.keys(f.byType).length>0&&l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"타입별 분포"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-3",children:Object.entries(f.byType).map(([v,w])=>l.jsxs("div",{className:`g7dt-badge g7dt-cursor-pointer ${o===v?"g7dt-badge-selected":""}`,onClick:()=>d(o===v?"all":v),children:[x(v)," ",v,": ",w]},v))})]}),l.jsx("div",{className:"g7dt-card",children:l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted",children:"타입:"}),l.jsxs("select",{value:o,onChange:v=>d(v.target.value),className:"g7dt-select",children:[l.jsx("option",{value:"all",children:"전체"}),l.jsx("option",{value:"expandChildren",children:"expandChildren"}),l.jsx("option",{value:"cellChildren",children:"cellChildren"}),l.jsx("option",{value:"iteration",children:"iteration"}),l.jsx("option",{value:"modal",children:"modal"}),l.jsx("option",{value:"slot",children:"slot"})]}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:[p.length,"개 표시"]})]})}),l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"컨텍스트 목록"}),p.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"추적된 Nested Context가 없습니다"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:p.slice().reverse().map(v=>{const w=v.accessAttempts?.some(A=>!A.found),k=v.mergedContext?.all||[];return l.jsxs("div",{className:`g7dt-list-item g7dt-cursor-pointer ${a===v.id?"g7dt-selected":""} ${w?"g7dt-border-red":""}`,onClick:()=>i(a===v.id?null:v.id),children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{className:"g7dt-text-muted g7dt-mono g7dt-text-xs",children:S(v.depth)}),l.jsx("span",{children:x(v.componentType)}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-white",children:v.componentId||v.componentType}),w&&l.jsx("span",{className:"g7dt-text-red g7dt-text-xs",children:"⚠️ 오류"}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:["깊이: ",v.depth]})]}),l.jsxs("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-1",children:["변수: ",k.slice(0,5).join(", "),k.length>5&&"..."]})]},v.id)})})]}),y&&l.jsxs("div",{className:"g7dt-card g7dt-border-blue",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:[x(y.componentType)," 컨텍스트 상세"]}),l.jsxs("div",{className:"g7dt-space-y-3",children:[l.jsxs("div",{className:"g7dt-grid-2 g7dt-gap-3",children:[l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"타입"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-white",children:y.componentType})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"깊이"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-white",children:y.depth})]})]}),y.componentId&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"컴포넌트 ID"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-blue g7dt-mono",children:y.componentId})]}),y.parentId&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"부모 컨텍스트"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-purple g7dt-mono",children:y.parentId})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"사용 가능한 변수"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1",children:(y.mergedContext?.all||[]).map(v=>l.jsx("span",{className:"g7dt-badge g7dt-badge-blue g7dt-text-xs",children:v},v))})]}),y.ownContext?.added&&y.ownContext.added.length>0&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"추가된 변수 (이 컨텍스트에서)"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1",children:y.ownContext.added.map(v=>l.jsxs("span",{className:"g7dt-badge g7dt-badge-green g7dt-text-xs",children:["+ ",v]},v))})]}),y.accessAttempts&&y.accessAttempts.length>0&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"접근 시도"}),l.jsx("div",{className:"g7dt-space-y-1",children:y.accessAttempts.slice(0,10).map((v,w)=>l.jsxs("div",{className:`g7dt-flex g7dt-justify-between g7dt-text-xs ${v.found?"":"g7dt-text-red"}`,children:[l.jsx("span",{className:"g7dt-mono",children:v.path}),l.jsx("span",{children:v.found?"✓":"✕"})]},w))})]})]})]})]})},Ok=({devTools:r})=>{const[e,t]=j.useState(null),[a,i]=j.useState(null),[o,d]=j.useState(null),[g,h]=j.useState("modals"),f=j.useCallback(()=>{t(r.getModalStateScopeTrackingInfo())},[r]);if(j.useEffect(()=>{f();const D=setInterval(f,2e3);return()=>clearInterval(D)},[f]),!e)return l.jsx("div",{className:"g7dt-empty-state",children:"로딩 중..."});const{modals:p,issues:y,relations:x,changeLogs:S,stats:v}=e,w=a?p.find(D=>D.modalId===a):null,k=o?y.find(D=>D.id===o):null,A=D=>{switch(D){case"isolated":return"🔒";case"shared":return"🔓";case"inherited":return"📥";default:return"❓"}},O=D=>{switch(D){case"state-leakage":return"💧";case"isolation-violation":return"🔓";case"parent-mutation":return"👆";case"orphaned-state":return"👻";case"scope-mismatch":return"🔀";case"cleanup-failure":return"🧹";case"missing-definition":return"🚫";default:return"❓"}},N=D=>{switch(D){case"error":return"❌";case"warning":return"⚠️";default:return"❓"}};return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"모달 상태 스코프 통계"}),l.jsxs("div",{className:"g7dt-stats-grid-3",children:[l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-blue",children:v.totalModals}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"총 모달"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-green",children:v.openModals}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"열린 모달"})]}),l.jsxs("div",{className:"g7dt-text-center",children:[l.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-red",children:v.totalIssues}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"이슈"})]})]})]}),l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"스코프별 / 이슈별"}),l.jsxs("div",{className:"g7dt-grid-2 g7dt-gap-4",children:[l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"스코프 타입"}),l.jsx("div",{className:"g7dt-space-y-1",children:Object.entries(v.byScope).map(([D,$])=>l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-text-xs",children:[l.jsxs("span",{children:[A(D)," ",D]}),l.jsx("span",{className:"g7dt-font-mono",children:$})]},D))})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"이슈 타입"}),l.jsxs("div",{className:"g7dt-space-y-1",children:[Object.entries(v.issuesByType).filter(([D,$])=>$>0).map(([D,$])=>l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-text-xs",children:[l.jsxs("span",{children:[O(D)," ",D]}),l.jsx("span",{className:"g7dt-font-mono g7dt-text-red",children:$})]},D)),Object.values(v.issuesByType).every(D=>D===0)&&l.jsx("div",{className:"g7dt-text-xs g7dt-text-green",children:"✅ 이슈 없음"})]})]})]})]}),l.jsx("div",{className:"g7dt-card",children:l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsxs("button",{className:`g7dt-tab-button ${g==="modals"?"g7dt-tab-active":""}`,onClick:()=>h("modals"),children:["🪟 모달 (",p.length,")"]}),l.jsxs("button",{className:`g7dt-tab-button ${g==="issues"?"g7dt-tab-active":""}`,onClick:()=>h("issues"),children:["⚠️ 이슈 (",y.length,")"]}),l.jsxs("button",{className:`g7dt-tab-button ${g==="logs"?"g7dt-tab-active":""}`,onClick:()=>h("logs"),children:["📝 로그 (",S.length,")"]})]})}),g==="modals"&&l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"모달 목록"}),p.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"추적된 모달이 없습니다"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:p.map(D=>{const $=y.some(M=>M.modalId===D.modalId);return l.jsx("div",{className:`g7dt-list-item g7dt-cursor-pointer ${a===D.modalId?"g7dt-selected":""} ${$?"g7dt-border-red":""}`,onClick:()=>i(a===D.modalId?null:D.modalId),children:l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{children:D.closedAt===null?"📭":"📪"}),l.jsx("span",{children:A(D.scopeType)}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-white",children:D.modalName}),$&&l.jsx("span",{className:"g7dt-text-red",children:"⚠️"}),l.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:["변경: ",D.stateChangeCount]})]})},D.modalId)})})]}),g==="issues"&&l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"이슈 목록"}),y.length===0?l.jsx("div",{className:"g7dt-empty-state g7dt-text-green",children:"✅ 모달 상태 이슈가 없습니다"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:y.slice().reverse().map(D=>l.jsxs("div",{className:`g7dt-list-item g7dt-cursor-pointer ${o===D.id?"g7dt-selected":""}`,onClick:()=>d(o===D.id?null:D.id),children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{children:N(D.severity)}),l.jsx("span",{children:O(D.type)}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-white",children:D.modalName}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:new Date(D.timestamp).toLocaleTimeString()})]}),l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-1 g7dt-truncate",children:D.description})]},D.id))})]}),g==="logs"&&l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"상태 변경 로그"}),S.length===0?l.jsx("div",{className:"g7dt-empty-state",children:"상태 변경 로그가 없습니다"}):l.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:S.slice().reverse().slice(0,50).map(D=>l.jsxs("div",{className:`g7dt-list-item ${D.violatesIsolation?"g7dt-border-red":""}`,children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[l.jsx("span",{className:"g7dt-text-xs g7dt-text-white",children:D.modalName}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-blue g7dt-mono",children:D.stateKey}),D.violatesIsolation&&l.jsx("span",{className:"g7dt-text-red",children:"⚠️ 격리 위반"}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:new Date(D.timestamp).toLocaleTimeString()})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-text-xs g7dt-mt-1",children:[l.jsx("span",{className:"g7dt-text-red g7dt-truncate",style:{maxWidth:"45%"},children:JSON.stringify(D.previousValue)}),l.jsx("span",{className:"g7dt-text-muted",children:"→"}),l.jsx("span",{className:"g7dt-text-green g7dt-truncate",style:{maxWidth:"45%"},children:JSON.stringify(D.newValue)})]})]},D.id))})]}),w&&g==="modals"&&l.jsxs("div",{className:"g7dt-card g7dt-border-blue",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:[A(w.scopeType)," 모달 상세: ",w.modalName]}),l.jsxs("div",{className:"g7dt-space-y-3",children:[l.jsxs("div",{className:"g7dt-grid-2 g7dt-gap-3",children:[l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"스코프"}),l.jsxs("div",{className:"g7dt-text-sm g7dt-text-white",children:[A(w.scopeType)," ",w.scopeType]})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"상태"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-white",children:w.closedAt===null?"📭 열림":"📪 닫힘"})]})]}),w.parentModalId&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"부모 모달"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-purple g7dt-mono",children:w.parentModalId})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"상태 변경 횟수"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-white",children:w.stateChangeCount})]}),w.isolatedStateKeys.length>0&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-1",children:"격리된 상태 키"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1",children:w.isolatedStateKeys.map(D=>l.jsxs("span",{className:"g7dt-badge g7dt-badge-red g7dt-text-xs",children:["🔒 ",D]},D))})]}),w.sharedStateKeys.length>0&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-1",children:"공유된 상태 키"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1",children:w.sharedStateKeys.map(D=>l.jsxs("span",{className:"g7dt-badge g7dt-badge-blue g7dt-text-xs",children:["🔓 ",D]},D))})]})]})]}),k&&g==="issues"&&l.jsxs("div",{className:"g7dt-card g7dt-border-red",children:[l.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:[N(k.severity)," 이슈 상세"]}),l.jsxs("div",{className:"g7dt-space-y-3",children:[l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"타입"}),l.jsxs("div",{className:"g7dt-text-sm g7dt-text-white",children:[O(k.type)," ",k.type]})]}),l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"설명"}),l.jsx("div",{className:"g7dt-text-sm g7dt-text-white",children:k.description})]}),k.affectedStateKeys.length>0&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"영향 받는 상태 키"}),l.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1",children:k.affectedStateKeys.map(D=>l.jsx("span",{className:"g7dt-badge g7dt-text-xs",children:D},D))})]}),k.leakedValue!==void 0&&l.jsxs("div",{children:[l.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"유출된 값"}),l.jsx("pre",{className:"g7dt-code-block g7dt-text-red",children:JSON.stringify(k.leakedValue,null,2)})]})]})]}),x.length>0&&l.jsxs("div",{className:"g7dt-card",children:[l.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"모달 관계"}),l.jsx("div",{className:"g7dt-space-y-2",children:x.map((D,$)=>l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-xs",children:[l.jsx("span",{className:"g7dt-text-purple",children:D.parentModalId}),l.jsx("span",{className:"g7dt-text-muted",children:"→"}),l.jsx("span",{className:"g7dt-text-blue",children:D.childModalId}),l.jsx("span",{className:"g7dt-badge g7dt-text-xs g7dt-ml-auto",children:D.relationType})]},$))})]})]})},Lk=({devTools:r})=>{const[e,t]=j.useState("definitions"),[a,i]=j.useState(null),[o,d]=j.useState(""),g=j.useCallback(()=>{r&&i(r.getNamedActionTrackingInfo())},[r]);if(j.useEffect(()=>{g();const v=setInterval(g,2e3);return()=>clearInterval(v)},[g]),!a)return l.jsx("div",{className:"g7dt-empty-message g7dt-py-4",children:"데이터 로딩 중..."});const{definitions:h,refLogs:f,stats:p}=a,y=Object.keys(h),x=y.filter(v=>!o||v.toLowerCase().includes(o.toLowerCase())||h[v]?.handler?.toLowerCase().includes(o.toLowerCase())),S=f.filter(v=>!o||v.actionRefName.toLowerCase().includes(o.toLowerCase())||v.resolvedHandler.toLowerCase().includes(o.toLowerCase()));return l.jsxs("div",{className:"g7dt-space-y-4",children:[l.jsxs("div",{className:"g7dt-grid g7dt-grid-cols-3 g7dt-gap-2",children:[l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value",children:p.totalDefinitions}),l.jsx("div",{className:"g7dt-stat-label",children:"정의"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value",children:p.totalRefs}),l.jsx("div",{className:"g7dt-stat-label",children:"참조"})]}),l.jsxs("div",{className:"g7dt-stat-card",children:[l.jsx("div",{className:"g7dt-stat-value",style:{color:p.unusedDefinitions.length>0?"#f59e0b":"#10b981"},children:p.unusedDefinitions.length}),l.jsx("div",{className:"g7dt-stat-label",children:"미사용"})]})]}),l.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[l.jsxs("button",{onClick:()=>t("definitions"),className:e==="definitions"?"g7dt-filter-btn g7dt-filter-active":"g7dt-filter-btn",children:["정의 목록 (",y.length,")"]}),l.jsxs("button",{onClick:()=>t("refs"),className:e==="refs"?"g7dt-filter-btn g7dt-filter-active":"g7dt-filter-btn",children:["참조 이력 (",f.length,")"]}),l.jsx("button",{onClick:g,className:"g7dt-filter-btn",title:"새로고침",children:"↻"})]}),l.jsx("input",{type:"text",placeholder:e==="definitions"?"액션 이름 검색...":"actionRef 검색...",value:o,onChange:v=>d(v.target.value),className:"g7dt-input g7dt-w-full"}),e==="definitions"&&l.jsx("div",{className:"g7dt-space-y-1",children:x.length===0?l.jsx("div",{className:"g7dt-empty-message g7dt-py-4",children:y.length===0?"정의된 named_actions가 없습니다":"검색 결과 없음"}):x.map(v=>{const w=h[v],k=p.refCountByName[v]||0,A=p.unusedDefinitions.includes(v);return l.jsxs("div",{className:"g7dt-card",style:{borderLeft:A?"3px solid #f59e0b":"3px solid #10b981"},children:[l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-font-bold",children:v}),l.jsxs("span",{className:"g7dt-text-muted g7dt-ml-2",children:["→ ",w.handler]})]}),l.jsxs("span",{className:"g7dt-badge",title:"참조 횟수",children:[k,"회"]})]}),w.params&&l.jsxs("details",{className:"g7dt-mt-1",children:[l.jsx("summary",{className:"g7dt-text-xs g7dt-text-muted g7dt-cursor-pointer",children:"params"}),l.jsx("pre",{className:"g7dt-pre g7dt-text-xs g7dt-mt-1",style:{maxHeight:"200px",overflow:"auto"},children:JSON.stringify(w.params,null,2)})]}),A&&l.jsx("div",{className:"g7dt-text-xs",style:{color:"#f59e0b",marginTop:"4px"},children:"⚠ 미사용 정의"})]},v)})}),e==="refs"&&l.jsx("div",{className:"g7dt-space-y-1",children:S.length===0?l.jsx("div",{className:"g7dt-empty-message g7dt-py-4",children:f.length===0?"actionRef 해석 이력이 없습니다":"검색 결과 없음"}):[...S].reverse().map(v=>l.jsx("div",{className:"g7dt-card",children:l.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[l.jsxs("div",{children:[l.jsx("span",{className:"g7dt-font-bold",children:v.actionRefName}),l.jsxs("span",{className:"g7dt-text-muted g7dt-ml-2",children:["→ ",v.resolvedHandler]})]}),l.jsx("span",{className:"g7dt-text-xs g7dt-text-muted",children:new Date(v.timestamp).toLocaleTimeString()})]})},v.id))})]})},Mk=()=>{j.useEffect(()=>{ok()},[]);const r=j.useRef(ix()),[e,t]=j.useState(r.current.isOpen??!1),[a,i]=j.useState(!1),[o,d]=j.useState("state"),[g,h]=j.useState({_global:{},_local:{},_computed:{}}),[f,p]=j.useState([]),[y,x]=j.useState({hits:0,misses:0,entries:0,hitRate:0}),[S,v]=j.useState(!1),[w,k]=j.useState(r.current.position??{x:-1,y:-1}),[A,O]=j.useState(!1),N=j.useRef(null),D=j.useRef(null),[$,M]=j.useState(r.current.size??{width:lk,height:ck}),[z,K]=j.useState(!1),[ye,we]=j.useState(null),J=j.useRef(null),[ve,le]=j.useState(!1),de=j.useRef(null),je=ka.getInstance(),W=tx();j.useEffect(()=>{if(w.x===-1&&w.y===-1){const U=window.innerWidth-$.width-16;k({x:U,y:16})}},[w,$.width]),j.useEffect(()=>{if(w.x===-1&&w.y===-1||A||z)return;const U=setTimeout(()=>{ox({position:w,size:$})},300);return()=>clearTimeout(U)},[w,$,A,z]),j.useEffect(()=>{ox({isOpen:e})},[e]);const he=j.useCallback(U=>{U.target.tagName!=="BUTTON"&&(O(!0),N.current={x:U.clientX,y:U.clientY,posX:w.x,posY:w.y},U.preventDefault())},[w]);j.useEffect(()=>{if(!A)return;const U=xe=>{if(!N.current)return;const oe=xe.clientX-N.current.x,ke=xe.clientY-N.current.y;let Oe=N.current.posX+oe,Te=N.current.posY+ke;const qe=window.innerWidth-$.width,Ie=window.innerHeight-$.height;Oe=Math.max(0,Math.min(Oe,qe)),Te=Math.max(0,Math.min(Te,Ie)),k({x:Oe,y:Te})},re=()=>{O(!1),N.current=null};return document.addEventListener("mousemove",U),document.addEventListener("mouseup",re),()=>{document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",re)}},[A,$.width,$.height]);const ee=j.useCallback(U=>re=>{re.preventDefault(),re.stopPropagation(),K(!0),we(U),J.current={x:re.clientX,y:re.clientY,width:$.width,height:$.height,posX:w.x,posY:w.y}},[$,w]);j.useEffect(()=>{if(!z||!ye)return;const U=xe=>{if(!J.current)return;const oe=xe.clientX-J.current.x,ke=xe.clientY-J.current.y;let Oe=J.current.width,Te=J.current.height,qe=J.current.posX,Ie=J.current.posY;if(ye.includes("e")&&(Oe=Math.max(ax,J.current.width+oe)),ye.includes("w")){const Nt=Math.min(oe,J.current.width-ax);Oe=J.current.width-Nt,qe=J.current.posX+Nt}if(ye.includes("s")&&(Te=Math.max(sx,J.current.height+ke)),ye.includes("n")){const Nt=Math.min(ke,J.current.height-sx);Te=J.current.height-Nt,Ie=J.current.posY+Nt}Oe=Math.min(Oe,window.innerWidth-qe),Te=Math.min(Te,window.innerHeight-Ie),qe=Math.max(0,qe),Ie=Math.max(0,Ie),M({width:Oe,height:Te}),k({x:qe,y:Ie})},re=()=>{K(!1),we(null),J.current=null};return document.addEventListener("mousemove",U),document.addEventListener("mouseup",re),()=>{document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",re)}},[z,ye]);const X=j.useCallback(()=>{ve?(de.current&&(k(de.current.position),M(de.current.size)),le(!1)):(de.current={position:w,size:$},k({x:0,y:0}),M({width:window.innerWidth,height:window.innerHeight}),le(!0))},[ve,w,$]),ae=j.useCallback(()=>{je.isEnabled()&&(h(je.getState()),p(je.getActionHistory()),x(je.getCacheStats()),v(W.isConnected()))},[je,W]);j.useEffect(()=>{const U=re=>{re.ctrlKey&&re.shiftKey&&re.key==="G"&&(re.preventDefault(),t(xe=>!xe))};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[]),j.useEffect(()=>{if(!e||!je.isEnabled())return;ae();const U=je.watchState("*",()=>{h(je.getState())}),re=je.watchActions(()=>{p(je.getActionHistory()),x(je.getCacheStats())}),xe=setInterval(ae,5e3);return()=>{U(),re(),clearInterval(xe)}},[e,je,ae]);const R=async()=>{try{const U=await W.dumpState();console.log("[G7DevTools] 상태 덤프 완료:",U),v(!0)}catch(U){console.error("[G7DevTools] 상태 덤프 실패:",U),v(!1)}};return je.isEnabled()?e?a?l.jsx("div",{className:"g7dt-minimized",children:l.jsxs("div",{className:"g7dt-minimized-content",children:[l.jsx("span",{className:"g7dt-font-bold g7dt-text-sm",children:"G7 DevTools"}),l.jsx("button",{onClick:()=>i(!1),className:"g7dt-btn g7dt-text-xs",title:"확장",children:"▲"}),l.jsx("button",{onClick:()=>t(!1),className:"g7dt-btn g7dt-text-xs",children:"✕"})]})}):l.jsxs("div",{ref:D,className:`g7dt-panel ${ve?"maximized":""} ${z?"g7dt-resizing":""}`,style:{left:`${w.x>=0?w.x:0}px`,top:`${w.y>=0?w.y:0}px`,width:`${$.width}px`,height:`${$.height}px`},children:[!ve&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"g7dt-resize-handle g7dt-resize-corner g7dt-resize-nw",onMouseDown:ee("nw")}),l.jsx("div",{className:"g7dt-resize-handle g7dt-resize-corner g7dt-resize-ne",onMouseDown:ee("ne")}),l.jsx("div",{className:"g7dt-resize-handle g7dt-resize-corner g7dt-resize-sw",onMouseDown:ee("sw")}),l.jsx("div",{className:"g7dt-resize-handle g7dt-resize-corner g7dt-resize-se",onMouseDown:ee("se")}),l.jsx("div",{className:"g7dt-resize-handle g7dt-resize-edge-h g7dt-resize-n",onMouseDown:ee("n")}),l.jsx("div",{className:"g7dt-resize-handle g7dt-resize-edge-h g7dt-resize-s",onMouseDown:ee("s")}),l.jsx("div",{className:"g7dt-resize-handle g7dt-resize-edge-v g7dt-resize-w",onMouseDown:ee("w")}),l.jsx("div",{className:"g7dt-resize-handle g7dt-resize-edge-v g7dt-resize-e",onMouseDown:ee("e")})]}),l.jsxs("div",{className:`g7dt-header ${A?"dragging":""}`,onMouseDown:he,children:[l.jsxs("div",{className:"g7dt-header-left",children:[l.jsx("span",{className:"g7dt-header-title",children:"G7 DevTools"}),l.jsx("span",{className:`g7dt-header-badge ${S?"connected":""}`,title:S?"서버 덤프 성공":"서버에 덤프되지 않음 (덤프 버튼 클릭)",children:S?"덤프 완료":"로컬 모드"})]}),l.jsxs("div",{className:"g7dt-header-right",children:[l.jsx("button",{onClick:R,className:"g7dt-btn g7dt-btn-primary",title:"서버로 상태 덤프",children:"덤프"}),l.jsx("button",{onClick:ae,className:"g7dt-btn",title:"새로고침",children:"↻"}),l.jsx("button",{onClick:X,className:"g7dt-btn",title:ve?"복원":"최대화",children:ve?"❐":"□"}),l.jsx("button",{onClick:()=>i(!0),className:"g7dt-btn",title:"최소화",children:"▼"}),l.jsx("button",{onClick:()=>t(!1),className:"g7dt-btn",children:"✕"})]})]}),l.jsx("div",{className:"g7dt-tabs",children:Object.keys(nx).map(U=>l.jsx("button",{onClick:()=>d(U),className:`g7dt-tab ${o===U?"active":""}`,children:nx[U]},U))}),l.jsxs("div",{className:"g7dt-content",children:[o==="state"&&l.jsx(gk,{state:g,devTools:je}),o==="actions"&&l.jsx(hk,{actions:f,devTools:je}),o==="cache"&&l.jsx(fk,{stats:y,devTools:je}),o==="diagnose"&&l.jsx(pk,{}),o==="performance"&&l.jsx(mk,{devTools:je}),o==="lifecycle"&&l.jsx(yk,{devTools:je}),o==="network"&&l.jsx(xk,{devTools:je}),o==="form"&&l.jsx(bk,{devTools:je}),o==="conditional"&&l.jsx(vk,{devTools:je}),o==="expression"&&l.jsx(wk,{devTools:je}),o==="handlers"&&l.jsx(Sk,{devTools:je}),o==="events"&&l.jsx(Ck,{devTools:je}),o==="datasources"&&l.jsx(jk,{devTools:je}),o==="renders"&&l.jsx(kk,{devTools:je}),o==="styles"&&l.jsx(Nk,{devTools:je}),o==="auth"&&l.jsx(Ek,{devTools:je}),o==="logs"&&l.jsx(_k,{devTools:je}),o==="layout"&&l.jsx(Ak,{devTools:je}),o==="changedetection"&&l.jsx(Tk,{devTools:je}),o==="staleclosure"&&l.jsx(Dk,{devTools:je}),o==="nestedcontext"&&l.jsx(Rk,{devTools:je}),o==="modalscope"&&l.jsx(Ok,{devTools:je}),o==="namedactions"&&l.jsx(Lk,{devTools:je})]}),l.jsxs("div",{className:"g7dt-footer",children:[l.jsx("span",{children:"Ctrl+Shift+G 토글 | 헤더 드래그로 이동"}),l.jsxs("span",{children:["액션: ",f.length," | 캐시 히트율: ",(y.hitRate*100).toFixed(1),"%"]})]})]}):l.jsx("button",{onClick:()=>t(!0),className:"g7dt-floating-btn",title:"G7 DevTools (Ctrl+Shift+G)",children:l.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:[l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}):e?l.jsxs("div",{className:"g7dt-disabled-notice",children:[l.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-justify-between g7dt-mb-2",children:[l.jsx("span",{className:"g7dt-font-bold g7dt-text-yellow",children:"G7 DevTools"}),l.jsx("button",{onClick:()=>t(!1),className:"g7dt-btn",children:"✕"})]}),l.jsx("p",{className:"g7dt-text-sm g7dt-text-gray",children:"DevTools가 비활성화되어 있습니다."}),l.jsx("p",{className:"g7dt-text-xs g7dt-text-gray-dark g7dt-mt-2",children:"환경설정 > 고급 설정 > 디버그 모드를 켜세요."})]}):null},$k=["display","visibility","opacity","position","zIndex","overflow","width","height","backgroundColor","color"],_r=class _r{constructor(){H(this,"enabled",!1);H(this,"trackedComponents",new Map);H(this,"mutationObserver",null);H(this,"scanInterval",null);H(this,"devTools");this.devTools=ka.getInstance()}static getInstance(){return _r.instance||(_r.instance=new _r),_r.instance}enable(){this.enabled||(this.enabled=!0,this.setupMutationObserver(),this.scanInterval=setInterval(()=>{this.scanVisibleComponents()},5e3),console.log("[StyleTracker] 스타일 추적 활성화됨"))}disable(){this.enabled&&(this.enabled=!1,this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.scanInterval&&(clearInterval(this.scanInterval),this.scanInterval=null),this.trackedComponents.clear(),console.log("[StyleTracker] 스타일 추적 비활성화됨"))}trackComponent(e,t,a){if(!this.enabled||!this.devTools.isEnabled()||!a)return;const i=this.extractClasses(a),o=this.getComputedStyles(a);this.devTools.trackComponentStyle(e,t,i,o),this.trackedComponents.set(e,{componentId:e,componentName:t,classes:i,computedStyles:o,element:new WeakRef(a),timestamp:Date.now()}),this.detectIssues(e,t,a,i,o)}untrackComponent(e){this.trackedComponents.delete(e)}scanVisibleComponents(){if(!this.enabled||!this.devTools.isEnabled())return;(this.devTools.getLifecycleInfo().mountedComponents||[]).forEach(i=>{const o=i.id,d=i.name;let g=null;if(o&&(g=document.getElementById(o)),!g&&o&&(g=document.querySelector(`[data-component-id="${o}"]`)),!g&&o&&(g=document.querySelector(`[data-editor-id="${o}"]`)),!g)return;const h=this.extractClasses(g),f=this.getComputedStyles(g);this.devTools.trackComponentStyle(o,d,h,f),this.detectIssues(o,d,g,h,f),this.trackedComponents.set(o,{componentId:o,componentName:d,classes:h,computedStyles:f,element:new WeakRef(g),timestamp:Date.now()})}),document.querySelectorAll('[data-editor-id], [id^="comp-"]').forEach(i=>{if(!(i instanceof HTMLElement))return;const o=i.getAttribute("data-editor-id")||i.id,d=i.getAttribute("data-editor-name")||i.tagName;if(!o||this.trackedComponents.has(o))return;const g=this.extractClasses(i),h=this.getComputedStyles(i);this.devTools.trackComponentStyle(o,d,g,h),this.detectIssues(o,d,i,g,h),this.trackedComponents.set(o,{componentId:o,componentName:d,classes:g,computedStyles:h,element:new WeakRef(i),timestamp:Date.now()})})}detectIssues(e,t,a,i,o){o.display==="none"&&this.addIssue({type:"invisible-element",componentId:e,componentName:t,property:"display",currentValue:"none",severity:"info",description:"요소가 display:none으로 숨겨져 있습니다",suggestion:"의도적인 숨김이 아니라면 조건부 렌더링(if)을 확인하세요"}),o.visibility==="hidden"&&this.addIssue({type:"invisible-element",componentId:e,componentName:t,property:"visibility",currentValue:"hidden",severity:"info",description:"요소가 visibility:hidden으로 숨겨져 있습니다",suggestion:"공간은 유지되지만 보이지 않습니다. 의도적인지 확인하세요"}),o.opacity==="0"&&this.addIssue({type:"invisible-element",componentId:e,componentName:t,property:"opacity",currentValue:"0",severity:"warning",description:"요소가 opacity:0으로 투명합니다",suggestion:"애니메이션 상태가 아니라면 스타일을 확인하세요"}),(o.width==="0px"||o.height==="0px")&&this.addIssue({type:"invisible-element",componentId:e,componentName:t,property:o.width==="0px"?"width":"height",currentValue:"0px",severity:"warning",description:"요소의 크기가 0입니다",suggestion:"컨텐츠가 있는데 크기가 0이라면 레이아웃 문제일 수 있습니다"}),o.overflow==="hidden"&&(a.scrollWidth>a.clientWidth||a.scrollHeight>a.clientHeight)&&this.addIssue({type:"overflow-hidden",componentId:e,componentName:t,property:"overflow",currentValue:"hidden",severity:"warning",description:"컨텐츠가 overflow:hidden으로 잘리고 있습니다",suggestion:"overflow-auto 또는 컨테이너 크기를 확인하세요"});const d=i.some(S=>S.startsWith("dark:"));i.some(S=>(S.startsWith("bg-white")||S.startsWith("bg-gray-"))&&!S.startsWith("dark:"))&&!d&&this.addIssue({type:"dark-mode-missing",componentId:e,componentName:t,property:"className",currentValue:i.filter(S=>S.startsWith("bg-")).join(" "),severity:"info",description:"다크 모드 변형 클래스가 누락되었을 수 있습니다",suggestion:"bg-white 사용 시 dark:bg-gray-800 등을 함께 지정하세요"});const h=parseInt(o.zIndex,10);!isNaN(h)&&h>50&&o.position!=="static"&&this.addIssue({type:"z-index-conflict",componentId:e,componentName:t,property:"z-index",currentValue:o.zIndex,severity:"info",description:`높은 z-index(${h})가 설정되어 있습니다`,suggestion:"z-index 충돌을 피하려면 10, 20, 30, 40, 50 단위를 사용하세요"});const f=i.some(S=>S.startsWith("sm:")||S.startsWith("md:")||S.startsWith("lg:")||S.startsWith("xl:")),p=i.includes("hidden"),y=i.includes("portable:block")||i.includes("portable:flex"),x=i.includes("desktop:block")||i.includes("desktop:flex");p&&!f&&!y&&!x&&this.addIssue({type:"responsive-issue",componentId:e,componentName:t,property:"className",currentValue:"hidden",severity:"info",description:"반응형 표시 클래스 없이 hidden이 설정되어 있습니다",suggestion:"조건에 따라 표시하려면 sm:block, desktop:flex 등을 추가하세요"})}addIssue(e){this.devTools.addStyleIssue(e)}extractClasses(e){return(e.getAttribute("class")||"").split(/\s+/).filter(Boolean)}getComputedStyles(e){const t=window.getComputedStyle(e),a={};for(const i of $k)a[i]=t.getPropertyValue(i.replace(/([A-Z])/g,"-$1").toLowerCase());return a}setupMutationObserver(){typeof MutationObserver>"u"||(this.mutationObserver=new MutationObserver(e=>{let t=!1;for(const a of e){if(a.type==="childList"&&a.addedNodes.length>0){t=!0;break}if(a.type==="attributes"&&(a.attributeName==="class"||a.attributeName==="style")){t=!0;break}}t&&setTimeout(()=>this.scanVisibleComponents(),100)}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","style"]}))}fullScan(){return this.scanVisibleComponents(),this.devTools.getStyleValidationInfo().issues}getIssues(){return this.devTools.getStyleValidationInfo().issues}getIssuesForComponent(e){return this.getIssues().filter(t=>t.componentId===e)}clear(){this.trackedComponents.clear(),this.devTools.clearStyleValidationData()}};H(_r,"instance",null);let qg=_r;function Ik(){return qg.getInstance()}function zk(r={}){const{checked:e,value:t,name:a,type:i="checkbox"}=r,o={checked:e??!1,value:t??String(e??""),name:a??"",type:i};return{target:o,currentTarget:o,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new Event("change"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"change",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{}}}function Hk(r={}){const{button:e=0,clientX:t=0,clientY:a=0}=r;return{button:e,clientX:t,clientY:a,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new MouseEvent("click"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"click",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("div"),currentTarget:document.createElement("div")}}function Pk(){return{preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new Event("submit"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"submit",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("form"),currentTarget:document.createElement("form")}}function Bk(r,e="keydown"){return{key:r,code:r.length===1?`Key${r.toUpperCase()}`:r,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new KeyboardEvent(e,{key:r}),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:e,isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("div"),currentTarget:document.createElement("div"),altKey:!1,ctrlKey:!1,metaKey:!1,shiftKey:!1,repeat:!1}}const Uk={justify:/^justify-(start|end|center|between|around|evenly)$/,items:/^items-(start|end|center|baseline|stretch)$/,content:/^content-(start|end|center|between|around|evenly|stretch)$/,self:/^self-(auto|start|end|center|stretch|baseline)$/,flex:/^flex-(row|row-reverse|col|col-reverse|wrap|wrap-reverse|nowrap|1|auto|initial|none)$/,grow:/^(grow|grow-0)$/,shrink:/^(shrink|shrink-0)$/,basis:/^basis-/,order:/^(order-|-)order-/,gap:/^gap(-x|-y)?-/,gridCols:/^grid-cols-/,gridRows:/^grid-rows-/,colSpan:/^col-(span-|start-|end-)/,rowSpan:/^row-(span-|start-|end-)/,display:/^(block|inline-block|inline|flex|inline-flex|table|inline-table|table-caption|table-cell|table-column|table-column-group|table-footer-group|table-header-group|table-row-group|table-row|flow-root|grid|inline-grid|contents|list-item|hidden)$/,position:/^(static|fixed|absolute|relative|sticky)$/,inset:/^(inset|top|right|bottom|left)-/,zIndex:/^z-/,width:/^w-/,minWidth:/^min-w-/,maxWidth:/^max-w-/,height:/^h-/,minHeight:/^min-h-/,maxHeight:/^max-h-/,padding:/^p[xytblr]?-/,margin:/^-?m[xytblr]?-/,space:/^space-(x|y)-/,fontSize:/^text-(xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl)$/,fontWeight:/^font-(thin|extralight|light|normal|medium|semibold|bold|extrabold|black)$/,fontStyle:/^(italic|not-italic)$/,fontFamily:/^font-(sans|serif|mono)/,textAlign:/^text-(left|center|right|justify|start|end)$/,textColor:/^text-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,textDecoration:/^(underline|overline|line-through|no-underline)$/,textTransform:/^(uppercase|lowercase|capitalize|normal-case)$/,lineHeight:/^leading-/,letterSpacing:/^tracking-/,textOverflow:/^(truncate|text-ellipsis|text-clip)$/,whitespace:/^whitespace-/,wordBreak:/^break-/,bgColor:/^bg-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,bgGradient:/^bg-gradient-/,bgSize:/^bg-(auto|cover|contain)$/,bgPosition:/^bg-(bottom|center|left|left-bottom|left-top|right|right-bottom|right-top|top)$/,bgRepeat:/^bg-(repeat|no-repeat|repeat-x|repeat-y|repeat-round|repeat-space)$/,bgAttachment:/^bg-(fixed|local|scroll)$/,bgClip:/^bg-clip-/,bgOrigin:/^bg-origin-/,borderWidth:/^border(-[xytblr])?(-0|-2|-4|-8)?$/,borderColor:/^border-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,borderStyle:/^border-(solid|dashed|dotted|double|hidden|none)$/,borderRadius:/^rounded(-[tblrse]{1,2})?(-none|-sm|-md|-lg|-xl|-2xl|-3xl|-full)?$/,ringWidth:/^ring(-0|-1|-2|-4|-8|-inset)?$/,ringColor:/^ring-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,ringOffset:/^ring-offset-/,shadow:/^shadow(-sm|-md|-lg|-xl|-2xl|-inner|-none)?$/,opacity:/^opacity-/,mixBlend:/^mix-blend-/,bgBlend:/^bg-blend-/,blur:/^blur(-none|-sm|-md|-lg|-xl|-2xl|-3xl)?$/,brightness:/^brightness-/,contrast:/^contrast-/,grayscale:/^grayscale(-0)?$/,hueRotate:/^-?hue-rotate-/,invert:/^invert(-0)?$/,saturate:/^saturate-/,sepia:/^sepia(-0)?$/,backdropBlur:/^backdrop-blur-/,backdropBrightness:/^backdrop-brightness-/,backdropContrast:/^backdrop-contrast-/,backdropGrayscale:/^backdrop-grayscale-/,backdropHueRotate:/^backdrop-hue-rotate-/,backdropInvert:/^backdrop-invert-/,backdropOpacity:/^backdrop-opacity-/,backdropSaturate:/^backdrop-saturate-/,backdropSepia:/^backdrop-sepia-/,scale:/^scale(-x|-y)?-/,rotate:/^-?rotate-/,translate:/^-?translate-[xy]-/,skew:/^-?skew-[xy]-/,transformOrigin:/^origin-/,transition:/^transition(-none|-all|-colors|-opacity|-shadow|-transform)?$/,duration:/^duration-/,ease:/^ease-(linear|in|out|in-out)$/,delay:/^delay-/,animate:/^animate-/,cursor:/^cursor-/,userSelect:/^select-/,pointerEvents:/^pointer-events-/,resize:/^resize(-none|-x|-y)?$/,scrollBehavior:/^scroll-(auto|smooth)$/,touchAction:/^touch-/,overflow:/^overflow(-x|-y)?-(auto|hidden|clip|visible|scroll)$/,overscroll:/^overscroll(-x|-y)?-(auto|contain|none)$/,visibility:/^(visible|invisible|collapse)$/,aspectRatio:/^aspect-/,columns:/^columns-/,breakAfter:/^break-after-/,breakBefore:/^break-before-/,breakInside:/^break-inside-/,boxDecorationBreak:/^box-decoration-/,boxSizing:/^box-(border|content)$/,float:/^float-(right|left|none)$/,clear:/^clear-(left|right|both|none)$/,isolation:/^(isolate|isolation-auto)$/,objectFit:/^object-(contain|cover|fill|none|scale-down)$/,objectPosition:/^object-/};function lx(r){const e=r.replace(/^(dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+/,"");for(const[t,a]of Object.entries(Uk))if(a.test(e))return t;return null}function cx(r){const e=r.match(/^((dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+)/);return e?e[1]:""}function qk(r,e){if(!e||e.trim()==="")return r;if(!r||r.trim()==="")return e;const t=r.split(/\s+/).filter(Boolean),a=e.split(/\s+/).filter(Boolean),i=new Map;for(const d of a){const g=lx(d);if(g){const h=cx(d),f=`${g}:${h}`;i.set(f,d)}}return[...t.filter(d=>{const g=lx(d);if(!g)return!0;const h=cx(d),f=`${g}:${h}`;return!i.has(f)}),...a].join(" ")}function Gk(r){return Object.entries(r).filter(([,e])=>e).map(([e])=>e).join(" ")}function Fk(...r){return r.filter(e=>typeof e=="string"&&e.length>0).join(" ")}const Ee=it("G7CoreGlobals");function Vk(){window.React=Ke,window.ReactDOM={...Hu,createPortal:Os.createPortal,unstable_batchedUpdates:r=>r()},window.ReactJSXRuntime=g7,Ee.log("전역 객체 window.React, window.ReactDOM, window.ReactJSXRuntime에 노출됨")}function Kk(r){const e=new Map,t=ka.getInstance();r.componentEvent={on:(a,i)=>(e.has(a)||e.set(a,new Set),e.get(a).add(i),t.trackEventSubscribe(a),()=>{e.get(a)?.delete(i),t.trackEventUnsubscribe(a)}),emit:async(a,i)=>{const o=e.get(a),d=o?.size??0;if(!o||o.size===0)return t.trackEventEmit(a,i,0),[];let g,h=[];try{h=await Promise.all(Array.from(o).map(async f=>{try{return await f(i)}catch(p){throw Ee.error(`componentEvent: Error in listener for "${a}":`,p),p}}))}catch(f){g=f instanceof Error?f:new Error(String(f))}if(t.trackEventEmit(a,i,d,h,g),g)throw g;return h},off:a=>{e.delete(a),t.trackEventOff(a)},clear:()=>{e.clear(),t.trackEventClear()}},Ee.log("전역 객체 window.G7Core.componentEvent에 노출됨")}function Wk(r,e){r.useTranslation=Dj,r.t=(t,a)=>{const i=e.getState();if(!i.translationEngine||!i.translationContext)return t;if(a){const o="|"+Object.entries(a).map(([d,g])=>`${d}=${g}`).join("|");return i.translationEngine.translate(t,i.translationContext,o)}return i.translationEngine.translate(t,i.translationContext)},Ee.log("전역 객체 window.G7Core.useTranslation에 노출됨")}function Yk(r,e){r.createChangeEvent=zk,r.createClickEvent=Hk,r.createSubmitEvent=Pk,r.createKeyboardEvent=Bk,r.uuid=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const a=Math.random()*16|0;return(t==="x"?a:a&3|8).toString(16)}),r.createLogger=it,Ee.log("전역 객체 window.G7Core.createLogger에 노출됨"),r.renderItemChildren=(t,a,i,o,d)=>{const g=e.getState(),p={_global:window.__templateApp?.getGlobalState?.()||{},_local:a._local||{},_computed:a._computed||{},...a},y=new Set,x=(v,w)=>{const k=p._global?._remountKeys;return v&&k?.[v]&&!y.has(v)?(y.add(v),`${v}-remount-${k[v]}`):v||w},S={translationContext:g.translationContext,translationEngine:g.translationEngine,bindingEngine:g.bindingEngine,actionDispatcher:g.actionDispatcher,getRemountKey:x,...d};return fo(t,p,i,o,S)},r.getComponentMap=()=>ba.getInstance().getComponentMap(),r.renderComponentLayout=(t,a,i)=>{if(!t||!Array.isArray(t)||t.length===0)return null;const o=ba.getInstance().getComponentMap(),d=e.getState(),h=window.__templateApp?.getGlobalState?.()||{},f={_global:h._global||{},_local:h._local||{},_computed:h._computed||{},...a},p=new Set,y=(x,S)=>{const v=f._global?._remountKeys;return x&&v?.[x]&&!p.has(x)?(p.add(x),`${x}-remount-${v[x]}`):x||S};return fo(t,f,o,i,{translationContext:d.translationContext,translationEngine:d.translationEngine,bindingEngine:d.bindingEngine,actionDispatcher:d.actionDispatcher,getRemountKey:y})},r.renderExpandContent=t=>{const{children:a,row:i,expandContext:o,componentContext:d,keyPrefix:g}=t;if(!a||!Array.isArray(a)||a.length===0)return null;const h=t.componentMap||ba.getInstance().getComponentMap(),f=e.getState(),p=r.state?.get?.()||{},y=d?.stateRef?.current??d?.state??{},x={...p._local||{},...y},S=d?.computedRef?.current??p._computed??{},v=f.bindingEngine??r.getDataBindingEngine?.(),w={...p,_local:x,_computed:S,row:i,item:i,$item:i};let k={};if(o&&typeof o=="object"&&v)try{for(const[D,$]of Object.entries(o))if(typeof $=="string"){const M=$.match(/^\{\{([^}]+)\}\}$/);if(M){const z=M[1].trim();try{k[D]=v.evaluateExpression(z,w,{skipCache:!0})}catch{k[D]=void 0}}else k[D]=v.resolveBindings($,w,{skipCache:!0})}else k[D]=$}catch(D){Ee.warn("renderExpandContent: expandContext 평가 오류:",D)}const A={row:i,item:i,$item:i,_local:x,_global:p._global||{},_computed:p._computed||{},...k},O=new Set,N=(D,$)=>{const M=A._global?._remountKeys;return D&&M?.[D]&&!O.has(D)?(O.add(D),`${D}-remount-${M[D]}`):D||$};return fo(a,A,h,g,{translationContext:f.translationContext,translationEngine:f.translationEngine??void 0,bindingEngine:f.bindingEngine??void 0,actionDispatcher:f.actionDispatcher,componentContext:d,getRemountKey:N})},r.$get=function(a,i,o=void 0){if(a==null)return o;const d=Array.isArray(i)?i:[i];if(d.length===0)return a;let g=a;for(const h of d){if(g==null||h==null)return o;g=g[h]}return g??o},Ee.log("전역 객체 window.G7Core.renderItemChildren에 노출됨"),Ee.log("전역 객체 window.G7Core.renderComponentLayout에 노출됨"),Ee.log("전역 객체 window.G7Core.renderExpandContent에 노출됨"),Ee.log("전역 객체 window.G7Core.$get에 노출됨")}function Jk(r){r.dispatch=async(e,t)=>{const a=window.__templateApp;if(!a)return Ee.warn("G7Core.dispatch: TemplateApp이 초기화되지 않았습니다."),{success:!1,error:new Error("TemplateApp이 초기화되지 않았습니다.")};const i=a.getActionDispatcher?.();if(!i)return Ee.warn("G7Core.dispatch: ActionDispatcher를 찾을 수 없습니다."),{success:!1,error:new Error("ActionDispatcher를 찾을 수 없습니다.")};const o=a.getRouter?.(),d=a.getGlobalState?.(),g=a.setGlobalState?.bind(a),f=t?.componentContext||window.__g7ActionContext,p=window.__g7PendingLocalState;let y=f?.state??d;p&&f&&(y=p,Ee.log("[dispatch] Using __g7PendingLocalState for context.state:",p));let x=f?.data??d;p&&f?.data?._local&&(x={...f.data,_local:p},Ee.log("[dispatch] Updated context.data._local with pendingLocalState"));const S={navigate:o?(v,w)=>o.navigate(v,w):void 0,setState:f?.setState??g,state:y,data:x,_isDispatchFallbackContext:!f?.setState};if(e.debounce){const v=e.debounceKey||`dispatch-${e.handler}`,w=typeof e.debounce=="number"?e.debounce:e.debounce.delay;return i.debouncedCall(v,w,()=>{const{debounce:k,debounceKey:A,...O}=e;i.dispatchAction(O,S)}),{success:!0,debounced:!0}}try{return await i.dispatchAction(e,S)}catch(v){return Ee.error("G7Core.dispatch: 액션 실행 오류:",v),{success:!1,error:v instanceof Error?v:new Error(String(v))}}},Ee.log("전역 객체 window.G7Core.dispatch에 노출됨")}function Lo(r){const e={};for(const[t,a]of Object.entries(r))if(t.includes(".")){const i=t.split(".");let o=e;for(let d=0;d0&&e.every(t=>/^\d+$/.test(t))}function ux(r,e){const t={...r};for(const a of Object.keys(e))a in t?t[a]!==null&&typeof t[a]=="object"&&!Array.isArray(t[a])&&e[a]!==null&&typeof e[a]=="object"&&!Array.isArray(e[a])&&(t[a]=ux(t[a],e[a])):t[a]=e[a];return t}function ia(r,e){if(Array.isArray(r)&&!Array.isArray(e)&&Xk(e)){const a=Object.keys(e).map(o=>parseInt(o,10));if(!((a.length>0?Math.max(...a):0)>=r.length+a.length+10)){const o=[...r];for(const[d,g]of Object.entries(e)){const h=parseInt(d,10);h>=0&&h=o.length&&(o[h]=g)}return o}}const t={...r};for(const[a,i]of Object.entries(e))i!==null&&typeof i=="object"&&!Array.isArray(i)?t[a]!==null&&typeof t[a]=="object"?t[a]=ia(t[a],i):t[a]={...i}:t[a]=i;return t}function Qk(r){r.state={get:()=>window.__templateApp?.getGlobalState?.()||{},set:(e,t)=>{const a=window.__templateApp;if(a?.setGlobalState&&a?.getGlobalState){const i=t?.merge||"deep",o=Lo(e);let d;if(i==="replace")d=o;else if(i==="shallow")d={...a.getGlobalState(),...o};else{const g=a.getGlobalState();d=ia(g,o)}a.setGlobalState(d,{render:t?.render})}else Ee.warn("G7Core.state.set: TemplateApp이 초기화되지 않았습니다.")},setLocal:(e,t)=>{const a=window.__templateApp;if(t?.render===!1&&!t?.selfManaged){const k=window.__g7AutoBindingPaths;k&&k.size>0&&dx(Lo(e)).some(O=>k.has(O))&&(Ee.log("[setLocal] render:false + 자동바인딩 경로 겹침 감지 → render:true 자동 승격 (engine-v1.43.0)"),t={...t,render:!0})}if(t?.debounce){const k=a?.getActionDispatcher?.();if(k){const A=t.debounceKey||`setLocal-${Object.keys(e).join(",")}`,{debounce:O,debounceKey:N,...D}=t;k.debouncedCall(A,t.debounce,()=>{r.state.setLocal(e,D)});return}}const i=t?.scope??"current",o=t?.merge||"deep",d=window.__g7ActionContext,g=Lo(e);if(i==="parent"||i==="root"){const k=window.__g7LayoutContextStack||[];if(k.length>0){const A=i==="parent"?k[k.length-1]:k[0];if(A?.setState){A.setState(O=>o==="replace"?g:o==="shallow"?{...O||{},...g}:ia(O||{},g)),Ee.log(`[setLocal] scope=${i}: 타겟 컨텍스트에 상태 업데이트 (mergeMode=${o})`,g);return}}Ee.warn(`[setLocal] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const h=window.__g7PendingLocalState,f=a?.getGlobalState?.()?._local||{},x=!((window.__g7LayoutContextStack||[]).length>0)&&d?.state?d.state:void 0,S=x?ux(f,x):f,v=h||S;let w;if(o==="replace"?w=g:o==="shallow"?w={...v,...g}:w=ia(v,g),a?.setGlobalState&&(a.setGlobalState({_local:w},{render:t?.render}),Ee.log(`[setLocal] globalLocal updated via setGlobalState (mergeMode=${o}, render=${t?.render??!0}):`,g)),window.__g7PendingLocalState=w,Ee.log("[setLocal] __g7PendingLocalState updated:",w),window.__g7SequenceLocalSync=w,window.__g7LastSetLocalSnapshot=w,o==="replace")window.__g7ForcedLocalFields=g;else{const k=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=ia(k,g)}if(Ee.log("[setLocal] __g7ForcedLocalFields updated:",g),o==="replace")window.__g7SetLocalOverrideKeys=g;else{const k=window.__g7SetLocalOverrideKeys||{};window.__g7SetLocalOverrideKeys=ia(k,g)}Ee.log("[setLocal] __g7SetLocalOverrideKeys updated:",g),d?.setState&&d.setState(k=>o==="replace"?g:o==="shallow"?{...k||{},...g}:ia(k||{},g)),a?.setGlobalState||Ee.warn("G7Core.state.setLocal: TemplateApp이 없습니다.")},getLocal:()=>{const a=(window.__templateApp?.getGlobalState?.()||{})._local||{},i=window.__g7PendingLocalState;if(i)return ia(a,i);const o=window.__g7LastSetLocalSnapshot;return o&&o!==a?ia(a,o):a},update:e=>{const t=window.__templateApp;if(t?.getGlobalState&&t?.setGlobalState){const a=t.getGlobalState(),i=e(a);t.setGlobalState(i)}else Ee.warn("G7Core.state.update: TemplateApp이 초기화되지 않았습니다.")},subscribe:e=>{const t=window.__templateApp;return t?.onGlobalStateChange?t.onGlobalStateChange(e):(Ee.warn("G7Core.state.subscribe: TemplateApp이 초기화되지 않았습니다."),()=>{})},getDataSource:e=>window.__templateApp?.getDataSource?.(e),getIsolated:e=>e?window.__g7IsolatedStates?.[e]?.state??null:window.__g7ActionContext?.isolatedContext?.state??null,setIsolated:(e,t,a)=>{let i,o,d;typeof e=="string"?(i=e,o=t||{},d=a):(o=e,d=t&&typeof t=="object"&&"merge"in t?t:a);const g=d?.merge||"deep",h=Lo(o);if(i){const y=window.__g7IsolatedStates?.[i];y?.mergeState?y.mergeState(h,g):Ee.warn(`G7Core.state.setIsolated: scopeId '${i}'를 찾을 수 없습니다.`);return}const f=window.__g7ActionContext;f?.isolatedContext?.mergeState?f.isolatedContext.mergeState(h,g):Ee.warn("G7Core.state.setIsolated: 액션 컨텍스트에 isolatedContext가 없습니다.")},getParent:()=>{const e=window.__g7LayoutContextStack||[];if(e.length===0)return Ee.log("[getParent] 레이아웃 컨텍스트 스택이 비어있습니다."),null;const t=e[e.length-1];if(!t)return null;const a=t.dataContext||{};return{_local:t.state||a._local||{},_global:a._global||r.state.get()||{},setState:t.setState}},setParentLocal:(e,t,a)=>{const i=window.__g7LayoutContextStack||[];if(i.length===0){Ee.warn("[setParentLocal] 레이아웃 컨텍스트 스택이 비어있습니다.");return}const o=i[i.length-1];if(!o?.setState){Ee.warn("[setParentLocal] 부모 컨텍스트에 setState가 없습니다.");return}let d,g;typeof e=="string"?(d={[e]:t},g=a):(d=e,g=t&&typeof t=="object"&&"merge"in t?t:a);const h=g?.merge||"deep",f=Lo(d),p=o.state?._local!==void 0,y=p?o.state._local:o.state||{};let x;h==="replace"?x=f:h==="shallow"?x={...y,...f}:x=ia(y,f),window.__g7PendingLocalState=x;const S=window.__templateApp;if(S?.setGlobalState&&S.setGlobalState({_local:x}),o.setState(x),p?o.state._local=x:o.state=x,o.dataContext&&(o.dataContext._local=x),h==="replace")window.__g7ForcedLocalFields=f;else{const v=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=ia(v,f)}dg()},setParentGlobal:(e,t)=>{let a;typeof e=="string"?a={[e]:t}:a=e,r.state.set(a),Ee.log("[setParentGlobal] 전역 상태 업데이트:",a)}},window.__g7IsolatedStates||(window.__g7IsolatedStates={}),r.state.getGlobal=r.state.get,r.state.setGlobal=r.state.set,Ee.log("전역 객체 window.G7Core.state에 노출됨")}function Zk(r){r.dataSource={get:e=>window.__templateApp?.getDataSource?.(e),set:(e,t,a)=>{const i=window.__templateApp;i?.setDataSource?i.setDataSource(e,t,a):Ee.warn("G7Core.dataSource.set: TemplateApp이 초기화되지 않았습니다.")},refetch:async(e,t)=>{const a=window.__templateApp;if(a?.refetchDataSource)return a.refetchDataSource(e,t);Ee.warn("G7Core.dataSource.refetch: TemplateApp이 초기화되지 않았습니다.")},updateItem:(e,t,a,i,o)=>{const d=window.__templateApp;return d?.updateDataSourceItem?d.updateDataSourceItem(e,t,a,i,o):(Ee.warn("G7Core.dataSource.updateItem: TemplateApp이 초기화되지 않았습니다."),!1)},updateData:(e,t,a,i="append")=>{const o=window.__templateApp;if(!o?.getDataSource||!o?.setDataSource)return Ee.warn("G7Core.dataSource.updateData: TemplateApp이 초기화되지 않았습니다."),!1;const d=o.getDataSource(e);if(!d)return Ee.warn(`G7Core.dataSource.updateData: 데이터 소스 '${e}'를 찾을 수 없습니다.`),!1;let g,h=d,f=null;if(t){const y=t.split(".");f=y.pop();for(const x of y)if(h&&typeof h=="object"&&x in h)h=h[x];else return Ee.warn(`G7Core.dataSource.updateData: 경로 '${t}'를 찾을 수 없습니다.`),!1;g=h[f]}else g=d;if(!Array.isArray(g))return Ee.warn("G7Core.dataSource.updateData: 대상 경로의 데이터가 배열이 아닙니다."),!1;if(!Array.isArray(a))return Ee.warn("G7Core.dataSource.updateData: newData가 배열이 아닙니다."),!1;const p=i==="prepend"?[...a,...g]:[...g,...a];return t&&f?(h[f]=p,o.setDataSource(e,d,{merge:!1})):o.setDataSource(e,p,{merge:!1}),Ee.log(`G7Core.dataSource.updateData: '${e}'에 ${a.length}개 항목 ${i==="prepend"?"앞에":"뒤에"} 추가됨`),!0}},Ee.log("전역 객체 window.G7Core.dataSource에 노출됨")}function eN(r,e){r.locale={current:()=>window.__templateApp?.getLocale?.()||"ko",supported:()=>e.getState().templateMetadata?.locales||["ko","en"],change:async t=>{const a=window.__templateApp;a?.changeLocale?await a.changeLocale(t):Ee.warn("G7Core.locale.change: TemplateApp이 초기화되지 않았습니다.")}},Ee.log("전역 객체 window.G7Core.locale에 노출됨")}function tN(r){r.toast={show:(e,t)=>{r.dispatch({handler:"toast",params:{message:e,type:t?.type||"info",...t?.duration&&{duration:t.duration}}})},success:(e,t)=>{r.toast.show(e,{type:"success",duration:t})},error:(e,t)=>{r.toast.show(e,{type:"error",duration:t})},warning:(e,t)=>{r.toast.show(e,{type:"warning",duration:t})},info:(e,t)=>{r.toast.show(e,{type:"info",duration:t})}},Ee.log("전역 객체 window.G7Core.toast에 노출됨")}function nN(r){r.modal={open:e=>{r.dispatch({handler:"openModal",target:e})},close:e=>{r.dispatch({handler:"closeModal",...e&&{target:e}})},closeAll:()=>{r.dispatch({handler:"closeAllModals"})},isOpen:e=>{const t=r.state.get();return t._global?.activeModal===e||t._global?.modalStack?.includes(e)||!1},getStack:()=>r.state.get()._global?.modalStack||[]},Ee.log("전역 객체 window.G7Core.modal에 노출됨")}function aN(r){r.style={mergeClasses:qk,conditionalClass:Gk,joinClasses:Fk},Ee.log("전역 객체 window.G7Core.style에 노출됨")}function sN(r,e){const{webSocketManager:t}=e;r.websocket={manager:t,subscribe:(a,i,o,d)=>t.subscribe(a,i,o,d),unsubscribe:a=>t.unsubscribe(a),leaveChannel:a=>t.leaveChannel(a),disconnect:()=>t.disconnect(),isInitialized:()=>t.isInitialized(),getSubscriptionCount:()=>t.getSubscriptionCount()},Ee.log("전역 객체 window.G7Core.websocket에 노출됨")}function rN(r,e){const{transitionManager:t}=e;r.navigation={isPending:()=>t?.getIsPending?.()||!1,onComplete:a=>{if(!t)return a(),()=>{};let i=t.getIsPending();const o=t.subscribe(d=>{d?i=!0:i&&(a(),o())});return o}},Ee.log("전역 객체 window.G7Core.navigation에 노출됨")}function iN(r){r.plugin={getSettings:e=>window.G7Config?.plugins?.[e],get:(e,t,a)=>window.G7Config?.plugins?.[e]?.[t]??a,getAll:()=>window.G7Config?.plugins??{}},Ee.log("전역 객체 window.G7Core.plugin에 노출됨")}function oN(r){r.module={getSettings:e=>window.G7Config?.modules?.[e],get:(e,t,a)=>window.G7Config?.modules?.[e]?.[t]??a,getAll:()=>window.G7Config?.modules??{}},Ee.log("전역 객체 window.G7Core.module에 노출됨")}function lN(r,e){const{transitionManager:t,responsiveManager:a}=e;r.AuthManager=as,r.api=ns(),r.TransitionManager=t,r.useTransitionState=Wm,r.ResponsiveManager=a,r.useResponsive=Xm,r.useControllableState=x7,r.shallowArrayEqual=b7,r.shallowObjectEqual=Qm,r.updateQueryParams=async(i,o)=>{const d=window.__templateApp;if(d?.updateQueryParams)return d.updateQueryParams(i,o);Ee.warn("G7Core.updateQueryParams: TemplateApp이 초기화되지 않았습니다.")},Ee.log("전역 객체 window.G7Core.AuthManager에 노출됨"),Ee.log("전역 객체 window.G7Core.api에 노출됨"),Ee.log("전역 객체 window.G7Core.ResponsiveManager에 노출됨"),Ee.log("전역 객체 window.G7Core.useResponsive에 노출됨"),Ee.log("전역 객체 window.G7Core.useControllableState에 노출됨"),Ee.log("전역 객체 window.G7Core.updateQueryParams에 노출됨")}function cN(r,e){r.getSlotContext=()=>window.__slotContextValue??null,r.getDynamicRenderer=()=>window.__DynamicRenderer??null,r.getComponentRegistry=()=>e.getComponentRegistry?.()??ba.getInstance(),r.getDataBindingEngine=()=>e.getDataBindingEngine?.()??e.getState().bindingEngine,r.getTranslationEngine=()=>e.getTranslationEngine?.()??e.getState().translationEngine,r.getActionDispatcher=()=>e.getActionDispatcher?.()??e.getState().actionDispatcher,Ee.log("전역 객체 window.G7Core 슬롯 API에 노출됨 (getSlotContext, getDynamicRenderer 등)")}function dN(r){let e=!1,t=null,a=null;r.wysiwyg={isEditMode:()=>e,setEditMode:(i,o)=>{e=!0,t=i,a=o,Ee.log(`위지윅 편집 모드 활성화: ${i} (${o})`)},clearEditMode:()=>{e=!1,t=null,a=null,Ee.log("위지윅 편집 모드 비활성화")},getCurrentLayoutName:()=>t,getCurrentTemplateId:()=>a,isEditModeFromUrl:()=>typeof window>"u"?!1:new URLSearchParams(window.location.search).get("mode")==="edit",getEditModeUrl:(i,o)=>{const d=window.location.origin,g=i.startsWith("/")?i:`/${i}`;return`${d}${g}?mode=edit&template=${encodeURIComponent(o)}`},enterEditMode:(i,o)=>{if(typeof window>"u")return;const d=r.wysiwyg.getEditModeUrl(i,o);window.location.href=d},exitEditMode:()=>{if(typeof window>"u")return;const i=new URLSearchParams(window.location.search);i.delete("mode"),i.delete("template");const o=`${window.location.pathname}${i.toString()?"?"+i.toString():""}`;window.location.href=o},getVersion:()=>"1.0.0",getPhase:()=>1},Ee.log("전역 객체 window.G7Core 위지윅 편집기 API에 노출됨 (wysiwyg)")}function uN(r){if(typeof window>"u")return;Vk(),window.G7Core||(window.G7Core={});const e=window.G7Core;Kk(e),lN(e,r),Wk(e,r),Yk(e,r),Jk(e),Qk(e),Zk(e),eN(e,r),tN(e),nN(e),aN(e),sN(e,r),rN(e,r),iN(e),oN(e),cN(e,r),dN(e),Ee.log("G7Core 전역 객체 초기화 완료")}function gN(){const r=window.G7Core;if(!r){Ee.warn("G7Core가 초기화되지 않았습니다.");return}const e=()=>ka.getInstance(),t={isEnabled:()=>{try{return e().isEnabled()}catch{return!1}},trackRender:a=>{try{e().isEnabled()&&e().trackRender(a)}catch{}},trackIteration:(a,i,o,d,g)=>{try{e().isEnabled()&&e().trackIteration(a,{source:i,itemVar:o,indexVar:d,sourceLength:g})}catch{}},trackIfCondition:(a,i,o,d)=>{try{e().isEnabled()&&e().trackIfCondition(a,i,o)}catch{}},trackMount:(a,i)=>{try{e().isEnabled()&&e().trackMount(a,{...i,id:a})}catch{}},trackUnmount:a=>{try{e().isEnabled()&&e().trackUnmount(a)}catch{}},trackExpressionEval:a=>{try{e().isEnabled()&&e().trackExpressionEval(a)}catch{}},trackBindingEval:a=>{try{e().isEnabled()&&e().trackBindingEval(a)}catch{}},recordCacheHit:()=>{try{e().isEnabled()&&e().recordCacheHit()}catch{}},recordCacheMiss:()=>{try{e().isEnabled()&&e().recordCacheMiss()}catch{}},trackHandlerRegistration:(a,i,o,d)=>{try{e().isEnabled()&&e().trackHandlerRegistration(a,i,o,d)}catch{}},trackHandlerUnregistration:a=>{try{e().isEnabled()&&e().trackHandlerUnregistration(a)}catch{}},logAction:a=>{try{e().isEnabled()&&e().logAction(a)}catch{}},trackRequest:(a,i)=>{try{return e().isEnabled()?e().trackRequest(a,i):""}catch{return""}},completeRequest:(a,i,o)=>{try{e().isEnabled()&&e().completeRequest(a,i,o)}catch{}},failRequest:(a,i)=>{try{e().isEnabled()&&e().failRequest(a,i)}catch{}},trackDataSourceDefinition:a=>{try{e().isEnabled()&&e().trackDataSourceDefinition(a)}catch{}},trackDataSourceLoading:a=>{try{e().isEnabled()&&e().trackDataSourceLoading(a)}catch{}},trackDataSourceLoaded:(a,i,o)=>{try{e().isEnabled()&&e().trackDataSourceLoaded(a,i,o)}catch{}},trackDataSourceError:(a,i)=>{try{e().isEnabled()&&e().trackDataSourceError(a,i)}catch{}},trackForm:(a,i,o)=>{try{e().isEnabled()&&e().trackForm(a,i,o)}catch{}},untrackForm:a=>{try{e().isEnabled()&&e().untrackForm(a)}catch{}},startStateChange:(a,i,o,d)=>{try{return e().isEnabled()?e().startStateChange(a,i,o,d):""}catch{return""}},completeStateChange:a=>{try{e().isEnabled()&&e().completeStateChange(a)}catch{}},trackComponentRender:(a,i,o,d,g,h)=>{try{e().isEnabled()&&e().trackComponentRender(a,i,o,d,g,h)}catch{}},updateLocalState:a=>{try{e().isEnabled()&&e().updateLocalState(a)}catch{}},updateComputedState:a=>{try{e().isEnabled()&&e().updateComputedState(a)}catch{}},updateParentContext:a=>{try{e().isEnabled()&&e().updateParentContext(a)}catch{}},trackComponentStateSource:(a,i,o,d)=>{try{e().isEnabled()&&e().trackComponentStateSource(a,i,o,d)}catch{}},trackDynamicState:(a,i)=>{try{e().isEnabled()&&e().trackDynamicState(a,i)}catch{}},trackContextFlow:(a,i,o,d,g,h)=>{try{e().isEnabled()&&e().trackContextFlow(a,i,o,d,g,h)}catch{}},trackComponentStyle:(a,i,o,d)=>{try{e().isEnabled()&&e().trackComponentStyle(a,i,o,d)}catch{}},trackAuthEvent:(a,i,o,d)=>{try{e().isEnabled()&&e().trackAuthEvent(a,i,o,d)}catch{}},trackAuthHeader:(a,i,o,d,g)=>{try{e().isEnabled()&&e().trackAuthHeader(a,i,o,d,g)}catch{}},trackLog:(a,i,o)=>{try{e().isEnabled()&&e().trackLog(a,i,o)}catch{}},trackAction:a=>{try{e().isEnabled()&&e().trackAction?.(a)}catch{}},trackDataSourceUpdate:a=>{try{e().isEnabled()&&e().trackDataSourceUpdate?.(a)}catch{}},startSequenceExecution:a=>{try{return e().isEnabled()?e().startSequenceExecution(a):""}catch{return""}},captureSequenceActionBefore:(a,i,o,d,g)=>{try{e().isEnabled()&&e().captureSequenceActionBefore(a,i,o,d,g)}catch{}},captureSequenceActionAfter:(a,i,o,d,g,h)=>{try{e().isEnabled()&&e().captureSequenceActionAfter(a,i,o,d,g,h)}catch{}},endSequenceExecution:(a,i)=>{try{e().isEnabled()&&e().endSequenceExecution(a,i)}catch{}},registerStateCaptureForHandler:(a,i,o)=>{try{e().isEnabled()&&e().registerStateCaptureForHandler(a,i,o)}catch{}},detectStaleClosure:(a,i,o,d,g)=>{try{return e().isEnabled()?e().detectStaleClosure(a,i,o,d,g):[]}catch{return[]}},trackStaleClosureWarning:a=>{try{e().isEnabled()&&e().trackStaleClosureWarning(a)}catch{}},trackModalOpen:a=>{try{e().isEnabled()&&e().trackModalOpen(a)}catch{}},trackModalClose:(a,i)=>{try{e().isEnabled()&&e().trackModalClose(a,i)}catch{}},trackModalStateChange:a=>{try{e().isEnabled()&&e().trackModalStateChange(a)}catch{}},trackNestedContext:a=>{try{return e().isEnabled()?e().trackNestedContext(a):""}catch{return""}},trackNestedContextAccess:(a,i)=>{try{e().isEnabled()&&e().trackNestedContextAccess(a,i)}catch{}},trackComputedProperty:(a,i,o,d,g,h,f)=>{try{e().isEnabled()&&e().trackComputedProperty(a,i,o,d,g,h,f)}catch{}},trackComputedRecalc:(a,i,o,d,g,h,f)=>{try{e().isEnabled()&&e().trackComputedRecalc(a,i,o,d,g,h,f)}catch{}},setNamedActionDefinitions:a=>{try{e().isEnabled()&&e().setNamedActionDefinitions(a)}catch{}},trackNamedActionRef:a=>{try{e().isEnabled()&&e().trackNamedActionRef(a)}catch{}}};r.devTools=t,Ee.log("G7Core.devTools 인터페이스 초기화 완료")}function hN(){const r=window.G7Core;if(!r){Ee.warn("G7Core가 초기화되지 않았습니다.");return}const e=ka.getInstance();if(e.initialize(),!e.isEnabled()){window.G7DevTools={isEnabled:()=>!1,enable:()=>{Ee.log("환경설정 > 고급 설정 > 디버그 모드를 켜세요")}},Hp(),Ee.log("G7DevTools 비활성화됨 (디버그 모드 꺼짐)");return}gN(),Hp();try{Ik().enable(),Ee.log("StyleTracker 활성화됨")}catch(o){Ee.warn("StyleTracker 활성화 실패:",o)}const t=new ex,a=tx(),i={isEnabled:()=>e.isEnabled(),state:{get:()=>e.getState(),getHistory:()=>e.getStateHistory(),watch:(o,d)=>e.watchState(o,d)},actions:{getHistory:()=>e.getActionHistory(),watch:o=>e.watchActions(o),getMetrics:()=>e.getActionMetrics()},binding:{evaluate:o=>{const d=r.getDataBindingEngine?.();if(!d){Ee.warn("DataBindingEngine이 없습니다.");return}return d.evaluateExpression(o,e.getState())},getCacheStats:()=>e.getCacheStats(),clearStats:()=>{e.resetCacheStats(),Ee.log("캐시 통계 초기화됨")}},diagnose:{analyze:o=>t.analyze(o),suggestFix:o=>t.suggestFix(o),getCommonIssues:()=>t.getCommonIssues(),getRulesByCategory:o=>t.getRulesByCategory(o)},server:{dumpState:o=>a.dumpState(o),sendLog:o=>a.sendLog(o),sendError:(o,d)=>a.sendError(o,d),isConnected:()=>a.isConnected(),testConnection:()=>a.testConnection()},config:{isDebugMode:()=>e.isEnabled(),setLogLevel:o=>e.setLogLevel(o),setMaxHistory:o=>e.setMaxHistory(o)},lifecycle:{getMountedComponents:()=>e.getLifecycleInfo().mountedComponents,getOrphanedListeners:()=>e.getLifecycleInfo().orphanedListeners},performance:{getRenderCount:()=>e.getPerformanceInfo().renderCounts,getBindingEvalCount:()=>e.getPerformanceInfo().bindingEvalCount,getMemoryWarnings:()=>e.getPerformanceInfo().memoryWarnings,startProfiling:()=>e.startProfiling(),stopProfiling:()=>e.stopProfiling()},network:{getActiveRequests:()=>e.getNetworkInfo().activeRequests,getRequestHistory:()=>e.getNetworkInfo().requestHistory,getPendingDataSources:()=>e.getNetworkInfo().pendingDataSources},conditional:{getIfConditions:()=>e.getConditionalInfo().ifConditions,getIterations:()=>e.getConditionalInfo().iterations},form:{getForms:()=>e.getFormInfo()},websocket:{getInfo:()=>e.getWebSocketInfo()}};window.G7DevTools=i,r.devtools=i,Ee.log("G7DevTools 전역 객체 초기화 완료 (window.G7DevTools)"),fN()}function fN(){if(document.getElementById("g7-devtools-root")){Ee.log("DevToolsPanel 이미 렌더링됨");return}const r=document.createElement("div");r.id="g7-devtools-root",document.body.appendChild(r);try{Hu.createRoot(r).render(Ke.createElement(Mk)),Ee.log("DevToolsPanel UI 렌더링 완료")}catch(e){Ee.error("DevToolsPanel UI 렌더링 실패:",e)}}const et=it("TemplateEngine"),ge={templateId:null,locale:"ko",isInitialized:!1,reactRoot:null,containerId:null,currentLayoutJson:null,currentDataContext:{},translationContext:{templateId:"",locale:"ko"},registry:null,bindingEngine:null,translationEngine:null,actionDispatcher:null,templateMetadata:null};let Pc=!1;const Mo=[];async function pN(r){try{et.log("템플릿 메타데이터 로드 중...",r);const e=r.split("-").map(a=>a.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join("")).join(""),t=window[e];return t?.templateMetadata?(et.log("템플릿 메타데이터 로드 완료 (전역 변수)",t.templateMetadata),t.templateMetadata):(et.warn(`템플릿 번들에 메타데이터가 없습니다. 전역 변수: ${e}`),{identifier:r,locales:["ko","en"],name:{ko:r,en:r},description:{ko:"",en:""},version:"1.0.0",type:"admin"})}catch(e){return et.error("템플릿 메타데이터 로드 실패",e),{identifier:r,locales:["ko","en"],name:{ko:r,en:r},description:{ko:"",en:""},version:"1.0.0",type:"admin"}}}function gx(){return{$locale:ge.locale,$locales:ge.templateMetadata?.locales||["ko","en"],$templateId:ge.templateId}}async function $o(r){try{if(et.log("템플릿 엔진 초기화 시작",r),ge.isInitialized)throw new Error("템플릿 엔진이 이미 초기화되었습니다. destroyTemplate()을 먼저 호출하세요.");if(!r.templateId)throw new Wj;Pc=r.debug??!1,typeof window<"u"&&(window.G7Config||(window.G7Config={}),window.G7Config.debug=Pc),hN(),ge.templateId=r.templateId,ge.locale=r.locale||"ko",et.log("엔진 인스턴스 생성 중..."),ge.registry=ba.getInstance(),ge.bindingEngine=new _n,ge.translationEngine=xr.getInstance(),r.cacheVersion!==void 0&&r.cacheVersion>0&&ge.translationEngine.setCacheVersion(r.cacheVersion),ge.translationContext={templateId:r.templateId,locale:ge.locale},ge.actionDispatcher=new So({},ge.translationEngine,ge.translationContext),p7(ge.actionDispatcher),et.log("다국어 파일 로드 중...",r.templateId,ge.locale);const e="en",t=[ge.translationEngine.loadTranslations(r.templateId,ge.locale).then(()=>{et.log(`다국어 파일 로드 완료: ${ge.locale}`)}).catch(a=>{et.warn(`다국어 파일 로드 실패 (${ge.locale}):`,a instanceof Error?a.message:a)})];ge.locale!==e&&t.push(ge.translationEngine.loadTranslations(r.templateId,e).then(()=>{et.log(`폴백 다국어 파일 로드 완료: ${e}`)}).catch(a=>{et.warn(`폴백 다국어 파일 로드 실패 (${e}):`,a instanceof Error?a.message:a)})),await Promise.allSettled(t),et.log("템플릿 메타데이터 로드 중...",r.templateId),ge.templateMetadata=await pN(r.templateId),ge.isInitialized=!0,et.log("템플릿 엔진 초기화 완료 (ComponentRegistry는 별도 로드)")}catch(e){throw et.error("템플릿 엔진 초기화 실패",e),ge.isInitialized=!1,ge.registry=null,ge.bindingEngine=null,ge.translationEngine=null,ge.actionDispatcher=null,e}}async function Io(r){try{if(et.log("템플릿 렌더링 시작",r),!ge.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다. initTemplateEngine()을 먼저 호출하세요.");if(!r.containerId)throw new Error("containerId는 필수입니다.");if(!r.layoutJson)throw new Error("layoutJson은 필수입니다.");const e=document.getElementById(r.containerId);if(!e)throw new Error(`컨테이너를 찾을 수 없습니다: #${r.containerId}`);const t=gx();ge.containerId=r.containerId,ge.currentLayoutJson=r.layoutJson,ge.currentDataContext={...t,...r.dataContext||{}},ge.translationContext=r.translationContext||{templateId:ge.templateId||"",locale:ge.locale},ge.reactRoot||(et.log("React Root 생성"),ge.reactRoot=Hu.createRoot(e));const a=fx();if(et.log("편집 모드:",a),a){await yN(r);return}const i=r.layoutJson.components||[];if(i.length===0){et.warn("렌더링할 컴포넌트가 없습니다.");return}const o=r.layoutJson.modals||[];if(et.log("modals 배열:",o),et.log("modals 개수:",o.length),et.log("DynamicRenderer로 렌더링 시작"),ge.reactRoot.render(Ke.createElement(Rc,{translationEngine:ge.translationEngine,translationContext:ge.translationContext},Ke.createElement(ug,null,Ke.createElement(gg,null,Ke.createElement(Og,null,[...i.map((d,g)=>{const h=ge.currentLayoutJson?.layout_name||"";return Ke.createElement(Ua,{key:h&&!d._fromBase?`${d.id}_${h}`:d.id,componentDef:d,dataContext:ge.currentDataContext,translationContext:ge.translationContext,registry:ge.registry,bindingEngine:ge.bindingEngine,translationEngine:ge.translationEngine,actionDispatcher:ge.actionDispatcher,isRootRenderer:g===0,layoutKey:h})}),Ke.createElement(qm,{key:"__modal_parent_context_provider"},o.map(d=>{const g=ge.currentDataContext._global?.modalStack||[],f=g.includes(d.id)||ge.currentDataContext._global?.activeModal===d.id,p=g.indexOf(d.id),y=p>=0?50+p:50,x=window.__g7LayoutContextStack||[],v=x[x.length-1]?.dataContext,w=Ke.createElement(Ua,{key:`modal_${d.id}_renderer`,componentDef:{...d,props:{...d.props,isOpen:f,style:{...d.props?.style,zIndex:y},onClose:ge.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},ge.currentDataContext)}},dataContext:ge.currentDataContext,translationContext:ge.translationContext,registry:ge.registry,bindingEngine:ge.bindingEngine,translationEngine:ge.translationEngine,actionDispatcher:ge.actionDispatcher,parentDataContext:v});return d.data_sources&&d.data_sources.length>0?Ke.createElement(Xy,{key:`modal_${d.id}`,isOpen:f,modalId:d.id,dataSources:d.data_sources,dataContext:ge.currentDataContext,globalStateUpdater:ge.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:ge.bindingEngine,debug:Pc,children:w}):w}))]))))),et.log("템플릿 렌더링 완료"),Mo.length>0){et.log(`대기 중인 데이터 업데이트 ${Mo.length}건 적용`);const d=[...Mo];Mo.length=0;for(const{data:g,options:h}of d)fi(g,h)}}catch(e){throw et.error("템플릿 렌더링 실패",e),e}}function fi(r,e){try{if(et.log("템플릿 데이터 업데이트 시작",Object.keys(r)),fx()){et.log("편집 모드에서는 updateTemplateData를 건너뜁니다.");return}if(!ge.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다.");if(!ge.reactRoot||!ge.currentLayoutJson){et.log("React 미준비 - 데이터 업데이트 큐잉:",Object.keys(r)),Mo.push({data:r,options:e});return}const t=gx(),a={...ge.currentDataContext._global||{},...r._global||{}};ge.currentDataContext={...t,...ge.currentDataContext,...r,_global:a},a._local!==void 0&&(ge.currentDataContext._local=a._local),a._computed!==void 0&&(ge.currentDataContext._computed=a._computed);const i=ge.currentLayoutJson.components||[],o=ge.currentLayoutJson.modals||[];et.log("updateTemplateData - modals 배열:",o),et.log("updateTemplateData - modals 개수:",o.length),et.log("updateTemplateData - activeModal:",ge.currentDataContext._global?.activeModal);const d=()=>{ge.reactRoot.render(Ke.createElement(Rc,{translationEngine:ge.translationEngine,translationContext:ge.translationContext},Ke.createElement(ug,null,Ke.createElement(gg,null,Ke.createElement(Og,null,[...i.map((g,h)=>{const f=ge.currentLayoutJson?.layout_name||"";return Ke.createElement(Ua,{key:f&&!g._fromBase?`${g.id}_${f}`:g.id,componentDef:g,dataContext:ge.currentDataContext,translationContext:ge.translationContext,registry:ge.registry,bindingEngine:ge.bindingEngine,translationEngine:ge.translationEngine,actionDispatcher:ge.actionDispatcher,isRootRenderer:h===0,layoutKey:f})}),Ke.createElement(qm,{key:"__modal_parent_context_provider_update"},o.map(g=>{const h=ge.currentDataContext._global?.modalStack||[],p=h.includes(g.id)||ge.currentDataContext._global?.activeModal===g.id,y=h.indexOf(g.id),x=y>=0?50+y:50,S=window.__g7LayoutContextStack||[],w=S[S.length-1]?.dataContext,k=Ke.createElement(Ua,{key:`modal_${g.id}_renderer`,componentDef:{...g,props:{...g.props,isOpen:p,style:{...g.props?.style,zIndex:x},onClose:ge.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},ge.currentDataContext)}},dataContext:ge.currentDataContext,translationContext:ge.translationContext,registry:ge.registry,bindingEngine:ge.bindingEngine,translationEngine:ge.translationEngine,actionDispatcher:ge.actionDispatcher,parentDataContext:w});return g.data_sources&&g.data_sources.length>0?Ke.createElement(Xy,{key:`modal_${g.id}`,isOpen:p,modalId:g.id,dataSources:g.data_sources,dataContext:ge.currentDataContext,globalStateUpdater:ge.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:ge.bindingEngine,debug:Pc,children:k}):k}))])))))};e?.sync?(et.log("재렌더링 시작 (sync mode - 즉시 렌더링)"),d()):(et.log("재렌더링 시작 (with startTransition)"),j.startTransition(()=>{d()})),et.log("템플릿 데이터 업데이트 완료")}catch(t){throw et.error("템플릿 데이터 업데이트 실패",t),t}}function Bc(){try{et.log("템플릿 정리 시작"),ge.reactRoot&&(et.log("React Root 언마운트"),ge.reactRoot.unmount(),ge.reactRoot=null),ge.templateId=null,ge.locale="ko",ge.isInitialized=!1,ge.containerId=null,ge.currentLayoutJson=null,ge.currentDataContext={},ge.translationContext={templateId:"",locale:"ko"},ge.registry=null,ge.bindingEngine=null,ge.translationEngine=null,ge.actionDispatcher=null,ge.templateMetadata=null,et.log("템플릿 정리 완료")}catch(r){throw et.error("템플릿 정리 실패",r),r}}function Is(){return Object.freeze({...ge})}function hx(){return ge.actionDispatcher}function fx(){if(typeof window>"u")return!1;const r=new URLSearchParams(window.location.search),e=r.get("mode"),t=r.get("template");return e==="edit"&&!!t}function mN(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("template")}async function yN(r){et.log("위지윅 편집기 렌더링 시작");try{const{WysiwygEditor:e}=await Promise.resolve().then(()=>n_),t=mN()||ge.templateId||"unknown",a=()=>{const o=new URLSearchParams(window.location.search);o.delete("mode"),o.delete("template");const d=`${window.location.pathname}${o.toString()?"?"+o.toString():""}`;window.location.href=d},i=o=>{et.log("레이아웃 저장 완료:",o)};et.log("WysiwygEditor 렌더링",{templateId:t,layoutName:r.layoutJson?.layout_name}),ge.reactRoot.render(Ke.createElement(Rc,{translationEngine:ge.translationEngine,translationContext:ge.translationContext},Ke.createElement(e,{layoutData:r.layoutJson,templateId:t,onClose:a,onSaveComplete:i,initialEditMode:"visual",readOnly:!1}))),et.log("위지윅 편집기 렌더링 완료")}catch(e){throw et.error("위지윅 편집기 로드 실패:",e),ge.reactRoot.render(Ke.createElement("div",{className:"flex items-center justify-center h-screen bg-gray-100 dark:bg-gray-900"},Ke.createElement("div",{className:"text-center p-8 bg-white dark:bg-gray-800 rounded-lg shadow-lg"},Ke.createElement("h1",{className:"text-xl font-bold text-red-600 dark:text-red-400 mb-4"},"위지윅 편집기 로드 실패"),Ke.createElement("p",{className:"text-gray-600 dark:text-gray-400 mb-4"},"편집기를 불러오는 중 오류가 발생했습니다."),Ke.createElement("button",{className:"px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700",onClick:()=>window.location.reload()},"새로고침")))),e}}const zo={initTemplateEngine:$o,renderTemplate:Io,updateTemplateData:fi,destroyTemplate:Bc,getState:Is};typeof window<"u"&&(window.G7Core||(window.G7Core={}),window.G7Core.TemplateEngine=zo,uN({getState:()=>({translationEngine:ge.translationEngine,translationContext:ge.translationContext,bindingEngine:ge.bindingEngine,actionDispatcher:ge.actionDispatcher,templateMetadata:ge.templateMetadata}),transitionManager:Pa,responsiveManager:ei,webSocketManager:Mc}),et.log("전역 객체 window.G7Core.TemplateEngine에 노출됨"));const qa=Object.freeze(Object.defineProperty({__proto__:null,DataSourceManager:is,LayoutLoader:Rg,TemplateApp:Oo,TemplateEngine:zo,default:zo,destroyTemplate:Bc,getActionDispatcher:hx,getState:Is,initTemplateApp:Pg,initTemplateEngine:$o,renderTemplate:Io,updateTemplateData:fi},Symbol.toStringTag,{value:"Module"})),px=r=>{let e;const t=new Set,a=(f,p)=>{const y=typeof f=="function"?f(e):f;if(!Object.is(y,e)){const x=e;e=p??(typeof y!="object"||y===null)?y:Object.assign({},e,y),t.forEach(S=>S(e,x))}},i=()=>e,g={setState:a,getState:i,getInitialState:()=>h,subscribe:f=>(t.add(f),()=>t.delete(f))},h=e=r(a,i,g);return g},xN=(r=>r?px(r):px),bN=r=>r;function vN(r,e=bN){const t=Ke.useSyncExternalStore(r.subscribe,Ke.useCallback(()=>e(r.getState()),[r,e]),Ke.useCallback(()=>e(r.getInitialState()),[r,e]));return Ke.useDebugValue(t),t}const mx=r=>{const e=xN(r),t=a=>vN(e,a);return Object.assign(t,e),t},wN=(r=>r?mx(r):mx);var yx=Symbol.for("immer-nothing"),xx=Symbol.for("immer-draftable"),An=Symbol.for("immer-state");function Na(r,...e){throw new Error(`[Immer] minified error nr: ${r}. Full error at: https://bit.ly/3cXEKWf`)}var Wn=Object,pi=Wn.getPrototypeOf,Uc="constructor",qc="prototype",Gg="configurable",Gc="enumerable",Fc="writable",Ho="value",zs=r=>!!r&&!!r[An];function os(r){return r?vx(r)||Wc(r)||!!r[xx]||!!r[Uc]?.[xx]||Yc(r)||Jc(r):!1}var SN=Wn[qc][Uc].toString(),bx=new WeakMap;function vx(r){if(!r||!Vg(r))return!1;const e=pi(r);if(e===null||e===Wn[qc])return!0;const t=Wn.hasOwnProperty.call(e,Uc)&&e[Uc];if(t===Object)return!0;if(!mi(t))return!1;let a=bx.get(t);return a===void 0&&(a=Function.toString.call(t),bx.set(t,a)),a===SN}function Vc(r,e,t=!0){Po(r)===0?(t?Reflect.ownKeys(r):Wn.keys(r)).forEach(i=>{e(i,r[i],r)}):r.forEach((a,i)=>e(i,a,r))}function Po(r){const e=r[An];return e?e.type_:Wc(r)?1:Yc(r)?2:Jc(r)?3:0}var wx=(r,e,t=Po(r))=>t===2?r.has(e):Wn[qc].hasOwnProperty.call(r,e),Fg=(r,e,t=Po(r))=>t===2?r.get(e):r[e],Kc=(r,e,t,a=Po(r))=>{a===2?r.set(e,t):a===3?r.add(t):r[e]=t};function CN(r,e){return r===e?r!==0||1/r===1/e:r!==r&&e!==e}var Wc=Array.isArray,Yc=r=>r instanceof Map,Jc=r=>r instanceof Set,Vg=r=>typeof r=="object",mi=r=>typeof r=="function",Kg=r=>typeof r=="boolean";function jN(r){const e=+r;return Number.isInteger(e)&&String(e)===r}var ls=r=>r.copy_||r.base_,Wg=r=>r.modified_?r.copy_:r.base_;function Yg(r,e){if(Yc(r))return new Map(r);if(Jc(r))return new Set(r);if(Wc(r))return Array[qc].slice.call(r);const t=vx(r);if(e===!0||e==="class_only"&&!t){const a=Wn.getOwnPropertyDescriptors(r);delete a[An];let i=Reflect.ownKeys(a);for(let o=0;o1&&Wn.defineProperties(r,{set:Xc,add:Xc,clear:Xc,delete:Xc}),Wn.freeze(r),e&&Vc(r,(t,a)=>{Jg(a,!0)},!1)),r}function kN(){Na(2)}var Xc={[Ho]:kN};function Qc(r){return r===null||!Vg(r)?!0:Wn.isFrozen(r)}var Zc="MapSet",Xg="Patches",Sx="ArrayMethods",Cx={};function Cr(r){const e=Cx[r];return e||Na(0,r),e}var jx=r=>!!Cx[r],Bo,kx=()=>Bo,NN=(r,e)=>({drafts_:[],parent_:r,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:jx(Zc)?Cr(Zc):void 0,arrayMethodsPlugin_:jx(Sx)?Cr(Sx):void 0});function Nx(r,e){e&&(r.patchPlugin_=Cr(Xg),r.patches_=[],r.inversePatches_=[],r.patchListener_=e)}function Qg(r){Zg(r),r.drafts_.forEach(EN),r.drafts_=null}function Zg(r){r===Bo&&(Bo=r.parent_)}var Ex=r=>Bo=NN(Bo,r);function EN(r){const e=r[An];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function _x(r,e){e.unfinalizedDrafts_=e.drafts_.length;const t=e.drafts_[0];if(r!==void 0&&r!==t){t[An].modified_&&(Qg(e),Na(4)),os(r)&&(r=Ax(e,r));const{patchPlugin_:i}=e;i&&i.generateReplacementPatches_(t[An].base_,r,e)}else r=Ax(e,t);return _N(e,r,!0),Qg(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),r!==yx?r:void 0}function Ax(r,e){if(Qc(e))return e;const t=e[An];if(!t)return td(e,r.handledSet_,r);if(!ed(t,r))return e;if(!t.modified_)return t.base_;if(!t.finalized_){const{callbacks_:a}=t;if(a)for(;a.length>0;)a.pop()(r);Rx(t,r)}return t.copy_}function _N(r,e,t=!1){!r.parent_&&r.immer_.autoFreeze_&&r.canAutoFreeze_&&Jg(e,t)}function Tx(r){r.finalized_=!0,r.scope_.unfinalizedDrafts_--}var ed=(r,e)=>r.scope_===e,AN=[];function Dx(r,e,t,a){const i=ls(r),o=r.type_;if(a!==void 0&&Fg(i,a,o)===e){Kc(i,a,t,o);return}if(!r.draftLocations_){const g=r.draftLocations_=new Map;Vc(i,(h,f)=>{if(zs(f)){const p=g.get(f)||[];p.push(h),g.set(f,p)}})}const d=r.draftLocations_.get(e)??AN;for(const g of d)Kc(i,g,t,o)}function TN(r,e,t){r.callbacks_.push(function(i){const o=e;if(!o||!ed(o,i))return;i.mapSetPlugin_?.fixSetContents(o);const d=Wg(o);Dx(r,o.draft_??o,d,t),Rx(o,i)})}function Rx(r,e){if(r.modified_&&!r.finalized_&&(r.type_===3||r.type_===1&&r.allIndicesReassigned_||(r.assigned_?.size??0)>0)){const{patchPlugin_:a}=e;if(a){const i=a.getPath(r);i&&a.generatePatches_(r,i,e)}Tx(r)}}function DN(r,e,t){const{scope_:a}=r;if(zs(t)){const i=t[An];ed(i,a)&&i.callbacks_.push(function(){ad(r);const d=Wg(i);Dx(r,t,d,e)})}else os(t)&&r.callbacks_.push(function(){const o=ls(r);r.type_===3?o.has(t)&&td(t,a.handledSet_,a):Fg(o,e,r.type_)===t&&a.drafts_.length>1&&(r.assigned_.get(e)??!1)===!0&&r.copy_&&td(Fg(r.copy_,e,r.type_),a.handledSet_,a)})}function td(r,e,t){return!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1||zs(r)||e.has(r)||!os(r)||Qc(r)||(e.add(r),Vc(r,(a,i)=>{if(zs(i)){const o=i[An];if(ed(o,t)){const d=Wg(o);Kc(r,a,d,r.type_),Tx(o)}}else os(i)&&td(i,e,t)})),r}function RN(r,e){const t=Wc(r),a={type_:t?1:0,scope_:e?e.scope_:kx(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:e,base_:r,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let i=a,o=nd;t&&(i=[a],o=Uo);const{revoke:d,proxy:g}=Proxy.revocable(i,o);return a.draft_=g,a.revoke_=d,[g,a]}var nd={get(r,e){if(e===An)return r;let t=r.scope_.arrayMethodsPlugin_;const a=r.type_===1&&typeof e=="string";if(a&&t?.isArrayOperationMethod(e))return t.createMethodInterceptor(r,e);const i=ls(r);if(!wx(i,e,r.type_))return ON(r,i,e);const o=i[e];if(r.finalized_||!os(o)||a&&r.operationMethod&&t?.isMutatingArrayMethod(r.operationMethod)&&jN(e))return o;if(o===eh(r.base_,e)){ad(r);const d=r.type_===1?+e:e,g=nh(r.scope_,o,r,d);return r.copy_[d]=g}return o},has(r,e){return e in ls(r)},ownKeys(r){return Reflect.ownKeys(ls(r))},set(r,e,t){const a=Ox(ls(r),e);if(a?.set)return a.set.call(r.draft_,t),!0;if(!r.modified_){const i=eh(ls(r),e),o=i?.[An];if(o&&o.base_===t)return r.copy_[e]=t,r.assigned_.set(e,!1),!0;if(CN(t,i)&&(t!==void 0||wx(r.base_,e,r.type_)))return!0;ad(r),th(r)}return r.copy_[e]===t&&(t!==void 0||e in r.copy_)||Number.isNaN(t)&&Number.isNaN(r.copy_[e])||(r.copy_[e]=t,r.assigned_.set(e,!0),DN(r,e,t)),!0},deleteProperty(r,e){return ad(r),eh(r.base_,e)!==void 0||e in r.base_?(r.assigned_.set(e,!1),th(r)):r.assigned_.delete(e),r.copy_&&delete r.copy_[e],!0},getOwnPropertyDescriptor(r,e){const t=ls(r),a=Reflect.getOwnPropertyDescriptor(t,e);return a&&{[Fc]:!0,[Gg]:r.type_!==1||e!=="length",[Gc]:a[Gc],[Ho]:t[e]}},defineProperty(){Na(11)},getPrototypeOf(r){return pi(r.base_)},setPrototypeOf(){Na(12)}},Uo={};for(let r in nd){let e=nd[r];Uo[r]=function(){const t=arguments;return t[0]=t[0][0],e.apply(this,t)}}Uo.deleteProperty=function(r,e){return Uo.set.call(this,r,e,void 0)},Uo.set=function(r,e,t){return nd.set.call(this,r[0],e,t,r[0])};function eh(r,e){const t=r[An];return(t?ls(t):r)[e]}function ON(r,e,t){const a=Ox(e,t);return a?Ho in a?a[Ho]:a.get?.call(r.draft_):void 0}function Ox(r,e){if(!(e in r))return;let t=pi(r);for(;t;){const a=Object.getOwnPropertyDescriptor(t,e);if(a)return a;t=pi(t)}}function th(r){r.modified_||(r.modified_=!0,r.parent_&&th(r.parent_))}function ad(r){r.copy_||(r.assigned_=new Map,r.copy_=Yg(r.base_,r.scope_.immer_.useStrictShallowCopy_))}var LN=class{constructor(r){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,a)=>{if(mi(e)&&!mi(t)){const o=t;t=e;const d=this;return function(h=o,...f){return d.produce(h,p=>t.call(this,p,...f))}}mi(t)||Na(6),a!==void 0&&!mi(a)&&Na(7);let i;if(os(e)){const o=Ex(this),d=nh(o,e,void 0);let g=!0;try{i=t(d),g=!1}finally{g?Qg(o):Zg(o)}return Nx(o,a),_x(i,o)}else if(!e||!Vg(e)){if(i=t(e),i===void 0&&(i=e),i===yx&&(i=void 0),this.autoFreeze_&&Jg(i,!0),a){const o=[],d=[];Cr(Xg).generateReplacementPatches_(e,i,{patches_:o,inversePatches_:d}),a(o,d)}return i}else Na(1,e)},this.produceWithPatches=(e,t)=>{if(mi(e))return(d,...g)=>this.produceWithPatches(d,h=>e(h,...g));let a,i;return[this.produce(e,t,(d,g)=>{a=d,i=g}),a,i]},Kg(r?.autoFreeze)&&this.setAutoFreeze(r.autoFreeze),Kg(r?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(r.useStrictShallowCopy),Kg(r?.useStrictIteration)&&this.setUseStrictIteration(r.useStrictIteration)}createDraft(r){os(r)||Na(8),zs(r)&&(r=MN(r));const e=Ex(this),t=nh(e,r,void 0);return t[An].isManual_=!0,Zg(e),t}finishDraft(r,e){const t=r&&r[An];(!t||!t.isManual_)&&Na(9);const{scope_:a}=t;return Nx(a,e),_x(void 0,a)}setAutoFreeze(r){this.autoFreeze_=r}setUseStrictShallowCopy(r){this.useStrictShallowCopy_=r}setUseStrictIteration(r){this.useStrictIteration_=r}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(r,e){let t;for(t=e.length-1;t>=0;t--){const i=e[t];if(i.path.length===0&&i.op==="replace"){r=i.value;break}}t>-1&&(e=e.slice(t+1));const a=Cr(Xg).applyPatches_;return zs(r)?a(r,e):this.produce(r,i=>a(i,e))}};function nh(r,e,t,a){const[i,o]=Yc(e)?Cr(Zc).proxyMap_(e,t):Jc(e)?Cr(Zc).proxySet_(e,t):RN(e,t);return(t?.scope_??kx()).drafts_.push(i),o.callbacks_=t?.callbacks_??[],o.key_=a,t&&a!==void 0?TN(t,o,a):o.callbacks_.push(function(h){h.mapSetPlugin_?.fixSetContents(o);const{patchPlugin_:f}=h;o.modified_&&f&&f.generatePatches_(o,[],h)}),i}function MN(r){return zs(r)||Na(10,r),Lx(r)}function Lx(r){if(!os(r)||Qc(r))return r;const e=r[An];let t,a=!0;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,t=Yg(r,e.scope_.immer_.useStrictShallowCopy_),a=e.scope_.immer_.shouldUseStrictIteration()}else t=Yg(r,!0);return Vc(t,(i,o)=>{Kc(t,i,Lx(o))},a),e&&(e.finalized_=!1),t}var $N=new LN,IN=$N.produce;const zN=r=>(e,t,a)=>(a.setState=(i,o,...d)=>{const g=typeof i=="function"?IN(i):i;return e(g,o,...d)},r(a.setState,t,a)),Mx={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_NAME:"그누보드7",VITE_REVERB_APP_KEY:"",VITE_REVERB_HOST:"localhost",VITE_REVERB_PORT:"8080",VITE_REVERB_SCHEME:"https"},qo=new Map,sd=r=>{const e=qo.get(r);return e?Object.fromEntries(Object.entries(e.stores).map(([t,a])=>[t,a.getState()])):{}},HN=(r,e,t)=>{if(r===void 0)return{type:"untracked",connection:e.connect(t)};const a=qo.get(t.name);if(a)return{type:"tracked",store:r,...a};const i={connection:e.connect(t),stores:{}};return qo.set(t.name,i),{type:"tracked",store:r,...i}},PN=(r,e)=>{if(e===void 0)return;const t=qo.get(r);t&&(delete t.stores[e],Object.keys(t.stores).length===0&&qo.delete(r))},BN=r=>{var e,t;if(!r)return;const a=r.split(` +`),i=a.findIndex(d=>d.includes("api.setState"));if(i<0)return;const o=((e=a[i+1])==null?void 0:e.trim())||"";return(t=/.+ (.+) .+/.exec(o))==null?void 0:t[1]},UN=(r,e={})=>(t,a,i)=>{const{enabled:o,anonymousActionType:d,store:g,...h}=e;let f;try{f=(o??(Mx?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!f)return r(t,a,i);const{connection:p,...y}=HN(g,f,h);let x=!0;i.setState=((w,k,A)=>{const O=t(w,k);if(!x)return O;const N=A===void 0?{type:d||BN(new Error().stack)||"anonymous"}:typeof A=="string"?{type:A}:A;return g===void 0?(p?.send(N,a()),O):(p?.send({...N,type:`${g}/${N.type}`},{...sd(h.name),[g]:i.getState()}),O)}),i.devtools={cleanup:()=>{p&&typeof p.unsubscribe=="function"&&p.unsubscribe(),PN(h.name,g)}};const S=(...w)=>{const k=x;x=!1,t(...w),x=k},v=r(i.setState,a,i);if(y.type==="untracked"?p?.init(v):(y.stores[y.store]=i,p?.init(Object.fromEntries(Object.entries(y.stores).map(([w,k])=>[w,w===y.store?v:k.getState()])))),i.dispatchFromDevtools&&typeof i.dispatch=="function"){let w=!1;const k=i.dispatch;i.dispatch=(...A)=>{(Mx?"production":void 0)!=="production"&&A[0].type==="__setState"&&!w&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),w=!0),k(...A)}}return p.subscribe(w=>{var k;switch(w.type){case"ACTION":if(typeof w.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return ah(w.payload,A=>{if(A.type==="__setState"){if(g===void 0){S(A.state);return}Object.keys(A.state).length!==1&&console.error(` [zustand devtools middleware] Unsupported __setState action format. When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(), and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } } - `);const O=A.state[g];if(O==null)return;JSON.stringify(i.getState())!==JSON.stringify(O)&&S(O);return}i.dispatchFromDevtools&&typeof i.dispatch=="function"&&i.dispatch(A)});case"DISPATCH":switch(w.payload.type){case"RESET":return S(v),g===void 0?p?.init(i.getState()):p?.init(sd(h.name));case"COMMIT":if(g===void 0){p?.init(i.getState());return}return p?.init(sd(h.name));case"ROLLBACK":return ah(w.state,A=>{if(g===void 0){S(A),p?.init(i.getState());return}S(A[g]),p?.init(sd(h.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return ah(w.state,A=>{if(g===void 0){S(A);return}JSON.stringify(i.getState())!==JSON.stringify(A[g])&&S(A[g])});case"IMPORT_STATE":{const{nextLiftedState:A}=w.payload,O=(k=A.computedStates.slice(-1)[0])==null?void 0:k.state;if(!O)return;S(g===void 0?O:O[g]),p?.send(null,A);return}case"PAUSE_RECORDING":return x=!x}return}}),v},ah=(r,e)=>{let t;try{t=JSON.parse(r)}catch(a){console.error("[zustand devtools middleware] Could not parse the received json",a)}t!==void 0&&e(t)},UN={maxHistorySize:50};function qo(r="component"){const e=Date.now().toString(36),t=Math.random().toString(36).substring(2,8);return`${r.toLowerCase().replace(/[^a-z0-9]/g,"_")}_${e}_${t}`}function sh(r,e){for(const t of r)if(typeof t!="string"&&(t.id===e||t.children&&sh(t.children,e)))return!0;return!1}function jr(r,e,t=null,a=[]){for(let i=0;i{if(typeof i=="string")return i;if(i.id===t)switch(a){case"before":return i;case"after":return i;case"inside":case"last-child":return{...i,children:[...i.children||[],e]};case"first-child":return{...i,children:[e,...i.children||[]]};default:return i}if(i.children){const o=[];for(let h=0;htypeof t=="string"?!0:t.id!==e).map(t=>typeof t=="string"?t:t.children?{...t,children:rd(t.children,e)}:t)}function id(r,e,t){return r.map(a=>{if(typeof a=="string")return a;if(a.id===e){const i=t.props?{...a.props,...t.props}:a.props;return{...a,...t,props:i}}return a.children?{...a,children:id(a.children,e,t)}:a})}function od(r,e,t,a){const i=jr(r,e);if(!i||e===t||qN(r,e,t))return r;const o=i.component,d=rd(r,e);return Go(d,o,t,a)}function qN(r,e,t){const a=jr(r,e);if(!a)return!1;const i=a.component;return i.children?sh(i.children,t):!1}function rh(r){const e={...r,id:qo(r.name),props:r.props?{...r.props}:void 0,data_binding:r.data_binding?{...r.data_binding}:void 0,style:r.style?{...r.style}:void 0,actions:r.actions?JSON.parse(JSON.stringify(r.actions)):void 0,iteration:r.iteration?{...r.iteration}:void 0,lifecycle:r.lifecycle?JSON.parse(JSON.stringify(r.lifecycle)):void 0,responsive:r.responsive?JSON.parse(JSON.stringify(r.responsive)):void 0};return r.children&&(e.children=r.children.map(t=>typeof t=="string"?t:rh(t))),e}function Mx(r,e){const t=jr(r,e);if(!t)return null;const a=rh(t.component);return{components:Go(r,a,e,"after"),newId:a.id}}function ih(r,e){if(!e)return null;const t=e.split(".");let a=r;for(let i=0;i=o.length)return o;const f=o[h];if(typeof f=="string")return o;if(d===a.length-1){const y={...f,...t,props:t.props?{...f.props,...t.props}:f.props};return[...o.slice(0,h),y,...o.slice(h+1)]}if(a[d+1]==="children"&&f.children){const y=i(f.children,d+2),x={...f,children:y};return[...o.slice(0,h),x,...o.slice(h+1)]}return o}return i(r,0)}const St=it("EditorState"),GN={layoutData:null,originalLayoutData:null,templateId:null,templateType:null,layoutName:null,selectedComponentId:null,hoveredComponentId:null,multiSelectedIds:[],editMode:"visual",previewDevice:"desktop",customWidth:1024,previewDarkMode:!1,loadingState:"idle",error:null,history:[],historyIndex:-1,maxHistorySize:UN.maxHistorySize,componentCategories:null,handlers:[],mockDataContext:{},versions:[],currentVersionId:null,inheritanceInfo:null,overlays:[],extensionPoints:[],activePropertyTab:"props",expandedTreeNodes:[],clipboard:null,draggingComponent:null,dropTargetId:null,dropPosition:null,hasChanges:!1,lastSavedAt:null};async function FN(r,e,t){const a=await fetch(`/api/admin/templates/${r}/layouts/${t}`);if(!a.ok)throw new Error(`Failed to fetch layout: ${a.status} ${a.statusText}`);return(await a.json()).data}async function VN(r,e,t,a){const i=await fetch(`/api/admin/templates/${r}/layouts/${e}`,{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({layout_data:t,description:a})});if(!i.ok)throw new Error(`Failed to save layout: ${i.status} ${i.statusText}`)}async function KN(r,e){const t=await fetch(`/api/admin/templates/${r}/layouts/${e}/versions`);if(!t.ok)throw new Error(`Failed to fetch versions: ${t.status} ${t.statusText}`);return(await t.json()).data.map(i=>({...i,createdAt:new Date(i.created_at)}))}async function WN(r,e,t){const a=await fetch(`/api/admin/templates/${r}/layouts/${e}/versions/${t}/restore`,{method:"POST",headers:{Accept:"application/json"}});if(!a.ok)throw new Error(`Failed to restore version: ${a.status} ${a.statusText}`);return(await a.json()).data}async function YN(r){const e=await fetch(`/api/templates/${r}/components.json`);if(!e.ok)throw new Error(`Failed to fetch component metadata: ${e.status}`);const t=await e.json();return{basic:t.components.basic||[],composite:t.components.composite||[],layout:t.components.layout||[],extension:[]}}const Se=vN()(BN(IN((r,e)=>({...GN,loadLayout:async(t,a,i)=>{r(o=>{o.loadingState="loading",o.error=null});try{const o=await FN(t,a,i),d=await YN(t);r(g=>{g.layoutData=o,g.originalLayoutData=JSON.parse(JSON.stringify(o)),g.templateId=t,g.templateType=a,g.layoutName=i,g.componentCategories=d,g.loadingState="loaded",g.hasChanges=!1,o.extends&&(g.inheritanceInfo={parentLayout:o.extends,inheritedSlots:[],overridableSlots:Object.keys(o.slots||{}),depth:1}),g.history=[],g.historyIndex=-1}),St.log("Layout loaded:",i)}catch(o){const d=o instanceof Error?o.message:"Unknown error";throw r(g=>{g.loadingState="error",g.error=d}),St.error("Failed to load layout:",d),o}},saveLayout:async t=>{const{templateId:a,layoutName:i,layoutData:o}=e();if(!a||!i||!o)throw new Error("No layout loaded");r(d=>{d.loadingState="saving"});try{await VN(a,i,o,t),r(d=>{d.originalLayoutData=JSON.parse(JSON.stringify(o)),d.hasChanges=!1,d.lastSavedAt=new Date,d.loadingState="loaded"}),St.log("Layout saved:",i)}catch(d){const g=d instanceof Error?d.message:"Unknown error";throw r(h=>{h.loadingState="error",h.error=g}),St.error("Failed to save layout:",g),d}},publishLayout:async()=>{await e().saveLayout("Published");try{await fetch("/api/admin/cache/refresh",{method:"POST"}),St.log("Cache refreshed after publish")}catch(t){St.warn("Cache refresh failed:",t)}},resetLayout:()=>{const{originalLayoutData:t}=e();t&&r(a=>{a.layoutData=JSON.parse(JSON.stringify(t)),a.hasChanges=!1,a.selectedComponentId=null,a.hoveredComponentId=null})},setLayoutData:(t,a)=>{St.log("Setting layout data directly:",{layoutName:t.layout_name,componentsCount:t.components?.length||0,templateId:a}),r(i=>{i.layoutData=t,i.originalLayoutData=JSON.parse(JSON.stringify(t)),i.templateId=a,i.loadingState="loaded",i.hasChanges=!1,t.extends&&(i.inheritanceInfo={parentLayout:t.extends,inheritedSlots:[],overridableSlots:Object.keys(t.slots||{}),depth:1}),i.history=[],i.historyIndex=-1})},updateLayoutMeta:t=>{const{layoutData:a}=e();a&&(St.log("Updating layout meta:",t),r(i=>{i.layoutData&&(t.permissions!==void 0&&(i.layoutData.permissions=t.permissions),t.version!==void 0&&(i.layoutData.version=t.version),t.layout_name!==void 0&&(i.layoutData.layout_name=t.layout_name),t.extends!==void 0&&(i.layoutData.extends=t.extends),i.hasChanges=!0)}))},selectComponent:t=>{r(a=>{let i=t;if(t?.startsWith("auto_path:")&&a.layoutData){const o=t.substring(10),d=Fo(a.layoutData.components,o);d&&(d.components!==a.layoutData.components&&(a.layoutData.components=d.components,St.log("Auto-assigned component ID:",d.id,"at path:",o)),i=d.id)}if(a.selectedComponentId=i,i&&a.layoutData){const o=jr(a.layoutData.components,i);o&&o.path.forEach(d=>{a.expandedTreeNodes.includes(d)||a.expandedTreeNodes.push(d)})}})},hoverComponent:t=>{r(a=>{a.hoveredComponentId=t})},setHoveredComponentId:t=>{r(a=>{a.hoveredComponentId=t})},addComponent:(t,a,i)=>{const{layoutData:o}=e();o&&(e().pushHistory("Add component"),r(d=>{if(!d.layoutData)return;const g={...t,id:qo(t.name)};d.layoutData.components=Go(d.layoutData.components,g,a,i),d.hasChanges=!0,d.selectedComponentId=g.id}))},deleteComponent:t=>{const{layoutData:a}=e();a&&(e().pushHistory("Delete component"),r(i=>{i.layoutData&&(i.layoutData.components=rd(i.layoutData.components,t),i.hasChanges=!0,i.selectedComponentId===t&&(i.selectedComponentId=null))}))},duplicateComponent:t=>{const{layoutData:a}=e();a&&(e().pushHistory("Duplicate component"),r(i=>{if(!i.layoutData)return;const o=Mx(i.layoutData.components,t);o&&(i.layoutData.components=o.components,i.hasChanges=!0,i.selectedComponentId=o.newId)}))},moveComponent:(t,a,i)=>{const{layoutData:o}=e();o&&(e().pushHistory("Move component"),r(d=>{d.layoutData&&(d.layoutData.components=od(d.layoutData.components,t,a,i),d.hasChanges=!0)}))},updateComponentProps:(t,a)=>{const{layoutData:i}=e();i&&(e().pushHistory("Update props"),r(o=>{o.layoutData&&(o.layoutData.components=id(o.layoutData.components,t,{props:{...a}}),o.hasChanges=!0)}))},updateComponent:(t,a)=>{const{layoutData:i}=e();i&&(e().pushHistory("Update component"),r(o=>{o.layoutData&&(o.layoutData.components=id(o.layoutData.components,t,a),o.hasChanges=!0)}))},ensureComponentId:t=>{const{layoutData:a}=e();if(!a)return null;const i=Fo(a.components,t);return i?(i.components!==a.components&&(e().pushHistory("Auto-assign component ID"),r(o=>{o.layoutData&&(o.layoutData.components=i.components,o.hasChanges=!0)}),St.log("Component ID auto-assigned:",i.id,"at path:",t)),i.id):(St.warn("ensureComponentId failed: component not found at path",t),null)},ensureComponentIdAndMove:(t,a,i)=>{const{layoutData:o}=e();if(!o)return!1;St.log("ensureComponentIdAndMove called:",{path:t,targetId:a,position:i});const d=Fo(o.components,t);if(!d)return St.warn("ensureComponentIdAndMove failed: component not found at path",t),!1;const g=d.id;if(St.log("ensureComponentIdAndMove: sourceId =",g),g===a)return St.log("ensureComponentIdAndMove: source and target are the same, skipping"),!1;const h=jr(d.components,a);return St.log("ensureComponentIdAndMove: targetResult =",h?"found":"NOT FOUND"),h?(e().pushHistory("Move component"),r(f=>{if(!f.layoutData)return;const p=od(d.components,g,a,i);St.log("ensureComponentIdAndMove: move result components count =",p.length),f.layoutData.components=p,f.hasChanges=!0}),St.log("ensureComponentIdAndMove success:",g,"->",a,i),!0):(St.warn("ensureComponentIdAndMove: target not found in components",a),!1)},moveComponentByPaths:(t,a,i)=>{const{layoutData:o}=e();if(!o)return!1;if(St.log("moveComponentByPaths called:",{sourcePath:t,targetPath:a,position:i}),t===a)return St.log("moveComponentByPaths: source and target paths are the same, skipping"),!1;const d=o.components,g=Fo(d,t);if(!g)return St.warn("moveComponentByPaths: source not found at path",t),!1;const h=g.id,f=Fo(g.components,a);if(!f)return St.warn("moveComponentByPaths: target not found at path",a),!1;const p=f.id;return St.log("moveComponentByPaths: sourceId =",h,", targetId =",p),h===p?(St.log("moveComponentByPaths: source and target are the same component, skipping"),!1):(e().pushHistory("Move component"),r(y=>{if(!y.layoutData)return;const x=od(f.components,h,p,i);St.log("moveComponentByPaths: move result components count =",x.length),y.layoutData.components=x,y.hasChanges=!0}),St.log("moveComponentByPaths success:",h,"->",p,i),!0)},updateComponentByPath:(t,a)=>{const{layoutData:i}=e();i&&(e().pushHistory("Update component by path"),r(o=>{o.layoutData&&(o.layoutData.components=$x(o.layoutData.components,t,a),o.hasChanges=!0)}))},undo:()=>{r(t=>{if(t.historyIndex<0||t.history.length===0)return;if(t.historyIndex===t.history.length-1&&t.layoutData){const i={layoutData:JSON.parse(JSON.stringify(t.layoutData)),description:"Current state",timestamp:Date.now()};t.history.push(i)}const a=t.history[t.historyIndex];a&&(t.layoutData=JSON.parse(JSON.stringify(a.layoutData)),t.historyIndex-=1,t.hasChanges=!0)})},redo:()=>{r(t=>{if(t.historyIndex>=t.history.length-1)return;t.historyIndex+=1;const a=t.history[t.historyIndex+1];a&&(t.layoutData=JSON.parse(JSON.stringify(a.layoutData)),t.hasChanges=!0)})},pushHistory:t=>{r(a=>{if(!a.layoutData)return;a.history=a.history.slice(0,a.historyIndex+1);const i={layoutData:JSON.parse(JSON.stringify(a.layoutData)),description:t,timestamp:Date.now()};for(a.history.push(i),a.historyIndex=a.history.length-1;a.history.length>a.maxHistorySize;)a.history.shift(),a.historyIndex-=1})},setEditMode:t=>{r(a=>{a.editMode=t})},setPreviewDevice:(t,a)=>{r(i=>{i.previewDevice=t,a!==void 0&&(i.customWidth=a)})},togglePreviewDarkMode:()=>{r(t=>{t.previewDarkMode=!t.previewDarkMode})},loadVersions:async()=>{const{templateId:t,layoutName:a}=e();if(!(!t||!a))try{const i=await KN(t,a);r(o=>{o.versions=i})}catch(i){St.error("Failed to load versions:",i)}},restoreVersion:async t=>{const{templateId:a,layoutName:i}=e();if(!(!a||!i))try{const o=await WN(a,i,t);r(d=>{d.layoutData=o,d.hasChanges=!0}),St.log("Version restored:",t)}catch(o){throw St.error("Failed to restore version:",o),o}},compareVersions:async(t,a)=>[],addDataSource:t=>{e().pushHistory("Add data source"),r(a=>{a.layoutData&&(a.layoutData.data_sources||(a.layoutData.data_sources=[]),a.layoutData.data_sources.push(t),a.hasChanges=!0)})},updateDataSource:(t,a)=>{e().pushHistory("Update data source"),r(i=>{if(!i.layoutData?.data_sources)return;const o=i.layoutData.data_sources.findIndex(d=>d.id===t);o!==-1&&(i.layoutData.data_sources[o]={...i.layoutData.data_sources[o],...a},i.hasChanges=!0)})},deleteDataSource:t=>{e().pushHistory("Delete data source"),r(a=>{a.layoutData?.data_sources&&(a.layoutData.data_sources=a.layoutData.data_sources.filter(i=>i.id!==t),a.hasChanges=!0)})},testDataSource:async t=>({success:!0,data:{}}),setMockData:(t,a)=>{r(i=>{i.mockDataContext[t]=a})},addModal:t=>{e().pushHistory("Add modal"),r(a=>{a.layoutData&&(a.layoutData.modals||(a.layoutData.modals=[]),a.layoutData.modals.push(t),a.hasChanges=!0)})},updateModal:(t,a)=>{e().pushHistory("Update modal"),r(i=>{if(!i.layoutData?.modals)return;const o=i.layoutData.modals.findIndex(d=>d.id===t);o!==-1&&(i.layoutData.modals[o]={...i.layoutData.modals[o],...a},i.hasChanges=!0)})},deleteModal:t=>{e().pushHistory("Delete modal"),r(a=>{a.layoutData?.modals&&(a.layoutData.modals=a.layoutData.modals.filter(i=>i.id!==t),a.hasChanges=!0)})},setActivePropertyTab:t=>{r(a=>{a.activePropertyTab=t})},toggleTreeNode:t=>{r(a=>{const i=a.expandedTreeNodes.indexOf(t);i===-1?a.expandedTreeNodes.push(t):a.expandedTreeNodes.splice(i,1)})},copyToClipboard:t=>{r(a=>{a.clipboard=JSON.parse(JSON.stringify(t))})},pasteFromClipboard:(t,a)=>{const{clipboard:i}=e();if(!i)return;const o={...JSON.parse(JSON.stringify(i)),id:qo(i.name)};e().addComponent(o,t,a)},startDrag:t=>{r(a=>{a.draggingComponent=t})},dragOver:(t,a)=>{r(i=>{i.dropTargetId=t,i.dropPosition=a})},endDrag:()=>{r(t=>{t.draggingComponent=null,t.dropTargetId=null,t.dropPosition=null})},saveExtensionOverride:async(t,a)=>{St.log("Save extension override:",t)},restoreExtensionOverride:async t=>{St.log("Restore extension override:",t)}})),{name:"WysiwygEditorState"})),ld=r=>r.historyIndex>=0,cd=r=>r.historyIndexne.loadLayout),f=Se(ne=>ne.setLayoutData),p=Se(ne=>ne.setEditMode),y=Se(ne=>ne.layoutData),x=Se(ne=>ne.selectedComponentId),S=Se(ne=>ne.loadingState),v=Se(ne=>ne.error),w=Se(ne=>ne.hasChanges),k=Se(ne=>ne.undo),A=Se(ne=>ne.redo),O=Se(ne=>ne.saveLayout),N=Se(ne=>ne.deleteComponent),D=Se(ne=>ne.duplicateComponent),$=Se(ne=>ne.copyToClipboard),M=Se(ne=>ne.pasteFromClipboard),z=Se(ne=>ne.clipboard),K=Se(ld),pe=Se(cd),we=j.useMemo(()=>({...XN,...e}),[e]),J=S==="loaded",be=S==="loading",le=S==="saving",de=j.useMemo(()=>{if(!y||!x)return null;const ne=(X,ae)=>{for(const R of X)if(typeof R!="string"){if(R.id===ae)return R;if(R.children){const U=ne(R.children,ae);if(U)return U}}return null};return ne(y.components,x)},[y,x]),je=j.useCallback(async(ne,X,ae)=>{oa.log("Initializing editor:",{tid:ne,ttype:X,lname:ae}),await h(ne,X,ae)},[h]),W=j.useCallback(()=>{oa.log("Deactivating editor")},[]);j.useEffect(()=>{d&&!y&&(oa.log("Setting initial layout data from props",{layoutName:d.layout_name,componentsCount:d.components?.length||0}),f(d,a||"unknown"),p(g))},[d,y,a,g,f,p]),j.useEffect(()=>{t&&a&&i&&o&&!d&&je(a,i,o).catch(ne=>{oa.error("Auto-initialize failed:",ne)})},[t,a,i,o,je,d]),j.useEffect(()=>{if(!we.keyboardShortcuts||!J)return;const ne=X=>{const ae=X.target;if(ae.tagName==="INPUT"||ae.tagName==="TEXTAREA"||ae.isContentEditable)return;const U=navigator.platform.toUpperCase().indexOf("MAC")>=0?X.metaKey:X.ctrlKey;if(U&&X.key==="z"&&!X.shiftKey){X.preventDefault(),K&&(k(),oa.log("Undo triggered"));return}if(U&&X.key==="z"&&X.shiftKey||U&&X.key==="y"){X.preventDefault(),pe&&(A(),oa.log("Redo triggered"));return}if(U&&X.key==="s"){X.preventDefault(),w&&O().catch(re=>{oa.error("Save failed:",re)});return}if((X.key==="Delete"||X.key==="Backspace")&&x){X.preventDefault(),N(x),oa.log("Delete triggered");return}if(U&&X.key==="d"&&x){X.preventDefault(),D(x),oa.log("Duplicate triggered");return}if(U&&X.key==="c"&&de){X.preventDefault(),$(de),oa.log("Copy triggered");return}if(U&&X.key==="v"&&z&&x){X.preventDefault(),M(x,"after"),oa.log("Paste triggered");return}if(X.key==="Escape"){const re=Se.getState().selectComponent;re(null);return}};return window.addEventListener("keydown",ne),()=>{window.removeEventListener("keydown",ne)}},[we.keyboardShortcuts,J,K,pe,w,x,de,z,k,A,O,N,D,$,M]),j.useEffect(()=>{if(!we.autoSave||!J||!w)return;const ne=setTimeout(()=>{O("Auto-save").catch(X=>{oa.error("Auto-save failed:",X)})},we.autoSaveInterval);return()=>{clearTimeout(ne)}},[we.autoSave,we.autoSaveInterval,J,w,O]),j.useEffect(()=>{if(!w)return;const ne=X=>{X.preventDefault(),X.returnValue=""};return window.addEventListener("beforeunload",ne),()=>{window.removeEventListener("beforeunload",ne)}},[w]);const ge=j.useMemo(()=>({isEditorActive:J,config:we,initialize:je,deactivate:W,selectedComponent:de,layoutData:y,canUndo:K,canRedo:pe,hasChanges:w,isLoading:be,isSaving:le,error:v}),[J,we,je,W,de,y,K,pe,w,be,le,v]);return l.jsx(JN.Provider,{value:ge,children:r})}const QN=500;function oh(r={}){const{debounceMs:e=QN}=r,t=Se(M=>M.history),a=Se(M=>M.historyIndex),i=Se(M=>M.undo),o=Se(M=>M.redo),d=Se(M=>M.pushHistory),g=Se(ld),h=Se(cd),f=j.useRef(null),p=j.useRef(null),y=j.useRef(null),x=j.useRef(!1),S=j.useCallback(()=>{f.current&&(clearTimeout(f.current),f.current=null),Se.setState({history:[],historyIndex:-1})},[]),v=j.useCallback(M=>{if(M<0||M>=t.length)return;const z=t[M];z&&Se.setState({layoutData:JSON.parse(JSON.stringify(z.layoutData)),historyIndex:M,hasChanges:!0})},[t]),w=j.useCallback(M=>{x.current||(f.current&&clearTimeout(f.current),p.current===M?f.current=setTimeout(()=>{d(M),f.current=null},e):(d(M),p.current=M))},[d,e]),k=j.useCallback(M=>{x.current||(x.current=!0,y.current=M,f.current&&(clearTimeout(f.current),f.current=null))},[]),A=j.useCallback(()=>{if(!x.current)return;const M=y.current||"Batch update";d(M),x.current=!1,y.current=null},[d]),O=j.useMemo(()=>a<0||a>=t.length?null:t[a],[t,a]),N=t.length,D=a+1,$=t.length-a-1;return{history:t,historyIndex:a,canUndo:g,canRedo:h,undo:i,redo:o,pushHistory:d,pushHistoryDebounced:w,startBatch:k,endBatch:A,isBatching:x.current,clearHistory:S,goToHistory:v,currentEntry:O,historySize:N,undoStackSize:D,redoStackSize:$}}const ZN=({value:r,onChange:e,disabled:t=!1,placeholder:a="권한을 선택하세요"})=>{const[i,o]=j.useState({}),[d,g]=j.useState(!0),[h,f]=j.useState(null),[p,y]=j.useState(new Set(["admin"])),[x,S]=j.useState("");j.useEffect(()=>{(async()=>{try{g(!0),f(null);const M=await fetch("/api/admin/permissions",{headers:{Authorization:`Bearer ${localStorage.getItem("auth_token")}`,Accept:"application/json"}});if(!M.ok)throw new Error(`HTTP ${M.status}`);const z=await M.json();o(z.data?.data?.permissions||{})}catch(M){console.error("권한 목록 조회 실패:",M),f("권한 목록을 불러올 수 없습니다")}finally{g(!1)}})()},[]);const v=j.useCallback($=>{t||(r.includes($)?e(r.filter(M=>M!==$)):e([...r,$]))},[r,e,t]),w=j.useCallback($=>{y(M=>{const z=new Set(M);return z.has($)?z.delete($):z.add($),z})},[]),k=j.useCallback(()=>{if(t)return;const $=[],M=z=>{z.forEach(K=>{$.push(K.identifier),K.children?.length&&M(K.children)})};Object.values(i).forEach(z=>{z.permissions&&M(z.permissions)}),e($)},[i,e,t]),A=j.useCallback(()=>{t||e([])},[e,t]),O=j.useCallback($=>{if(!x.trim())return $;const M=x.toLowerCase(),z=K=>{const pe=K.name.toLowerCase().includes(M),we=K.identifier.toLowerCase().includes(M),J=K.children?.map(z).filter(Boolean);return pe||we||J&&J.length>0?{...K,children:J}:null};return $.map(z).filter(Boolean)},[x]),N=($,M=0)=>{const z=r.includes($.identifier),K=$.children&&$.children.length>0;return l.jsxs("div",{children:[l.jsxs("label",{className:`flex items-center gap-2 py-1.5 px-2 rounded cursor-pointer transition-colors + `);const O=A.state[g];if(O==null)return;JSON.stringify(i.getState())!==JSON.stringify(O)&&S(O);return}i.dispatchFromDevtools&&typeof i.dispatch=="function"&&i.dispatch(A)});case"DISPATCH":switch(w.payload.type){case"RESET":return S(v),g===void 0?p?.init(i.getState()):p?.init(sd(h.name));case"COMMIT":if(g===void 0){p?.init(i.getState());return}return p?.init(sd(h.name));case"ROLLBACK":return ah(w.state,A=>{if(g===void 0){S(A),p?.init(i.getState());return}S(A[g]),p?.init(sd(h.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return ah(w.state,A=>{if(g===void 0){S(A);return}JSON.stringify(i.getState())!==JSON.stringify(A[g])&&S(A[g])});case"IMPORT_STATE":{const{nextLiftedState:A}=w.payload,O=(k=A.computedStates.slice(-1)[0])==null?void 0:k.state;if(!O)return;S(g===void 0?O:O[g]),p?.send(null,A);return}case"PAUSE_RECORDING":return x=!x}return}}),v},ah=(r,e)=>{let t;try{t=JSON.parse(r)}catch(a){console.error("[zustand devtools middleware] Could not parse the received json",a)}t!==void 0&&e(t)},qN={maxHistorySize:50};function Go(r="component"){const e=Date.now().toString(36),t=Math.random().toString(36).substring(2,8);return`${r.toLowerCase().replace(/[^a-z0-9]/g,"_")}_${e}_${t}`}function sh(r,e){for(const t of r)if(typeof t!="string"&&(t.id===e||t.children&&sh(t.children,e)))return!0;return!1}function jr(r,e,t=null,a=[]){for(let i=0;i{if(typeof i=="string")return i;if(i.id===t)switch(a){case"before":return i;case"after":return i;case"inside":case"last-child":return{...i,children:[...i.children||[],e]};case"first-child":return{...i,children:[e,...i.children||[]]};default:return i}if(i.children){const o=[];for(let h=0;htypeof t=="string"?!0:t.id!==e).map(t=>typeof t=="string"?t:t.children?{...t,children:rd(t.children,e)}:t)}function id(r,e,t){return r.map(a=>{if(typeof a=="string")return a;if(a.id===e){const i=t.props?{...a.props,...t.props}:a.props;return{...a,...t,props:i}}return a.children?{...a,children:id(a.children,e,t)}:a})}function od(r,e,t,a){const i=jr(r,e);if(!i||e===t||GN(r,e,t))return r;const o=i.component,d=rd(r,e);return Fo(d,o,t,a)}function GN(r,e,t){const a=jr(r,e);if(!a)return!1;const i=a.component;return i.children?sh(i.children,t):!1}function rh(r){const e={...r,id:Go(r.name),props:r.props?{...r.props}:void 0,data_binding:r.data_binding?{...r.data_binding}:void 0,style:r.style?{...r.style}:void 0,actions:r.actions?JSON.parse(JSON.stringify(r.actions)):void 0,iteration:r.iteration?{...r.iteration}:void 0,lifecycle:r.lifecycle?JSON.parse(JSON.stringify(r.lifecycle)):void 0,responsive:r.responsive?JSON.parse(JSON.stringify(r.responsive)):void 0};return r.children&&(e.children=r.children.map(t=>typeof t=="string"?t:rh(t))),e}function $x(r,e){const t=jr(r,e);if(!t)return null;const a=rh(t.component);return{components:Fo(r,a,e,"after"),newId:a.id}}function ih(r,e){if(!e)return null;const t=e.split(".");let a=r;for(let i=0;i=o.length)return o;const f=o[h];if(typeof f=="string")return o;if(d===a.length-1){const y={...f,...t,props:t.props?{...f.props,...t.props}:f.props};return[...o.slice(0,h),y,...o.slice(h+1)]}if(a[d+1]==="children"&&f.children){const y=i(f.children,d+2),x={...f,children:y};return[...o.slice(0,h),x,...o.slice(h+1)]}return o}return i(r,0)}const St=it("EditorState"),FN={layoutData:null,originalLayoutData:null,templateId:null,templateType:null,layoutName:null,selectedComponentId:null,hoveredComponentId:null,multiSelectedIds:[],editMode:"visual",previewDevice:"desktop",customWidth:1024,previewDarkMode:!1,loadingState:"idle",error:null,history:[],historyIndex:-1,maxHistorySize:qN.maxHistorySize,componentCategories:null,handlers:[],mockDataContext:{},versions:[],currentVersionId:null,inheritanceInfo:null,overlays:[],extensionPoints:[],activePropertyTab:"props",expandedTreeNodes:[],clipboard:null,draggingComponent:null,dropTargetId:null,dropPosition:null,hasChanges:!1,lastSavedAt:null};async function VN(r,e,t){const a=await fetch(`/api/admin/templates/${r}/layouts/${t}`);if(!a.ok)throw new Error(`Failed to fetch layout: ${a.status} ${a.statusText}`);return(await a.json()).data}async function KN(r,e,t,a){const i=await fetch(`/api/admin/templates/${r}/layouts/${e}`,{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({layout_data:t,description:a})});if(!i.ok)throw new Error(`Failed to save layout: ${i.status} ${i.statusText}`)}async function WN(r,e){const t=await fetch(`/api/admin/templates/${r}/layouts/${e}/versions`);if(!t.ok)throw new Error(`Failed to fetch versions: ${t.status} ${t.statusText}`);return(await t.json()).data.map(i=>({...i,createdAt:new Date(i.created_at)}))}async function YN(r,e,t){const a=await fetch(`/api/admin/templates/${r}/layouts/${e}/versions/${t}/restore`,{method:"POST",headers:{Accept:"application/json"}});if(!a.ok)throw new Error(`Failed to restore version: ${a.status} ${a.statusText}`);return(await a.json()).data}async function JN(r){const e=await fetch(`/api/templates/${r}/components.json`);if(!e.ok)throw new Error(`Failed to fetch component metadata: ${e.status}`);const t=await e.json();return{basic:t.components.basic||[],composite:t.components.composite||[],layout:t.components.layout||[],extension:[]}}const Se=wN()(UN(zN((r,e)=>({...FN,loadLayout:async(t,a,i)=>{r(o=>{o.loadingState="loading",o.error=null});try{const o=await VN(t,a,i),d=await JN(t);r(g=>{g.layoutData=o,g.originalLayoutData=JSON.parse(JSON.stringify(o)),g.templateId=t,g.templateType=a,g.layoutName=i,g.componentCategories=d,g.loadingState="loaded",g.hasChanges=!1,o.extends&&(g.inheritanceInfo={parentLayout:o.extends,inheritedSlots:[],overridableSlots:Object.keys(o.slots||{}),depth:1}),g.history=[],g.historyIndex=-1}),St.log("Layout loaded:",i)}catch(o){const d=o instanceof Error?o.message:"Unknown error";throw r(g=>{g.loadingState="error",g.error=d}),St.error("Failed to load layout:",d),o}},saveLayout:async t=>{const{templateId:a,layoutName:i,layoutData:o}=e();if(!a||!i||!o)throw new Error("No layout loaded");r(d=>{d.loadingState="saving"});try{await KN(a,i,o,t),r(d=>{d.originalLayoutData=JSON.parse(JSON.stringify(o)),d.hasChanges=!1,d.lastSavedAt=new Date,d.loadingState="loaded"}),St.log("Layout saved:",i)}catch(d){const g=d instanceof Error?d.message:"Unknown error";throw r(h=>{h.loadingState="error",h.error=g}),St.error("Failed to save layout:",g),d}},publishLayout:async()=>{await e().saveLayout("Published");try{await fetch("/api/admin/cache/refresh",{method:"POST"}),St.log("Cache refreshed after publish")}catch(t){St.warn("Cache refresh failed:",t)}},resetLayout:()=>{const{originalLayoutData:t}=e();t&&r(a=>{a.layoutData=JSON.parse(JSON.stringify(t)),a.hasChanges=!1,a.selectedComponentId=null,a.hoveredComponentId=null})},setLayoutData:(t,a)=>{St.log("Setting layout data directly:",{layoutName:t.layout_name,componentsCount:t.components?.length||0,templateId:a}),r(i=>{i.layoutData=t,i.originalLayoutData=JSON.parse(JSON.stringify(t)),i.templateId=a,i.loadingState="loaded",i.hasChanges=!1,t.extends&&(i.inheritanceInfo={parentLayout:t.extends,inheritedSlots:[],overridableSlots:Object.keys(t.slots||{}),depth:1}),i.history=[],i.historyIndex=-1})},updateLayoutMeta:t=>{const{layoutData:a}=e();a&&(St.log("Updating layout meta:",t),r(i=>{i.layoutData&&(t.permissions!==void 0&&(i.layoutData.permissions=t.permissions),t.version!==void 0&&(i.layoutData.version=t.version),t.layout_name!==void 0&&(i.layoutData.layout_name=t.layout_name),t.extends!==void 0&&(i.layoutData.extends=t.extends),i.hasChanges=!0)}))},selectComponent:t=>{r(a=>{let i=t;if(t?.startsWith("auto_path:")&&a.layoutData){const o=t.substring(10),d=Vo(a.layoutData.components,o);d&&(d.components!==a.layoutData.components&&(a.layoutData.components=d.components,St.log("Auto-assigned component ID:",d.id,"at path:",o)),i=d.id)}if(a.selectedComponentId=i,i&&a.layoutData){const o=jr(a.layoutData.components,i);o&&o.path.forEach(d=>{a.expandedTreeNodes.includes(d)||a.expandedTreeNodes.push(d)})}})},hoverComponent:t=>{r(a=>{a.hoveredComponentId=t})},setHoveredComponentId:t=>{r(a=>{a.hoveredComponentId=t})},addComponent:(t,a,i)=>{const{layoutData:o}=e();o&&(e().pushHistory("Add component"),r(d=>{if(!d.layoutData)return;const g={...t,id:Go(t.name)};d.layoutData.components=Fo(d.layoutData.components,g,a,i),d.hasChanges=!0,d.selectedComponentId=g.id}))},deleteComponent:t=>{const{layoutData:a}=e();a&&(e().pushHistory("Delete component"),r(i=>{i.layoutData&&(i.layoutData.components=rd(i.layoutData.components,t),i.hasChanges=!0,i.selectedComponentId===t&&(i.selectedComponentId=null))}))},duplicateComponent:t=>{const{layoutData:a}=e();a&&(e().pushHistory("Duplicate component"),r(i=>{if(!i.layoutData)return;const o=$x(i.layoutData.components,t);o&&(i.layoutData.components=o.components,i.hasChanges=!0,i.selectedComponentId=o.newId)}))},moveComponent:(t,a,i)=>{const{layoutData:o}=e();o&&(e().pushHistory("Move component"),r(d=>{d.layoutData&&(d.layoutData.components=od(d.layoutData.components,t,a,i),d.hasChanges=!0)}))},updateComponentProps:(t,a)=>{const{layoutData:i}=e();i&&(e().pushHistory("Update props"),r(o=>{o.layoutData&&(o.layoutData.components=id(o.layoutData.components,t,{props:{...a}}),o.hasChanges=!0)}))},updateComponent:(t,a)=>{const{layoutData:i}=e();i&&(e().pushHistory("Update component"),r(o=>{o.layoutData&&(o.layoutData.components=id(o.layoutData.components,t,a),o.hasChanges=!0)}))},ensureComponentId:t=>{const{layoutData:a}=e();if(!a)return null;const i=Vo(a.components,t);return i?(i.components!==a.components&&(e().pushHistory("Auto-assign component ID"),r(o=>{o.layoutData&&(o.layoutData.components=i.components,o.hasChanges=!0)}),St.log("Component ID auto-assigned:",i.id,"at path:",t)),i.id):(St.warn("ensureComponentId failed: component not found at path",t),null)},ensureComponentIdAndMove:(t,a,i)=>{const{layoutData:o}=e();if(!o)return!1;St.log("ensureComponentIdAndMove called:",{path:t,targetId:a,position:i});const d=Vo(o.components,t);if(!d)return St.warn("ensureComponentIdAndMove failed: component not found at path",t),!1;const g=d.id;if(St.log("ensureComponentIdAndMove: sourceId =",g),g===a)return St.log("ensureComponentIdAndMove: source and target are the same, skipping"),!1;const h=jr(d.components,a);return St.log("ensureComponentIdAndMove: targetResult =",h?"found":"NOT FOUND"),h?(e().pushHistory("Move component"),r(f=>{if(!f.layoutData)return;const p=od(d.components,g,a,i);St.log("ensureComponentIdAndMove: move result components count =",p.length),f.layoutData.components=p,f.hasChanges=!0}),St.log("ensureComponentIdAndMove success:",g,"->",a,i),!0):(St.warn("ensureComponentIdAndMove: target not found in components",a),!1)},moveComponentByPaths:(t,a,i)=>{const{layoutData:o}=e();if(!o)return!1;if(St.log("moveComponentByPaths called:",{sourcePath:t,targetPath:a,position:i}),t===a)return St.log("moveComponentByPaths: source and target paths are the same, skipping"),!1;const d=o.components,g=Vo(d,t);if(!g)return St.warn("moveComponentByPaths: source not found at path",t),!1;const h=g.id,f=Vo(g.components,a);if(!f)return St.warn("moveComponentByPaths: target not found at path",a),!1;const p=f.id;return St.log("moveComponentByPaths: sourceId =",h,", targetId =",p),h===p?(St.log("moveComponentByPaths: source and target are the same component, skipping"),!1):(e().pushHistory("Move component"),r(y=>{if(!y.layoutData)return;const x=od(f.components,h,p,i);St.log("moveComponentByPaths: move result components count =",x.length),y.layoutData.components=x,y.hasChanges=!0}),St.log("moveComponentByPaths success:",h,"->",p,i),!0)},updateComponentByPath:(t,a)=>{const{layoutData:i}=e();i&&(e().pushHistory("Update component by path"),r(o=>{o.layoutData&&(o.layoutData.components=Ix(o.layoutData.components,t,a),o.hasChanges=!0)}))},undo:()=>{r(t=>{if(t.historyIndex<0||t.history.length===0)return;if(t.historyIndex===t.history.length-1&&t.layoutData){const i={layoutData:JSON.parse(JSON.stringify(t.layoutData)),description:"Current state",timestamp:Date.now()};t.history.push(i)}const a=t.history[t.historyIndex];a&&(t.layoutData=JSON.parse(JSON.stringify(a.layoutData)),t.historyIndex-=1,t.hasChanges=!0)})},redo:()=>{r(t=>{if(t.historyIndex>=t.history.length-1)return;t.historyIndex+=1;const a=t.history[t.historyIndex+1];a&&(t.layoutData=JSON.parse(JSON.stringify(a.layoutData)),t.hasChanges=!0)})},pushHistory:t=>{r(a=>{if(!a.layoutData)return;a.history=a.history.slice(0,a.historyIndex+1);const i={layoutData:JSON.parse(JSON.stringify(a.layoutData)),description:t,timestamp:Date.now()};for(a.history.push(i),a.historyIndex=a.history.length-1;a.history.length>a.maxHistorySize;)a.history.shift(),a.historyIndex-=1})},setEditMode:t=>{r(a=>{a.editMode=t})},setPreviewDevice:(t,a)=>{r(i=>{i.previewDevice=t,a!==void 0&&(i.customWidth=a)})},togglePreviewDarkMode:()=>{r(t=>{t.previewDarkMode=!t.previewDarkMode})},loadVersions:async()=>{const{templateId:t,layoutName:a}=e();if(!(!t||!a))try{const i=await WN(t,a);r(o=>{o.versions=i})}catch(i){St.error("Failed to load versions:",i)}},restoreVersion:async t=>{const{templateId:a,layoutName:i}=e();if(!(!a||!i))try{const o=await YN(a,i,t);r(d=>{d.layoutData=o,d.hasChanges=!0}),St.log("Version restored:",t)}catch(o){throw St.error("Failed to restore version:",o),o}},compareVersions:async(t,a)=>[],addDataSource:t=>{e().pushHistory("Add data source"),r(a=>{a.layoutData&&(a.layoutData.data_sources||(a.layoutData.data_sources=[]),a.layoutData.data_sources.push(t),a.hasChanges=!0)})},updateDataSource:(t,a)=>{e().pushHistory("Update data source"),r(i=>{if(!i.layoutData?.data_sources)return;const o=i.layoutData.data_sources.findIndex(d=>d.id===t);o!==-1&&(i.layoutData.data_sources[o]={...i.layoutData.data_sources[o],...a},i.hasChanges=!0)})},deleteDataSource:t=>{e().pushHistory("Delete data source"),r(a=>{a.layoutData?.data_sources&&(a.layoutData.data_sources=a.layoutData.data_sources.filter(i=>i.id!==t),a.hasChanges=!0)})},testDataSource:async t=>({success:!0,data:{}}),setMockData:(t,a)=>{r(i=>{i.mockDataContext[t]=a})},addModal:t=>{e().pushHistory("Add modal"),r(a=>{a.layoutData&&(a.layoutData.modals||(a.layoutData.modals=[]),a.layoutData.modals.push(t),a.hasChanges=!0)})},updateModal:(t,a)=>{e().pushHistory("Update modal"),r(i=>{if(!i.layoutData?.modals)return;const o=i.layoutData.modals.findIndex(d=>d.id===t);o!==-1&&(i.layoutData.modals[o]={...i.layoutData.modals[o],...a},i.hasChanges=!0)})},deleteModal:t=>{e().pushHistory("Delete modal"),r(a=>{a.layoutData?.modals&&(a.layoutData.modals=a.layoutData.modals.filter(i=>i.id!==t),a.hasChanges=!0)})},setActivePropertyTab:t=>{r(a=>{a.activePropertyTab=t})},toggleTreeNode:t=>{r(a=>{const i=a.expandedTreeNodes.indexOf(t);i===-1?a.expandedTreeNodes.push(t):a.expandedTreeNodes.splice(i,1)})},copyToClipboard:t=>{r(a=>{a.clipboard=JSON.parse(JSON.stringify(t))})},pasteFromClipboard:(t,a)=>{const{clipboard:i}=e();if(!i)return;const o={...JSON.parse(JSON.stringify(i)),id:Go(i.name)};e().addComponent(o,t,a)},startDrag:t=>{r(a=>{a.draggingComponent=t})},dragOver:(t,a)=>{r(i=>{i.dropTargetId=t,i.dropPosition=a})},endDrag:()=>{r(t=>{t.draggingComponent=null,t.dropTargetId=null,t.dropPosition=null})},saveExtensionOverride:async(t,a)=>{St.log("Save extension override:",t)},restoreExtensionOverride:async t=>{St.log("Restore extension override:",t)}})),{name:"WysiwygEditorState"})),ld=r=>r.historyIndex>=0,cd=r=>r.historyIndexee.loadLayout),f=Se(ee=>ee.setLayoutData),p=Se(ee=>ee.setEditMode),y=Se(ee=>ee.layoutData),x=Se(ee=>ee.selectedComponentId),S=Se(ee=>ee.loadingState),v=Se(ee=>ee.error),w=Se(ee=>ee.hasChanges),k=Se(ee=>ee.undo),A=Se(ee=>ee.redo),O=Se(ee=>ee.saveLayout),N=Se(ee=>ee.deleteComponent),D=Se(ee=>ee.duplicateComponent),$=Se(ee=>ee.copyToClipboard),M=Se(ee=>ee.pasteFromClipboard),z=Se(ee=>ee.clipboard),K=Se(ld),ye=Se(cd),we=j.useMemo(()=>({...QN,...e}),[e]),J=S==="loaded",ve=S==="loading",le=S==="saving",de=j.useMemo(()=>{if(!y||!x)return null;const ee=(X,ae)=>{for(const R of X)if(typeof R!="string"){if(R.id===ae)return R;if(R.children){const U=ee(R.children,ae);if(U)return U}}return null};return ee(y.components,x)},[y,x]),je=j.useCallback(async(ee,X,ae)=>{oa.log("Initializing editor:",{tid:ee,ttype:X,lname:ae}),await h(ee,X,ae)},[h]),W=j.useCallback(()=>{oa.log("Deactivating editor")},[]);j.useEffect(()=>{d&&!y&&(oa.log("Setting initial layout data from props",{layoutName:d.layout_name,componentsCount:d.components?.length||0}),f(d,a||"unknown"),p(g))},[d,y,a,g,f,p]),j.useEffect(()=>{t&&a&&i&&o&&!d&&je(a,i,o).catch(ee=>{oa.error("Auto-initialize failed:",ee)})},[t,a,i,o,je,d]),j.useEffect(()=>{if(!we.keyboardShortcuts||!J)return;const ee=X=>{const ae=X.target;if(ae.tagName==="INPUT"||ae.tagName==="TEXTAREA"||ae.isContentEditable)return;const U=navigator.platform.toUpperCase().indexOf("MAC")>=0?X.metaKey:X.ctrlKey;if(U&&X.key==="z"&&!X.shiftKey){X.preventDefault(),K&&(k(),oa.log("Undo triggered"));return}if(U&&X.key==="z"&&X.shiftKey||U&&X.key==="y"){X.preventDefault(),ye&&(A(),oa.log("Redo triggered"));return}if(U&&X.key==="s"){X.preventDefault(),w&&O().catch(re=>{oa.error("Save failed:",re)});return}if((X.key==="Delete"||X.key==="Backspace")&&x){X.preventDefault(),N(x),oa.log("Delete triggered");return}if(U&&X.key==="d"&&x){X.preventDefault(),D(x),oa.log("Duplicate triggered");return}if(U&&X.key==="c"&&de){X.preventDefault(),$(de),oa.log("Copy triggered");return}if(U&&X.key==="v"&&z&&x){X.preventDefault(),M(x,"after"),oa.log("Paste triggered");return}if(X.key==="Escape"){const re=Se.getState().selectComponent;re(null);return}};return window.addEventListener("keydown",ee),()=>{window.removeEventListener("keydown",ee)}},[we.keyboardShortcuts,J,K,ye,w,x,de,z,k,A,O,N,D,$,M]),j.useEffect(()=>{if(!we.autoSave||!J||!w)return;const ee=setTimeout(()=>{O("Auto-save").catch(X=>{oa.error("Auto-save failed:",X)})},we.autoSaveInterval);return()=>{clearTimeout(ee)}},[we.autoSave,we.autoSaveInterval,J,w,O]),j.useEffect(()=>{if(!w)return;const ee=X=>{X.preventDefault(),X.returnValue=""};return window.addEventListener("beforeunload",ee),()=>{window.removeEventListener("beforeunload",ee)}},[w]);const he=j.useMemo(()=>({isEditorActive:J,config:we,initialize:je,deactivate:W,selectedComponent:de,layoutData:y,canUndo:K,canRedo:ye,hasChanges:w,isLoading:ve,isSaving:le,error:v}),[J,we,je,W,de,y,K,ye,w,ve,le,v]);return l.jsx(XN.Provider,{value:he,children:r})}const ZN=500;function oh(r={}){const{debounceMs:e=ZN}=r,t=Se(M=>M.history),a=Se(M=>M.historyIndex),i=Se(M=>M.undo),o=Se(M=>M.redo),d=Se(M=>M.pushHistory),g=Se(ld),h=Se(cd),f=j.useRef(null),p=j.useRef(null),y=j.useRef(null),x=j.useRef(!1),S=j.useCallback(()=>{f.current&&(clearTimeout(f.current),f.current=null),Se.setState({history:[],historyIndex:-1})},[]),v=j.useCallback(M=>{if(M<0||M>=t.length)return;const z=t[M];z&&Se.setState({layoutData:JSON.parse(JSON.stringify(z.layoutData)),historyIndex:M,hasChanges:!0})},[t]),w=j.useCallback(M=>{x.current||(f.current&&clearTimeout(f.current),p.current===M?f.current=setTimeout(()=>{d(M),f.current=null},e):(d(M),p.current=M))},[d,e]),k=j.useCallback(M=>{x.current||(x.current=!0,y.current=M,f.current&&(clearTimeout(f.current),f.current=null))},[]),A=j.useCallback(()=>{if(!x.current)return;const M=y.current||"Batch update";d(M),x.current=!1,y.current=null},[d]),O=j.useMemo(()=>a<0||a>=t.length?null:t[a],[t,a]),N=t.length,D=a+1,$=t.length-a-1;return{history:t,historyIndex:a,canUndo:g,canRedo:h,undo:i,redo:o,pushHistory:d,pushHistoryDebounced:w,startBatch:k,endBatch:A,isBatching:x.current,clearHistory:S,goToHistory:v,currentEntry:O,historySize:N,undoStackSize:D,redoStackSize:$}}const eE=({value:r,onChange:e,disabled:t=!1,placeholder:a="권한을 선택하세요"})=>{const[i,o]=j.useState({}),[d,g]=j.useState(!0),[h,f]=j.useState(null),[p,y]=j.useState(new Set(["admin"])),[x,S]=j.useState("");j.useEffect(()=>{(async()=>{try{g(!0),f(null);const M=await fetch("/api/admin/permissions",{headers:{Authorization:`Bearer ${localStorage.getItem("auth_token")}`,Accept:"application/json"}});if(!M.ok)throw new Error(`HTTP ${M.status}`);const z=await M.json();o(z.data?.data?.permissions||{})}catch(M){console.error("권한 목록 조회 실패:",M),f("권한 목록을 불러올 수 없습니다")}finally{g(!1)}})()},[]);const v=j.useCallback($=>{t||(r.includes($)?e(r.filter(M=>M!==$)):e([...r,$]))},[r,e,t]),w=j.useCallback($=>{y(M=>{const z=new Set(M);return z.has($)?z.delete($):z.add($),z})},[]),k=j.useCallback(()=>{if(t)return;const $=[],M=z=>{z.forEach(K=>{$.push(K.identifier),K.children?.length&&M(K.children)})};Object.values(i).forEach(z=>{z.permissions&&M(z.permissions)}),e($)},[i,e,t]),A=j.useCallback(()=>{t||e([])},[e,t]),O=j.useCallback($=>{if(!x.trim())return $;const M=x.toLowerCase(),z=K=>{const ye=K.name.toLowerCase().includes(M),we=K.identifier.toLowerCase().includes(M),J=K.children?.map(z).filter(Boolean);return ye||we||J&&J.length>0?{...K,children:J}:null};return $.map(z).filter(Boolean)},[x]),N=($,M=0)=>{const z=r.includes($.identifier),K=$.children&&$.children.length>0;return l.jsxs("div",{children:[l.jsxs("label",{className:`flex items-center gap-2 py-1.5 px-2 rounded cursor-pointer transition-colors ${t?"opacity-50 cursor-not-allowed":"hover:bg-gray-100 dark:hover:bg-gray-700"} ${z?"bg-blue-50 dark:bg-blue-900/30":""} - `,style:{paddingLeft:`${8+M*16}px`},children:[l.jsx("input",{type:"checkbox",checked:z,onChange:()=>v($.identifier),disabled:t,className:"w-4 h-4 rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500"}),l.jsxs("span",{className:"flex-1 text-sm text-gray-900 dark:text-gray-100",children:[$.name,l.jsxs("span",{className:"ml-2 text-xs text-gray-500 dark:text-gray-400",children:["(",$.identifier,")"]})]})]}),K&&$.children?.map(pe=>N(pe,M+1))]},$.identifier)};if(d)return l.jsxs("div",{className:"p-4 text-center text-sm text-gray-500 dark:text-gray-400",children:[l.jsx("span",{className:"inline-block animate-spin mr-2",children:"⏳"}),"권한 목록 로딩 중..."]});if(h)return l.jsx("div",{className:"p-4 text-center text-sm text-red-500 dark:text-red-400",children:h});const D=Object.entries(i);return l.jsxs("div",{className:"border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 overflow-hidden",children:[l.jsxs("div",{className:"p-3 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900",children:[l.jsxs("div",{className:"flex items-center justify-between mb-2",children:[l.jsxs("span",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:["선택된 권한: ",l.jsxs("span",{className:"text-blue-600 dark:text-blue-400",children:[r.length,"개"]}),r.length===0&&l.jsx("span",{className:"text-gray-500 ml-1",children:"(공개 레이아웃)"})]}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx("button",{type:"button",onClick:k,disabled:t,className:"text-xs text-blue-600 dark:text-blue-400 hover:underline disabled:opacity-50",children:"전체 선택"}),l.jsx("button",{type:"button",onClick:A,disabled:t||r.length===0,className:"text-xs text-red-600 dark:text-red-400 hover:underline disabled:opacity-50",children:"전체 해제"})]})]}),l.jsx("input",{type:"text",value:x,onChange:$=>S($.target.value),placeholder:"권한 검색...",className:"w-full px-3 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"})]}),l.jsx("div",{className:"max-h-64 overflow-y-auto",children:D.length===0?l.jsx("div",{className:"p-4 text-center text-sm text-gray-500 dark:text-gray-400",children:"권한이 없습니다"}):D.map(([$,M])=>{const z=O(M.permissions||[]);if(x&&z.length===0)return null;const K=p.has($);return l.jsxs("div",{className:"border-b border-gray-100 dark:border-gray-800 last:border-b-0",children:[l.jsxs("button",{type:"button",onClick:()=>w($),className:"w-full flex items-center gap-2 px-3 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",children:[l.jsx("span",{className:"text-gray-400",children:K?"▼":"▶"}),l.jsx("span",{children:M.label}),l.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400 ml-auto",children:[z.length,"개"]})]}),K&&l.jsx("div",{className:"pb-2",children:z.map(pe=>N(pe))})]},$)})}),r.length>0&&l.jsxs("div",{className:"p-2 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900",children:[l.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-400 mb-1",children:"선택됨:"}),l.jsxs("div",{className:"flex flex-wrap gap-1",children:[r.slice(0,5).map($=>l.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 text-xs bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-300 rounded",title:$,children:[$,l.jsx("button",{type:"button",onClick:()=>v($),disabled:t,className:"hover:text-red-500",children:"×"})]},$)),r.length>5&&l.jsxs("span",{className:"text-xs text-gray-500",children:["+",r.length-5,"개 더..."]})]})]}),l.jsx("div",{className:"p-2 border-t border-gray-200 dark:border-gray-700 text-xs text-gray-500 dark:text-gray-400",children:"권한을 선택하지 않으면 공개 레이아웃이 됩니다. 선택된 권한은 AND 조건으로 적용됩니다."})]})},eE=it("LayoutSettingsModal");function tE({isOpen:r,onClose:e}){const t=Se(x=>x.layoutData),a=Se(x=>x.updateLayoutMeta),i=Se(x=>x.pushHistory),[o,d]=j.useState([]),[g,h]=j.useState(!1);j.useEffect(()=>{t&&r&&(d(t.permissions||[]),h(!1))},[t,r]);const f=j.useCallback(x=>{d(x),h(!0)},[]),p=j.useCallback(()=>{t&&(eE.log("Saving layout permissions:",o),i("레이아웃 권한 변경"),a({permissions:o}),h(!1),e())},[t,o,i,a,e]),y=j.useCallback(()=>{g&&!window.confirm("변경사항이 저장되지 않습니다. 정말 닫으시겠습니까?")||e()},[g,e]);return r?l.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[l.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:y}),l.jsxs("div",{className:"relative w-full max-w-2xl mx-4 bg-white dark:bg-gray-800 rounded-lg shadow-xl max-h-[90vh] flex flex-col",children:[l.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:"레이아웃 설정"}),t&&l.jsxs("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-0.5",children:[t.layout_name,t.version&&l.jsxs("span",{className:"ml-2 text-xs bg-gray-100 dark:bg-gray-700 px-2 py-0.5 rounded",children:["v",t.version]})]})]}),l.jsx("button",{onClick:y,className:"p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",title:"닫기",children:l.jsx("span",{className:"text-xl",children:"✕"})})]}),l.jsxs("div",{className:"flex-1 overflow-auto px-6 py-4",children:[l.jsxs("div",{className:"mb-6",children:[l.jsx("h3",{className:"text-sm font-medium text-gray-700 dark:text-gray-300 mb-3",children:"레이아웃 정보"}),l.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"이름:"}),l.jsx("span",{className:"ml-2 text-gray-900 dark:text-white font-mono",children:t?.layout_name||"-"})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"버전:"}),l.jsx("span",{className:"ml-2 text-gray-900 dark:text-white",children:t?.version||"-"})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"상속:"}),l.jsx("span",{className:"ml-2 text-gray-900 dark:text-white font-mono",children:t?.extends||"없음"})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"컴포넌트:"}),l.jsxs("span",{className:"ml-2 text-gray-900 dark:text-white",children:[t?.components?.length||0,"개"]})]})]})]}),l.jsx("hr",{className:"border-gray-200 dark:border-gray-700 mb-6"}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"접근 권한"}),l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-3",children:"이 레이아웃에 접근하기 위해 필요한 권한을 설정합니다. 권한을 선택하지 않으면 공개 레이아웃이 됩니다. 선택된 권한은 AND 조건으로 적용됩니다."}),l.jsx(ZN,{value:o,onChange:f})]})]}),l.jsxs("div",{className:"flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900",children:[l.jsx("button",{onClick:y,className:"px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:"취소"}),l.jsx("button",{onClick:p,disabled:!g,className:"px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed rounded-lg transition-colors",children:g?"저장":"변경 없음"})]})]})]}):null}const yi=it("Toolbar");function lh({icon:r,label:e,onClick:t,disabled:a=!1,variant:i="default",loading:o=!1}){const d="flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed",g={default:"text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700",primary:"bg-blue-500 text-white hover:bg-blue-600 dark:bg-blue-600 dark:hover:bg-blue-700",danger:"text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900"};return l.jsxs("button",{className:`${d} ${g[i]}`,onClick:t,disabled:a||o,title:e,children:[o?l.jsx("span",{className:"animate-spin",children:"⏳"}):l.jsx("span",{children:r}),l.jsx("span",{className:"hidden sm:inline",children:e})]})}function ch({icon:r,label:e,onClick:t,disabled:a=!1,active:i=!1}){return l.jsx("button",{className:`p-2 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${i?"bg-blue-100 dark:bg-blue-900 text-blue-600 dark:text-blue-400":"text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700"}`,onClick:t,disabled:a,title:e,children:l.jsx("span",{children:r})})}function nE({currentMode:r,onChange:e}){const t=[{id:"visual",icon:"🎨",label:"비주얼"},{id:"json",icon:"📝",label:"JSON"},{id:"split",icon:"⬛",label:"분할"}];return l.jsx("div",{className:"flex items-center bg-gray-100 dark:bg-gray-800 rounded-lg p-0.5",children:t.map(a=>l.jsxs("button",{className:`flex items-center gap-1 px-3 py-1 text-sm rounded transition-colors ${r===a.id?"bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm":"text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"}`,onClick:()=>e(a.id),title:`${a.label} 모드`,children:[l.jsx("span",{children:a.icon}),l.jsx("span",{className:"hidden md:inline",children:a.label})]},a.id))})}function aE({hasChanges:r,isSaving:e,lastSaved:t}){return e?l.jsxs("div",{className:"flex items-center gap-1 text-sm text-blue-600 dark:text-blue-400",children:[l.jsx("span",{className:"animate-spin",children:"⏳"}),l.jsx("span",{children:"저장 중..."})]}):r?l.jsxs("div",{className:"flex items-center gap-1 text-sm text-orange-600 dark:text-orange-400",children:[l.jsx("span",{children:"🔶"}),l.jsx("span",{children:"변경사항 있음"})]}):t?l.jsxs("div",{className:"flex items-center gap-1 text-sm text-green-600 dark:text-green-400",children:[l.jsx("span",{children:"✅"}),l.jsx("span",{children:"저장됨"}),l.jsxs("span",{className:"text-gray-400 dark:text-gray-500 text-xs",children:["(",t.toLocaleTimeString(),")"]})]}):null}function sE({currentVersion:r,onVersionSelect:e}){const[t,a]=j.useState(!1);return l.jsxs("div",{className:"relative",children:[l.jsxs("button",{className:"flex items-center gap-1 px-3 py-1.5 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:()=>a(!t),children:[l.jsx("span",{children:"📋"}),l.jsx("span",{className:"hidden sm:inline",children:"버전"}),r&&l.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:["(",r,")"]}),l.jsx("span",{className:"text-xs",children:t?"▲":"▼"})]}),t&&l.jsx("div",{className:"absolute top-full right-0 mt-1 w-64 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50",children:l.jsx("div",{className:"p-3",children:l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 text-center",children:"버전 관리 (Phase 4)"})})})]})}function zx({className:r="",onClose:e,onSaveComplete:t}){const a=Se(we=>we.layoutData),i=Se(we=>we.editMode),o=Se(we=>we.hasChanges),d=Se(we=>we.loadingState),g=Se(we=>we.setEditMode),h=Se(we=>we.saveLayout),f=Se(ld),p=Se(cd),{undo:y,redo:x,undoStackSize:S,redoStackSize:v}=oh(),[w,k]=j.useState(void 0),[A,O]=j.useState(!1),N=d==="saving",D=j.useCallback(async()=>{try{await h("Manual save"),k(new Date),t?.(),yi.log("Layout saved")}catch(we){yi.error("Save failed:",we)}},[h,t]),$=j.useCallback(()=>{f&&(y(),yi.log("Undo performed"))},[f,y]),M=j.useCallback(()=>{p&&(x(),yi.log("Redo performed"))},[p,x]),z=j.useCallback(()=>{o&&!window.confirm("저장되지 않은 변경사항이 있습니다. 정말 닫으시겠습니까?")||e?.()},[o,e]),K=j.useCallback(async()=>{yi.log("Publish requested"),alert("발행 기능은 Phase 4에서 구현됩니다.")},[]),pe=j.useCallback(we=>{yi.log("Version selected:",we)},[]);return l.jsxs("div",{className:`flex items-center justify-between px-4 py-2 bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700 ${r}`,children:[l.jsxs("div",{className:"flex items-center gap-4",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-xl",children:"✏️"}),l.jsxs("div",{children:[l.jsx("h1",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"위지윅 편집기"}),a&&l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:a.layout_name})]})]}),l.jsx("div",{className:"h-6 w-px bg-gray-200 dark:bg-gray-700"}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(ch,{icon:"↩️",label:`실행 취소 (${S})`,onClick:$,disabled:!f}),l.jsx(ch,{icon:"↪️",label:`다시 실행 (${v})`,onClick:M,disabled:!p})]}),l.jsx("div",{className:"h-6 w-px bg-gray-200 dark:bg-gray-700"}),l.jsx(nE,{currentMode:i,onChange:g})]}),l.jsx("div",{className:"flex-1 flex justify-center",children:l.jsx(aE,{hasChanges:o,isSaving:N,lastSaved:w})}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(lh,{icon:"⚙️",label:"환경설정",onClick:()=>O(!0)}),l.jsx(sE,{currentVersion:a?.version,onVersionSelect:pe}),l.jsx("div",{className:"h-6 w-px bg-gray-200 dark:bg-gray-700"}),l.jsx(lh,{icon:"💾",label:"저장",onClick:D,disabled:!o,loading:N}),l.jsx(lh,{icon:"🚀",label:"발행",onClick:K,variant:"primary",disabled:o}),l.jsx("div",{className:"h-6 w-px bg-gray-200 dark:bg-gray-700"}),l.jsx(ch,{icon:"✕",label:"닫기",onClick:z})]}),l.jsx(tE,{isOpen:A,onClose:()=>O(!1)})]})}const xi=it("LayoutTree");function rE(r){const e=r.split(".");return e.length===1?e[0]:e[0]+e.slice(1).map(t=>`.children.${t}`).join("")}function Hx(r,e,t=""){for(let a=0;a0){const g=Hx(i.children,e,o);if(g)return[d,...g]}}return null}function iE(r,e){const t=r.props?._extensionSource,a=r.children?r.children.filter(i=>typeof i!="string").length:0;return{id:r.id,name:r.name,type:r.type==="extension_point"?"extension_point":r.type,hasCondition:!!r.if,hasIteration:!!r.iteration,isFromExtension:!!t,extensionSource:t,childCount:a,depth:e}}function oE(r){switch(r){case"basic":return"📦";case"composite":return"🧩";case"layout":return"📐";case"extension_point":return"🔌";default:return"📄"}}function lE(r){if(r.isFromExtension)return"text-purple-600 dark:text-purple-400";switch(r.type){case"basic":return"text-blue-600 dark:text-blue-400";case"composite":return"text-green-600 dark:text-green-400";case"layout":return"text-orange-600 dark:text-orange-400";case"extension_point":return"text-pink-600 dark:text-pink-400";default:return"text-gray-600 dark:text-gray-400"}}const cE=Ke.memo(function r({component:e,depth:t,treePath:a,enableDragDrop:i,expandedNodes:o,onToggleExpand:d,onNodeClick:g,onNodeDoubleClick:h,onDragStart:f,onDragOver:p,onDrop:y,onDragEnd:x,draggedNodeId:S,dropTargetId:v,dropPosition:w}){const k=Se(ae=>ae.selectedComponentId),A=Se(ae=>ae.hoveredComponentId),O=Se(ae=>ae.setHoveredComponentId),N=e.id||`tree_${a}`,D=j.useMemo(()=>iE(e,t),[e,t]),$=e.children&&e.children.length>0,M=o.has(N),z=j.useMemo(()=>k?k===N||k===e.id:!1,[k,N,e.id]),K=A===N,pe=S===N,we=v===N,J=j.useCallback(ae=>{ae.stopPropagation(),g?.(N)},[N,g]),be=j.useCallback(ae=>{ae.stopPropagation(),h?.(N)},[N,h]),le=j.useCallback(ae=>{ae.stopPropagation(),d(N)},[N,d]),de=j.useCallback(()=>{O(N)},[N,O]),je=j.useCallback(()=>{O(null)},[O]),W=j.useCallback(ae=>{i&&f(ae,N)},[N,i,f]),ge=j.useCallback(ae=>{i&&(ae.preventDefault(),p(ae,N))},[N,i,p]),ne=j.useCallback(ae=>{if(!i)return;ae.preventDefault();const R=ae.currentTarget.getBoundingClientRect(),U=ae.clientY-R.top,re=R.height;let ye;Ure*.75?ye="after":ye="inside",y(ae,N,ye)},[N,i,y]),X=j.useMemo(()=>{const ae=["flex items-center gap-1 px-2 py-1 rounded cursor-pointer","transition-colors duration-150","hover:bg-gray-100 dark:hover:bg-gray-700"];return z?ae.push("bg-blue-100 dark:bg-blue-900"):K&&ae.push("bg-gray-50 dark:bg-gray-800"),pe&&ae.push("opacity-50"),we&&(w==="before"?ae.push("border-t-2 border-blue-500"):w==="after"?ae.push("border-b-2 border-blue-500"):w==="inside"&&ae.push("ring-2 ring-blue-500")),ae.join(" ")},[z,K,pe,we,w]);return l.jsxs("div",{className:"select-none",children:[l.jsxs("div",{className:X,style:{paddingLeft:`${t*16+8}px`},onClick:J,onDoubleClick:be,onMouseEnter:de,onMouseLeave:je,draggable:i,onDragStart:W,onDragOver:ge,onDrop:ne,onDragEnd:x,role:"treeitem","aria-selected":z,"aria-expanded":$?M:void 0,children:[$?l.jsx("button",{className:"w-4 h-4 flex items-center justify-center text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200",onClick:le,"aria-label":M?"접기":"펼치기",children:M?"▼":"▶"}):l.jsx("span",{className:"w-4"}),l.jsx("span",{className:"text-sm",title:D.type,children:oE(D.type)}),l.jsx("span",{className:`text-sm font-medium ${lE(D)}`,children:D.name}),e.id?l.jsxs("span",{className:"text-xs text-gray-400 dark:text-gray-500 ml-1",children:["#",e.id.length>10?e.id.slice(0,8)+"…":e.id]}):l.jsx("span",{className:"text-xs text-gray-300 dark:text-gray-600 ml-1",title:"ID 미정의",children:"(no id)"}),l.jsxs("div",{className:"flex items-center gap-1 ml-auto",children:[D.hasCondition&&l.jsx("span",{className:"px-1 text-xs bg-yellow-100 dark:bg-yellow-900 text-yellow-700 dark:text-yellow-300 rounded",title:`조건: ${e.if}`,children:"if"}),D.hasIteration&&l.jsx("span",{className:"px-1 text-xs bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300 rounded",title:`반복: ${e.iteration?.source}`,children:"∞"}),D.isFromExtension&&D.extensionSource&&l.jsx("span",{className:"px-1 text-xs bg-purple-100 dark:bg-purple-900 text-purple-700 dark:text-purple-300 rounded",title:`출처: ${D.extensionSource}`,children:D.extensionSource})]})]}),$&&M&&l.jsx("div",{role:"group",children:e.children.map((ae,R)=>{if(typeof ae=="string")return null;const U=`${a}.${R}`,re=ae.id||`tree_${U}`;return l.jsx(r,{component:ae,depth:t+1,treePath:U,enableDragDrop:i,expandedNodes:o,onToggleExpand:d,onNodeClick:g,onNodeDoubleClick:h,onDragStart:f,onDragOver:p,onDrop:y,onDragEnd:x,draggedNodeId:S,dropTargetId:v,dropPosition:w},re)})})]})}),dE=Ke.memo(function({x:e,y:t,nodeId:a,onClose:i}){const o=Se(k=>k.deleteComponent),d=Se(k=>k.duplicateComponent),g=Se(k=>k.copyToClipboard),h=Se(k=>k.pasteFromClipboard),f=Se(k=>k.clipboard),p=Se(k=>k.layoutData),y=j.useMemo(()=>{if(!p)return null;const k=A=>{for(const O of A)if(typeof O!="string"){if(O.id===a)return O;if(O.children){const N=k(O.children);if(N)return N}}return null};return k(p.components)},[p,a]),x=j.useCallback(()=>{y&&(g(y),xi.log("Copied component:",a)),i()},[y,g,a,i]),S=j.useCallback(()=>{f&&(h(a,"inside"),xi.log("Pasted component inside:",a)),i()},[f,h,a,i]),v=j.useCallback(()=>{d(a),xi.log("Duplicated component:",a),i()},[d,a,i]),w=j.useCallback(()=>{o(a),xi.log("Deleted component:",a),i()},[o,a,i]);return Ke.useEffect(()=>{const k=()=>i();return document.addEventListener("click",k),()=>document.removeEventListener("click",k)},[i]),l.jsxs("div",{className:"fixed z-50 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg py-1 min-w-32",style:{left:e,top:t},onClick:k=>k.stopPropagation(),children:[l.jsx("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300",onClick:x,children:"📋 복사"}),l.jsx("button",{className:`w-full px-4 py-2 text-left text-sm ${f?"hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300":"text-gray-400 dark:text-gray-600 cursor-not-allowed"}`,onClick:S,disabled:!f,children:"📥 붙여넣기"}),l.jsx("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300",onClick:v,children:"📑 복제"}),l.jsx("div",{className:"border-t border-gray-200 dark:border-gray-700 my-1"}),l.jsx("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-red-50 dark:hover:bg-red-900 text-red-600 dark:text-red-400",onClick:w,children:"🗑️ 삭제"})]})});function Px({className:r="",showContextMenu:e=!0,enableDragDrop:t=!0,onNodeClick:a,onNodeDoubleClick:i}){const o=Se(J=>J.layoutData),d=Se(J=>J.selectComponent),g=Se(J=>J.moveComponent),h=Se(J=>J.selectedComponentId),[f,p]=j.useState(new Set),[y,x]=j.useState(null),[S,v]=j.useState(null),[w,k]=j.useState(null),[A,O]=j.useState({visible:!1,x:0,y:0,nodeId:null});Ke.useEffect(()=>{if(o){const J=new Set;o.components.forEach((be,le)=>{if(typeof be!="string"){const je=be.id||`tree_${le}`;J.add(je)}}),p(J)}},[o?.layout_name]),Ke.useEffect(()=>{if(!h||!o)return;const J=Hx(o.components,h);J&&J.length>0&&p(be=>{const le=new Set(be);return J.slice(0,-1).forEach(de=>le.add(de)),le})},[h,o]);const N=j.useCallback(J=>{p(be=>{const le=new Set(be);return le.has(J)?le.delete(J):le.add(J),le})},[]),D=j.useCallback(J=>{let be=J;if(J.startsWith("tree_")){const le=J.substring(5);be=`auto_path:${rE(le)}`}d(be),a?.(be)},[d,a]),$=j.useCallback(J=>{if(!e)return;J.preventDefault();const le=J.target.closest('[role="treeitem"]');if(le){const de=le.getAttribute("data-node-id");de&&O({visible:!0,x:J.clientX,y:J.clientY,nodeId:de})}},[e]),M=j.useCallback((J,be)=>{x(be),J.dataTransfer.effectAllowed="move",J.dataTransfer.setData("text/plain",be),xi.log("Drag start:",be)},[]),z=j.useCallback((J,be)=>{if(y===be)return;const le=J.target.getBoundingClientRect(),de=J.clientY-le.top,je=le.height;let W;deje*.75?W="after":W="inside",v(be),k(W)},[y]),K=j.useCallback((J,be,le)=>{y&&y!==be&&(g(y,be,le),xi.log("Dropped:",y,"to",be,le)),x(null),v(null),k(null)},[y,g]),pe=j.useCallback(()=>{x(null),v(null),k(null)},[]),we=j.useCallback(()=>{O({visible:!1,x:0,y:0,nodeId:null})},[]);return o?l.jsxs("div",{className:`h-full overflow-auto bg-white dark:bg-gray-900 ${r}`,onContextMenu:$,role:"tree","aria-label":"레이아웃 트리",children:[l.jsxs("div",{className:"sticky top-0 bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700 px-3 py-2",children:[l.jsx("h3",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300",children:"레이아웃 트리"}),l.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:[o.layout_name,o.extends&&l.jsxs("span",{className:"ml-1 text-blue-500",children:["(extends: ",o.extends,")"]})]})]}),l.jsx("div",{className:"p-2",children:o.components.map((J,be)=>{if(typeof J=="string")return null;const le=J,de=`${be}`,je=le.id||`tree_${de}`;return l.jsx(cE,{component:le,depth:0,treePath:de,enableDragDrop:t,expandedNodes:f,onToggleExpand:N,onNodeClick:D,onNodeDoubleClick:i,onDragStart:M,onDragOver:z,onDrop:K,onDragEnd:pe,draggedNodeId:y,dropTargetId:S,dropPosition:w},je)})}),A.visible&&A.nodeId&&l.jsx(dE,{x:A.x,y:A.y,nodeId:A.nodeId,onClose:we})]}):l.jsx("div",{className:`flex items-center justify-center h-full text-gray-500 dark:text-gray-400 ${r}`,children:l.jsx("p",{children:"레이아웃을 로드하세요"})})}const mn=it("PreviewCanvas"),dh={desktop:{width:1920,label:"Desktop",icon:"🖥️"},tablet:{width:768,label:"Tablet",icon:"📱"},mobile:{width:375,label:"Mobile",icon:"📱"},custom:{width:0,label:"Custom",icon:"📐"}};function uE({currentDevice:r,customWidth:e,onDeviceChange:t,onCustomWidthChange:a}){const i=["desktop","tablet","mobile","custom"];return l.jsxs("div",{className:"flex items-center gap-2 p-2 bg-gray-100 dark:bg-gray-800 rounded-lg",children:[i.map(o=>{const d=dh[o],g=r===o;return l.jsxs("button",{className:`flex items-center gap-1 px-3 py-1.5 rounded text-sm transition-colors ${g?"bg-blue-500 text-white":"bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600"}`,onClick:()=>t(o),title:`${d.label} (${o==="custom"?e:d.width}px)`,children:[l.jsx("span",{children:d.icon}),l.jsx("span",{className:"hidden sm:inline",children:d.label})]},o)}),r==="custom"&&l.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[l.jsx("input",{type:"number",value:e,onChange:o=>a(parseInt(o.target.value,10)||320),min:320,max:2560,className:"w-20 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300"}),l.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:"px"})]})]})}function gE({zoom:r,onZoomChange:e}){const t=[25,50,75,100,125,150,200];return l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("button",{className:"p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700",onClick:()=>e(Math.max(25,r-25)),disabled:r<=25,title:"축소",children:"➖"}),l.jsx("select",{value:r,onChange:a=>e(parseInt(a.target.value,10)),className:"px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300",children:t.map(a=>l.jsxs("option",{value:a,children:[a,"%"]},a))}),l.jsx("button",{className:"p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700",onClick:()=>e(Math.min(200,r+25)),disabled:r>=200,title:"확대",children:"➕"}),l.jsx("button",{className:"p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700",onClick:()=>e(100),title:"100%로 리셋",children:"🔄"})]})}function hE({targetId:r,position:e,containerRef:t}){const[a,i]=j.useState(null);return j.useEffect(()=>{if(!r||!e||!t.current){i(null);return}const o=t.current,d=o.querySelector(`[data-editor-id="${r}"]`);if(d){const g=o.getBoundingClientRect(),h=o.scrollLeft,f=o.scrollTop,p=d.getBoundingClientRect();i(new DOMRect(p.left-g.left+h,p.top-g.top+f,p.width,p.height))}else i(null)},[r,e,t]),!a||!e?null:e==="before"?l.jsx("div",{className:"absolute h-1 bg-blue-500 rounded pointer-events-none z-50",style:{left:a.x,top:a.y-2,width:a.width}}):e==="after"?l.jsx("div",{className:"absolute h-1 bg-blue-500 rounded pointer-events-none z-50",style:{left:a.x,top:a.y+a.height,width:a.width}}):l.jsx("div",{className:"absolute border-2 border-dashed border-blue-500 rounded pointer-events-none z-50",style:{left:a.x,top:a.y,width:a.width,height:a.height}})}function Bx(r,e){return r.querySelector(`[data-editor-id="${e}"]`)}function fE({selectedId:r,hoveredId:e,containerRef:t,zoom:a}){const[i,o]=j.useState(null),[d,g]=j.useState(null);return j.useEffect(()=>{if(!t.current)return;const h=()=>{const k=t.current;if(!k)return;const A=k.getBoundingClientRect(),O=k.scrollLeft,N=k.scrollTop;if(r){const D=Bx(k,r);if(D){const $=D.getBoundingClientRect();o(new DOMRect($.left-A.left+O,$.top-A.top+N,$.width,$.height))}else o(null)}else o(null);if(e&&e!==r){const D=Bx(k,e);if(D){const $=D.getBoundingClientRect();g(new DOMRect($.left-A.left+O,$.top-A.top+N,$.width,$.height))}else g(null)}else g(null)};h();let f,p=null;const y=350,x=k=>{p===null&&(p=k);const A=k-p;h(),A{cancelAnimationFrame(f),S.disconnect(),w.disconnect(),v?.removeEventListener("scroll",h),window.removeEventListener("scroll",h,!0)}},[r,e,t,a]),l.jsxs(l.Fragment,{children:[i&&l.jsxs("div",{className:"absolute pointer-events-none border-2 border-blue-500",style:{left:i.x,top:i.y,width:i.width,height:i.height},children:[l.jsx("div",{className:"absolute -left-1 -top-1 w-2 h-2 bg-blue-500 rounded-full"}),l.jsx("div",{className:"absolute -right-1 -top-1 w-2 h-2 bg-blue-500 rounded-full"}),l.jsx("div",{className:"absolute -left-1 -bottom-1 w-2 h-2 bg-blue-500 rounded-full"}),l.jsx("div",{className:"absolute -right-1 -bottom-1 w-2 h-2 bg-blue-500 rounded-full"}),l.jsx("div",{className:"absolute -top-6 left-0 px-1 py-0.5 text-xs bg-blue-500 text-white rounded whitespace-nowrap",children:r})]}),d&&l.jsx("div",{className:"absolute pointer-events-none border border-dashed border-green-400",style:{left:d.x,top:d.y,width:d.width,height:d.height},children:l.jsx("div",{className:"absolute -top-5 left-0 px-1 py-0.5 text-xs bg-green-400 text-white rounded whitespace-nowrap opacity-80",children:e})})]})}function pE(){return l.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-gray-500 dark:text-gray-400",children:[l.jsx("div",{className:"text-6xl mb-4",children:"📄"}),l.jsx("h3",{className:"text-lg font-medium mb-2",children:"레이아웃이 없습니다"}),l.jsx("p",{className:"text-sm text-center max-w-xs",children:"편집할 레이아웃을 선택하거나, 새 레이아웃을 생성하세요."})]})}function mE(){return l.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-gray-500 dark:text-gray-400",children:[l.jsx("div",{className:"animate-spin text-4xl mb-4",children:"⏳"}),l.jsx("p",{className:"text-sm",children:"레이아웃 로딩 중..."})]})}function yE({message:r,onRetry:e}){return l.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-red-500 dark:text-red-400",children:[l.jsx("div",{className:"text-6xl mb-4",children:"⚠️"}),l.jsx("h3",{className:"text-lg font-medium mb-2",children:"오류 발생"}),l.jsx("p",{className:"text-sm text-center max-w-xs mb-4",children:r}),e&&l.jsx("button",{className:"px-4 py-2 bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300 rounded hover:bg-red-200 dark:hover:bg-red-800",onClick:e,children:"다시 시도"})]})}function xE({width:r,zoom:e,children:t}){const a=e/100,i=r*a;return l.jsxs("div",{className:"mx-auto bg-white dark:bg-gray-900 shadow-xl rounded-lg overflow-hidden transition-all duration-300",style:{width:i,transform:`scale(${a})`,transformOrigin:"top center"},children:[l.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-gray-100 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700",children:[l.jsxs("div",{className:"flex gap-1.5",children:[l.jsx("div",{className:"w-3 h-3 rounded-full bg-red-500"}),l.jsx("div",{className:"w-3 h-3 rounded-full bg-yellow-500"}),l.jsx("div",{className:"w-3 h-3 rounded-full bg-green-500"})]}),l.jsx("div",{className:"flex-1 mx-4",children:l.jsxs("div",{className:"px-3 py-1 text-xs bg-white dark:bg-gray-700 rounded text-gray-500 dark:text-gray-400 truncate",children:[window.location.origin,"/preview"]})})]}),l.jsx("div",{className:"min-h-96",children:t})]})}function uh({className:r="",showOverlay:e=!0,onComponentSelect:t,onComponentHover:a,onComponentDrop:i}){const o=j.useRef(null),d=Se(Ce=>Ce.layoutData),g=Se(Ce=>Ce.loadingState),h=Se(Ce=>Ce.error),f=Se(Ce=>Ce.previewDevice),p=Se(Ce=>Ce.customWidth),y=Se(Ce=>Ce.selectedComponentId),x=Se(Ce=>Ce.hoveredComponentId),S=Se(Ce=>Ce.setPreviewDevice),v=Se(Ce=>Ce.selectComponent),w=Se(Ce=>Ce.setHoveredComponentId),k=Se(Ce=>Ce.mockDataContext),A=Se(Ce=>Ce.templateId),O=Se(Ce=>Ce.moveComponent),N=Se(Ce=>Ce.startDrag),D=Se(Ce=>Ce.dragOver),$=Se(Ce=>Ce.endDrag),M=Se(Ce=>Ce.dropTargetId),z=Se(Ce=>Ce.dropPosition),K=Se(Ce=>Ce.ensureComponentIdAndMove),pe=Se(Ce=>Ce.moveComponentByPaths),[we,J]=j.useState(100),[be,le]=j.useState(!1),de=j.useRef(null),je=50,W=8,ge=j.useRef(null),ne=j.useRef(null),X=j.useRef(null),ae=j.useRef(null),R=j.useMemo(()=>({templateId:A||"sirsoft-basic",locale:"ko"}),[A]),U=j.useMemo(()=>({_global:{sidebarOpen:!1,...k?._global||{}},_local:{...k?._local||{}},$locale:"ko",$templateId:A||"sirsoft-basic",route:{},query:{},...k||{}}),[k,A]);j.useEffect(()=>{(async()=>{try{ge.current||(ge.current=ba.getInstance(),A&&await ge.current.loadComponents(A,"user")),ne.current||(ne.current=new _n),X.current||(X.current=xr.getInstance()),!ae.current&&X.current&&(ae.current=new So({},X.current,R)),le(!0),mn.log("Editor engines initialized")}catch(Ge){mn.error("Failed to initialize engines:",Ge)}})()},[A,R]);const re=j.useCallback((Ce,Ge)=>{if(Ge.stopPropagation(),Ce.startsWith("auto_")){const bt=Ge.target.closest("[data-editor-path]")?.getAttribute("data-editor-path");if(bt){const Et=`auto_path:${bt}`;v(Et),t?.(Et),mn.log("Component selected via DynamicRenderer:",Ce,"-> path:",bt);return}}v(Ce),t?.(Ce),mn.log("Component selected via DynamicRenderer:",Ce)},[v,t]),ye=j.useCallback((Ce,Ge)=>{mn.log("handleDynamicHover called:",Ce),w(Ce),a?.(Ce)},[w,a]),oe=j.useCallback((Ce,Ge)=>{if(!d){Ge.dataTransfer.effectAllowed="none";return}if(Ce.startsWith("auto_")){const pt=Ge.target.closest("[data-editor-path]")?.getAttribute("data-editor-path");if(pt){const tt=ih(d.components,pt);if(tt){N(tt),Ge.dataTransfer.effectAllowed="move",Ge.dataTransfer.setData("text/plain",`path:${pt}`),mn.log("Drag started (path-based):",pt);return}}mn.warn("Auto-generated component without valid path:",Ce),Ge.dataTransfer.effectAllowed="none";return}const at=(bt,Et)=>{for(const pt of bt){if(typeof pt=="string")continue;const tt=pt;if(tt.id===Et)return tt;if(tt.children){const bn=at(tt.children,Et);if(bn)return bn}}return null},ft=at(d.components,Ce);ft?(N(ft),Ge.dataTransfer.effectAllowed="move",Ge.dataTransfer.setData("text/plain",Ce),mn.log("Drag started (id-based):",Ce)):(mn.warn("Component not found for drag:",Ce),Ge.dataTransfer.effectAllowed="none")},[d,N]),ke=j.useCallback(Ce=>{de.current&&(cancelAnimationFrame(de.current),de.current=null),$(),mn.log("Drag ended")},[$]),Oe=j.useMemo(()=>f==="custom"?p:dh[f].width,[f,p]),Te=j.useCallback(Ce=>{S(Ce),mn.log("Device changed:",Ce)},[S]),qe=j.useCallback(Ce=>{S("custom",Ce),mn.log("Custom width changed:",Ce)},[S]),Ie=j.useCallback(Ce=>{const Ge=Ce.target;let at=null;if(Ge.hasAttribute("data-editor-id")?at=Ge:at=Ge.closest("[data-editor-id]"),at){const ft=at.getAttribute("data-editor-id");ft&&(v(ft),t?.(ft),mn.log("Component selected:",ft))}else v(null),t?.(null)},[v,t]),Nt=j.useCallback(Ce=>{const Ge=Ce.target;let at=null;if(Ge.hasAttribute("data-editor-id")?at=Ge:at=Ge.closest("[data-editor-id]"),at){const ft=at.getAttribute("data-editor-id");ft&&ft!==x&&(w(ft),a?.(ft))}},[x,w,a]),Tt=j.useCallback(()=>{w(null),a?.(null)},[w,a]),Xt=j.useCallback(Ce=>{Ce.preventDefault();const Ge=Ce.dataTransfer.getData("text/plain"),ft=Ce.target.closest("[data-editor-id]");if(ft&&Ge){let bt=ft.getAttribute("data-editor-id");const Et=ft.getAttribute("data-editor-path");if(bt?.startsWith("auto_")&&Et&&d?.components){const dn=d.components,Ta=ih(dn,Et);Ta?.id?bt=Ta.id:mn.log("Target is auto ID, will use path-based move")}const pt=ft.getBoundingClientRect(),tt=Ce.clientY-pt.top,bn=pt.height;let wt;ttbn*.75?wt="after":wt="inside";const At=Ge.startsWith("path:"),qt=At?Ge.substring(5):null,Yn=bt?.startsWith("auto_");At&&Et&&Yn?(mn.log("Both source and target are path-based:",qt,"->",Et),qt&&Et&&qt!==Et&&pe(qt,Et,wt)&&(i?.(bt||"",wt),mn.log("Component moved (both path-based):",qt,"->",Et,wt))):At&&bt&&!Yn?qt&&K(qt,bt,wt)&&(i?.(bt,wt),mn.log("Component moved (source path, target id):",qt,"->",bt,wt)):!At&&bt&&Ge!==bt&&(O(Ge,bt,wt),i?.(bt,wt),mn.log("Component moved (id-based):",Ge,"->",bt,wt))}$()},[d,O,$,i,K,pe]),Ot=j.useCallback((Ce,Ge)=>{if(de.current)return;const at=()=>{Ce.scrollTop+=Ge,de.current=requestAnimationFrame(at)};de.current=requestAnimationFrame(at)},[]),Qt=j.useCallback(()=>{de.current&&(cancelAnimationFrame(de.current),de.current=null)},[]),It=j.useCallback(Ce=>{Ce.preventDefault(),Ce.dataTransfer.dropEffect="move";const Ge=o.current;if(!Ge)return;const at=Ge.getBoundingClientRect(),ft=Ce.clientY;ft-at.topwt*.75?At="after":At="inside",D(pt,At)}}},[D,Ot,Qt,je,W]),Tn=()=>g==="loading"?l.jsx(mE,{}):h?l.jsx(yE,{message:h}):d?!be||!ge.current||!ne.current||!X.current||!ae.current?l.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-gray-500 dark:text-gray-400",children:[l.jsx("div",{className:"animate-spin text-4xl mb-4",children:"⏳"}),l.jsx("p",{className:"text-sm",children:"렌더링 엔진 초기화 중..."})]}):l.jsx(Dc,{translationEngine:X.current,translationContext:R,children:l.jsx(ug,{children:l.jsx(gg,{overrideWidth:Oe,children:l.jsx(Og,{children:d.components.map((Ce,Ge)=>{if(typeof Ce=="string")return null;const at=Ce;return l.jsx(Ua,{componentDef:at,dataContext:U,translationContext:R,onDragStart:oe,onDragEnd:ke,registry:ge.current,bindingEngine:ne.current,translationEngine:X.current,actionDispatcher:ae.current,isEditMode:!0,onComponentSelect:re,onComponentHover:ye,isRootRenderer:!0,componentPath:`${Ge}`},at.id||`component-${Ge}`)})})})})}):l.jsx(pE,{});return l.jsxs("div",{className:`flex flex-col h-full bg-gray-50 dark:bg-gray-950 ${r}`,children:[l.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-200 dark:border-gray-800",children:[l.jsx(uE,{currentDevice:f,customWidth:p,onDeviceChange:Te,onCustomWidthChange:qe}),l.jsx(gE,{zoom:we,onZoomChange:J})]}),l.jsxs("div",{ref:o,className:"flex-1 overflow-auto p-8 relative",onClick:Ie,onMouseMove:Nt,onMouseLeave:Tt,onDrop:Xt,onDragOver:It,children:[l.jsx(xE,{width:Oe,zoom:we,children:Tn()}),e&&d&&l.jsx(fE,{selectedId:y,hoveredId:x,containerRef:o,zoom:we}),M&&l.jsx(hE,{targetId:M,position:z,containerRef:o})]}),l.jsxs("div",{className:"flex items-center justify-between px-4 py-1 text-xs border-t border-gray-200 dark:border-gray-800 bg-gray-100 dark:bg-gray-900 text-gray-500 dark:text-gray-400",children:[l.jsxs("div",{className:"flex items-center gap-4",children:[l.jsxs("span",{children:[f==="custom"?p:dh[f].width,"px"]}),l.jsxs("span",{children:["Zoom: ",we,"%"]})]}),l.jsxs("div",{className:"flex items-center gap-4",children:[y&&l.jsxs("span",{children:["선택됨: ",l.jsx("span",{className:"text-blue-500",children:y})]}),d&&l.jsxs("span",{children:[d.components.length,"개 컴포넌트"]})]})]})]})}const Ux={Div:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}],Span:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}],Button:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"type",type:"select",label:"버튼 타입",options:[{label:"Button",value:"button"},{label:"Submit",value:"submit"},{label:"Reset",value:"reset"}]},{name:"disabled",type:"boolean",label:"비활성화",allowBinding:!0}],Input:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"type",type:"select",label:"입력 타입",options:[{label:"Text",value:"text"},{label:"Password",value:"password"},{label:"Email",value:"email"},{label:"Number",value:"number"},{label:"Tel",value:"tel"},{label:"Date",value:"date"},{label:"Hidden",value:"hidden"}]},{name:"name",type:"text",label:"Name",required:!0},{name:"placeholder",type:"text",label:"Placeholder",allowBinding:!0},{name:"disabled",type:"boolean",label:"비활성화",allowBinding:!0},{name:"required",type:"boolean",label:"필수"}],Label:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"htmlFor",type:"text",label:"For (ID)"}],Image:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"src",type:"text",label:"이미지 URL",required:!0,allowBinding:!0},{name:"alt",type:"text",label:"대체 텍스트",allowBinding:!0}],Link:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"href",type:"text",label:"URL",allowBinding:!0},{name:"target",type:"select",label:"열기 방식",options:[{label:"현재 창",value:"_self"},{label:"새 창",value:"_blank"}]}],Icon:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"name",type:"icon",label:"아이콘 이름",required:!0},{name:"size",type:"select",label:"크기",options:[{label:"xs",value:"xs"},{label:"sm",value:"sm"},{label:"md",value:"md"},{label:"lg",value:"lg"},{label:"xl",value:"xl"}]}],H1:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}],H2:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}],H3:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}],H4:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}],H5:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}],H6:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}],P:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}],Form:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"dataKey",type:"text",label:"데이터 키",required:!0}],Select:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"name",type:"text",label:"Name",required:!0},{name:"placeholder",type:"text",label:"Placeholder"},{name:"disabled",type:"boolean",label:"비활성화",allowBinding:!0}],Textarea:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"name",type:"text",label:"Name",required:!0},{name:"placeholder",type:"text",label:"Placeholder",allowBinding:!0},{name:"rows",type:"number",label:"행 수",defaultValue:3},{name:"disabled",type:"boolean",label:"비활성화",allowBinding:!0}],Card:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"title",type:"text",label:"제목",allowBinding:!0}],Modal:[{name:"id",type:"text",label:"모달 ID",required:!0},{name:"title",type:"text",label:"제목",allowBinding:!0},{name:"size",type:"select",label:"크기",options:[{label:"Small",value:"sm"},{label:"Medium",value:"md"},{label:"Large",value:"lg"},{label:"XLarge",value:"xl"},{label:"Full",value:"full"}]}],DataGrid:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"columns",type:"array",label:"컬럼 정의",required:!0},{name:"data",type:"expression",label:"데이터",required:!0,allowBinding:!0},{name:"rowKey",type:"text",label:"행 키",defaultValue:"id"}],PageHeader:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"title",type:"text",label:"제목",allowBinding:!0},{name:"description",type:"text",label:"설명",allowBinding:!0}],Pagination:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"current",type:"expression",label:"현재 페이지",allowBinding:!0},{name:"total",type:"expression",label:"전체 항목 수",allowBinding:!0},{name:"perPage",type:"number",label:"페이지당 항목 수",defaultValue:10}],Tabs:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"defaultTab",type:"text",label:"기본 탭"}],Tab:[{name:"id",type:"text",label:"탭 ID",required:!0},{name:"label",type:"text",label:"탭 레이블",required:!0,allowBinding:!0}],Alert:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"type",type:"select",label:"타입",options:[{label:"Info",value:"info"},{label:"Success",value:"success"},{label:"Warning",value:"warning"},{label:"Error",value:"error"}]},{name:"dismissible",type:"boolean",label:"닫기 가능"}],Container:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"maxWidth",type:"select",label:"최대 너비",options:[{label:"sm",value:"sm"},{label:"md",value:"md"},{label:"lg",value:"lg"},{label:"xl",value:"xl"},{label:"2xl",value:"2xl"},{label:"Full",value:"full"}]}],Grid:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"cols",type:"number",label:"컬럼 수",defaultValue:1},{name:"gap",type:"number",label:"간격",defaultValue:4}],Flex:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"direction",type:"select",label:"방향",options:[{label:"Row",value:"row"},{label:"Column",value:"col"},{label:"Row Reverse",value:"row-reverse"},{label:"Column Reverse",value:"col-reverse"}]},{name:"justify",type:"select",label:"주축 정렬",options:[{label:"Start",value:"start"},{label:"Center",value:"center"},{label:"End",value:"end"},{label:"Between",value:"between"},{label:"Around",value:"around"},{label:"Evenly",value:"evenly"}]},{name:"align",type:"select",label:"교차축 정렬",options:[{label:"Start",value:"start"},{label:"Center",value:"center"},{label:"End",value:"end"},{label:"Stretch",value:"stretch"},{label:"Baseline",value:"baseline"}]},{name:"gap",type:"number",label:"간격",defaultValue:0}]};function Vo(){const r=Se(y=>y.componentCategories),e=Se(y=>y.handlers),t=j.useMemo(()=>r?[...r.basic,...r.composite,...r.layout]:[],[r]),a=j.useMemo(()=>r?.extension||[],[r]),i=j.useCallback(y=>t.find(x=>x.name===y)||null,[t]),o=j.useCallback(y=>{if(Ux[y])return Ux[y];const x=i(y);return x?.props?x.props.map(S=>({name:S,type:"text",label:S,allowBinding:!0})):[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}]},[i]),d=j.useCallback(y=>{const x=y.toLowerCase(),S=t.filter(w=>w.name.toLowerCase().includes(x)||w.description?.toLowerCase().includes(x)),v=a.filter(w=>w.name.toLowerCase().includes(x)||w.description?.toLowerCase().includes(x)||w.source.toLowerCase().includes(x));return[...S,...v]},[t,a]),g=j.useCallback(y=>r?y==="extension"?r.extension:r[y]:[],[r]),h=j.useCallback(y=>{const x=i(y);return x?.allowsChildren!==void 0?x.allowsChildren:x?.type==="layout"||x?.type==="composite"?!0:["Div","Span","Button","Form","Label","Link"].includes(y)},[i]),f=j.useCallback(y=>e.find(x=>x.name===y)||null,[e]),p=j.useCallback(y=>e.filter(x=>x.category===y),[e]);return{categories:r,allComponents:t,extensionComponents:a,handlers:e,getMetadata:i,getPropsSchema:o,searchComponents:d,filterByCategory:g,allowsChildren:h,getHandler:f,filterHandlersByCategory:p}}const qx=it("PropsEditor");function Gx({schema:r,value:e,onChange:t}){const[a,i]=j.useState(typeof e=="string"&&e.includes("{{")),o=j.useCallback(h=>{t(h.target.value)},[t]),d=r.type==="textarea",g=typeof e=="string"?e:"";return l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between mb-1",children:[l.jsxs("label",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:[r.label||r.name,r.required&&l.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),l.jsx("button",{type:"button",className:`text-xs px-1.5 py-0.5 rounded ${a?"bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300":"text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800"}`,onClick:()=>i(!a),title:"바인딩 표현식 사용",children:"{{}}"})]}),d?l.jsx("textarea",{value:g,onChange:o,placeholder:r.placeholder||`${r.name} 입력`,rows:3,className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 resize-none"}):l.jsx("input",{type:"text",value:g,onChange:o,placeholder:r.placeholder||`${r.name} 입력`,className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"}),r.description&&l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:r.description}),a&&l.jsxs("p",{className:"mt-1 text-xs text-blue-600 dark:text-blue-400",children:["바인딩 예시: ","{{users.data[0].name}}"]})]})}function bE({schema:r,value:e,onChange:t}){const a=j.useCallback(o=>{const d=parseFloat(o.target.value);t(isNaN(d)?void 0:d)},[t]),i=typeof e=="number"?e:"";return l.jsxs("div",{children:[l.jsxs("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:[r.label||r.name,r.required&&l.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),l.jsx("input",{type:"number",value:i,onChange:a,placeholder:r.placeholder||"0",min:r.min,max:r.max,step:r.step||1,className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"}),r.description&&l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:r.description})]})}function vE({schema:r,value:e,onChange:t}){const a=j.useCallback(o=>{t(o.target.checked)},[t]),i=!!e;return l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx("input",{type:"checkbox",id:`prop-${r.name}`,checked:i,onChange:a,className:"mt-0.5 w-4 h-4 text-blue-600 border-gray-300 dark:border-gray-600 rounded focus:ring-blue-500"}),l.jsxs("div",{children:[l.jsx("label",{htmlFor:`prop-${r.name}`,className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:r.label||r.name}),r.description&&l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:r.description})]})]})}function wE({schema:r,value:e,onChange:t}){const a=j.useCallback(d=>{t(d.target.value||void 0)},[t]),i=typeof e=="string"?e:"",o=r.options||[];return l.jsxs("div",{children:[l.jsxs("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:[r.label||r.name,r.required&&l.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),l.jsxs("select",{value:i,onChange:a,className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white",children:[l.jsx("option",{value:"",children:"선택하세요"}),o.map(d=>l.jsx("option",{value:d.value,children:d.label},d.value))]}),r.description&&l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:r.description})]})}function SE({schema:r,value:e,onChange:t}){const a=j.useCallback(o=>{t(o.target.value)},[t]),i=typeof e=="string"?e:"#000000";return l.jsxs("div",{children:[l.jsxs("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:[r.label||r.name,r.required&&l.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("input",{type:"color",value:i,onChange:a,className:"w-10 h-10 p-0 border border-gray-300 dark:border-gray-600 rounded cursor-pointer"}),l.jsx("input",{type:"text",value:i,onChange:a,placeholder:"#000000",className:"flex-1 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white font-mono"})]}),r.description&&l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:r.description})]})}function CE({schema:r,value:e,onChange:t}){const a=j.useCallback(d=>{t(d.target.value)},[t]),i=typeof e=="string"?e:"",o=i.split(/\s+/).filter(Boolean);return l.jsxs("div",{children:[l.jsxs("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:[r.label||r.name,r.required&&l.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),l.jsx("textarea",{value:i,onChange:a,placeholder:"space-y-4 p-4 bg-white dark:bg-gray-800",rows:3,className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 font-mono resize-none"}),o.length>0&&l.jsxs("div",{className:"mt-2 flex flex-wrap gap-1",children:[o.slice(0,10).map((d,g)=>l.jsx("span",{className:"px-1.5 py-0.5 text-xs bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded",children:d},g)),o.length>10&&l.jsxs("span",{className:"px-1.5 py-0.5 text-xs text-gray-500 dark:text-gray-400",children:["+",o.length-10,"개 더"]})]}),r.description&&l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:r.description})]})}function jE({schema:r,value:e,onChange:t}){j.useCallback(i=>{t(i.target.value)},[t]);const a=typeof e=="string"?e:"";return l.jsxs("div",{children:[l.jsxs("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:[r.label||r.name,r.required&&l.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),l.jsxs("div",{className:"relative",children:[l.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 text-sm",children:"{{"}),l.jsx("input",{type:"text",value:a.replace(/^\{\{|\}\}$/g,""),onChange:i=>t(`{{${i.target.value}}}`),placeholder:"expression",className:"w-full pl-8 pr-8 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 font-mono"}),l.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 text-sm",children:"}}"})]}),r.description&&l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:r.description})]})}function Fx({schema:r,value:e,onChange:t}){const[a,i]=j.useState(null),o=j.useCallback(g=>{const h=g.target.value;try{const f=JSON.parse(h);t(f),i(null)}catch{i("유효한 JSON이 아닙니다")}},[t]),d=j.useMemo(()=>{try{return JSON.stringify(e,null,2)}catch{return""}},[e]);return l.jsxs("div",{children:[l.jsxs("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:[r.label||r.name,r.required&&l.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),l.jsx("textarea",{value:d,onChange:o,placeholder:"{}",rows:4,className:`w-full px-3 py-2 text-sm border rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 font-mono resize-none ${a?"border-red-500 dark:border-red-400":"border-gray-300 dark:border-gray-600"}`}),a&&l.jsx("p",{className:"mt-1 text-xs text-red-500 dark:text-red-400",children:a}),r.description&&!a&&l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:r.description})]})}function kE(r,e,t){const a={schema:r,value:e,onChange:t};switch(r.type){case"text":case"textarea":return l.jsx(Gx,{...a});case"number":return l.jsx(bE,{...a});case"boolean":return l.jsx(vE,{...a});case"select":return l.jsx(wE,{...a});case"color":return l.jsx(SE,{...a});case"className":return l.jsx(CE,{...a});case"expression":return l.jsx(jE,{...a});case"object":return l.jsx(Fx,{...a});default:return l.jsx(Gx,{...a})}}function Vx({component:r,onChange:e}){const{getPropsSchema:t}=Vo(),a=j.useMemo(()=>t(r.name),[r.name,t]),i=r.props||{},o=j.useCallback((g,h)=>{const f={...i,[g]:h};(h===void 0||h==="")&&delete f[g],e({props:f}),qx.log("Prop changed:",g,h)},[i,e]),d=j.useCallback(g=>{e({text:g||void 0}),qx.log("Text changed:",g)},[e]);return l.jsxs("div",{className:"p-4 space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"텍스트 (text)"}),l.jsx("input",{type:"text",value:r.text||"",onChange:g=>d(g.target.value),placeholder:"컴포넌트 텍스트 내용",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"}),l.jsxs("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:["$t:key 또는 ","{{expression}}"," 사용 가능"]})]}),l.jsx("hr",{className:"border-gray-200 dark:border-gray-700"}),a.length>0?a.map(g=>l.jsx("div",{children:kE(g,i[g.name],h=>o(g.name,h))},g.name)):l.jsxs("div",{className:"text-center py-4 text-gray-400 dark:text-gray-500",children:[l.jsx("p",{className:"text-sm",children:"이 컴포넌트의 props 스키마가 정의되지 않았습니다."}),l.jsx("p",{className:"text-xs mt-1",children:"Raw JSON으로 편집하세요."})]}),l.jsx("hr",{className:"border-gray-200 dark:border-gray-700"}),l.jsxs("div",{children:[l.jsx("h4",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-2",children:"모든 Props (Raw JSON)"}),l.jsx(Fx,{schema:{name:"props",type:"object",label:"Props",description:"컴포넌트의 모든 속성을 JSON으로 직접 편집"},value:i,onChange:g=>{typeof g=="object"&&g!==null&&e({props:g})}})]})]})}function gh(r){const e=r.match(/\{\{(.+?)\}\}/);return e?e[1].trim():null}function dd(r){return typeof r=="string"&&r.includes("{{")}function hh(r){return`{{${r}}}`}function NE({sources:r,selectedPath:e,onSelect:t}){const[a,i]=j.useState(null);return l.jsx("div",{className:"space-y-2",children:r.map(o=>l.jsxs("div",{className:"border border-gray-200 dark:border-gray-700 rounded",children:[l.jsxs("button",{className:"w-full flex items-center gap-2 px-3 py-2 text-sm hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",onClick:()=>i(a===o.id?null:o.id),children:[l.jsx("span",{children:o.icon}),l.jsx("span",{className:"flex-1 text-left font-medium text-gray-700 dark:text-gray-300",children:o.label}),l.jsx("span",{className:"text-gray-400",children:a===o.id?"▼":"▶"})]}),a===o.id&&l.jsx("div",{className:"border-t border-gray-200 dark:border-gray-700 max-h-40 overflow-auto",children:o.paths.length>0?o.paths.map(d=>{const g=o.type==="dataSource"?`${o.id}.${d}`:d,h=e===g;return l.jsx("button",{className:`w-full px-4 py-1.5 text-xs text-left hover:bg-gray-100 dark:hover:bg-gray-700 ${h?"bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400":"text-gray-600 dark:text-gray-400"}`,onClick:()=>t(g),children:l.jsx("code",{className:"font-mono",children:d})},d)}):l.jsx("div",{className:"px-4 py-2 text-xs text-gray-400 dark:text-gray-500",children:"사용 가능한 경로가 없습니다"})})]},o.id))})}function EE({isOpen:r,propKey:e,currentValue:t,sources:a,onSave:i,onCancel:o}){const[d,g]=j.useState("simple"),[h,f]=j.useState(()=>gh(t)||""),[p,y]=j.useState(()=>gh(t)||""),x=j.useCallback(()=>{const v=d==="simple"?h:p;i(v?hh(v):"")},[d,h,p,i]),S=j.useCallback(v=>{f(v),y(v)},[]);return r?l.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:l.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-lg mx-4",children:[l.jsx("div",{className:"px-4 py-3 border-b border-gray-200 dark:border-gray-700",children:l.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:["바인딩 편집: ",e]})}),l.jsx("div",{className:"px-4 py-3 border-b border-gray-200 dark:border-gray-700",children:l.jsxs("div",{className:"flex gap-2",children:[l.jsx("button",{className:`px-3 py-1.5 text-sm rounded ${d==="simple"?"bg-blue-500 text-white":"bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300"}`,onClick:()=>g("simple"),children:"단순 모드"}),l.jsx("button",{className:`px-3 py-1.5 text-sm rounded ${d==="advanced"?"bg-blue-500 text-white":"bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300"}`,onClick:()=>g("advanced"),children:"고급 모드"})]})}),l.jsx("div",{className:"p-4 max-h-96 overflow-auto",children:d==="simple"?l.jsxs("div",{className:"space-y-4",children:[l.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"바인딩할 데이터 소스를 선택하세요:"}),l.jsx(NE,{sources:a,selectedPath:h,onSelect:S}),h&&l.jsxs("div",{className:"mt-4 p-3 bg-gray-50 dark:bg-gray-900 rounded",children:[l.jsx("label",{className:"text-xs text-gray-500 dark:text-gray-400",children:"미리보기:"}),l.jsx("code",{className:"block mt-1 text-sm text-blue-600 dark:text-blue-400 font-mono",children:hh(h)})]})]}):l.jsxs("div",{className:"space-y-4",children:[l.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"표현식을 직접 입력하세요:"}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs text-gray-500 dark:text-gray-400 mb-1",children:"표현식 (중괄호 없이)"}),l.jsx("input",{type:"text",value:p,onChange:v=>y(v.target.value),placeholder:"users?.data?.total ?? 0",className:"w-full px-3 py-2 text-sm font-mono border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"})]}),l.jsxs("div",{className:"text-xs text-gray-500 dark:text-gray-400 space-y-1",children:[l.jsx("p",{children:"지원되는 문법:"}),l.jsxs("ul",{className:"list-disc list-inside ml-2",children:[l.jsxs("li",{children:["Optional Chaining: ",l.jsx("code",{children:"users?.data"})]}),l.jsxs("li",{children:["Nullish Coalescing: ",l.jsx("code",{children:"value ?? 'default'"})]}),l.jsxs("li",{children:["삼항 연산자: ",l.jsx("code",{children:"condition ? a : b"})]})]})]}),p&&l.jsxs("div",{className:"mt-4 p-3 bg-gray-50 dark:bg-gray-900 rounded",children:[l.jsx("label",{className:"text-xs text-gray-500 dark:text-gray-400",children:"미리보기:"}),l.jsx("code",{className:"block mt-1 text-sm text-blue-600 dark:text-blue-400 font-mono",children:hh(p)})]})]})}),l.jsxs("div",{className:"px-4 py-3 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-2",children:[l.jsx("button",{className:"px-4 py-2 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:o,children:"취소"}),l.jsx("button",{className:"px-4 py-2 text-sm bg-blue-500 text-white rounded hover:bg-blue-600",onClick:x,children:"적용"})]})]})}):null}function _E({binding:r,onEdit:e,onRemove:t}){const a=gh(r.value);return l.jsx("div",{className:"p-3 bg-gray-50 dark:bg-gray-800 rounded border border-gray-200 dark:border-gray-700 group",children:l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:r.key}),l.jsx("span",{className:"text-xs px-1.5 py-0.5 bg-gray-200 dark:bg-gray-700 text-gray-500 dark:text-gray-400 rounded",children:r.type})]}),l.jsx("code",{className:"block mt-1 text-xs text-blue-600 dark:text-blue-400 font-mono truncate",children:r.value}),a&&l.jsxs("div",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:["경로: ",l.jsx("code",{className:"font-mono",children:a})]})]}),l.jsxs("div",{className:"flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[l.jsx("button",{className:"p-1 text-gray-400 hover:text-blue-500",onClick:e,title:"편집",children:"✏️"}),l.jsx("button",{className:"p-1 text-gray-400 hover:text-red-500",onClick:t,title:"바인딩 제거",children:"🗑️"})]})]})})}function AE({component:r,onChange:e}){const[t,a]=j.useState(null),[i,o]=j.useState(!1),[d,g]=j.useState(""),h=Se(N=>N.layoutData),f=Se(N=>N.mockDataContext),p=j.useMemo(()=>h?{dataSources:h.data_sources||[],globalState:Object.keys(f._global||{}),localState:Object.keys(f._local||{}),routeParams:["id","slug"],queryParams:["page","per_page","search","sort","order"],defines:h.defines||{},computed:h.computed||{}}:{dataSources:[],globalState:[],localState:[],routeParams:["id","slug"],queryParams:["page","per_page","search","sort","order"],defines:{},computed:{}},[h,f]),{getMetadata:y}=Vo(),x=y(r.name),S=j.useMemo(()=>{const N=[];return r.props&&Object.entries(r.props).forEach(([D,$])=>{dd($)&&N.push({key:D,value:$,type:"prop"})}),r.text&&dd(r.text)&&N.push({key:"text",value:r.text,type:"text"}),r.if&&dd(r.if)&&N.push({key:"if",value:r.if,type:"if"}),r.iteration?.source&&dd(r.iteration.source)&&N.push({key:"iteration.source",value:r.iteration.source,type:"iteration"}),N},[r]),v=j.useMemo(()=>{const N=new Set(S.filter($=>$.type==="prop").map($=>$.key));return(x?.props?Object.keys(x.props):[]).filter($=>!N.has($))},[S,x]),w=j.useMemo(()=>{const N=[];return p.dataSources.forEach(D=>{N.push({id:D.id,label:D.id,icon:"📡",type:"dataSource",paths:["data","loading","error","data.items","data.total","data.per_page"]})}),p.globalState.length>0&&N.push({id:"_global",label:"Global State",icon:"🌐",type:"global",paths:p.globalState.map(D=>`_global.${D}`)}),p.localState.length>0&&N.push({id:"_local",label:"Local State",icon:"📍",type:"local",paths:p.localState.map(D=>`_local.${D}`)}),N.push({id:"route",label:"Route Params",icon:"🛤️",type:"route",paths:p.routeParams.map(D=>`route.${D}`)}),N.push({id:"query",label:"Query Params",icon:"❓",type:"query",paths:p.queryParams.map(D=>`query.${D}`)}),Object.keys(p.defines).length>0&&N.push({id:"defines",label:"Defines",icon:"📝",type:"defines",paths:Object.keys(p.defines).map(D=>`defines.${D}`)}),Object.keys(p.computed).length>0&&N.push({id:"computed",label:"Computed",icon:"⚡",type:"computed",paths:Object.keys(p.computed).map(D=>`computed.${D}`)}),N},[p]),k=j.useCallback((N,D)=>{const $={};N==="text"?$.text=D||void 0:N==="if"?$.if=D||void 0:N==="iteration.source"?$.iteration=D?{...r.iteration,source:D,item_var:r.iteration?.item_var||"item"}:void 0:($.props={...r.props,[N]:D||void 0},!D&&$.props&&delete $.props[N]),e($),a(null),o(!1),g("")},[r,e]),A=j.useCallback(N=>{k(N.key,"")},[k]),O=j.useCallback(()=>{d&&(a(d),o(!1))},[d]);return l.jsxs("div",{className:"p-4 space-y-4",children:[l.jsxs("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:[l.jsx("p",{children:"데이터 바인딩을 설정하여 동적 데이터를 컴포넌트에 연결합니다."}),l.jsxs("p",{className:"mt-1 text-xs",children:["문법: ",l.jsx("code",{className:"bg-gray-100 dark:bg-gray-700 px-1 rounded",children:"{{expression}}"})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("h4",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase",children:["현재 바인딩 (",S.length,")"]}),l.jsx("button",{className:"text-xs text-blue-500 hover:text-blue-600",onClick:()=>o(!0),children:"+ 바인딩 추가"})]}),S.length>0?l.jsx("div",{className:"space-y-2",children:S.map(N=>l.jsx(_E,{binding:N,onEdit:()=>a(N.key),onRemove:()=>A(N)},`${N.type}-${N.key}`))}):l.jsx("div",{className:"text-center py-8 text-gray-400 dark:text-gray-500",children:l.jsx("p",{children:"설정된 바인딩이 없습니다"})})]}),i&&l.jsxs("div",{className:"p-3 border border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-900/20 rounded",children:[l.jsx("label",{className:"block text-xs text-gray-700 dark:text-gray-300 mb-2",children:"바인딩할 속성 선택"}),l.jsxs("div",{className:"flex gap-2",children:[l.jsxs("select",{value:d,onChange:N=>g(N.target.value),className:"flex-1 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white",children:[l.jsx("option",{value:"",children:"속성 선택..."}),l.jsx("option",{value:"text",children:"text (텍스트)"}),l.jsx("option",{value:"if",children:"if (조건부 렌더링)"}),l.jsx("option",{value:"iteration.source",children:"iteration.source (반복 소스)"}),v.map(N=>l.jsx("option",{value:N,children:N},N))]}),l.jsx("button",{className:"px-3 py-2 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",onClick:O,disabled:!d,children:"다음"}),l.jsx("button",{className:"px-3 py-2 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:()=>{o(!1),g("")},children:"취소"})]})]}),l.jsx(EE,{isOpen:t!==null,propKey:t||"",currentValue:t&&S.find(N=>N.key===t)?.value||"",sources:w,onSave:N=>t&&k(t,N),onCancel:()=>a(null)})]})}const TE=[{value:"navigate",label:"navigate",description:"페이지 이동"},{value:"navigateBack",label:"navigateBack",description:"브라우저 뒤로가기"},{value:"navigateForward",label:"navigateForward",description:"브라우저 앞으로가기"},{value:"apiCall",label:"apiCall",description:"API 호출"},{value:"login",label:"login",description:"로그인 (토큰 저장)"},{value:"logout",label:"logout",description:"로그아웃"},{value:"setState",label:"setState",description:"상태 변경"},{value:"setError",label:"setError",description:"에러 상태 설정"},{value:"openModal",label:"openModal",description:"모달 열기"},{value:"closeModal",label:"closeModal",description:"모달 닫기"},{value:"showAlert",label:"showAlert",description:"알림 표시"},{value:"toast",label:"toast",description:"토스트 알림"},{value:"switch",label:"switch",description:"조건 분기"},{value:"sequence",label:"sequence",description:"순차 실행"},{value:"parallel",label:"parallel",description:"병렬 실행"},{value:"showErrorPage",label:"showErrorPage",description:"에러 페이지 표시"},{value:"loadScript",label:"loadScript",description:"외부 스크립트 로드"},{value:"callExternal",label:"callExternal",description:"외부 함수 호출"},{value:"callExternalEmbed",label:"callExternalEmbed",description:"외부 임베드"},{value:"saveToLocalStorage",label:"saveToLocalStorage",description:"로컬스토리지 저장"},{value:"loadFromLocalStorage",label:"loadFromLocalStorage",description:"로컬스토리지 로드"},{value:"appendDataSource",label:"appendDataSource",description:"데이터소스 병합 (무한스크롤용)"},{value:"scrollIntoView",label:"scrollIntoView",description:"요소로 스크롤"},{value:"refetchDataSource",label:"refetchDataSource",description:"데이터소스 재조회"},{value:"remount",label:"remount",description:"컴포넌트 재마운트"},{value:"custom",label:"custom",description:"커스텀 액션"}],DE=[{value:"click",label:"click",description:"클릭"},{value:"change",label:"change",description:"값 변경"},{value:"input",label:"input",description:"입력"},{value:"submit",label:"submit",description:"폼 제출"},{value:"keydown",label:"keydown",description:"키 누름"},{value:"keyup",label:"keyup",description:"키 뗌"},{value:"focus",label:"focus",description:"포커스"},{value:"blur",label:"blur",description:"블러"},{value:"mount",label:"mount",description:"마운트"},{value:"unmount",label:"unmount",description:"언마운트"},{value:"scroll",label:"scroll",description:"스크롤 (무한스크롤용)"}];function RE({component:r,onChange:e}){const[t,a]=j.useState(null),[i,o]=j.useState(!1),d=j.useMemo(()=>r.actions||[],[r.actions]),g=j.useCallback(()=>{const x={type:"click",handler:"navigate",params:{}},S=[...d,x];e({actions:S}),a(S.length-1),o(!1)},[d,e]),h=j.useCallback(x=>{const S=d.filter((v,w)=>w!==x);e({actions:S.length>0?S:void 0}),t===x?a(null):t!==null&&t>x&&a(t-1)},[d,t,e]),f=j.useCallback((x,S)=>{const v=d.map((w,k)=>k===x?{...w,...S}:w);e({actions:v})},[d,e]),p=j.useCallback(x=>{const S=d[x],v=JSON.parse(JSON.stringify(S)),w=[...d.slice(0,x+1),v,...d.slice(x+1)];e({actions:w})},[d,e]),y=j.useCallback((x,S)=>{const v=S==="up"?x-1:x+1;if(v<0||v>=d.length)return;const w=[...d];[w[x],w[v]]=[w[v],w[x]],e({actions:w}),t===x?a(v):t===v&&a(x)},[d,t,e]);return l.jsxs("div",{className:"p-4 space-y-4",children:[l.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-400 mb-4",children:"이벤트 핸들러를 설정하여 사용자 상호작용에 반응합니다."}),d.length>0?l.jsxs("div",{className:"space-y-2",children:[l.jsxs("h4",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase",children:["등록된 액션 (",d.length,")"]}),d.map((x,S)=>l.jsx(OE,{action:x,index:S,isEditing:t===S,isFirst:S===0,isLast:S===d.length-1,onEdit:()=>a(t===S?null:S),onDelete:()=>h(S),onDuplicate:()=>p(S),onMove:v=>y(S,v),onUpdate:v=>f(S,v)},S))]}):l.jsxs("div",{className:"text-center py-8 text-gray-400 dark:text-gray-500",children:[l.jsx("p",{children:"등록된 액션이 없습니다"}),l.jsx("p",{className:"text-xs mt-1",children:"아래 버튼을 클릭하여 액션을 추가하세요"})]}),i?l.jsxs("div",{className:"flex gap-2",children:[l.jsx("button",{onClick:g,className:"flex-1 px-3 py-2 bg-blue-500 text-white text-sm rounded hover:bg-blue-600 transition-colors",children:"기본 액션 추가"}),l.jsx("button",{onClick:()=>o(!1),className:"px-3 py-2 text-gray-600 dark:text-gray-400 text-sm rounded border border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors",children:"취소"})]}):l.jsx("button",{onClick:()=>o(!0),className:"w-full px-3 py-2 border-2 border-dashed border-gray-300 dark:border-gray-600 text-gray-500 dark:text-gray-400 text-sm rounded hover:border-blue-400 hover:text-blue-500 transition-colors",children:"+ 액션 추가"})]})}function OE({action:r,index:e,isEditing:t,isFirst:a,isLast:i,onEdit:o,onDelete:d,onDuplicate:g,onMove:h,onUpdate:f}){const p=r.event||r.type||"click",y=!!r.event;return l.jsxs("div",{className:`rounded border transition-colors ${t?"border-blue-500 bg-blue-50 dark:bg-blue-900/20":"border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800"}`,children:[l.jsxs("div",{className:"p-2 flex items-center gap-2 cursor-pointer",onClick:o,children:[l.jsx("span",{className:"w-5 h-5 flex items-center justify-center text-xs font-medium text-gray-500 dark:text-gray-400 bg-gray-200 dark:bg-gray-700 rounded",children:e+1}),l.jsx("span",{className:`text-xs font-medium px-2 py-0.5 rounded ${y?"text-purple-600 dark:text-purple-400 bg-purple-100 dark:bg-purple-900/30":"text-blue-600 dark:text-blue-400 bg-blue-100 dark:bg-blue-900/30"}`,children:p}),l.jsx("span",{className:"text-xs text-gray-400",children:"→"}),l.jsx("span",{className:"text-xs font-medium text-green-600 dark:text-green-400",children:r.handler}),r.target&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"text-xs text-gray-400",children:":"}),l.jsx("span",{className:"text-xs text-gray-600 dark:text-gray-400 truncate max-w-[100px]",children:r.target})]}),(r.onSuccess||r.onError)&&l.jsx("span",{className:"text-xs text-orange-500 dark:text-orange-400",children:"+chain"}),r.confirm&&l.jsx("span",{className:"text-xs text-yellow-600 dark:text-yellow-400",children:"⚠️"}),r.debounce&&l.jsxs("span",{className:"text-xs text-purple-500 dark:text-purple-400",title:"Debounce 적용됨",children:["⏱️",typeof r.debounce=="number"?r.debounce:r.debounce.delay,"ms"]}),l.jsx("span",{className:"ml-auto text-gray-400",children:t?"▼":"▶"})]}),t&&l.jsxs("div",{className:"p-3 border-t border-gray-200 dark:border-gray-700 space-y-3",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"이벤트 타입"}),l.jsx("div",{className:"flex gap-2",children:l.jsxs("select",{value:r.event?"custom":r.type||"click",onChange:x=>{const S=x.target.value;f(S==="custom"?{type:"click",event:"onChange"}:{type:S,event:void 0})},className:"flex-1 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white",children:[DE.map(x=>l.jsxs("option",{value:x.value,children:[x.label," (",x.description,")"]},x.value)),l.jsx("option",{value:"custom",children:"커스텀 이벤트"})]})}),r.event&&l.jsx("input",{type:"text",value:r.event,onChange:x=>f({event:x.target.value}),placeholder:"이벤트명 (예: onChange, onRowAction)",className:"mt-2 w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"핸들러"}),l.jsx("select",{value:r.handler,onChange:x=>f({handler:x.target.value}),className:"w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white",children:TE.map(x=>l.jsxs("option",{value:x.value,children:[x.label," - ",x.description]},x.value))})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"Target (선택)"}),l.jsx("input",{type:"text",value:r.target||"",onChange:x=>f({target:x.target.value||void 0}),placeholder:"URL, 모달 ID, API 엔드포인트 등",className:"w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"})]}),l.jsx(LE,{params:r.params||{},onChange:x=>f({params:x}),handler:r.handler}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"확인 메시지 (선택)"}),l.jsx("input",{type:"text",value:r.confirm||"",onChange:x=>f({confirm:x.target.value||void 0}),placeholder:"실행 전 확인 대화상자 메시지",className:"w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"})]}),(r.type==="keydown"||r.type==="keyup")&&l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"키 필터"}),l.jsx("input",{type:"text",value:r.key||"",onChange:x=>f({key:x.target.value||void 0}),placeholder:"Enter, Escape, ArrowDown 등",className:"w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"})]}),l.jsx(ME,{debounce:r.debounce,onChange:x=>f({debounce:x})}),(r.onSuccess||r.onError)&&l.jsxs("div",{className:"text-xs text-gray-500 dark:text-gray-400 p-2 bg-gray-100 dark:bg-gray-700 rounded",children:[l.jsxs("p",{children:[l.jsx("span",{className:"text-green-600 dark:text-green-400",children:"onSuccess:"})," ",r.onSuccess?Array.isArray(r.onSuccess)?`${r.onSuccess.length}개 액션`:"1개 액션":"없음"]}),l.jsxs("p",{children:[l.jsx("span",{className:"text-red-600 dark:text-red-400",children:"onError:"})," ",r.onError?Array.isArray(r.onError)?`${r.onError.length}개 액션`:"1개 액션":"없음"]})]}),l.jsxs("div",{className:"flex gap-2 pt-2 border-t border-gray-200 dark:border-gray-700",children:[l.jsx("button",{onClick:()=>h("up"),disabled:a,className:"px-2 py-1 text-xs text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white disabled:opacity-30 disabled:cursor-not-allowed",title:"위로 이동",children:"↑"}),l.jsx("button",{onClick:()=>h("down"),disabled:i,className:"px-2 py-1 text-xs text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white disabled:opacity-30 disabled:cursor-not-allowed",title:"아래로 이동",children:"↓"}),l.jsx("button",{onClick:g,className:"px-2 py-1 text-xs text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300",title:"복제",children:"복제"}),l.jsx("button",{onClick:d,className:"px-2 py-1 text-xs text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 ml-auto",title:"삭제",children:"삭제"})]})]})]})}function LE({params:r,onChange:e,handler:t}){const[a,i]=j.useState(""),[o,d]=j.useState(""),g=j.useMemo(()=>{switch(t){case"navigate":return["path","query","mergeQuery","replace"];case"apiCall":return["method","body","headers"];case"setState":return["target","merge"];case"toast":return["type","message"];case"openModal":return[];case"closeModal":return[];case"showErrorPage":return["errorCode","target","containerId","layout"];case"refetchDataSource":return["dataSourceId"];case"remount":return["componentId"];case"appendDataSource":return["id","dataPath","sourcePath"];case"scrollIntoView":return["selector","behavior","block","scrollContainer","waitForElement"];case"switch":return["value"];case"sequence":case"parallel":return["actions"];default:return[]}},[t]),h=j.useCallback(()=>{if(!a.trim())return;const x={...r,[a.trim()]:o};e(x),i(""),d("")},[r,a,o,e]),f=j.useCallback(x=>{const{[x]:S,...v}=r;e(v)},[r,e]),p=j.useCallback((x,S)=>{const v={...r,[x]:S};e(v)},[r,e]),y=Object.entries(r);return l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"파라미터"}),y.length>0&&l.jsx("div",{className:"space-y-1 mb-2",children:y.map(([x,S])=>l.jsxs("div",{className:"flex gap-1 items-center",children:[l.jsxs("span",{className:"text-xs text-gray-600 dark:text-gray-400 w-24 truncate",children:[x,":"]}),l.jsx("input",{type:"text",value:typeof S=="object"?JSON.stringify(S):String(S),onChange:v=>p(x,v.target.value),className:"flex-1 px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"}),l.jsx("button",{onClick:()=>f(x),className:"text-red-500 hover:text-red-700 text-xs px-1",title:"삭제",children:"×"})]},x))}),l.jsxs("div",{className:"flex gap-1",children:[l.jsx("input",{type:"text",value:a,onChange:x=>i(x.target.value),placeholder:"키",list:`suggested-params-${t}`,className:"w-24 px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"}),l.jsx("datalist",{id:`suggested-params-${t}`,children:g.filter(x=>!r[x]).map(x=>l.jsx("option",{value:x},x))}),l.jsx("input",{type:"text",value:o,onChange:x=>d(x.target.value),placeholder:"값",className:"flex-1 px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white",onKeyDown:x=>{x.key==="Enter"&&h()}}),l.jsx("button",{onClick:h,disabled:!a.trim(),className:"px-2 py-1 text-xs bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-300 dark:hover:bg-gray-500 disabled:opacity-50",children:"+"})]}),g.length>0&&l.jsxs("p",{className:"text-xs text-gray-400 dark:text-gray-500 mt-1",children:["권장: ",g.join(", ")]})]})}function ME({debounce:r,onChange:e}){const[t,a]=j.useState(!1),i=typeof r=="number"?r:r?.delay||0,o=typeof r=="object"?r.leading??!1:!1,d=typeof r=="object"?r.trailing??!0:!0,g=r!==void 0&&i>0,h=j.useCallback(()=>{e(g?void 0:300)},[g,e]),f=j.useCallback(x=>{const S=parseInt(x,10);if(isNaN(S)||S<=0){e(void 0);return}e(t?{delay:S,leading:o,trailing:d}:S)},[t,o,d,e]),p=j.useCallback((x,S)=>{e({delay:i||300,leading:x==="leading"?S:o,trailing:x==="trailing"?S:d})},[i,o,d,e]),y=j.useCallback(()=>{!t&&g?e({delay:i,leading:!1,trailing:!0}):t&&g&&e(i),a(!t)},[t,g,i,e]);return l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between mb-1",children:[l.jsx("label",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:"Debounce (연속 호출 제어)"}),l.jsx("button",{type:"button",onClick:h,className:`relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${g?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,children:l.jsx("span",{className:`pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${g?"translate-x-4":"translate-x-0"}`})})]}),g&&l.jsxs("div",{className:"space-y-2 mt-2 p-2 bg-gray-50 dark:bg-gray-800 rounded",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("label",{className:"text-xs text-gray-600 dark:text-gray-400 w-16",children:"지연 시간"}),l.jsx("input",{type:"number",value:i,onChange:x=>f(x.target.value),min:0,step:100,placeholder:"300",className:"flex-1 px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"}),l.jsx("span",{className:"text-xs text-gray-500",children:"ms"})]}),l.jsx("button",{type:"button",onClick:y,className:"text-xs text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300",children:t?"▼ 고급 설정 숨기기":"▶ 고급 설정 보기"}),t&&l.jsxs("div",{className:"space-y-2 pt-2 border-t border-gray-200 dark:border-gray-700",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("input",{type:"checkbox",id:"debounce-leading",checked:o,onChange:x=>p("leading",x.target.checked),className:"h-3 w-3 rounded border-gray-300 dark:border-gray-600"}),l.jsx("label",{htmlFor:"debounce-leading",className:"text-xs text-gray-600 dark:text-gray-400",children:"Leading (첫 호출 즉시 실행)"})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("input",{type:"checkbox",id:"debounce-trailing",checked:d,onChange:x=>p("trailing",x.target.checked),className:"h-3 w-3 rounded border-gray-300 dark:border-gray-600"}),l.jsx("label",{htmlFor:"debounce-trailing",className:"text-xs text-gray-600 dark:text-gray-400",children:"Trailing (마지막 호출 후 실행)"})]}),l.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"권장: change 이벤트에 300ms, 검색에 300~500ms"})]})]}),!g&&l.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500 mt-1",children:"텍스트 입력 필드에서 연속 호출을 제어합니다"})]})}const Kx=[{label:"상태 확인",value:"{{_local.isVisible}}",description:"로컬 상태가 참일 때"},{label:"값 존재 확인",value:"{{data?.length > 0}}",description:"데이터가 존재할 때"},{label:"권한 확인",value:'{{_global.user?.permissions?.includes("admin")}}',description:"관리자 권한이 있을 때"},{label:"로딩 완료",value:"{{!_local.isLoading}}",description:"로딩이 완료되었을 때"},{label:"에러 없음",value:"{{!_local.error}}",description:"에러가 없을 때"}];function $E({component:r,onChange:e}){const[t,a]=j.useState(!1),[i,o]=j.useState(!1),d=Se(x=>x.layoutData),g=Se(x=>x.mockDataContext),h=j.useMemo(()=>{const x=[];return d?.data_sources&&d.data_sources.forEach(S=>{x.push({label:S.id,value:`{{${S.id}.data}}`,description:`데이터 소스: ${S.id}`})}),g._global&&Object.keys(g._global).forEach(S=>{Array.isArray(g._global[S])&&x.push({label:`_global.${S}`,value:`{{_global.${S}}}`,description:"전역 상태 배열"})}),g._local&&Object.keys(g._local).forEach(S=>{Array.isArray(g._local[S])&&x.push({label:`_local.${S}`,value:`{{_local.${S}}}`,description:"로컬 상태 배열"})}),x},[d,g]),f=j.useCallback(x=>{e({if:x||void 0})},[e]),p=j.useCallback(x=>{if(x===null)e({iteration:void 0});else{const S=r.iteration||{source:"",item_var:"item",index_var:"index"};e({iteration:{...S,...x}})}},[r.iteration,e]),y=j.useCallback(()=>{e({iteration:{source:"",item_var:"item",index_var:"index"}}),o(!0)},[e]);return l.jsxs("div",{className:"p-4 space-y-6",children:[l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between mb-2",children:[l.jsx("h4",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase",children:"조건부 렌더링 (if)"}),r.if&&l.jsx("button",{onClick:()=>f(""),className:"text-xs text-red-500 hover:text-red-700",title:"조건 삭제",children:"삭제"})]}),l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-2",children:"조건이 참일 때만 컴포넌트를 렌더링합니다."}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("input",{type:"text",value:r.if||"",onChange:x=>f(x.target.value),placeholder:"{{_local.showComponent}}",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"}),l.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[l.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"빠른 입력:"}),Kx.slice(0,3).map(x=>l.jsx("button",{onClick:()=>f(x.value),className:"px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors",title:x.description,children:x.label},x.value)),l.jsx("button",{onClick:()=>a(!t),className:"px-2 py-0.5 text-xs text-blue-600 dark:text-blue-400 hover:underline",children:t?"닫기":"더보기..."})]}),t&&l.jsxs("div",{className:"mt-2 p-2 bg-gray-50 dark:bg-gray-800 rounded border border-gray-200 dark:border-gray-700",children:[l.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-400 mb-2",children:"조건 템플릿 선택:"}),l.jsx("div",{className:"space-y-1",children:Kx.map(x=>l.jsxs("button",{onClick:()=>{f(x.value),a(!1)},className:"w-full text-left px-2 py-1 text-xs hover:bg-gray-200 dark:hover:bg-gray-700 rounded transition-colors",children:[l.jsx("span",{className:"font-medium text-gray-700 dark:text-gray-300",children:x.label}),l.jsx("span",{className:"text-gray-500 dark:text-gray-400 ml-2",children:x.description}),l.jsx("code",{className:"block text-xs text-blue-600 dark:text-blue-400 mt-0.5",children:x.value})]},x.value))})]})]}),r.if&&l.jsx("div",{className:"mt-2 flex items-center gap-2 text-xs",children:l.jsx("span",{className:"px-2 py-0.5 bg-yellow-100 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-400 rounded",children:"⚠️ 조건부 렌더링 활성화"})})]}),l.jsx("hr",{className:"border-gray-200 dark:border-gray-700"}),l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between mb-2",children:[l.jsx("h4",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase",children:"반복 렌더링 (iteration)"}),r.iteration&&l.jsx("button",{onClick:()=>p(null),className:"text-xs text-red-500 hover:text-red-700",title:"반복 삭제",children:"삭제"})]}),l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-2",children:"데이터 배열을 순회하며 컴포넌트를 반복 렌더링합니다."}),r.iteration?l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"Source (반복할 배열)"}),l.jsx("input",{type:"text",value:r.iteration.source||"",onChange:x=>p({source:x.target.value}),placeholder:"{{users.data}}",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"}),h.length>0&&l.jsxs("div",{className:"flex items-center gap-1 flex-wrap mt-1",children:[l.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"사용 가능:"}),h.slice(0,3).map(x=>l.jsx("button",{onClick:()=>p({source:x.value}),className:"px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors",title:x.description,children:x.label},x.value))]})]}),l.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"Item 변수명"}),l.jsx("input",{type:"text",value:r.iteration.item_var||"item",onChange:x=>p({item_var:x.target.value||"item"}),placeholder:"item",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"Index 변수명"}),l.jsx("input",{type:"text",value:r.iteration.index_var||"index",onChange:x=>p({index_var:x.target.value||"index"}),placeholder:"index",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"})]})]}),l.jsxs("div",{className:"p-2 bg-blue-50 dark:bg-blue-900/20 rounded text-xs text-blue-700 dark:text-blue-300",children:[l.jsx("p",{className:"font-medium mb-1",children:"사용법:"}),l.jsxs("code",{className:"block",children:[`{{${r.iteration.item_var||"item"}.속성}}`," - 현재 아이템 접근"]}),l.jsxs("code",{className:"block",children:[`{{${r.iteration.index_var||"index"}}}`," - 현재 인덱스 접근"]})]}),l.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[l.jsx("span",{className:"px-2 py-0.5 bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-400 rounded",children:"🔁 반복 렌더링 활성화"}),r.iteration.source&&l.jsxs("span",{className:"text-gray-500 dark:text-gray-400",children:["소스: ",r.iteration.source]})]})]}):l.jsxs("div",{className:"text-center py-4",children:[l.jsx("p",{className:"text-gray-400 dark:text-gray-500 mb-2",children:"반복 설정이 없습니다"}),l.jsx("button",{onClick:y,className:"px-3 py-1.5 text-sm bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-400 rounded hover:bg-purple-200 dark:hover:bg-purple-900/50 transition-colors",children:"+ 반복 렌더링 추가"})]})]}),r.if&&r.iteration&&l.jsxs("div",{className:"p-2 bg-amber-50 dark:bg-amber-900/20 rounded border border-amber-200 dark:border-amber-800 text-xs text-amber-700 dark:text-amber-300",children:[l.jsx("p",{className:"font-medium",children:"⚠️ 조건 + 반복 조합"}),l.jsx("p",{className:"mt-1",children:"조건(if)과 반복(iteration)이 함께 설정되어 있습니다. 조건이 먼저 평가되고, 참일 때만 반복이 실행됩니다."})]})]})}const Wx=[{key:"mobile",label:"모바일",range:"0 ~ 767px",icon:"📱"},{key:"tablet",label:"태블릿",range:"768 ~ 1023px",icon:"📲"},{key:"desktop",label:"데스크톱",range:"1024px 이상",icon:"🖥️"},{key:"portable",label:"포터블",range:"0 ~ 1023px",icon:"📱+📲",description:"모바일 + 태블릿"}],IE=[{label:"숨김",value:"hidden"},{label:"표시",value:"block"},{label:"Flex 표시",value:"flex"},{label:"Grid 표시",value:"grid"},{label:"1열 그리드",value:"grid grid-cols-1"},{label:"2열 그리드",value:"grid grid-cols-2"},{label:"3열 그리드",value:"grid grid-cols-3"},{label:"세로 정렬",value:"flex flex-col"},{label:"가로 정렬",value:"flex flex-row"},{label:"전체 너비",value:"w-full"},{label:"작은 패딩",value:"p-2"},{label:"중간 패딩",value:"p-4"},{label:"큰 패딩",value:"p-6"}];function zE({breakpointKey:r,label:e,range:t,icon:a,description:i,config:o,component:d,isOpen:g,onToggle:h,onChange:f}){const p=o!==void 0,{getMetadata:y}=Vo(),x=y(d.name),S=j.useCallback((O,N)=>{const D=o?.props||{};let $;if(N===""){const{[O]:M,...z}=D;$=z}else $={...D,[O]:N};Object.keys($).length===0&&!o?.text&&!o?.if?f(null):f({...o,props:$})},[o,f]),v=j.useCallback(O=>{if(O===""){const{text:N,...D}=o||{};Object.keys(D.props||{}).length===0&&!D.if?f(null):f(D)}else f({...o,text:O})},[o,f]),w=j.useCallback(O=>{if(O===""){const{if:N,...D}=o||{};Object.keys(D.props||{}).length===0&&!D.text?f(null):f(D)}else f({...o,if:O})},[o,f]),k=j.useCallback(()=>{f(p?null:{props:{}})},[p,f]),A=j.useCallback(O=>{const N=o?.props||{},D=N.className||"",$=D?`${D} ${O}`:O;f({...o,props:{...N,className:$}})},[o,f]);return l.jsxs("div",{className:"border border-gray-200 dark:border-gray-700 rounded overflow-hidden",children:[l.jsxs("div",{className:`flex items-center justify-between px-3 py-2 cursor-pointer transition-colors ${p?"bg-blue-50 dark:bg-blue-900/20":"bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-750"}`,onClick:h,children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{children:a}),l.jsxs("div",{children:[l.jsx("span",{className:"text-sm font-medium text-gray-900 dark:text-white",children:e}),l.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 ml-2",children:t}),i&&l.jsxs("span",{className:"text-xs text-gray-400 dark:text-gray-500 ml-1",children:["(",i,")"]})]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("button",{onClick:O=>{O.stopPropagation(),k()},className:`px-2 py-0.5 text-xs rounded transition-colors ${p?"bg-blue-500 text-white":"bg-gray-200 dark:bg-gray-600 text-gray-600 dark:text-gray-300"}`,children:p?"활성":"비활성"}),l.jsx("span",{className:`text-gray-400 transition-transform ${g?"rotate-180":""}`,children:"▼"})]})]}),g&&p&&l.jsxs("div",{className:"p-3 space-y-4 border-t border-gray-200 dark:border-gray-700",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"className"}),l.jsx("input",{type:"text",value:o?.props?.className||"",onChange:O=>S("className",O.target.value),placeholder:d.props?.className||"기본값 사용",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"}),l.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:IE.slice(0,6).map(O=>l.jsx("button",{onClick:()=>A(O.value),className:"px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors",title:O.value,children:O.label},O.value))})]}),x?.props?.filter(O=>O.name!=="className"&&O.name!=="children").slice(0,5).map(O=>l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:O.label||O.name}),O.type==="boolean"?l.jsxs("select",{value:o?.props?.[O.name]===void 0?"":String(o.props[O.name]),onChange:N=>{const D=N.target.value;D===""?S(O.name,""):S(O.name,D==="true")},className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white",children:[l.jsx("option",{value:"",children:"기본값"}),l.jsx("option",{value:"true",children:"true"}),l.jsx("option",{value:"false",children:"false"})]}):O.type==="select"&&O.options?l.jsxs("select",{value:o?.props?.[O.name]||"",onChange:N=>S(O.name,N.target.value),className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white",children:[l.jsx("option",{value:"",children:"기본값"}),O.options.map(N=>l.jsx("option",{value:String(N.value),children:N.label},String(N.value)))]}):l.jsx("input",{type:O.type==="number"?"number":"text",value:o?.props?.[O.name]||"",onChange:N=>S(O.name,N.target.value),placeholder:d.props?.[O.name]?String(d.props[O.name]):"기본값",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"})]},O.name)),d.text!==void 0&&l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"text"}),l.jsx("input",{type:"text",value:o?.text||"",onChange:O=>v(O.target.value),placeholder:d.text||"기본값 사용",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"if (조건부 렌더링)"}),l.jsx("input",{type:"text",value:o?.if||"",onChange:O=>w(O.target.value),placeholder:d.if||"{{true}}",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"}),l.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:["예: ",l.jsx("code",{className:"text-blue-600 dark:text-blue-400",children:"{{_global.sidebarOpen}}"})]})]}),o&&Object.keys(o).length>0&&l.jsxs("div",{className:"mt-3 p-2 bg-gray-50 dark:bg-gray-800 rounded text-xs",children:[l.jsx("p",{className:"font-medium text-gray-700 dark:text-gray-300 mb-1",children:"설정된 오버라이드:"}),l.jsx("pre",{className:"text-gray-600 dark:text-gray-400 overflow-auto max-h-24",children:JSON.stringify(o,null,2)})]})]})]})}function HE({responsive:r,onChange:e,onAddRange:t,onRemoveRange:a}){const[i,o]=j.useState(""),[d,g]=j.useState(""),h=j.useMemo(()=>{if(!r)return[];const p=Wx.map(y=>y.key);return Object.keys(r).filter(y=>!p.includes(y))},[r]),f=j.useCallback(()=>{let p;if(i&&d)p=`${i}-${d}`;else if(i&&!d)p=`${i}-`;else if(!i&&d)p=`-${d}`;else return;t(p),o(""),g("")},[i,d,t]);return l.jsxs("div",{className:"space-y-3",children:[l.jsx("h5",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase",children:"커스텀 범위"}),l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"특정 화면 너비 범위에 대한 오버라이드를 설정합니다."}),h.length>0&&l.jsx("div",{className:"space-y-2",children:h.map(p=>l.jsxs("div",{className:"flex items-center justify-between p-2 bg-gray-50 dark:bg-gray-800 rounded",children:[l.jsxs("span",{className:"text-sm font-mono text-gray-700 dark:text-gray-300",children:[p,"px"]}),l.jsx("button",{onClick:()=>a(p),className:"text-xs text-red-500 hover:text-red-700",children:"삭제"})]},p))}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("input",{type:"number",value:i,onChange:p=>o(p.target.value),placeholder:"최소",className:"w-20 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400"}),l.jsx("span",{className:"text-gray-500",children:"~"}),l.jsx("input",{type:"number",value:d,onChange:p=>g(p.target.value),placeholder:"최대",className:"w-20 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400"}),l.jsx("span",{className:"text-gray-500 text-sm",children:"px"}),l.jsx("button",{onClick:f,disabled:!i&&!d,className:"px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"추가"})]}),l.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"예: 0-599 (작은 모바일), 600-899 (큰 모바일), 1200- (와이드 데스크톱)"})]})}function PE({component:r,onChange:e}){const[t,a]=j.useState(new Set),[i,o]=j.useState(!1),d=r.responsive,g=j.useCallback(S=>{a(v=>{const w=new Set(v);return w.has(S)?w.delete(S):w.add(S),w})},[]),h=j.useCallback((S,v)=>{const w={...d||{}};v===null?delete w[S]:w[S]=v,Object.keys(w).length===0?e({responsive:void 0}):e({responsive:w})},[d,e]),f=j.useCallback(S=>{const v={...d||{}};v[S]={props:{}},e({responsive:v}),a(w=>new Set(w).add(S))},[d,e]),p=j.useCallback(S=>{const v={...d||{}};delete v[S],Object.keys(v).length===0?e({responsive:void 0}):e({responsive:v})},[d,e]),y=j.useCallback(()=>{e({responsive:void 0})},[e]),x=j.useMemo(()=>d?Object.keys(d).length:0,[d]);return l.jsxs("div",{className:"p-4 space-y-6",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("h4",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase",children:"반응형 오버라이드"}),l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:"브레이크포인트별로 다른 속성을 설정합니다."})]}),x>0&&l.jsx("button",{onClick:y,className:"text-xs text-red-500 hover:text-red-700",children:"모두 삭제"})]}),x>0&&l.jsx("div",{className:"flex items-center gap-2",children:l.jsxs("span",{className:"px-2 py-0.5 text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 rounded",children:["📱 ",x,"개 브레이크포인트 활성화"]})}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("h5",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase",children:"프리셋 브레이크포인트"}),Wx.map(S=>l.jsx(zE,{breakpointKey:S.key,label:S.label,range:S.range,icon:S.icon,description:S.description,config:d?.[S.key],component:r,isOpen:t.has(S.key),onToggle:()=>g(S.key),onChange:v=>h(S.key,v)},S.key))]}),l.jsx("hr",{className:"border-gray-200 dark:border-gray-700"}),l.jsxs("div",{children:[l.jsxs("button",{onClick:()=>o(!i),className:"flex items-center gap-2 text-sm text-blue-600 dark:text-blue-400 hover:underline",children:[l.jsx("span",{children:i?"▼":"▶"}),l.jsx("span",{children:"커스텀 범위 설정"})]}),i&&l.jsx("div",{className:"mt-3",children:l.jsx(HE,{responsive:d,onChange:h,onAddRange:f,onRemoveRange:p})})]}),l.jsxs("div",{className:"p-3 bg-blue-50 dark:bg-blue-900/20 rounded text-xs text-blue-700 dark:text-blue-300",children:[l.jsx("p",{className:"font-medium mb-2",children:"반응형 규칙:"}),l.jsxs("ul",{className:"list-disc list-inside space-y-1 text-blue-600 dark:text-blue-400",children:[l.jsxs("li",{children:[l.jsx("strong",{children:"portable"}),"을 사용할 때는 mobile/tablet과 혼용 금지"]}),l.jsx("li",{children:"프리셋 브레이크포인트보다 커스텀 범위가 우선 적용"}),l.jsx("li",{children:"좁은 범위가 넓은 범위보다 우선 적용"}),l.jsx("li",{children:"Props는 얕은 머지 (shallow merge) 적용"})]})]}),d&&Object.keys(d).length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsx("h5",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase",children:"설정 미리보기 (JSON)"}),l.jsx("pre",{className:"p-3 bg-gray-50 dark:bg-gray-800 rounded border border-gray-200 dark:border-gray-700 text-xs text-gray-600 dark:text-gray-400 overflow-auto max-h-48",children:JSON.stringify(d,null,2)})]})]})}it("ClassMapEditor");function BE({variantKey:r,variantClass:e,onKeyChange:t,onClassChange:a,onDelete:i}){return l.jsxs("div",{className:"flex items-start gap-2 p-2 bg-gray-50 dark:bg-gray-800 rounded",children:[l.jsxs("div",{className:"flex-1",children:[l.jsx("label",{className:"block text-xs text-gray-500 dark:text-gray-400 mb-1",children:"키 (variant name)"}),l.jsx("input",{type:"text",value:r,onChange:o=>t(o.target.value),placeholder:"success, error, warning...",className:"w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"})]}),l.jsxs("div",{className:"flex-[2]",children:[l.jsx("label",{className:"block text-xs text-gray-500 dark:text-gray-400 mb-1",children:"클래스"}),l.jsx("input",{type:"text",value:e,onChange:o=>a(o.target.value),placeholder:"bg-green-100 text-green-800",className:"w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 font-mono"})]}),l.jsx("button",{type:"button",onClick:i,className:"mt-5 p-1 text-red-500 dark:text-red-400 hover:bg-red-100 dark:hover:bg-red-900/30 rounded",title:"variant 삭제",children:l.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"w-4 h-4",viewBox:"0 0 20 20",fill:"currentColor",children:l.jsx("path",{fillRule:"evenodd",d:"M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z",clipRule:"evenodd"})})})]})}function Yx({classes:r}){const e=r.split(/\s+/).filter(Boolean);return e.length===0?null:l.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[e.slice(0,8).map((t,a)=>l.jsx("span",{className:"px-1.5 py-0.5 text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded",children:t},a)),e.length>8&&l.jsxs("span",{className:"px-1.5 py-0.5 text-xs text-gray-500 dark:text-gray-400",children:["+",e.length-8,"개 더"]})]})}function UE({value:r,onChange:e,label:t="classMap",description:a}){const[i,o]=j.useState(!!r),d=j.useCallback(()=>{r?(e(void 0),o(!1)):(e({base:"",variants:{},key:"",default:""}),o(!0))},[r,e]),g=j.useCallback(w=>{e({...r,base:w||void 0})},[r,e]),h=j.useCallback(w=>{e({...r,key:w||void 0})},[r,e]),f=j.useCallback(w=>{e({...r,default:w||void 0})},[r,e]),p=j.useCallback(()=>{const w=r?.variants||{},k=`variant_${Object.keys(w).length+1}`;e({...r,variants:{...w,[k]:""}})},[r,e]),y=j.useCallback((w,k)=>{if(!r?.variants||w===k)return;const A={...r.variants},O=A[w];delete A[w],A[k]=O,e({...r,variants:A})},[r,e]),x=j.useCallback((w,k)=>{e({...r,variants:{...r?.variants,[w]:k}})},[r,e]),S=j.useCallback(w=>{if(!r?.variants)return;const k={...r.variants};delete k[w],e({...r,variants:k})},[r,e]),v=j.useMemo(()=>Object.entries(r?.variants||{}),[r?.variants]);return l.jsxs("div",{className:"border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden",children:[l.jsxs("div",{className:"flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800 cursor-pointer",onClick:()=>o(!i),children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:`w-4 h-4 text-gray-500 dark:text-gray-400 transition-transform ${i?"rotate-90":""}`,viewBox:"0 0 20 20",fill:"currentColor",children:l.jsx("path",{fillRule:"evenodd",d:"M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z",clipRule:"evenodd"})}),l.jsx("span",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:t}),r&&l.jsx("span",{className:"px-1.5 py-0.5 text-xs bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 rounded",children:"활성화"})]}),l.jsx("button",{type:"button",onClick:w=>{w.stopPropagation(),d()},className:`px-2 py-1 text-xs rounded ${r?"bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300 hover:bg-red-200 dark:hover:bg-red-900/50":"bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 hover:bg-green-200 dark:hover:bg-green-900/50"}`,children:r?"제거":"추가"})]}),i&&r&&l.jsxs("div",{className:"p-3 space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"기본 클래스 (base)"}),l.jsx("textarea",{value:r.base||"",onChange:w=>g(w.target.value),placeholder:"px-2 py-1 rounded-full text-xs font-medium",rows:2,className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 font-mono resize-none"}),l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:"모든 상태에서 항상 적용되는 클래스"}),r.base&&l.jsx(Yx,{classes:r.base})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"키 표현식 (key)"}),l.jsxs("div",{className:"relative",children:[l.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 text-sm",children:"{{"}),l.jsx("input",{type:"text",value:(r.key||"").replace(/^\{\{|\}\}$/g,""),onChange:w=>h(`{{${w.target.value}}}`),placeholder:"row.status",className:"w-full pl-8 pr-8 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 font-mono"}),l.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 text-sm",children:"}}"})]}),l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:"variant를 결정하는 표현식 (예: row.status, item.type)"})]}),l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between mb-2",children:[l.jsxs("label",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:["Variants (",v.length,")"]}),l.jsx("button",{type:"button",onClick:p,className:"px-2 py-1 text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded hover:bg-blue-200 dark:hover:bg-blue-900/50",children:"+ 추가"})]}),v.length>0?l.jsx("div",{className:"space-y-2",children:v.map(([w,k])=>l.jsx(BE,{variantKey:w,variantClass:k,onKeyChange:A=>y(w,A),onClassChange:A=>x(w,A),onDelete:()=>S(w)},w))}):l.jsxs("div",{className:"p-4 text-center text-gray-400 dark:text-gray-500 bg-gray-50 dark:bg-gray-800 rounded",children:[l.jsx("p",{className:"text-sm",children:"variant가 없습니다"}),l.jsx("p",{className:"text-xs mt-1",children:"+ 추가 버튼을 클릭하여 variant를 추가하세요"})]})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"기본값 클래스 (default)"}),l.jsx("input",{type:"text",value:r.default||"",onChange:w=>f(w.target.value),placeholder:"bg-gray-100 text-gray-600",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 font-mono"}),l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:"매칭되는 variant가 없을 때 적용되는 클래스"}),r.default&&l.jsx(Yx,{classes:r.default})]}),l.jsxs("div",{className:"p-3 bg-gray-100 dark:bg-gray-900 rounded text-xs",children:[l.jsx("div",{className:"font-medium text-gray-700 dark:text-gray-300 mb-2",children:"생성될 JSON 미리보기:"}),l.jsx("pre",{className:"text-gray-600 dark:text-gray-400 overflow-x-auto",children:JSON.stringify({classMap:{...r.base&&{base:r.base},...Object.keys(r.variants||{}).length>0&&{variants:r.variants},...r.key&&{key:r.key},...r.default&&{default:r.default}}},null,2)})]})]}),a&&!i&&l.jsx("p",{className:"px-3 pb-2 text-xs text-gray-500 dark:text-gray-400",children:a})]})}it("AdvancedEditor");function ud({title:r,badge:e,isExpanded:t,onToggle:a}){return l.jsxs("button",{type:"button",className:"w-full flex items-center justify-between p-2 text-left bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors",onClick:a,children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:`w-4 h-4 text-gray-500 dark:text-gray-400 transition-transform ${t?"rotate-90":""}`,viewBox:"0 0 20 20",fill:"currentColor",children:l.jsx("path",{fillRule:"evenodd",d:"M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z",clipRule:"evenodd"})}),l.jsx("span",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase",children:r})]}),e&&l.jsx("span",{className:"px-1.5 py-0.5 text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded",children:e})]})}function qE({component:r,onChange:e}){const[t,a]=j.useState({basic:!0,classMap:!1,expressionHelpers:!1,rawJson:!1}),i=j.useCallback(f=>{a(p=>({...p,[f]:!p[f]}))},[]),o=j.useCallback(f=>{f&&f!==r.id&&e({id:f})},[r.id,e]),d=j.useCallback(f=>{const p={...r.props};f?p.classMap=f:delete p.classMap,e({props:p})},[r.props,e]),g=j.useCallback(f=>{e({blur_until_loaded:f||void 0})},[e]),h=r.props?.classMap;return l.jsxs("div",{className:"p-4 space-y-4",children:[l.jsxs("div",{children:[l.jsx(ud,{title:"기본 설정",isExpanded:t.basic,onToggle:()=>i("basic")}),t.basic&&l.jsxs("div",{className:"mt-3 space-y-4 pl-2",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"컴포넌트 ID"}),l.jsx("input",{type:"text",value:r.id,onChange:f=>o(f.target.value),className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white font-mono"}),l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:"레이아웃 내에서 고유해야 합니다"})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"슬롯 (Slot)"}),l.jsx("input",{type:"text",value:r.slot||"",readOnly:!0,placeholder:"(없음)",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300"})]}),r.slot&&l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"슬롯 순서"}),l.jsx("input",{type:"number",value:r.slotOrder||0,readOnly:!0,className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300"})]}),l.jsx("div",{children:l.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[l.jsx("input",{type:"checkbox",checked:r.blur_until_loaded||!1,onChange:f=>g(f.target.checked),className:"w-4 h-4 text-blue-600 border-gray-300 dark:border-gray-600 rounded focus:ring-blue-500"}),l.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300",children:"데이터 로드 전까지 블러 처리"})]})}),r.lifecycle&&l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"Lifecycle"}),l.jsxs("div",{className:"space-y-2",children:[r.lifecycle.onMount&&l.jsxs("div",{className:"p-2 bg-gray-50 dark:bg-gray-800 rounded",children:[l.jsx("span",{className:"text-xs text-gray-600 dark:text-gray-400",children:"onMount:"}),l.jsxs("span",{className:"text-xs text-gray-700 dark:text-gray-300 ml-2",children:[r.lifecycle.onMount.length,"개 액션"]})]}),r.lifecycle.onUnmount&&l.jsxs("div",{className:"p-2 bg-gray-50 dark:bg-gray-800 rounded",children:[l.jsx("span",{className:"text-xs text-gray-600 dark:text-gray-400",children:"onUnmount:"}),l.jsxs("span",{className:"text-xs text-gray-700 dark:text-gray-300 ml-2",children:[r.lifecycle.onUnmount.length,"개 액션"]})]})]})]})]})]}),l.jsxs("div",{children:[l.jsx(ud,{title:"classMap (조건부 스타일)",badge:h?"활성화":void 0,isExpanded:t.classMap,onToggle:()=>i("classMap")}),t.classMap&&l.jsx("div",{className:"mt-3",children:l.jsx(UE,{value:h,onChange:d,label:"조건부 클래스 매핑",description:"상태에 따라 다른 CSS 클래스를 적용합니다. 중첩 삼항 연산자 대신 사용하세요."})})]}),l.jsxs("div",{children:[l.jsx(ud,{title:"표현식 헬퍼",isExpanded:t.expressionHelpers,onToggle:()=>i("expressionHelpers")}),t.expressionHelpers&&l.jsxs("div",{className:"mt-3 space-y-4",children:[l.jsxs("div",{className:"p-3 bg-orange-50 dark:bg-orange-900/20 rounded text-xs",children:[l.jsx("div",{className:"font-medium text-orange-700 dark:text-orange-300 mb-2",children:"$switch 표현식"}),l.jsx("p",{className:"text-orange-600 dark:text-orange-400 mb-2",children:"중첩 삼항 연산자 대신 선언적 switch-case 패턴을 사용할 수 있습니다."}),l.jsx("pre",{className:"bg-white dark:bg-gray-800 p-2 rounded font-mono overflow-x-auto text-gray-700 dark:text-gray-300",children:`{ + `,style:{paddingLeft:`${8+M*16}px`},children:[l.jsx("input",{type:"checkbox",checked:z,onChange:()=>v($.identifier),disabled:t,className:"w-4 h-4 rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500"}),l.jsxs("span",{className:"flex-1 text-sm text-gray-900 dark:text-gray-100",children:[$.name,l.jsxs("span",{className:"ml-2 text-xs text-gray-500 dark:text-gray-400",children:["(",$.identifier,")"]})]})]}),K&&$.children?.map(ye=>N(ye,M+1))]},$.identifier)};if(d)return l.jsxs("div",{className:"p-4 text-center text-sm text-gray-500 dark:text-gray-400",children:[l.jsx("span",{className:"inline-block animate-spin mr-2",children:"⏳"}),"권한 목록 로딩 중..."]});if(h)return l.jsx("div",{className:"p-4 text-center text-sm text-red-500 dark:text-red-400",children:h});const D=Object.entries(i);return l.jsxs("div",{className:"border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 overflow-hidden",children:[l.jsxs("div",{className:"p-3 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900",children:[l.jsxs("div",{className:"flex items-center justify-between mb-2",children:[l.jsxs("span",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:["선택된 권한: ",l.jsxs("span",{className:"text-blue-600 dark:text-blue-400",children:[r.length,"개"]}),r.length===0&&l.jsx("span",{className:"text-gray-500 ml-1",children:"(공개 레이아웃)"})]}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx("button",{type:"button",onClick:k,disabled:t,className:"text-xs text-blue-600 dark:text-blue-400 hover:underline disabled:opacity-50",children:"전체 선택"}),l.jsx("button",{type:"button",onClick:A,disabled:t||r.length===0,className:"text-xs text-red-600 dark:text-red-400 hover:underline disabled:opacity-50",children:"전체 해제"})]})]}),l.jsx("input",{type:"text",value:x,onChange:$=>S($.target.value),placeholder:"권한 검색...",className:"w-full px-3 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"})]}),l.jsx("div",{className:"max-h-64 overflow-y-auto",children:D.length===0?l.jsx("div",{className:"p-4 text-center text-sm text-gray-500 dark:text-gray-400",children:"권한이 없습니다"}):D.map(([$,M])=>{const z=O(M.permissions||[]);if(x&&z.length===0)return null;const K=p.has($);return l.jsxs("div",{className:"border-b border-gray-100 dark:border-gray-800 last:border-b-0",children:[l.jsxs("button",{type:"button",onClick:()=>w($),className:"w-full flex items-center gap-2 px-3 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",children:[l.jsx("span",{className:"text-gray-400",children:K?"▼":"▶"}),l.jsx("span",{children:M.label}),l.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400 ml-auto",children:[z.length,"개"]})]}),K&&l.jsx("div",{className:"pb-2",children:z.map(ye=>N(ye))})]},$)})}),r.length>0&&l.jsxs("div",{className:"p-2 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900",children:[l.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-400 mb-1",children:"선택됨:"}),l.jsxs("div",{className:"flex flex-wrap gap-1",children:[r.slice(0,5).map($=>l.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 text-xs bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-300 rounded",title:$,children:[$,l.jsx("button",{type:"button",onClick:()=>v($),disabled:t,className:"hover:text-red-500",children:"×"})]},$)),r.length>5&&l.jsxs("span",{className:"text-xs text-gray-500",children:["+",r.length-5,"개 더..."]})]})]}),l.jsx("div",{className:"p-2 border-t border-gray-200 dark:border-gray-700 text-xs text-gray-500 dark:text-gray-400",children:"권한을 선택하지 않으면 공개 레이아웃이 됩니다. 선택된 권한은 AND 조건으로 적용됩니다."})]})},tE=it("LayoutSettingsModal");function nE({isOpen:r,onClose:e}){const t=Se(x=>x.layoutData),a=Se(x=>x.updateLayoutMeta),i=Se(x=>x.pushHistory),[o,d]=j.useState([]),[g,h]=j.useState(!1);j.useEffect(()=>{t&&r&&(d(t.permissions||[]),h(!1))},[t,r]);const f=j.useCallback(x=>{d(x),h(!0)},[]),p=j.useCallback(()=>{t&&(tE.log("Saving layout permissions:",o),i("레이아웃 권한 변경"),a({permissions:o}),h(!1),e())},[t,o,i,a,e]),y=j.useCallback(()=>{g&&!window.confirm("변경사항이 저장되지 않습니다. 정말 닫으시겠습니까?")||e()},[g,e]);return r?l.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[l.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:y}),l.jsxs("div",{className:"relative w-full max-w-2xl mx-4 bg-white dark:bg-gray-800 rounded-lg shadow-xl max-h-[90vh] flex flex-col",children:[l.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:"레이아웃 설정"}),t&&l.jsxs("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-0.5",children:[t.layout_name,t.version&&l.jsxs("span",{className:"ml-2 text-xs bg-gray-100 dark:bg-gray-700 px-2 py-0.5 rounded",children:["v",t.version]})]})]}),l.jsx("button",{onClick:y,className:"p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",title:"닫기",children:l.jsx("span",{className:"text-xl",children:"✕"})})]}),l.jsxs("div",{className:"flex-1 overflow-auto px-6 py-4",children:[l.jsxs("div",{className:"mb-6",children:[l.jsx("h3",{className:"text-sm font-medium text-gray-700 dark:text-gray-300 mb-3",children:"레이아웃 정보"}),l.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"이름:"}),l.jsx("span",{className:"ml-2 text-gray-900 dark:text-white font-mono",children:t?.layout_name||"-"})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"버전:"}),l.jsx("span",{className:"ml-2 text-gray-900 dark:text-white",children:t?.version||"-"})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"상속:"}),l.jsx("span",{className:"ml-2 text-gray-900 dark:text-white font-mono",children:t?.extends||"없음"})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"컴포넌트:"}),l.jsxs("span",{className:"ml-2 text-gray-900 dark:text-white",children:[t?.components?.length||0,"개"]})]})]})]}),l.jsx("hr",{className:"border-gray-200 dark:border-gray-700 mb-6"}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"접근 권한"}),l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-3",children:"이 레이아웃에 접근하기 위해 필요한 권한을 설정합니다. 권한을 선택하지 않으면 공개 레이아웃이 됩니다. 선택된 권한은 AND 조건으로 적용됩니다."}),l.jsx(eE,{value:o,onChange:f})]})]}),l.jsxs("div",{className:"flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900",children:[l.jsx("button",{onClick:y,className:"px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:"취소"}),l.jsx("button",{onClick:p,disabled:!g,className:"px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed rounded-lg transition-colors",children:g?"저장":"변경 없음"})]})]})]}):null}const yi=it("Toolbar");function lh({icon:r,label:e,onClick:t,disabled:a=!1,variant:i="default",loading:o=!1}){const d="flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed",g={default:"text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700",primary:"bg-blue-500 text-white hover:bg-blue-600 dark:bg-blue-600 dark:hover:bg-blue-700",danger:"text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900"};return l.jsxs("button",{className:`${d} ${g[i]}`,onClick:t,disabled:a||o,title:e,children:[o?l.jsx("span",{className:"animate-spin",children:"⏳"}):l.jsx("span",{children:r}),l.jsx("span",{className:"hidden sm:inline",children:e})]})}function ch({icon:r,label:e,onClick:t,disabled:a=!1,active:i=!1}){return l.jsx("button",{className:`p-2 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${i?"bg-blue-100 dark:bg-blue-900 text-blue-600 dark:text-blue-400":"text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700"}`,onClick:t,disabled:a,title:e,children:l.jsx("span",{children:r})})}function aE({currentMode:r,onChange:e}){const t=[{id:"visual",icon:"🎨",label:"비주얼"},{id:"json",icon:"📝",label:"JSON"},{id:"split",icon:"⬛",label:"분할"}];return l.jsx("div",{className:"flex items-center bg-gray-100 dark:bg-gray-800 rounded-lg p-0.5",children:t.map(a=>l.jsxs("button",{className:`flex items-center gap-1 px-3 py-1 text-sm rounded transition-colors ${r===a.id?"bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm":"text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"}`,onClick:()=>e(a.id),title:`${a.label} 모드`,children:[l.jsx("span",{children:a.icon}),l.jsx("span",{className:"hidden md:inline",children:a.label})]},a.id))})}function sE({hasChanges:r,isSaving:e,lastSaved:t}){return e?l.jsxs("div",{className:"flex items-center gap-1 text-sm text-blue-600 dark:text-blue-400",children:[l.jsx("span",{className:"animate-spin",children:"⏳"}),l.jsx("span",{children:"저장 중..."})]}):r?l.jsxs("div",{className:"flex items-center gap-1 text-sm text-orange-600 dark:text-orange-400",children:[l.jsx("span",{children:"🔶"}),l.jsx("span",{children:"변경사항 있음"})]}):t?l.jsxs("div",{className:"flex items-center gap-1 text-sm text-green-600 dark:text-green-400",children:[l.jsx("span",{children:"✅"}),l.jsx("span",{children:"저장됨"}),l.jsxs("span",{className:"text-gray-400 dark:text-gray-500 text-xs",children:["(",t.toLocaleTimeString(),")"]})]}):null}function rE({currentVersion:r,onVersionSelect:e}){const[t,a]=j.useState(!1);return l.jsxs("div",{className:"relative",children:[l.jsxs("button",{className:"flex items-center gap-1 px-3 py-1.5 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:()=>a(!t),children:[l.jsx("span",{children:"📋"}),l.jsx("span",{className:"hidden sm:inline",children:"버전"}),r&&l.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:["(",r,")"]}),l.jsx("span",{className:"text-xs",children:t?"▲":"▼"})]}),t&&l.jsx("div",{className:"absolute top-full right-0 mt-1 w-64 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50",children:l.jsx("div",{className:"p-3",children:l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 text-center",children:"버전 관리 (Phase 4)"})})})]})}function Hx({className:r="",onClose:e,onSaveComplete:t}){const a=Se(we=>we.layoutData),i=Se(we=>we.editMode),o=Se(we=>we.hasChanges),d=Se(we=>we.loadingState),g=Se(we=>we.setEditMode),h=Se(we=>we.saveLayout),f=Se(ld),p=Se(cd),{undo:y,redo:x,undoStackSize:S,redoStackSize:v}=oh(),[w,k]=j.useState(void 0),[A,O]=j.useState(!1),N=d==="saving",D=j.useCallback(async()=>{try{await h("Manual save"),k(new Date),t?.(),yi.log("Layout saved")}catch(we){yi.error("Save failed:",we)}},[h,t]),$=j.useCallback(()=>{f&&(y(),yi.log("Undo performed"))},[f,y]),M=j.useCallback(()=>{p&&(x(),yi.log("Redo performed"))},[p,x]),z=j.useCallback(()=>{o&&!window.confirm("저장되지 않은 변경사항이 있습니다. 정말 닫으시겠습니까?")||e?.()},[o,e]),K=j.useCallback(async()=>{yi.log("Publish requested"),alert("발행 기능은 Phase 4에서 구현됩니다.")},[]),ye=j.useCallback(we=>{yi.log("Version selected:",we)},[]);return l.jsxs("div",{className:`flex items-center justify-between px-4 py-2 bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700 ${r}`,children:[l.jsxs("div",{className:"flex items-center gap-4",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-xl",children:"✏️"}),l.jsxs("div",{children:[l.jsx("h1",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"위지윅 편집기"}),a&&l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:a.layout_name})]})]}),l.jsx("div",{className:"h-6 w-px bg-gray-200 dark:bg-gray-700"}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(ch,{icon:"↩️",label:`실행 취소 (${S})`,onClick:$,disabled:!f}),l.jsx(ch,{icon:"↪️",label:`다시 실행 (${v})`,onClick:M,disabled:!p})]}),l.jsx("div",{className:"h-6 w-px bg-gray-200 dark:bg-gray-700"}),l.jsx(aE,{currentMode:i,onChange:g})]}),l.jsx("div",{className:"flex-1 flex justify-center",children:l.jsx(sE,{hasChanges:o,isSaving:N,lastSaved:w})}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(lh,{icon:"⚙️",label:"환경설정",onClick:()=>O(!0)}),l.jsx(rE,{currentVersion:a?.version,onVersionSelect:ye}),l.jsx("div",{className:"h-6 w-px bg-gray-200 dark:bg-gray-700"}),l.jsx(lh,{icon:"💾",label:"저장",onClick:D,disabled:!o,loading:N}),l.jsx(lh,{icon:"🚀",label:"발행",onClick:K,variant:"primary",disabled:o}),l.jsx("div",{className:"h-6 w-px bg-gray-200 dark:bg-gray-700"}),l.jsx(ch,{icon:"✕",label:"닫기",onClick:z})]}),l.jsx(nE,{isOpen:A,onClose:()=>O(!1)})]})}const xi=it("LayoutTree");function iE(r){const e=r.split(".");return e.length===1?e[0]:e[0]+e.slice(1).map(t=>`.children.${t}`).join("")}function Px(r,e,t=""){for(let a=0;a0){const g=Px(i.children,e,o);if(g)return[d,...g]}}return null}function oE(r,e){const t=r.props?._extensionSource,a=r.children?r.children.filter(i=>typeof i!="string").length:0;return{id:r.id,name:r.name,type:r.type==="extension_point"?"extension_point":r.type,hasCondition:!!r.if,hasIteration:!!r.iteration,isFromExtension:!!t,extensionSource:t,childCount:a,depth:e}}function lE(r){switch(r){case"basic":return"📦";case"composite":return"🧩";case"layout":return"📐";case"extension_point":return"🔌";default:return"📄"}}function cE(r){if(r.isFromExtension)return"text-purple-600 dark:text-purple-400";switch(r.type){case"basic":return"text-blue-600 dark:text-blue-400";case"composite":return"text-green-600 dark:text-green-400";case"layout":return"text-orange-600 dark:text-orange-400";case"extension_point":return"text-pink-600 dark:text-pink-400";default:return"text-gray-600 dark:text-gray-400"}}const dE=Ke.memo(function r({component:e,depth:t,treePath:a,enableDragDrop:i,expandedNodes:o,onToggleExpand:d,onNodeClick:g,onNodeDoubleClick:h,onDragStart:f,onDragOver:p,onDrop:y,onDragEnd:x,draggedNodeId:S,dropTargetId:v,dropPosition:w}){const k=Se(ae=>ae.selectedComponentId),A=Se(ae=>ae.hoveredComponentId),O=Se(ae=>ae.setHoveredComponentId),N=e.id||`tree_${a}`,D=j.useMemo(()=>oE(e,t),[e,t]),$=e.children&&e.children.length>0,M=o.has(N),z=j.useMemo(()=>k?k===N||k===e.id:!1,[k,N,e.id]),K=A===N,ye=S===N,we=v===N,J=j.useCallback(ae=>{ae.stopPropagation(),g?.(N)},[N,g]),ve=j.useCallback(ae=>{ae.stopPropagation(),h?.(N)},[N,h]),le=j.useCallback(ae=>{ae.stopPropagation(),d(N)},[N,d]),de=j.useCallback(()=>{O(N)},[N,O]),je=j.useCallback(()=>{O(null)},[O]),W=j.useCallback(ae=>{i&&f(ae,N)},[N,i,f]),he=j.useCallback(ae=>{i&&(ae.preventDefault(),p(ae,N))},[N,i,p]),ee=j.useCallback(ae=>{if(!i)return;ae.preventDefault();const R=ae.currentTarget.getBoundingClientRect(),U=ae.clientY-R.top,re=R.height;let xe;Ure*.75?xe="after":xe="inside",y(ae,N,xe)},[N,i,y]),X=j.useMemo(()=>{const ae=["flex items-center gap-1 px-2 py-1 rounded cursor-pointer","transition-colors duration-150","hover:bg-gray-100 dark:hover:bg-gray-700"];return z?ae.push("bg-blue-100 dark:bg-blue-900"):K&&ae.push("bg-gray-50 dark:bg-gray-800"),ye&&ae.push("opacity-50"),we&&(w==="before"?ae.push("border-t-2 border-blue-500"):w==="after"?ae.push("border-b-2 border-blue-500"):w==="inside"&&ae.push("ring-2 ring-blue-500")),ae.join(" ")},[z,K,ye,we,w]);return l.jsxs("div",{className:"select-none",children:[l.jsxs("div",{className:X,style:{paddingLeft:`${t*16+8}px`},onClick:J,onDoubleClick:ve,onMouseEnter:de,onMouseLeave:je,draggable:i,onDragStart:W,onDragOver:he,onDrop:ee,onDragEnd:x,role:"treeitem","aria-selected":z,"aria-expanded":$?M:void 0,children:[$?l.jsx("button",{className:"w-4 h-4 flex items-center justify-center text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200",onClick:le,"aria-label":M?"접기":"펼치기",children:M?"▼":"▶"}):l.jsx("span",{className:"w-4"}),l.jsx("span",{className:"text-sm",title:D.type,children:lE(D.type)}),l.jsx("span",{className:`text-sm font-medium ${cE(D)}`,children:D.name}),e.id?l.jsxs("span",{className:"text-xs text-gray-400 dark:text-gray-500 ml-1",children:["#",e.id.length>10?e.id.slice(0,8)+"…":e.id]}):l.jsx("span",{className:"text-xs text-gray-300 dark:text-gray-600 ml-1",title:"ID 미정의",children:"(no id)"}),l.jsxs("div",{className:"flex items-center gap-1 ml-auto",children:[D.hasCondition&&l.jsx("span",{className:"px-1 text-xs bg-yellow-100 dark:bg-yellow-900 text-yellow-700 dark:text-yellow-300 rounded",title:`조건: ${e.if}`,children:"if"}),D.hasIteration&&l.jsx("span",{className:"px-1 text-xs bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300 rounded",title:`반복: ${e.iteration?.source}`,children:"∞"}),D.isFromExtension&&D.extensionSource&&l.jsx("span",{className:"px-1 text-xs bg-purple-100 dark:bg-purple-900 text-purple-700 dark:text-purple-300 rounded",title:`출처: ${D.extensionSource}`,children:D.extensionSource})]})]}),$&&M&&l.jsx("div",{role:"group",children:e.children.map((ae,R)=>{if(typeof ae=="string")return null;const U=`${a}.${R}`,re=ae.id||`tree_${U}`;return l.jsx(r,{component:ae,depth:t+1,treePath:U,enableDragDrop:i,expandedNodes:o,onToggleExpand:d,onNodeClick:g,onNodeDoubleClick:h,onDragStart:f,onDragOver:p,onDrop:y,onDragEnd:x,draggedNodeId:S,dropTargetId:v,dropPosition:w},re)})})]})}),uE=Ke.memo(function({x:e,y:t,nodeId:a,onClose:i}){const o=Se(k=>k.deleteComponent),d=Se(k=>k.duplicateComponent),g=Se(k=>k.copyToClipboard),h=Se(k=>k.pasteFromClipboard),f=Se(k=>k.clipboard),p=Se(k=>k.layoutData),y=j.useMemo(()=>{if(!p)return null;const k=A=>{for(const O of A)if(typeof O!="string"){if(O.id===a)return O;if(O.children){const N=k(O.children);if(N)return N}}return null};return k(p.components)},[p,a]),x=j.useCallback(()=>{y&&(g(y),xi.log("Copied component:",a)),i()},[y,g,a,i]),S=j.useCallback(()=>{f&&(h(a,"inside"),xi.log("Pasted component inside:",a)),i()},[f,h,a,i]),v=j.useCallback(()=>{d(a),xi.log("Duplicated component:",a),i()},[d,a,i]),w=j.useCallback(()=>{o(a),xi.log("Deleted component:",a),i()},[o,a,i]);return Ke.useEffect(()=>{const k=()=>i();return document.addEventListener("click",k),()=>document.removeEventListener("click",k)},[i]),l.jsxs("div",{className:"fixed z-50 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg py-1 min-w-32",style:{left:e,top:t},onClick:k=>k.stopPropagation(),children:[l.jsx("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300",onClick:x,children:"📋 복사"}),l.jsx("button",{className:`w-full px-4 py-2 text-left text-sm ${f?"hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300":"text-gray-400 dark:text-gray-600 cursor-not-allowed"}`,onClick:S,disabled:!f,children:"📥 붙여넣기"}),l.jsx("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300",onClick:v,children:"📑 복제"}),l.jsx("div",{className:"border-t border-gray-200 dark:border-gray-700 my-1"}),l.jsx("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-red-50 dark:hover:bg-red-900 text-red-600 dark:text-red-400",onClick:w,children:"🗑️ 삭제"})]})});function Bx({className:r="",showContextMenu:e=!0,enableDragDrop:t=!0,onNodeClick:a,onNodeDoubleClick:i}){const o=Se(J=>J.layoutData),d=Se(J=>J.selectComponent),g=Se(J=>J.moveComponent),h=Se(J=>J.selectedComponentId),[f,p]=j.useState(new Set),[y,x]=j.useState(null),[S,v]=j.useState(null),[w,k]=j.useState(null),[A,O]=j.useState({visible:!1,x:0,y:0,nodeId:null});Ke.useEffect(()=>{if(o){const J=new Set;o.components.forEach((ve,le)=>{if(typeof ve!="string"){const je=ve.id||`tree_${le}`;J.add(je)}}),p(J)}},[o?.layout_name]),Ke.useEffect(()=>{if(!h||!o)return;const J=Px(o.components,h);J&&J.length>0&&p(ve=>{const le=new Set(ve);return J.slice(0,-1).forEach(de=>le.add(de)),le})},[h,o]);const N=j.useCallback(J=>{p(ve=>{const le=new Set(ve);return le.has(J)?le.delete(J):le.add(J),le})},[]),D=j.useCallback(J=>{let ve=J;if(J.startsWith("tree_")){const le=J.substring(5);ve=`auto_path:${iE(le)}`}d(ve),a?.(ve)},[d,a]),$=j.useCallback(J=>{if(!e)return;J.preventDefault();const le=J.target.closest('[role="treeitem"]');if(le){const de=le.getAttribute("data-node-id");de&&O({visible:!0,x:J.clientX,y:J.clientY,nodeId:de})}},[e]),M=j.useCallback((J,ve)=>{x(ve),J.dataTransfer.effectAllowed="move",J.dataTransfer.setData("text/plain",ve),xi.log("Drag start:",ve)},[]),z=j.useCallback((J,ve)=>{if(y===ve)return;const le=J.target.getBoundingClientRect(),de=J.clientY-le.top,je=le.height;let W;deje*.75?W="after":W="inside",v(ve),k(W)},[y]),K=j.useCallback((J,ve,le)=>{y&&y!==ve&&(g(y,ve,le),xi.log("Dropped:",y,"to",ve,le)),x(null),v(null),k(null)},[y,g]),ye=j.useCallback(()=>{x(null),v(null),k(null)},[]),we=j.useCallback(()=>{O({visible:!1,x:0,y:0,nodeId:null})},[]);return o?l.jsxs("div",{className:`h-full overflow-auto bg-white dark:bg-gray-900 ${r}`,onContextMenu:$,role:"tree","aria-label":"레이아웃 트리",children:[l.jsxs("div",{className:"sticky top-0 bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700 px-3 py-2",children:[l.jsx("h3",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300",children:"레이아웃 트리"}),l.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:[o.layout_name,o.extends&&l.jsxs("span",{className:"ml-1 text-blue-500",children:["(extends: ",o.extends,")"]})]})]}),l.jsx("div",{className:"p-2",children:o.components.map((J,ve)=>{if(typeof J=="string")return null;const le=J,de=`${ve}`,je=le.id||`tree_${de}`;return l.jsx(dE,{component:le,depth:0,treePath:de,enableDragDrop:t,expandedNodes:f,onToggleExpand:N,onNodeClick:D,onNodeDoubleClick:i,onDragStart:M,onDragOver:z,onDrop:K,onDragEnd:ye,draggedNodeId:y,dropTargetId:S,dropPosition:w},je)})}),A.visible&&A.nodeId&&l.jsx(uE,{x:A.x,y:A.y,nodeId:A.nodeId,onClose:we})]}):l.jsx("div",{className:`flex items-center justify-center h-full text-gray-500 dark:text-gray-400 ${r}`,children:l.jsx("p",{children:"레이아웃을 로드하세요"})})}const mn=it("PreviewCanvas"),dh={desktop:{width:1920,label:"Desktop",icon:"🖥️"},tablet:{width:768,label:"Tablet",icon:"📱"},mobile:{width:375,label:"Mobile",icon:"📱"},custom:{width:0,label:"Custom",icon:"📐"}};function gE({currentDevice:r,customWidth:e,onDeviceChange:t,onCustomWidthChange:a}){const i=["desktop","tablet","mobile","custom"];return l.jsxs("div",{className:"flex items-center gap-2 p-2 bg-gray-100 dark:bg-gray-800 rounded-lg",children:[i.map(o=>{const d=dh[o],g=r===o;return l.jsxs("button",{className:`flex items-center gap-1 px-3 py-1.5 rounded text-sm transition-colors ${g?"bg-blue-500 text-white":"bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600"}`,onClick:()=>t(o),title:`${d.label} (${o==="custom"?e:d.width}px)`,children:[l.jsx("span",{children:d.icon}),l.jsx("span",{className:"hidden sm:inline",children:d.label})]},o)}),r==="custom"&&l.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[l.jsx("input",{type:"number",value:e,onChange:o=>a(parseInt(o.target.value,10)||320),min:320,max:2560,className:"w-20 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300"}),l.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:"px"})]})]})}function hE({zoom:r,onZoomChange:e}){const t=[25,50,75,100,125,150,200];return l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("button",{className:"p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700",onClick:()=>e(Math.max(25,r-25)),disabled:r<=25,title:"축소",children:"➖"}),l.jsx("select",{value:r,onChange:a=>e(parseInt(a.target.value,10)),className:"px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300",children:t.map(a=>l.jsxs("option",{value:a,children:[a,"%"]},a))}),l.jsx("button",{className:"p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700",onClick:()=>e(Math.min(200,r+25)),disabled:r>=200,title:"확대",children:"➕"}),l.jsx("button",{className:"p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700",onClick:()=>e(100),title:"100%로 리셋",children:"🔄"})]})}function fE({targetId:r,position:e,containerRef:t}){const[a,i]=j.useState(null);return j.useEffect(()=>{if(!r||!e||!t.current){i(null);return}const o=t.current,d=o.querySelector(`[data-editor-id="${r}"]`);if(d){const g=o.getBoundingClientRect(),h=o.scrollLeft,f=o.scrollTop,p=d.getBoundingClientRect();i(new DOMRect(p.left-g.left+h,p.top-g.top+f,p.width,p.height))}else i(null)},[r,e,t]),!a||!e?null:e==="before"?l.jsx("div",{className:"absolute h-1 bg-blue-500 rounded pointer-events-none z-50",style:{left:a.x,top:a.y-2,width:a.width}}):e==="after"?l.jsx("div",{className:"absolute h-1 bg-blue-500 rounded pointer-events-none z-50",style:{left:a.x,top:a.y+a.height,width:a.width}}):l.jsx("div",{className:"absolute border-2 border-dashed border-blue-500 rounded pointer-events-none z-50",style:{left:a.x,top:a.y,width:a.width,height:a.height}})}function Ux(r,e){return r.querySelector(`[data-editor-id="${e}"]`)}function pE({selectedId:r,hoveredId:e,containerRef:t,zoom:a}){const[i,o]=j.useState(null),[d,g]=j.useState(null);return j.useEffect(()=>{if(!t.current)return;const h=()=>{const k=t.current;if(!k)return;const A=k.getBoundingClientRect(),O=k.scrollLeft,N=k.scrollTop;if(r){const D=Ux(k,r);if(D){const $=D.getBoundingClientRect();o(new DOMRect($.left-A.left+O,$.top-A.top+N,$.width,$.height))}else o(null)}else o(null);if(e&&e!==r){const D=Ux(k,e);if(D){const $=D.getBoundingClientRect();g(new DOMRect($.left-A.left+O,$.top-A.top+N,$.width,$.height))}else g(null)}else g(null)};h();let f,p=null;const y=350,x=k=>{p===null&&(p=k);const A=k-p;h(),A{cancelAnimationFrame(f),S.disconnect(),w.disconnect(),v?.removeEventListener("scroll",h),window.removeEventListener("scroll",h,!0)}},[r,e,t,a]),l.jsxs(l.Fragment,{children:[i&&l.jsxs("div",{className:"absolute pointer-events-none border-2 border-blue-500",style:{left:i.x,top:i.y,width:i.width,height:i.height},children:[l.jsx("div",{className:"absolute -left-1 -top-1 w-2 h-2 bg-blue-500 rounded-full"}),l.jsx("div",{className:"absolute -right-1 -top-1 w-2 h-2 bg-blue-500 rounded-full"}),l.jsx("div",{className:"absolute -left-1 -bottom-1 w-2 h-2 bg-blue-500 rounded-full"}),l.jsx("div",{className:"absolute -right-1 -bottom-1 w-2 h-2 bg-blue-500 rounded-full"}),l.jsx("div",{className:"absolute -top-6 left-0 px-1 py-0.5 text-xs bg-blue-500 text-white rounded whitespace-nowrap",children:r})]}),d&&l.jsx("div",{className:"absolute pointer-events-none border border-dashed border-green-400",style:{left:d.x,top:d.y,width:d.width,height:d.height},children:l.jsx("div",{className:"absolute -top-5 left-0 px-1 py-0.5 text-xs bg-green-400 text-white rounded whitespace-nowrap opacity-80",children:e})})]})}function mE(){return l.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-gray-500 dark:text-gray-400",children:[l.jsx("div",{className:"text-6xl mb-4",children:"📄"}),l.jsx("h3",{className:"text-lg font-medium mb-2",children:"레이아웃이 없습니다"}),l.jsx("p",{className:"text-sm text-center max-w-xs",children:"편집할 레이아웃을 선택하거나, 새 레이아웃을 생성하세요."})]})}function yE(){return l.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-gray-500 dark:text-gray-400",children:[l.jsx("div",{className:"animate-spin text-4xl mb-4",children:"⏳"}),l.jsx("p",{className:"text-sm",children:"레이아웃 로딩 중..."})]})}function xE({message:r,onRetry:e}){return l.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-red-500 dark:text-red-400",children:[l.jsx("div",{className:"text-6xl mb-4",children:"⚠️"}),l.jsx("h3",{className:"text-lg font-medium mb-2",children:"오류 발생"}),l.jsx("p",{className:"text-sm text-center max-w-xs mb-4",children:r}),e&&l.jsx("button",{className:"px-4 py-2 bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300 rounded hover:bg-red-200 dark:hover:bg-red-800",onClick:e,children:"다시 시도"})]})}function bE({width:r,zoom:e,children:t}){const a=e/100,i=r*a;return l.jsxs("div",{className:"mx-auto bg-white dark:bg-gray-900 shadow-xl rounded-lg overflow-hidden transition-all duration-300",style:{width:i,transform:`scale(${a})`,transformOrigin:"top center"},children:[l.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-gray-100 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700",children:[l.jsxs("div",{className:"flex gap-1.5",children:[l.jsx("div",{className:"w-3 h-3 rounded-full bg-red-500"}),l.jsx("div",{className:"w-3 h-3 rounded-full bg-yellow-500"}),l.jsx("div",{className:"w-3 h-3 rounded-full bg-green-500"})]}),l.jsx("div",{className:"flex-1 mx-4",children:l.jsxs("div",{className:"px-3 py-1 text-xs bg-white dark:bg-gray-700 rounded text-gray-500 dark:text-gray-400 truncate",children:[window.location.origin,"/preview"]})})]}),l.jsx("div",{className:"min-h-96",children:t})]})}function uh({className:r="",showOverlay:e=!0,onComponentSelect:t,onComponentHover:a,onComponentDrop:i}){const o=j.useRef(null),d=Se(Ce=>Ce.layoutData),g=Se(Ce=>Ce.loadingState),h=Se(Ce=>Ce.error),f=Se(Ce=>Ce.previewDevice),p=Se(Ce=>Ce.customWidth),y=Se(Ce=>Ce.selectedComponentId),x=Se(Ce=>Ce.hoveredComponentId),S=Se(Ce=>Ce.setPreviewDevice),v=Se(Ce=>Ce.selectComponent),w=Se(Ce=>Ce.setHoveredComponentId),k=Se(Ce=>Ce.mockDataContext),A=Se(Ce=>Ce.templateId),O=Se(Ce=>Ce.moveComponent),N=Se(Ce=>Ce.startDrag),D=Se(Ce=>Ce.dragOver),$=Se(Ce=>Ce.endDrag),M=Se(Ce=>Ce.dropTargetId),z=Se(Ce=>Ce.dropPosition),K=Se(Ce=>Ce.ensureComponentIdAndMove),ye=Se(Ce=>Ce.moveComponentByPaths),[we,J]=j.useState(100),[ve,le]=j.useState(!1),de=j.useRef(null),je=50,W=8,he=j.useRef(null),ee=j.useRef(null),X=j.useRef(null),ae=j.useRef(null),R=j.useMemo(()=>({templateId:A||"sirsoft-basic",locale:"ko"}),[A]),U=j.useMemo(()=>({_global:{sidebarOpen:!1,...k?._global||{}},_local:{...k?._local||{}},$locale:"ko",$templateId:A||"sirsoft-basic",route:{},query:{},...k||{}}),[k,A]);j.useEffect(()=>{(async()=>{try{he.current||(he.current=ba.getInstance(),A&&await he.current.loadComponents(A,"user")),ee.current||(ee.current=new _n),X.current||(X.current=xr.getInstance()),!ae.current&&X.current&&(ae.current=new So({},X.current,R)),le(!0),mn.log("Editor engines initialized")}catch(Ge){mn.error("Failed to initialize engines:",Ge)}})()},[A,R]);const re=j.useCallback((Ce,Ge)=>{if(Ge.stopPropagation(),Ce.startsWith("auto_")){const bt=Ge.target.closest("[data-editor-path]")?.getAttribute("data-editor-path");if(bt){const _t=`auto_path:${bt}`;v(_t),t?.(_t),mn.log("Component selected via DynamicRenderer:",Ce,"-> path:",bt);return}}v(Ce),t?.(Ce),mn.log("Component selected via DynamicRenderer:",Ce)},[v,t]),xe=j.useCallback((Ce,Ge)=>{mn.log("handleDynamicHover called:",Ce),w(Ce),a?.(Ce)},[w,a]),oe=j.useCallback((Ce,Ge)=>{if(!d){Ge.dataTransfer.effectAllowed="none";return}if(Ce.startsWith("auto_")){const mt=Ge.target.closest("[data-editor-path]")?.getAttribute("data-editor-path");if(mt){const tt=ih(d.components,mt);if(tt){N(tt),Ge.dataTransfer.effectAllowed="move",Ge.dataTransfer.setData("text/plain",`path:${mt}`),mn.log("Drag started (path-based):",mt);return}}mn.warn("Auto-generated component without valid path:",Ce),Ge.dataTransfer.effectAllowed="none";return}const at=(bt,_t)=>{for(const mt of bt){if(typeof mt=="string")continue;const tt=mt;if(tt.id===_t)return tt;if(tt.children){const bn=at(tt.children,_t);if(bn)return bn}}return null},pt=at(d.components,Ce);pt?(N(pt),Ge.dataTransfer.effectAllowed="move",Ge.dataTransfer.setData("text/plain",Ce),mn.log("Drag started (id-based):",Ce)):(mn.warn("Component not found for drag:",Ce),Ge.dataTransfer.effectAllowed="none")},[d,N]),ke=j.useCallback(Ce=>{de.current&&(cancelAnimationFrame(de.current),de.current=null),$(),mn.log("Drag ended")},[$]),Oe=j.useMemo(()=>f==="custom"?p:dh[f].width,[f,p]),Te=j.useCallback(Ce=>{S(Ce),mn.log("Device changed:",Ce)},[S]),qe=j.useCallback(Ce=>{S("custom",Ce),mn.log("Custom width changed:",Ce)},[S]),Ie=j.useCallback(Ce=>{const Ge=Ce.target;let at=null;if(Ge.hasAttribute("data-editor-id")?at=Ge:at=Ge.closest("[data-editor-id]"),at){const pt=at.getAttribute("data-editor-id");pt&&(v(pt),t?.(pt),mn.log("Component selected:",pt))}else v(null),t?.(null)},[v,t]),Nt=j.useCallback(Ce=>{const Ge=Ce.target;let at=null;if(Ge.hasAttribute("data-editor-id")?at=Ge:at=Ge.closest("[data-editor-id]"),at){const pt=at.getAttribute("data-editor-id");pt&&pt!==x&&(w(pt),a?.(pt))}},[x,w,a]),Rt=j.useCallback(()=>{w(null),a?.(null)},[w,a]),Xt=j.useCallback(Ce=>{Ce.preventDefault();const Ge=Ce.dataTransfer.getData("text/plain"),pt=Ce.target.closest("[data-editor-id]");if(pt&&Ge){let bt=pt.getAttribute("data-editor-id");const _t=pt.getAttribute("data-editor-path");if(bt?.startsWith("auto_")&&_t&&d?.components){const dn=d.components,Ta=ih(dn,_t);Ta?.id?bt=Ta.id:mn.log("Target is auto ID, will use path-based move")}const mt=pt.getBoundingClientRect(),tt=Ce.clientY-mt.top,bn=mt.height;let wt;ttbn*.75?wt="after":wt="inside";const Tt=Ge.startsWith("path:"),qt=Tt?Ge.substring(5):null,Yn=bt?.startsWith("auto_");Tt&&_t&&Yn?(mn.log("Both source and target are path-based:",qt,"->",_t),qt&&_t&&qt!==_t&&ye(qt,_t,wt)&&(i?.(bt||"",wt),mn.log("Component moved (both path-based):",qt,"->",_t,wt))):Tt&&bt&&!Yn?qt&&K(qt,bt,wt)&&(i?.(bt,wt),mn.log("Component moved (source path, target id):",qt,"->",bt,wt)):!Tt&&bt&&Ge!==bt&&(O(Ge,bt,wt),i?.(bt,wt),mn.log("Component moved (id-based):",Ge,"->",bt,wt))}$()},[d,O,$,i,K,ye]),Mt=j.useCallback((Ce,Ge)=>{if(de.current)return;const at=()=>{Ce.scrollTop+=Ge,de.current=requestAnimationFrame(at)};de.current=requestAnimationFrame(at)},[]),Qt=j.useCallback(()=>{de.current&&(cancelAnimationFrame(de.current),de.current=null)},[]),Et=j.useCallback(Ce=>{Ce.preventDefault(),Ce.dataTransfer.dropEffect="move";const Ge=o.current;if(!Ge)return;const at=Ge.getBoundingClientRect(),pt=Ce.clientY;pt-at.topwt*.75?Tt="after":Tt="inside",D(mt,Tt)}}},[D,Mt,Qt,je,W]),Tn=()=>g==="loading"?l.jsx(yE,{}):h?l.jsx(xE,{message:h}):d?!ve||!he.current||!ee.current||!X.current||!ae.current?l.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-gray-500 dark:text-gray-400",children:[l.jsx("div",{className:"animate-spin text-4xl mb-4",children:"⏳"}),l.jsx("p",{className:"text-sm",children:"렌더링 엔진 초기화 중..."})]}):l.jsx(Rc,{translationEngine:X.current,translationContext:R,children:l.jsx(ug,{children:l.jsx(gg,{overrideWidth:Oe,children:l.jsx(Og,{children:d.components.map((Ce,Ge)=>{if(typeof Ce=="string")return null;const at=Ce;return l.jsx(Ua,{componentDef:at,dataContext:U,translationContext:R,onDragStart:oe,onDragEnd:ke,registry:he.current,bindingEngine:ee.current,translationEngine:X.current,actionDispatcher:ae.current,isEditMode:!0,onComponentSelect:re,onComponentHover:xe,isRootRenderer:!0,componentPath:`${Ge}`},at.id||`component-${Ge}`)})})})})}):l.jsx(mE,{});return l.jsxs("div",{className:`flex flex-col h-full bg-gray-50 dark:bg-gray-950 ${r}`,children:[l.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-200 dark:border-gray-800",children:[l.jsx(gE,{currentDevice:f,customWidth:p,onDeviceChange:Te,onCustomWidthChange:qe}),l.jsx(hE,{zoom:we,onZoomChange:J})]}),l.jsxs("div",{ref:o,className:"flex-1 overflow-auto p-8 relative",onClick:Ie,onMouseMove:Nt,onMouseLeave:Rt,onDrop:Xt,onDragOver:Et,children:[l.jsx(bE,{width:Oe,zoom:we,children:Tn()}),e&&d&&l.jsx(pE,{selectedId:y,hoveredId:x,containerRef:o,zoom:we}),M&&l.jsx(fE,{targetId:M,position:z,containerRef:o})]}),l.jsxs("div",{className:"flex items-center justify-between px-4 py-1 text-xs border-t border-gray-200 dark:border-gray-800 bg-gray-100 dark:bg-gray-900 text-gray-500 dark:text-gray-400",children:[l.jsxs("div",{className:"flex items-center gap-4",children:[l.jsxs("span",{children:[f==="custom"?p:dh[f].width,"px"]}),l.jsxs("span",{children:["Zoom: ",we,"%"]})]}),l.jsxs("div",{className:"flex items-center gap-4",children:[y&&l.jsxs("span",{children:["선택됨: ",l.jsx("span",{className:"text-blue-500",children:y})]}),d&&l.jsxs("span",{children:[d.components.length,"개 컴포넌트"]})]})]})]})}const qx={Div:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}],Span:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}],Button:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"type",type:"select",label:"버튼 타입",options:[{label:"Button",value:"button"},{label:"Submit",value:"submit"},{label:"Reset",value:"reset"}]},{name:"disabled",type:"boolean",label:"비활성화",allowBinding:!0}],Input:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"type",type:"select",label:"입력 타입",options:[{label:"Text",value:"text"},{label:"Password",value:"password"},{label:"Email",value:"email"},{label:"Number",value:"number"},{label:"Tel",value:"tel"},{label:"Date",value:"date"},{label:"Hidden",value:"hidden"}]},{name:"name",type:"text",label:"Name",required:!0},{name:"placeholder",type:"text",label:"Placeholder",allowBinding:!0},{name:"disabled",type:"boolean",label:"비활성화",allowBinding:!0},{name:"required",type:"boolean",label:"필수"}],Label:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"htmlFor",type:"text",label:"For (ID)"}],Image:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"src",type:"text",label:"이미지 URL",required:!0,allowBinding:!0},{name:"alt",type:"text",label:"대체 텍스트",allowBinding:!0}],Link:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"href",type:"text",label:"URL",allowBinding:!0},{name:"target",type:"select",label:"열기 방식",options:[{label:"현재 창",value:"_self"},{label:"새 창",value:"_blank"}]}],Icon:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"name",type:"icon",label:"아이콘 이름",required:!0},{name:"size",type:"select",label:"크기",options:[{label:"xs",value:"xs"},{label:"sm",value:"sm"},{label:"md",value:"md"},{label:"lg",value:"lg"},{label:"xl",value:"xl"}]}],H1:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}],H2:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}],H3:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}],H4:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}],H5:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}],H6:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}],P:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}],Form:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"dataKey",type:"text",label:"데이터 키",required:!0}],Select:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"name",type:"text",label:"Name",required:!0},{name:"placeholder",type:"text",label:"Placeholder"},{name:"disabled",type:"boolean",label:"비활성화",allowBinding:!0}],Textarea:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"name",type:"text",label:"Name",required:!0},{name:"placeholder",type:"text",label:"Placeholder",allowBinding:!0},{name:"rows",type:"number",label:"행 수",defaultValue:3},{name:"disabled",type:"boolean",label:"비활성화",allowBinding:!0}],Card:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"title",type:"text",label:"제목",allowBinding:!0}],Modal:[{name:"id",type:"text",label:"모달 ID",required:!0},{name:"title",type:"text",label:"제목",allowBinding:!0},{name:"size",type:"select",label:"크기",options:[{label:"Small",value:"sm"},{label:"Medium",value:"md"},{label:"Large",value:"lg"},{label:"XLarge",value:"xl"},{label:"Full",value:"full"}]}],DataGrid:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"columns",type:"array",label:"컬럼 정의",required:!0},{name:"data",type:"expression",label:"데이터",required:!0,allowBinding:!0},{name:"rowKey",type:"text",label:"행 키",defaultValue:"id"}],PageHeader:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"title",type:"text",label:"제목",allowBinding:!0},{name:"description",type:"text",label:"설명",allowBinding:!0}],Pagination:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"current",type:"expression",label:"현재 페이지",allowBinding:!0},{name:"total",type:"expression",label:"전체 항목 수",allowBinding:!0},{name:"perPage",type:"number",label:"페이지당 항목 수",defaultValue:10}],Tabs:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"defaultTab",type:"text",label:"기본 탭"}],Tab:[{name:"id",type:"text",label:"탭 ID",required:!0},{name:"label",type:"text",label:"탭 레이블",required:!0,allowBinding:!0}],Alert:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"type",type:"select",label:"타입",options:[{label:"Info",value:"info"},{label:"Success",value:"success"},{label:"Warning",value:"warning"},{label:"Error",value:"error"}]},{name:"dismissible",type:"boolean",label:"닫기 가능"}],Container:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"maxWidth",type:"select",label:"최대 너비",options:[{label:"sm",value:"sm"},{label:"md",value:"md"},{label:"lg",value:"lg"},{label:"xl",value:"xl"},{label:"2xl",value:"2xl"},{label:"Full",value:"full"}]}],Grid:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"cols",type:"number",label:"컬럼 수",defaultValue:1},{name:"gap",type:"number",label:"간격",defaultValue:4}],Flex:[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0},{name:"direction",type:"select",label:"방향",options:[{label:"Row",value:"row"},{label:"Column",value:"col"},{label:"Row Reverse",value:"row-reverse"},{label:"Column Reverse",value:"col-reverse"}]},{name:"justify",type:"select",label:"주축 정렬",options:[{label:"Start",value:"start"},{label:"Center",value:"center"},{label:"End",value:"end"},{label:"Between",value:"between"},{label:"Around",value:"around"},{label:"Evenly",value:"evenly"}]},{name:"align",type:"select",label:"교차축 정렬",options:[{label:"Start",value:"start"},{label:"Center",value:"center"},{label:"End",value:"end"},{label:"Stretch",value:"stretch"},{label:"Baseline",value:"baseline"}]},{name:"gap",type:"number",label:"간격",defaultValue:0}]};function Ko(){const r=Se(y=>y.componentCategories),e=Se(y=>y.handlers),t=j.useMemo(()=>r?[...r.basic,...r.composite,...r.layout]:[],[r]),a=j.useMemo(()=>r?.extension||[],[r]),i=j.useCallback(y=>t.find(x=>x.name===y)||null,[t]),o=j.useCallback(y=>{if(qx[y])return qx[y];const x=i(y);return x?.props?x.props.map(S=>({name:S,type:"text",label:S,allowBinding:!0})):[{name:"className",type:"className",label:"CSS 클래스",allowBinding:!0}]},[i]),d=j.useCallback(y=>{const x=y.toLowerCase(),S=t.filter(w=>w.name.toLowerCase().includes(x)||w.description?.toLowerCase().includes(x)),v=a.filter(w=>w.name.toLowerCase().includes(x)||w.description?.toLowerCase().includes(x)||w.source.toLowerCase().includes(x));return[...S,...v]},[t,a]),g=j.useCallback(y=>r?y==="extension"?r.extension:r[y]:[],[r]),h=j.useCallback(y=>{const x=i(y);return x?.allowsChildren!==void 0?x.allowsChildren:x?.type==="layout"||x?.type==="composite"?!0:["Div","Span","Button","Form","Label","Link"].includes(y)},[i]),f=j.useCallback(y=>e.find(x=>x.name===y)||null,[e]),p=j.useCallback(y=>e.filter(x=>x.category===y),[e]);return{categories:r,allComponents:t,extensionComponents:a,handlers:e,getMetadata:i,getPropsSchema:o,searchComponents:d,filterByCategory:g,allowsChildren:h,getHandler:f,filterHandlersByCategory:p}}const Gx=it("PropsEditor");function Fx({schema:r,value:e,onChange:t}){const[a,i]=j.useState(typeof e=="string"&&e.includes("{{")),o=j.useCallback(h=>{t(h.target.value)},[t]),d=r.type==="textarea",g=typeof e=="string"?e:"";return l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between mb-1",children:[l.jsxs("label",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:[r.label||r.name,r.required&&l.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),l.jsx("button",{type:"button",className:`text-xs px-1.5 py-0.5 rounded ${a?"bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300":"text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800"}`,onClick:()=>i(!a),title:"바인딩 표현식 사용",children:"{{}}"})]}),d?l.jsx("textarea",{value:g,onChange:o,placeholder:r.placeholder||`${r.name} 입력`,rows:3,className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 resize-none"}):l.jsx("input",{type:"text",value:g,onChange:o,placeholder:r.placeholder||`${r.name} 입력`,className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"}),r.description&&l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:r.description}),a&&l.jsxs("p",{className:"mt-1 text-xs text-blue-600 dark:text-blue-400",children:["바인딩 예시: ","{{users.data[0].name}}"]})]})}function vE({schema:r,value:e,onChange:t}){const a=j.useCallback(o=>{const d=parseFloat(o.target.value);t(isNaN(d)?void 0:d)},[t]),i=typeof e=="number"?e:"";return l.jsxs("div",{children:[l.jsxs("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:[r.label||r.name,r.required&&l.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),l.jsx("input",{type:"number",value:i,onChange:a,placeholder:r.placeholder||"0",min:r.min,max:r.max,step:r.step||1,className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"}),r.description&&l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:r.description})]})}function wE({schema:r,value:e,onChange:t}){const a=j.useCallback(o=>{t(o.target.checked)},[t]),i=!!e;return l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx("input",{type:"checkbox",id:`prop-${r.name}`,checked:i,onChange:a,className:"mt-0.5 w-4 h-4 text-blue-600 border-gray-300 dark:border-gray-600 rounded focus:ring-blue-500"}),l.jsxs("div",{children:[l.jsx("label",{htmlFor:`prop-${r.name}`,className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:r.label||r.name}),r.description&&l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:r.description})]})]})}function SE({schema:r,value:e,onChange:t}){const a=j.useCallback(d=>{t(d.target.value||void 0)},[t]),i=typeof e=="string"?e:"",o=r.options||[];return l.jsxs("div",{children:[l.jsxs("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:[r.label||r.name,r.required&&l.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),l.jsxs("select",{value:i,onChange:a,className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white",children:[l.jsx("option",{value:"",children:"선택하세요"}),o.map(d=>l.jsx("option",{value:d.value,children:d.label},d.value))]}),r.description&&l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:r.description})]})}function CE({schema:r,value:e,onChange:t}){const a=j.useCallback(o=>{t(o.target.value)},[t]),i=typeof e=="string"?e:"#000000";return l.jsxs("div",{children:[l.jsxs("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:[r.label||r.name,r.required&&l.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("input",{type:"color",value:i,onChange:a,className:"w-10 h-10 p-0 border border-gray-300 dark:border-gray-600 rounded cursor-pointer"}),l.jsx("input",{type:"text",value:i,onChange:a,placeholder:"#000000",className:"flex-1 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white font-mono"})]}),r.description&&l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:r.description})]})}function jE({schema:r,value:e,onChange:t}){const a=j.useCallback(d=>{t(d.target.value)},[t]),i=typeof e=="string"?e:"",o=i.split(/\s+/).filter(Boolean);return l.jsxs("div",{children:[l.jsxs("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:[r.label||r.name,r.required&&l.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),l.jsx("textarea",{value:i,onChange:a,placeholder:"space-y-4 p-4 bg-white dark:bg-gray-800",rows:3,className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 font-mono resize-none"}),o.length>0&&l.jsxs("div",{className:"mt-2 flex flex-wrap gap-1",children:[o.slice(0,10).map((d,g)=>l.jsx("span",{className:"px-1.5 py-0.5 text-xs bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded",children:d},g)),o.length>10&&l.jsxs("span",{className:"px-1.5 py-0.5 text-xs text-gray-500 dark:text-gray-400",children:["+",o.length-10,"개 더"]})]}),r.description&&l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:r.description})]})}function kE({schema:r,value:e,onChange:t}){j.useCallback(i=>{t(i.target.value)},[t]);const a=typeof e=="string"?e:"";return l.jsxs("div",{children:[l.jsxs("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:[r.label||r.name,r.required&&l.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),l.jsxs("div",{className:"relative",children:[l.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 text-sm",children:"{{"}),l.jsx("input",{type:"text",value:a.replace(/^\{\{|\}\}$/g,""),onChange:i=>t(`{{${i.target.value}}}`),placeholder:"expression",className:"w-full pl-8 pr-8 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 font-mono"}),l.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 text-sm",children:"}}"})]}),r.description&&l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:r.description})]})}function Vx({schema:r,value:e,onChange:t}){const[a,i]=j.useState(null),o=j.useCallback(g=>{const h=g.target.value;try{const f=JSON.parse(h);t(f),i(null)}catch{i("유효한 JSON이 아닙니다")}},[t]),d=j.useMemo(()=>{try{return JSON.stringify(e,null,2)}catch{return""}},[e]);return l.jsxs("div",{children:[l.jsxs("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:[r.label||r.name,r.required&&l.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),l.jsx("textarea",{value:d,onChange:o,placeholder:"{}",rows:4,className:`w-full px-3 py-2 text-sm border rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 font-mono resize-none ${a?"border-red-500 dark:border-red-400":"border-gray-300 dark:border-gray-600"}`}),a&&l.jsx("p",{className:"mt-1 text-xs text-red-500 dark:text-red-400",children:a}),r.description&&!a&&l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:r.description})]})}function NE(r,e,t){const a={schema:r,value:e,onChange:t};switch(r.type){case"text":case"textarea":return l.jsx(Fx,{...a});case"number":return l.jsx(vE,{...a});case"boolean":return l.jsx(wE,{...a});case"select":return l.jsx(SE,{...a});case"color":return l.jsx(CE,{...a});case"className":return l.jsx(jE,{...a});case"expression":return l.jsx(kE,{...a});case"object":return l.jsx(Vx,{...a});default:return l.jsx(Fx,{...a})}}function Kx({component:r,onChange:e}){const{getPropsSchema:t}=Ko(),a=j.useMemo(()=>t(r.name),[r.name,t]),i=r.props||{},o=j.useCallback((g,h)=>{const f={...i,[g]:h};(h===void 0||h==="")&&delete f[g],e({props:f}),Gx.log("Prop changed:",g,h)},[i,e]),d=j.useCallback(g=>{e({text:g||void 0}),Gx.log("Text changed:",g)},[e]);return l.jsxs("div",{className:"p-4 space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"텍스트 (text)"}),l.jsx("input",{type:"text",value:r.text||"",onChange:g=>d(g.target.value),placeholder:"컴포넌트 텍스트 내용",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"}),l.jsxs("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:["$t:key 또는 ","{{expression}}"," 사용 가능"]})]}),l.jsx("hr",{className:"border-gray-200 dark:border-gray-700"}),a.length>0?a.map(g=>l.jsx("div",{children:NE(g,i[g.name],h=>o(g.name,h))},g.name)):l.jsxs("div",{className:"text-center py-4 text-gray-400 dark:text-gray-500",children:[l.jsx("p",{className:"text-sm",children:"이 컴포넌트의 props 스키마가 정의되지 않았습니다."}),l.jsx("p",{className:"text-xs mt-1",children:"Raw JSON으로 편집하세요."})]}),l.jsx("hr",{className:"border-gray-200 dark:border-gray-700"}),l.jsxs("div",{children:[l.jsx("h4",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-2",children:"모든 Props (Raw JSON)"}),l.jsx(Vx,{schema:{name:"props",type:"object",label:"Props",description:"컴포넌트의 모든 속성을 JSON으로 직접 편집"},value:i,onChange:g=>{typeof g=="object"&&g!==null&&e({props:g})}})]})]})}function gh(r){const e=r.match(/\{\{(.+?)\}\}/);return e?e[1].trim():null}function dd(r){return typeof r=="string"&&r.includes("{{")}function hh(r){return`{{${r}}}`}function EE({sources:r,selectedPath:e,onSelect:t}){const[a,i]=j.useState(null);return l.jsx("div",{className:"space-y-2",children:r.map(o=>l.jsxs("div",{className:"border border-gray-200 dark:border-gray-700 rounded",children:[l.jsxs("button",{className:"w-full flex items-center gap-2 px-3 py-2 text-sm hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",onClick:()=>i(a===o.id?null:o.id),children:[l.jsx("span",{children:o.icon}),l.jsx("span",{className:"flex-1 text-left font-medium text-gray-700 dark:text-gray-300",children:o.label}),l.jsx("span",{className:"text-gray-400",children:a===o.id?"▼":"▶"})]}),a===o.id&&l.jsx("div",{className:"border-t border-gray-200 dark:border-gray-700 max-h-40 overflow-auto",children:o.paths.length>0?o.paths.map(d=>{const g=o.type==="dataSource"?`${o.id}.${d}`:d,h=e===g;return l.jsx("button",{className:`w-full px-4 py-1.5 text-xs text-left hover:bg-gray-100 dark:hover:bg-gray-700 ${h?"bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400":"text-gray-600 dark:text-gray-400"}`,onClick:()=>t(g),children:l.jsx("code",{className:"font-mono",children:d})},d)}):l.jsx("div",{className:"px-4 py-2 text-xs text-gray-400 dark:text-gray-500",children:"사용 가능한 경로가 없습니다"})})]},o.id))})}function _E({isOpen:r,propKey:e,currentValue:t,sources:a,onSave:i,onCancel:o}){const[d,g]=j.useState("simple"),[h,f]=j.useState(()=>gh(t)||""),[p,y]=j.useState(()=>gh(t)||""),x=j.useCallback(()=>{const v=d==="simple"?h:p;i(v?hh(v):"")},[d,h,p,i]),S=j.useCallback(v=>{f(v),y(v)},[]);return r?l.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:l.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-lg mx-4",children:[l.jsx("div",{className:"px-4 py-3 border-b border-gray-200 dark:border-gray-700",children:l.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:["바인딩 편집: ",e]})}),l.jsx("div",{className:"px-4 py-3 border-b border-gray-200 dark:border-gray-700",children:l.jsxs("div",{className:"flex gap-2",children:[l.jsx("button",{className:`px-3 py-1.5 text-sm rounded ${d==="simple"?"bg-blue-500 text-white":"bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300"}`,onClick:()=>g("simple"),children:"단순 모드"}),l.jsx("button",{className:`px-3 py-1.5 text-sm rounded ${d==="advanced"?"bg-blue-500 text-white":"bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300"}`,onClick:()=>g("advanced"),children:"고급 모드"})]})}),l.jsx("div",{className:"p-4 max-h-96 overflow-auto",children:d==="simple"?l.jsxs("div",{className:"space-y-4",children:[l.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"바인딩할 데이터 소스를 선택하세요:"}),l.jsx(EE,{sources:a,selectedPath:h,onSelect:S}),h&&l.jsxs("div",{className:"mt-4 p-3 bg-gray-50 dark:bg-gray-900 rounded",children:[l.jsx("label",{className:"text-xs text-gray-500 dark:text-gray-400",children:"미리보기:"}),l.jsx("code",{className:"block mt-1 text-sm text-blue-600 dark:text-blue-400 font-mono",children:hh(h)})]})]}):l.jsxs("div",{className:"space-y-4",children:[l.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"표현식을 직접 입력하세요:"}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs text-gray-500 dark:text-gray-400 mb-1",children:"표현식 (중괄호 없이)"}),l.jsx("input",{type:"text",value:p,onChange:v=>y(v.target.value),placeholder:"users?.data?.total ?? 0",className:"w-full px-3 py-2 text-sm font-mono border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"})]}),l.jsxs("div",{className:"text-xs text-gray-500 dark:text-gray-400 space-y-1",children:[l.jsx("p",{children:"지원되는 문법:"}),l.jsxs("ul",{className:"list-disc list-inside ml-2",children:[l.jsxs("li",{children:["Optional Chaining: ",l.jsx("code",{children:"users?.data"})]}),l.jsxs("li",{children:["Nullish Coalescing: ",l.jsx("code",{children:"value ?? 'default'"})]}),l.jsxs("li",{children:["삼항 연산자: ",l.jsx("code",{children:"condition ? a : b"})]})]})]}),p&&l.jsxs("div",{className:"mt-4 p-3 bg-gray-50 dark:bg-gray-900 rounded",children:[l.jsx("label",{className:"text-xs text-gray-500 dark:text-gray-400",children:"미리보기:"}),l.jsx("code",{className:"block mt-1 text-sm text-blue-600 dark:text-blue-400 font-mono",children:hh(p)})]})]})}),l.jsxs("div",{className:"px-4 py-3 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-2",children:[l.jsx("button",{className:"px-4 py-2 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:o,children:"취소"}),l.jsx("button",{className:"px-4 py-2 text-sm bg-blue-500 text-white rounded hover:bg-blue-600",onClick:x,children:"적용"})]})]})}):null}function AE({binding:r,onEdit:e,onRemove:t}){const a=gh(r.value);return l.jsx("div",{className:"p-3 bg-gray-50 dark:bg-gray-800 rounded border border-gray-200 dark:border-gray-700 group",children:l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:r.key}),l.jsx("span",{className:"text-xs px-1.5 py-0.5 bg-gray-200 dark:bg-gray-700 text-gray-500 dark:text-gray-400 rounded",children:r.type})]}),l.jsx("code",{className:"block mt-1 text-xs text-blue-600 dark:text-blue-400 font-mono truncate",children:r.value}),a&&l.jsxs("div",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:["경로: ",l.jsx("code",{className:"font-mono",children:a})]})]}),l.jsxs("div",{className:"flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[l.jsx("button",{className:"p-1 text-gray-400 hover:text-blue-500",onClick:e,title:"편집",children:"✏️"}),l.jsx("button",{className:"p-1 text-gray-400 hover:text-red-500",onClick:t,title:"바인딩 제거",children:"🗑️"})]})]})})}function TE({component:r,onChange:e}){const[t,a]=j.useState(null),[i,o]=j.useState(!1),[d,g]=j.useState(""),h=Se(N=>N.layoutData),f=Se(N=>N.mockDataContext),p=j.useMemo(()=>h?{dataSources:h.data_sources||[],globalState:Object.keys(f._global||{}),localState:Object.keys(f._local||{}),routeParams:["id","slug"],queryParams:["page","per_page","search","sort","order"],defines:h.defines||{},computed:h.computed||{}}:{dataSources:[],globalState:[],localState:[],routeParams:["id","slug"],queryParams:["page","per_page","search","sort","order"],defines:{},computed:{}},[h,f]),{getMetadata:y}=Ko(),x=y(r.name),S=j.useMemo(()=>{const N=[];return r.props&&Object.entries(r.props).forEach(([D,$])=>{dd($)&&N.push({key:D,value:$,type:"prop"})}),r.text&&dd(r.text)&&N.push({key:"text",value:r.text,type:"text"}),r.if&&dd(r.if)&&N.push({key:"if",value:r.if,type:"if"}),r.iteration?.source&&dd(r.iteration.source)&&N.push({key:"iteration.source",value:r.iteration.source,type:"iteration"}),N},[r]),v=j.useMemo(()=>{const N=new Set(S.filter($=>$.type==="prop").map($=>$.key));return(x?.props?Object.keys(x.props):[]).filter($=>!N.has($))},[S,x]),w=j.useMemo(()=>{const N=[];return p.dataSources.forEach(D=>{N.push({id:D.id,label:D.id,icon:"📡",type:"dataSource",paths:["data","loading","error","data.items","data.total","data.per_page"]})}),p.globalState.length>0&&N.push({id:"_global",label:"Global State",icon:"🌐",type:"global",paths:p.globalState.map(D=>`_global.${D}`)}),p.localState.length>0&&N.push({id:"_local",label:"Local State",icon:"📍",type:"local",paths:p.localState.map(D=>`_local.${D}`)}),N.push({id:"route",label:"Route Params",icon:"🛤️",type:"route",paths:p.routeParams.map(D=>`route.${D}`)}),N.push({id:"query",label:"Query Params",icon:"❓",type:"query",paths:p.queryParams.map(D=>`query.${D}`)}),Object.keys(p.defines).length>0&&N.push({id:"defines",label:"Defines",icon:"📝",type:"defines",paths:Object.keys(p.defines).map(D=>`defines.${D}`)}),Object.keys(p.computed).length>0&&N.push({id:"computed",label:"Computed",icon:"⚡",type:"computed",paths:Object.keys(p.computed).map(D=>`computed.${D}`)}),N},[p]),k=j.useCallback((N,D)=>{const $={};N==="text"?$.text=D||void 0:N==="if"?$.if=D||void 0:N==="iteration.source"?$.iteration=D?{...r.iteration,source:D,item_var:r.iteration?.item_var||"item"}:void 0:($.props={...r.props,[N]:D||void 0},!D&&$.props&&delete $.props[N]),e($),a(null),o(!1),g("")},[r,e]),A=j.useCallback(N=>{k(N.key,"")},[k]),O=j.useCallback(()=>{d&&(a(d),o(!1))},[d]);return l.jsxs("div",{className:"p-4 space-y-4",children:[l.jsxs("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:[l.jsx("p",{children:"데이터 바인딩을 설정하여 동적 데이터를 컴포넌트에 연결합니다."}),l.jsxs("p",{className:"mt-1 text-xs",children:["문법: ",l.jsx("code",{className:"bg-gray-100 dark:bg-gray-700 px-1 rounded",children:"{{expression}}"})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("h4",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase",children:["현재 바인딩 (",S.length,")"]}),l.jsx("button",{className:"text-xs text-blue-500 hover:text-blue-600",onClick:()=>o(!0),children:"+ 바인딩 추가"})]}),S.length>0?l.jsx("div",{className:"space-y-2",children:S.map(N=>l.jsx(AE,{binding:N,onEdit:()=>a(N.key),onRemove:()=>A(N)},`${N.type}-${N.key}`))}):l.jsx("div",{className:"text-center py-8 text-gray-400 dark:text-gray-500",children:l.jsx("p",{children:"설정된 바인딩이 없습니다"})})]}),i&&l.jsxs("div",{className:"p-3 border border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-900/20 rounded",children:[l.jsx("label",{className:"block text-xs text-gray-700 dark:text-gray-300 mb-2",children:"바인딩할 속성 선택"}),l.jsxs("div",{className:"flex gap-2",children:[l.jsxs("select",{value:d,onChange:N=>g(N.target.value),className:"flex-1 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white",children:[l.jsx("option",{value:"",children:"속성 선택..."}),l.jsx("option",{value:"text",children:"text (텍스트)"}),l.jsx("option",{value:"if",children:"if (조건부 렌더링)"}),l.jsx("option",{value:"iteration.source",children:"iteration.source (반복 소스)"}),v.map(N=>l.jsx("option",{value:N,children:N},N))]}),l.jsx("button",{className:"px-3 py-2 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",onClick:O,disabled:!d,children:"다음"}),l.jsx("button",{className:"px-3 py-2 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:()=>{o(!1),g("")},children:"취소"})]})]}),l.jsx(_E,{isOpen:t!==null,propKey:t||"",currentValue:t&&S.find(N=>N.key===t)?.value||"",sources:w,onSave:N=>t&&k(t,N),onCancel:()=>a(null)})]})}const DE=[{value:"navigate",label:"navigate",description:"페이지 이동"},{value:"navigateBack",label:"navigateBack",description:"브라우저 뒤로가기"},{value:"navigateForward",label:"navigateForward",description:"브라우저 앞으로가기"},{value:"apiCall",label:"apiCall",description:"API 호출"},{value:"login",label:"login",description:"로그인 (토큰 저장)"},{value:"logout",label:"logout",description:"로그아웃"},{value:"setState",label:"setState",description:"상태 변경"},{value:"setError",label:"setError",description:"에러 상태 설정"},{value:"openModal",label:"openModal",description:"모달 열기"},{value:"closeModal",label:"closeModal",description:"모달 닫기"},{value:"showAlert",label:"showAlert",description:"알림 표시"},{value:"toast",label:"toast",description:"토스트 알림"},{value:"switch",label:"switch",description:"조건 분기"},{value:"sequence",label:"sequence",description:"순차 실행"},{value:"parallel",label:"parallel",description:"병렬 실행"},{value:"showErrorPage",label:"showErrorPage",description:"에러 페이지 표시"},{value:"loadScript",label:"loadScript",description:"외부 스크립트 로드"},{value:"callExternal",label:"callExternal",description:"외부 함수 호출"},{value:"callExternalEmbed",label:"callExternalEmbed",description:"외부 임베드"},{value:"saveToLocalStorage",label:"saveToLocalStorage",description:"로컬스토리지 저장"},{value:"loadFromLocalStorage",label:"loadFromLocalStorage",description:"로컬스토리지 로드"},{value:"appendDataSource",label:"appendDataSource",description:"데이터소스 병합 (무한스크롤용)"},{value:"scrollIntoView",label:"scrollIntoView",description:"요소로 스크롤"},{value:"refetchDataSource",label:"refetchDataSource",description:"데이터소스 재조회"},{value:"remount",label:"remount",description:"컴포넌트 재마운트"},{value:"custom",label:"custom",description:"커스텀 액션"}],RE=[{value:"click",label:"click",description:"클릭"},{value:"change",label:"change",description:"값 변경"},{value:"input",label:"input",description:"입력"},{value:"submit",label:"submit",description:"폼 제출"},{value:"keydown",label:"keydown",description:"키 누름"},{value:"keyup",label:"keyup",description:"키 뗌"},{value:"focus",label:"focus",description:"포커스"},{value:"blur",label:"blur",description:"블러"},{value:"mount",label:"mount",description:"마운트"},{value:"unmount",label:"unmount",description:"언마운트"},{value:"scroll",label:"scroll",description:"스크롤 (무한스크롤용)"}];function OE({component:r,onChange:e}){const[t,a]=j.useState(null),[i,o]=j.useState(!1),d=j.useMemo(()=>r.actions||[],[r.actions]),g=j.useCallback(()=>{const x={type:"click",handler:"navigate",params:{}},S=[...d,x];e({actions:S}),a(S.length-1),o(!1)},[d,e]),h=j.useCallback(x=>{const S=d.filter((v,w)=>w!==x);e({actions:S.length>0?S:void 0}),t===x?a(null):t!==null&&t>x&&a(t-1)},[d,t,e]),f=j.useCallback((x,S)=>{const v=d.map((w,k)=>k===x?{...w,...S}:w);e({actions:v})},[d,e]),p=j.useCallback(x=>{const S=d[x],v=JSON.parse(JSON.stringify(S)),w=[...d.slice(0,x+1),v,...d.slice(x+1)];e({actions:w})},[d,e]),y=j.useCallback((x,S)=>{const v=S==="up"?x-1:x+1;if(v<0||v>=d.length)return;const w=[...d];[w[x],w[v]]=[w[v],w[x]],e({actions:w}),t===x?a(v):t===v&&a(x)},[d,t,e]);return l.jsxs("div",{className:"p-4 space-y-4",children:[l.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-400 mb-4",children:"이벤트 핸들러를 설정하여 사용자 상호작용에 반응합니다."}),d.length>0?l.jsxs("div",{className:"space-y-2",children:[l.jsxs("h4",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase",children:["등록된 액션 (",d.length,")"]}),d.map((x,S)=>l.jsx(LE,{action:x,index:S,isEditing:t===S,isFirst:S===0,isLast:S===d.length-1,onEdit:()=>a(t===S?null:S),onDelete:()=>h(S),onDuplicate:()=>p(S),onMove:v=>y(S,v),onUpdate:v=>f(S,v)},S))]}):l.jsxs("div",{className:"text-center py-8 text-gray-400 dark:text-gray-500",children:[l.jsx("p",{children:"등록된 액션이 없습니다"}),l.jsx("p",{className:"text-xs mt-1",children:"아래 버튼을 클릭하여 액션을 추가하세요"})]}),i?l.jsxs("div",{className:"flex gap-2",children:[l.jsx("button",{onClick:g,className:"flex-1 px-3 py-2 bg-blue-500 text-white text-sm rounded hover:bg-blue-600 transition-colors",children:"기본 액션 추가"}),l.jsx("button",{onClick:()=>o(!1),className:"px-3 py-2 text-gray-600 dark:text-gray-400 text-sm rounded border border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors",children:"취소"})]}):l.jsx("button",{onClick:()=>o(!0),className:"w-full px-3 py-2 border-2 border-dashed border-gray-300 dark:border-gray-600 text-gray-500 dark:text-gray-400 text-sm rounded hover:border-blue-400 hover:text-blue-500 transition-colors",children:"+ 액션 추가"})]})}function LE({action:r,index:e,isEditing:t,isFirst:a,isLast:i,onEdit:o,onDelete:d,onDuplicate:g,onMove:h,onUpdate:f}){const p=r.event||r.type||"click",y=!!r.event;return l.jsxs("div",{className:`rounded border transition-colors ${t?"border-blue-500 bg-blue-50 dark:bg-blue-900/20":"border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800"}`,children:[l.jsxs("div",{className:"p-2 flex items-center gap-2 cursor-pointer",onClick:o,children:[l.jsx("span",{className:"w-5 h-5 flex items-center justify-center text-xs font-medium text-gray-500 dark:text-gray-400 bg-gray-200 dark:bg-gray-700 rounded",children:e+1}),l.jsx("span",{className:`text-xs font-medium px-2 py-0.5 rounded ${y?"text-purple-600 dark:text-purple-400 bg-purple-100 dark:bg-purple-900/30":"text-blue-600 dark:text-blue-400 bg-blue-100 dark:bg-blue-900/30"}`,children:p}),l.jsx("span",{className:"text-xs text-gray-400",children:"→"}),l.jsx("span",{className:"text-xs font-medium text-green-600 dark:text-green-400",children:r.handler}),r.target&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"text-xs text-gray-400",children:":"}),l.jsx("span",{className:"text-xs text-gray-600 dark:text-gray-400 truncate max-w-[100px]",children:r.target})]}),(r.onSuccess||r.onError)&&l.jsx("span",{className:"text-xs text-orange-500 dark:text-orange-400",children:"+chain"}),r.confirm&&l.jsx("span",{className:"text-xs text-yellow-600 dark:text-yellow-400",children:"⚠️"}),r.debounce&&l.jsxs("span",{className:"text-xs text-purple-500 dark:text-purple-400",title:"Debounce 적용됨",children:["⏱️",typeof r.debounce=="number"?r.debounce:r.debounce.delay,"ms"]}),l.jsx("span",{className:"ml-auto text-gray-400",children:t?"▼":"▶"})]}),t&&l.jsxs("div",{className:"p-3 border-t border-gray-200 dark:border-gray-700 space-y-3",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"이벤트 타입"}),l.jsx("div",{className:"flex gap-2",children:l.jsxs("select",{value:r.event?"custom":r.type||"click",onChange:x=>{const S=x.target.value;f(S==="custom"?{type:"click",event:"onChange"}:{type:S,event:void 0})},className:"flex-1 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white",children:[RE.map(x=>l.jsxs("option",{value:x.value,children:[x.label," (",x.description,")"]},x.value)),l.jsx("option",{value:"custom",children:"커스텀 이벤트"})]})}),r.event&&l.jsx("input",{type:"text",value:r.event,onChange:x=>f({event:x.target.value}),placeholder:"이벤트명 (예: onChange, onRowAction)",className:"mt-2 w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"핸들러"}),l.jsx("select",{value:r.handler,onChange:x=>f({handler:x.target.value}),className:"w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white",children:DE.map(x=>l.jsxs("option",{value:x.value,children:[x.label," - ",x.description]},x.value))})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"Target (선택)"}),l.jsx("input",{type:"text",value:r.target||"",onChange:x=>f({target:x.target.value||void 0}),placeholder:"URL, 모달 ID, API 엔드포인트 등",className:"w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"})]}),l.jsx(ME,{params:r.params||{},onChange:x=>f({params:x}),handler:r.handler}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"확인 메시지 (선택)"}),l.jsx("input",{type:"text",value:r.confirm||"",onChange:x=>f({confirm:x.target.value||void 0}),placeholder:"실행 전 확인 대화상자 메시지",className:"w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"})]}),(r.type==="keydown"||r.type==="keyup")&&l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"키 필터"}),l.jsx("input",{type:"text",value:r.key||"",onChange:x=>f({key:x.target.value||void 0}),placeholder:"Enter, Escape, ArrowDown 등",className:"w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"})]}),l.jsx($E,{debounce:r.debounce,onChange:x=>f({debounce:x})}),(r.onSuccess||r.onError)&&l.jsxs("div",{className:"text-xs text-gray-500 dark:text-gray-400 p-2 bg-gray-100 dark:bg-gray-700 rounded",children:[l.jsxs("p",{children:[l.jsx("span",{className:"text-green-600 dark:text-green-400",children:"onSuccess:"})," ",r.onSuccess?Array.isArray(r.onSuccess)?`${r.onSuccess.length}개 액션`:"1개 액션":"없음"]}),l.jsxs("p",{children:[l.jsx("span",{className:"text-red-600 dark:text-red-400",children:"onError:"})," ",r.onError?Array.isArray(r.onError)?`${r.onError.length}개 액션`:"1개 액션":"없음"]})]}),l.jsxs("div",{className:"flex gap-2 pt-2 border-t border-gray-200 dark:border-gray-700",children:[l.jsx("button",{onClick:()=>h("up"),disabled:a,className:"px-2 py-1 text-xs text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white disabled:opacity-30 disabled:cursor-not-allowed",title:"위로 이동",children:"↑"}),l.jsx("button",{onClick:()=>h("down"),disabled:i,className:"px-2 py-1 text-xs text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white disabled:opacity-30 disabled:cursor-not-allowed",title:"아래로 이동",children:"↓"}),l.jsx("button",{onClick:g,className:"px-2 py-1 text-xs text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300",title:"복제",children:"복제"}),l.jsx("button",{onClick:d,className:"px-2 py-1 text-xs text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 ml-auto",title:"삭제",children:"삭제"})]})]})]})}function ME({params:r,onChange:e,handler:t}){const[a,i]=j.useState(""),[o,d]=j.useState(""),g=j.useMemo(()=>{switch(t){case"navigate":return["path","query","mergeQuery","replace"];case"apiCall":return["method","body","headers"];case"setState":return["target","merge"];case"toast":return["type","message"];case"openModal":return[];case"closeModal":return[];case"showErrorPage":return["errorCode","target","containerId","layout"];case"refetchDataSource":return["dataSourceId"];case"remount":return["componentId"];case"appendDataSource":return["id","dataPath","sourcePath"];case"scrollIntoView":return["selector","behavior","block","scrollContainer","waitForElement"];case"switch":return["value"];case"sequence":case"parallel":return["actions"];default:return[]}},[t]),h=j.useCallback(()=>{if(!a.trim())return;const x={...r,[a.trim()]:o};e(x),i(""),d("")},[r,a,o,e]),f=j.useCallback(x=>{const{[x]:S,...v}=r;e(v)},[r,e]),p=j.useCallback((x,S)=>{const v={...r,[x]:S};e(v)},[r,e]),y=Object.entries(r);return l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"파라미터"}),y.length>0&&l.jsx("div",{className:"space-y-1 mb-2",children:y.map(([x,S])=>l.jsxs("div",{className:"flex gap-1 items-center",children:[l.jsxs("span",{className:"text-xs text-gray-600 dark:text-gray-400 w-24 truncate",children:[x,":"]}),l.jsx("input",{type:"text",value:typeof S=="object"?JSON.stringify(S):String(S),onChange:v=>p(x,v.target.value),className:"flex-1 px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"}),l.jsx("button",{onClick:()=>f(x),className:"text-red-500 hover:text-red-700 text-xs px-1",title:"삭제",children:"×"})]},x))}),l.jsxs("div",{className:"flex gap-1",children:[l.jsx("input",{type:"text",value:a,onChange:x=>i(x.target.value),placeholder:"키",list:`suggested-params-${t}`,className:"w-24 px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"}),l.jsx("datalist",{id:`suggested-params-${t}`,children:g.filter(x=>!r[x]).map(x=>l.jsx("option",{value:x},x))}),l.jsx("input",{type:"text",value:o,onChange:x=>d(x.target.value),placeholder:"값",className:"flex-1 px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white",onKeyDown:x=>{x.key==="Enter"&&h()}}),l.jsx("button",{onClick:h,disabled:!a.trim(),className:"px-2 py-1 text-xs bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-300 dark:hover:bg-gray-500 disabled:opacity-50",children:"+"})]}),g.length>0&&l.jsxs("p",{className:"text-xs text-gray-400 dark:text-gray-500 mt-1",children:["권장: ",g.join(", ")]})]})}function $E({debounce:r,onChange:e}){const[t,a]=j.useState(!1),i=typeof r=="number"?r:r?.delay||0,o=typeof r=="object"?r.leading??!1:!1,d=typeof r=="object"?r.trailing??!0:!0,g=r!==void 0&&i>0,h=j.useCallback(()=>{e(g?void 0:300)},[g,e]),f=j.useCallback(x=>{const S=parseInt(x,10);if(isNaN(S)||S<=0){e(void 0);return}e(t?{delay:S,leading:o,trailing:d}:S)},[t,o,d,e]),p=j.useCallback((x,S)=>{e({delay:i||300,leading:x==="leading"?S:o,trailing:x==="trailing"?S:d})},[i,o,d,e]),y=j.useCallback(()=>{!t&&g?e({delay:i,leading:!1,trailing:!0}):t&&g&&e(i),a(!t)},[t,g,i,e]);return l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between mb-1",children:[l.jsx("label",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:"Debounce (연속 호출 제어)"}),l.jsx("button",{type:"button",onClick:h,className:`relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${g?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,children:l.jsx("span",{className:`pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${g?"translate-x-4":"translate-x-0"}`})})]}),g&&l.jsxs("div",{className:"space-y-2 mt-2 p-2 bg-gray-50 dark:bg-gray-800 rounded",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("label",{className:"text-xs text-gray-600 dark:text-gray-400 w-16",children:"지연 시간"}),l.jsx("input",{type:"number",value:i,onChange:x=>f(x.target.value),min:0,step:100,placeholder:"300",className:"flex-1 px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"}),l.jsx("span",{className:"text-xs text-gray-500",children:"ms"})]}),l.jsx("button",{type:"button",onClick:y,className:"text-xs text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300",children:t?"▼ 고급 설정 숨기기":"▶ 고급 설정 보기"}),t&&l.jsxs("div",{className:"space-y-2 pt-2 border-t border-gray-200 dark:border-gray-700",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("input",{type:"checkbox",id:"debounce-leading",checked:o,onChange:x=>p("leading",x.target.checked),className:"h-3 w-3 rounded border-gray-300 dark:border-gray-600"}),l.jsx("label",{htmlFor:"debounce-leading",className:"text-xs text-gray-600 dark:text-gray-400",children:"Leading (첫 호출 즉시 실행)"})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("input",{type:"checkbox",id:"debounce-trailing",checked:d,onChange:x=>p("trailing",x.target.checked),className:"h-3 w-3 rounded border-gray-300 dark:border-gray-600"}),l.jsx("label",{htmlFor:"debounce-trailing",className:"text-xs text-gray-600 dark:text-gray-400",children:"Trailing (마지막 호출 후 실행)"})]}),l.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"권장: change 이벤트에 300ms, 검색에 300~500ms"})]})]}),!g&&l.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500 mt-1",children:"텍스트 입력 필드에서 연속 호출을 제어합니다"})]})}const Wx=[{label:"상태 확인",value:"{{_local.isVisible}}",description:"로컬 상태가 참일 때"},{label:"값 존재 확인",value:"{{data?.length > 0}}",description:"데이터가 존재할 때"},{label:"권한 확인",value:'{{_global.user?.permissions?.includes("admin")}}',description:"관리자 권한이 있을 때"},{label:"로딩 완료",value:"{{!_local.isLoading}}",description:"로딩이 완료되었을 때"},{label:"에러 없음",value:"{{!_local.error}}",description:"에러가 없을 때"}];function IE({component:r,onChange:e}){const[t,a]=j.useState(!1),[i,o]=j.useState(!1),d=Se(x=>x.layoutData),g=Se(x=>x.mockDataContext),h=j.useMemo(()=>{const x=[];return d?.data_sources&&d.data_sources.forEach(S=>{x.push({label:S.id,value:`{{${S.id}.data}}`,description:`데이터 소스: ${S.id}`})}),g._global&&Object.keys(g._global).forEach(S=>{Array.isArray(g._global[S])&&x.push({label:`_global.${S}`,value:`{{_global.${S}}}`,description:"전역 상태 배열"})}),g._local&&Object.keys(g._local).forEach(S=>{Array.isArray(g._local[S])&&x.push({label:`_local.${S}`,value:`{{_local.${S}}}`,description:"로컬 상태 배열"})}),x},[d,g]),f=j.useCallback(x=>{e({if:x||void 0})},[e]),p=j.useCallback(x=>{if(x===null)e({iteration:void 0});else{const S=r.iteration||{source:"",item_var:"item",index_var:"index"};e({iteration:{...S,...x}})}},[r.iteration,e]),y=j.useCallback(()=>{e({iteration:{source:"",item_var:"item",index_var:"index"}}),o(!0)},[e]);return l.jsxs("div",{className:"p-4 space-y-6",children:[l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between mb-2",children:[l.jsx("h4",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase",children:"조건부 렌더링 (if)"}),r.if&&l.jsx("button",{onClick:()=>f(""),className:"text-xs text-red-500 hover:text-red-700",title:"조건 삭제",children:"삭제"})]}),l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-2",children:"조건이 참일 때만 컴포넌트를 렌더링합니다."}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("input",{type:"text",value:r.if||"",onChange:x=>f(x.target.value),placeholder:"{{_local.showComponent}}",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"}),l.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[l.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"빠른 입력:"}),Wx.slice(0,3).map(x=>l.jsx("button",{onClick:()=>f(x.value),className:"px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors",title:x.description,children:x.label},x.value)),l.jsx("button",{onClick:()=>a(!t),className:"px-2 py-0.5 text-xs text-blue-600 dark:text-blue-400 hover:underline",children:t?"닫기":"더보기..."})]}),t&&l.jsxs("div",{className:"mt-2 p-2 bg-gray-50 dark:bg-gray-800 rounded border border-gray-200 dark:border-gray-700",children:[l.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-400 mb-2",children:"조건 템플릿 선택:"}),l.jsx("div",{className:"space-y-1",children:Wx.map(x=>l.jsxs("button",{onClick:()=>{f(x.value),a(!1)},className:"w-full text-left px-2 py-1 text-xs hover:bg-gray-200 dark:hover:bg-gray-700 rounded transition-colors",children:[l.jsx("span",{className:"font-medium text-gray-700 dark:text-gray-300",children:x.label}),l.jsx("span",{className:"text-gray-500 dark:text-gray-400 ml-2",children:x.description}),l.jsx("code",{className:"block text-xs text-blue-600 dark:text-blue-400 mt-0.5",children:x.value})]},x.value))})]})]}),r.if&&l.jsx("div",{className:"mt-2 flex items-center gap-2 text-xs",children:l.jsx("span",{className:"px-2 py-0.5 bg-yellow-100 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-400 rounded",children:"⚠️ 조건부 렌더링 활성화"})})]}),l.jsx("hr",{className:"border-gray-200 dark:border-gray-700"}),l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between mb-2",children:[l.jsx("h4",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase",children:"반복 렌더링 (iteration)"}),r.iteration&&l.jsx("button",{onClick:()=>p(null),className:"text-xs text-red-500 hover:text-red-700",title:"반복 삭제",children:"삭제"})]}),l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-2",children:"데이터 배열을 순회하며 컴포넌트를 반복 렌더링합니다."}),r.iteration?l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"Source (반복할 배열)"}),l.jsx("input",{type:"text",value:r.iteration.source||"",onChange:x=>p({source:x.target.value}),placeholder:"{{users.data}}",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"}),h.length>0&&l.jsxs("div",{className:"flex items-center gap-1 flex-wrap mt-1",children:[l.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"사용 가능:"}),h.slice(0,3).map(x=>l.jsx("button",{onClick:()=>p({source:x.value}),className:"px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors",title:x.description,children:x.label},x.value))]})]}),l.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"Item 변수명"}),l.jsx("input",{type:"text",value:r.iteration.item_var||"item",onChange:x=>p({item_var:x.target.value||"item"}),placeholder:"item",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"Index 변수명"}),l.jsx("input",{type:"text",value:r.iteration.index_var||"index",onChange:x=>p({index_var:x.target.value||"index"}),placeholder:"index",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"})]})]}),l.jsxs("div",{className:"p-2 bg-blue-50 dark:bg-blue-900/20 rounded text-xs text-blue-700 dark:text-blue-300",children:[l.jsx("p",{className:"font-medium mb-1",children:"사용법:"}),l.jsxs("code",{className:"block",children:[`{{${r.iteration.item_var||"item"}.속성}}`," - 현재 아이템 접근"]}),l.jsxs("code",{className:"block",children:[`{{${r.iteration.index_var||"index"}}}`," - 현재 인덱스 접근"]})]}),l.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[l.jsx("span",{className:"px-2 py-0.5 bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-400 rounded",children:"🔁 반복 렌더링 활성화"}),r.iteration.source&&l.jsxs("span",{className:"text-gray-500 dark:text-gray-400",children:["소스: ",r.iteration.source]})]})]}):l.jsxs("div",{className:"text-center py-4",children:[l.jsx("p",{className:"text-gray-400 dark:text-gray-500 mb-2",children:"반복 설정이 없습니다"}),l.jsx("button",{onClick:y,className:"px-3 py-1.5 text-sm bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-400 rounded hover:bg-purple-200 dark:hover:bg-purple-900/50 transition-colors",children:"+ 반복 렌더링 추가"})]})]}),r.if&&r.iteration&&l.jsxs("div",{className:"p-2 bg-amber-50 dark:bg-amber-900/20 rounded border border-amber-200 dark:border-amber-800 text-xs text-amber-700 dark:text-amber-300",children:[l.jsx("p",{className:"font-medium",children:"⚠️ 조건 + 반복 조합"}),l.jsx("p",{className:"mt-1",children:"조건(if)과 반복(iteration)이 함께 설정되어 있습니다. 조건이 먼저 평가되고, 참일 때만 반복이 실행됩니다."})]})]})}const Yx=[{key:"mobile",label:"모바일",range:"0 ~ 767px",icon:"📱"},{key:"tablet",label:"태블릿",range:"768 ~ 1023px",icon:"📲"},{key:"desktop",label:"데스크톱",range:"1024px 이상",icon:"🖥️"},{key:"portable",label:"포터블",range:"0 ~ 1023px",icon:"📱+📲",description:"모바일 + 태블릿"}],zE=[{label:"숨김",value:"hidden"},{label:"표시",value:"block"},{label:"Flex 표시",value:"flex"},{label:"Grid 표시",value:"grid"},{label:"1열 그리드",value:"grid grid-cols-1"},{label:"2열 그리드",value:"grid grid-cols-2"},{label:"3열 그리드",value:"grid grid-cols-3"},{label:"세로 정렬",value:"flex flex-col"},{label:"가로 정렬",value:"flex flex-row"},{label:"전체 너비",value:"w-full"},{label:"작은 패딩",value:"p-2"},{label:"중간 패딩",value:"p-4"},{label:"큰 패딩",value:"p-6"}];function HE({breakpointKey:r,label:e,range:t,icon:a,description:i,config:o,component:d,isOpen:g,onToggle:h,onChange:f}){const p=o!==void 0,{getMetadata:y}=Ko(),x=y(d.name),S=j.useCallback((O,N)=>{const D=o?.props||{};let $;if(N===""){const{[O]:M,...z}=D;$=z}else $={...D,[O]:N};Object.keys($).length===0&&!o?.text&&!o?.if?f(null):f({...o,props:$})},[o,f]),v=j.useCallback(O=>{if(O===""){const{text:N,...D}=o||{};Object.keys(D.props||{}).length===0&&!D.if?f(null):f(D)}else f({...o,text:O})},[o,f]),w=j.useCallback(O=>{if(O===""){const{if:N,...D}=o||{};Object.keys(D.props||{}).length===0&&!D.text?f(null):f(D)}else f({...o,if:O})},[o,f]),k=j.useCallback(()=>{f(p?null:{props:{}})},[p,f]),A=j.useCallback(O=>{const N=o?.props||{},D=N.className||"",$=D?`${D} ${O}`:O;f({...o,props:{...N,className:$}})},[o,f]);return l.jsxs("div",{className:"border border-gray-200 dark:border-gray-700 rounded overflow-hidden",children:[l.jsxs("div",{className:`flex items-center justify-between px-3 py-2 cursor-pointer transition-colors ${p?"bg-blue-50 dark:bg-blue-900/20":"bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-750"}`,onClick:h,children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{children:a}),l.jsxs("div",{children:[l.jsx("span",{className:"text-sm font-medium text-gray-900 dark:text-white",children:e}),l.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 ml-2",children:t}),i&&l.jsxs("span",{className:"text-xs text-gray-400 dark:text-gray-500 ml-1",children:["(",i,")"]})]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("button",{onClick:O=>{O.stopPropagation(),k()},className:`px-2 py-0.5 text-xs rounded transition-colors ${p?"bg-blue-500 text-white":"bg-gray-200 dark:bg-gray-600 text-gray-600 dark:text-gray-300"}`,children:p?"활성":"비활성"}),l.jsx("span",{className:`text-gray-400 transition-transform ${g?"rotate-180":""}`,children:"▼"})]})]}),g&&p&&l.jsxs("div",{className:"p-3 space-y-4 border-t border-gray-200 dark:border-gray-700",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"className"}),l.jsx("input",{type:"text",value:o?.props?.className||"",onChange:O=>S("className",O.target.value),placeholder:d.props?.className||"기본값 사용",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"}),l.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:zE.slice(0,6).map(O=>l.jsx("button",{onClick:()=>A(O.value),className:"px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors",title:O.value,children:O.label},O.value))})]}),x?.props?.filter(O=>O.name!=="className"&&O.name!=="children").slice(0,5).map(O=>l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:O.label||O.name}),O.type==="boolean"?l.jsxs("select",{value:o?.props?.[O.name]===void 0?"":String(o.props[O.name]),onChange:N=>{const D=N.target.value;D===""?S(O.name,""):S(O.name,D==="true")},className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white",children:[l.jsx("option",{value:"",children:"기본값"}),l.jsx("option",{value:"true",children:"true"}),l.jsx("option",{value:"false",children:"false"})]}):O.type==="select"&&O.options?l.jsxs("select",{value:o?.props?.[O.name]||"",onChange:N=>S(O.name,N.target.value),className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white",children:[l.jsx("option",{value:"",children:"기본값"}),O.options.map(N=>l.jsx("option",{value:String(N.value),children:N.label},String(N.value)))]}):l.jsx("input",{type:O.type==="number"?"number":"text",value:o?.props?.[O.name]||"",onChange:N=>S(O.name,N.target.value),placeholder:d.props?.[O.name]?String(d.props[O.name]):"기본값",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"})]},O.name)),d.text!==void 0&&l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"text"}),l.jsx("input",{type:"text",value:o?.text||"",onChange:O=>v(O.target.value),placeholder:d.text||"기본값 사용",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"if (조건부 렌더링)"}),l.jsx("input",{type:"text",value:o?.if||"",onChange:O=>w(O.target.value),placeholder:d.if||"{{true}}",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"}),l.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:["예: ",l.jsx("code",{className:"text-blue-600 dark:text-blue-400",children:"{{_global.sidebarOpen}}"})]})]}),o&&Object.keys(o).length>0&&l.jsxs("div",{className:"mt-3 p-2 bg-gray-50 dark:bg-gray-800 rounded text-xs",children:[l.jsx("p",{className:"font-medium text-gray-700 dark:text-gray-300 mb-1",children:"설정된 오버라이드:"}),l.jsx("pre",{className:"text-gray-600 dark:text-gray-400 overflow-auto max-h-24",children:JSON.stringify(o,null,2)})]})]})]})}function PE({responsive:r,onChange:e,onAddRange:t,onRemoveRange:a}){const[i,o]=j.useState(""),[d,g]=j.useState(""),h=j.useMemo(()=>{if(!r)return[];const p=Yx.map(y=>y.key);return Object.keys(r).filter(y=>!p.includes(y))},[r]),f=j.useCallback(()=>{let p;if(i&&d)p=`${i}-${d}`;else if(i&&!d)p=`${i}-`;else if(!i&&d)p=`-${d}`;else return;t(p),o(""),g("")},[i,d,t]);return l.jsxs("div",{className:"space-y-3",children:[l.jsx("h5",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase",children:"커스텀 범위"}),l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"특정 화면 너비 범위에 대한 오버라이드를 설정합니다."}),h.length>0&&l.jsx("div",{className:"space-y-2",children:h.map(p=>l.jsxs("div",{className:"flex items-center justify-between p-2 bg-gray-50 dark:bg-gray-800 rounded",children:[l.jsxs("span",{className:"text-sm font-mono text-gray-700 dark:text-gray-300",children:[p,"px"]}),l.jsx("button",{onClick:()=>a(p),className:"text-xs text-red-500 hover:text-red-700",children:"삭제"})]},p))}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("input",{type:"number",value:i,onChange:p=>o(p.target.value),placeholder:"최소",className:"w-20 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400"}),l.jsx("span",{className:"text-gray-500",children:"~"}),l.jsx("input",{type:"number",value:d,onChange:p=>g(p.target.value),placeholder:"최대",className:"w-20 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400"}),l.jsx("span",{className:"text-gray-500 text-sm",children:"px"}),l.jsx("button",{onClick:f,disabled:!i&&!d,className:"px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"추가"})]}),l.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"예: 0-599 (작은 모바일), 600-899 (큰 모바일), 1200- (와이드 데스크톱)"})]})}function BE({component:r,onChange:e}){const[t,a]=j.useState(new Set),[i,o]=j.useState(!1),d=r.responsive,g=j.useCallback(S=>{a(v=>{const w=new Set(v);return w.has(S)?w.delete(S):w.add(S),w})},[]),h=j.useCallback((S,v)=>{const w={...d||{}};v===null?delete w[S]:w[S]=v,Object.keys(w).length===0?e({responsive:void 0}):e({responsive:w})},[d,e]),f=j.useCallback(S=>{const v={...d||{}};v[S]={props:{}},e({responsive:v}),a(w=>new Set(w).add(S))},[d,e]),p=j.useCallback(S=>{const v={...d||{}};delete v[S],Object.keys(v).length===0?e({responsive:void 0}):e({responsive:v})},[d,e]),y=j.useCallback(()=>{e({responsive:void 0})},[e]),x=j.useMemo(()=>d?Object.keys(d).length:0,[d]);return l.jsxs("div",{className:"p-4 space-y-6",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("h4",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase",children:"반응형 오버라이드"}),l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:"브레이크포인트별로 다른 속성을 설정합니다."})]}),x>0&&l.jsx("button",{onClick:y,className:"text-xs text-red-500 hover:text-red-700",children:"모두 삭제"})]}),x>0&&l.jsx("div",{className:"flex items-center gap-2",children:l.jsxs("span",{className:"px-2 py-0.5 text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 rounded",children:["📱 ",x,"개 브레이크포인트 활성화"]})}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("h5",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase",children:"프리셋 브레이크포인트"}),Yx.map(S=>l.jsx(HE,{breakpointKey:S.key,label:S.label,range:S.range,icon:S.icon,description:S.description,config:d?.[S.key],component:r,isOpen:t.has(S.key),onToggle:()=>g(S.key),onChange:v=>h(S.key,v)},S.key))]}),l.jsx("hr",{className:"border-gray-200 dark:border-gray-700"}),l.jsxs("div",{children:[l.jsxs("button",{onClick:()=>o(!i),className:"flex items-center gap-2 text-sm text-blue-600 dark:text-blue-400 hover:underline",children:[l.jsx("span",{children:i?"▼":"▶"}),l.jsx("span",{children:"커스텀 범위 설정"})]}),i&&l.jsx("div",{className:"mt-3",children:l.jsx(PE,{responsive:d,onChange:h,onAddRange:f,onRemoveRange:p})})]}),l.jsxs("div",{className:"p-3 bg-blue-50 dark:bg-blue-900/20 rounded text-xs text-blue-700 dark:text-blue-300",children:[l.jsx("p",{className:"font-medium mb-2",children:"반응형 규칙:"}),l.jsxs("ul",{className:"list-disc list-inside space-y-1 text-blue-600 dark:text-blue-400",children:[l.jsxs("li",{children:[l.jsx("strong",{children:"portable"}),"을 사용할 때는 mobile/tablet과 혼용 금지"]}),l.jsx("li",{children:"프리셋 브레이크포인트보다 커스텀 범위가 우선 적용"}),l.jsx("li",{children:"좁은 범위가 넓은 범위보다 우선 적용"}),l.jsx("li",{children:"Props는 얕은 머지 (shallow merge) 적용"})]})]}),d&&Object.keys(d).length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsx("h5",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase",children:"설정 미리보기 (JSON)"}),l.jsx("pre",{className:"p-3 bg-gray-50 dark:bg-gray-800 rounded border border-gray-200 dark:border-gray-700 text-xs text-gray-600 dark:text-gray-400 overflow-auto max-h-48",children:JSON.stringify(d,null,2)})]})]})}it("ClassMapEditor");function UE({variantKey:r,variantClass:e,onKeyChange:t,onClassChange:a,onDelete:i}){return l.jsxs("div",{className:"flex items-start gap-2 p-2 bg-gray-50 dark:bg-gray-800 rounded",children:[l.jsxs("div",{className:"flex-1",children:[l.jsx("label",{className:"block text-xs text-gray-500 dark:text-gray-400 mb-1",children:"키 (variant name)"}),l.jsx("input",{type:"text",value:r,onChange:o=>t(o.target.value),placeholder:"success, error, warning...",className:"w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500"})]}),l.jsxs("div",{className:"flex-[2]",children:[l.jsx("label",{className:"block text-xs text-gray-500 dark:text-gray-400 mb-1",children:"클래스"}),l.jsx("input",{type:"text",value:e,onChange:o=>a(o.target.value),placeholder:"bg-green-100 text-green-800",className:"w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 font-mono"})]}),l.jsx("button",{type:"button",onClick:i,className:"mt-5 p-1 text-red-500 dark:text-red-400 hover:bg-red-100 dark:hover:bg-red-900/30 rounded",title:"variant 삭제",children:l.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"w-4 h-4",viewBox:"0 0 20 20",fill:"currentColor",children:l.jsx("path",{fillRule:"evenodd",d:"M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z",clipRule:"evenodd"})})})]})}function Jx({classes:r}){const e=r.split(/\s+/).filter(Boolean);return e.length===0?null:l.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[e.slice(0,8).map((t,a)=>l.jsx("span",{className:"px-1.5 py-0.5 text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded",children:t},a)),e.length>8&&l.jsxs("span",{className:"px-1.5 py-0.5 text-xs text-gray-500 dark:text-gray-400",children:["+",e.length-8,"개 더"]})]})}function qE({value:r,onChange:e,label:t="classMap",description:a}){const[i,o]=j.useState(!!r),d=j.useCallback(()=>{r?(e(void 0),o(!1)):(e({base:"",variants:{},key:"",default:""}),o(!0))},[r,e]),g=j.useCallback(w=>{e({...r,base:w||void 0})},[r,e]),h=j.useCallback(w=>{e({...r,key:w||void 0})},[r,e]),f=j.useCallback(w=>{e({...r,default:w||void 0})},[r,e]),p=j.useCallback(()=>{const w=r?.variants||{},k=`variant_${Object.keys(w).length+1}`;e({...r,variants:{...w,[k]:""}})},[r,e]),y=j.useCallback((w,k)=>{if(!r?.variants||w===k)return;const A={...r.variants},O=A[w];delete A[w],A[k]=O,e({...r,variants:A})},[r,e]),x=j.useCallback((w,k)=>{e({...r,variants:{...r?.variants,[w]:k}})},[r,e]),S=j.useCallback(w=>{if(!r?.variants)return;const k={...r.variants};delete k[w],e({...r,variants:k})},[r,e]),v=j.useMemo(()=>Object.entries(r?.variants||{}),[r?.variants]);return l.jsxs("div",{className:"border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden",children:[l.jsxs("div",{className:"flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800 cursor-pointer",onClick:()=>o(!i),children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:`w-4 h-4 text-gray-500 dark:text-gray-400 transition-transform ${i?"rotate-90":""}`,viewBox:"0 0 20 20",fill:"currentColor",children:l.jsx("path",{fillRule:"evenodd",d:"M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z",clipRule:"evenodd"})}),l.jsx("span",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:t}),r&&l.jsx("span",{className:"px-1.5 py-0.5 text-xs bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 rounded",children:"활성화"})]}),l.jsx("button",{type:"button",onClick:w=>{w.stopPropagation(),d()},className:`px-2 py-1 text-xs rounded ${r?"bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300 hover:bg-red-200 dark:hover:bg-red-900/50":"bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 hover:bg-green-200 dark:hover:bg-green-900/50"}`,children:r?"제거":"추가"})]}),i&&r&&l.jsxs("div",{className:"p-3 space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"기본 클래스 (base)"}),l.jsx("textarea",{value:r.base||"",onChange:w=>g(w.target.value),placeholder:"px-2 py-1 rounded-full text-xs font-medium",rows:2,className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 font-mono resize-none"}),l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:"모든 상태에서 항상 적용되는 클래스"}),r.base&&l.jsx(Jx,{classes:r.base})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"키 표현식 (key)"}),l.jsxs("div",{className:"relative",children:[l.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 text-sm",children:"{{"}),l.jsx("input",{type:"text",value:(r.key||"").replace(/^\{\{|\}\}$/g,""),onChange:w=>h(`{{${w.target.value}}}`),placeholder:"row.status",className:"w-full pl-8 pr-8 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 font-mono"}),l.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 text-sm",children:"}}"})]}),l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:"variant를 결정하는 표현식 (예: row.status, item.type)"})]}),l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between mb-2",children:[l.jsxs("label",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:["Variants (",v.length,")"]}),l.jsx("button",{type:"button",onClick:p,className:"px-2 py-1 text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded hover:bg-blue-200 dark:hover:bg-blue-900/50",children:"+ 추가"})]}),v.length>0?l.jsx("div",{className:"space-y-2",children:v.map(([w,k])=>l.jsx(UE,{variantKey:w,variantClass:k,onKeyChange:A=>y(w,A),onClassChange:A=>x(w,A),onDelete:()=>S(w)},w))}):l.jsxs("div",{className:"p-4 text-center text-gray-400 dark:text-gray-500 bg-gray-50 dark:bg-gray-800 rounded",children:[l.jsx("p",{className:"text-sm",children:"variant가 없습니다"}),l.jsx("p",{className:"text-xs mt-1",children:"+ 추가 버튼을 클릭하여 variant를 추가하세요"})]})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"기본값 클래스 (default)"}),l.jsx("input",{type:"text",value:r.default||"",onChange:w=>f(w.target.value),placeholder:"bg-gray-100 text-gray-600",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 font-mono"}),l.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:"매칭되는 variant가 없을 때 적용되는 클래스"}),r.default&&l.jsx(Jx,{classes:r.default})]}),l.jsxs("div",{className:"p-3 bg-gray-100 dark:bg-gray-900 rounded text-xs",children:[l.jsx("div",{className:"font-medium text-gray-700 dark:text-gray-300 mb-2",children:"생성될 JSON 미리보기:"}),l.jsx("pre",{className:"text-gray-600 dark:text-gray-400 overflow-x-auto",children:JSON.stringify({classMap:{...r.base&&{base:r.base},...Object.keys(r.variants||{}).length>0&&{variants:r.variants},...r.key&&{key:r.key},...r.default&&{default:r.default}}},null,2)})]})]}),a&&!i&&l.jsx("p",{className:"px-3 pb-2 text-xs text-gray-500 dark:text-gray-400",children:a})]})}it("AdvancedEditor");function ud({title:r,badge:e,isExpanded:t,onToggle:a}){return l.jsxs("button",{type:"button",className:"w-full flex items-center justify-between p-2 text-left bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors",onClick:a,children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:`w-4 h-4 text-gray-500 dark:text-gray-400 transition-transform ${t?"rotate-90":""}`,viewBox:"0 0 20 20",fill:"currentColor",children:l.jsx("path",{fillRule:"evenodd",d:"M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z",clipRule:"evenodd"})}),l.jsx("span",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase",children:r})]}),e&&l.jsx("span",{className:"px-1.5 py-0.5 text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded",children:e})]})}function GE({component:r,onChange:e}){const[t,a]=j.useState({basic:!0,classMap:!1,expressionHelpers:!1,rawJson:!1}),i=j.useCallback(f=>{a(p=>({...p,[f]:!p[f]}))},[]),o=j.useCallback(f=>{f&&f!==r.id&&e({id:f})},[r.id,e]),d=j.useCallback(f=>{const p={...r.props};f?p.classMap=f:delete p.classMap,e({props:p})},[r.props,e]),g=j.useCallback(f=>{e({blur_until_loaded:f||void 0})},[e]),h=r.props?.classMap;return l.jsxs("div",{className:"p-4 space-y-4",children:[l.jsxs("div",{children:[l.jsx(ud,{title:"기본 설정",isExpanded:t.basic,onToggle:()=>i("basic")}),t.basic&&l.jsxs("div",{className:"mt-3 space-y-4 pl-2",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"컴포넌트 ID"}),l.jsx("input",{type:"text",value:r.id,onChange:f=>o(f.target.value),className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white font-mono"}),l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:"레이아웃 내에서 고유해야 합니다"})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"슬롯 (Slot)"}),l.jsx("input",{type:"text",value:r.slot||"",readOnly:!0,placeholder:"(없음)",className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300"})]}),r.slot&&l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"슬롯 순서"}),l.jsx("input",{type:"number",value:r.slotOrder||0,readOnly:!0,className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300"})]}),l.jsx("div",{children:l.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[l.jsx("input",{type:"checkbox",checked:r.blur_until_loaded||!1,onChange:f=>g(f.target.checked),className:"w-4 h-4 text-blue-600 border-gray-300 dark:border-gray-600 rounded focus:ring-blue-500"}),l.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300",children:"데이터 로드 전까지 블러 처리"})]})}),r.lifecycle&&l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:"Lifecycle"}),l.jsxs("div",{className:"space-y-2",children:[r.lifecycle.onMount&&l.jsxs("div",{className:"p-2 bg-gray-50 dark:bg-gray-800 rounded",children:[l.jsx("span",{className:"text-xs text-gray-600 dark:text-gray-400",children:"onMount:"}),l.jsxs("span",{className:"text-xs text-gray-700 dark:text-gray-300 ml-2",children:[r.lifecycle.onMount.length,"개 액션"]})]}),r.lifecycle.onUnmount&&l.jsxs("div",{className:"p-2 bg-gray-50 dark:bg-gray-800 rounded",children:[l.jsx("span",{className:"text-xs text-gray-600 dark:text-gray-400",children:"onUnmount:"}),l.jsxs("span",{className:"text-xs text-gray-700 dark:text-gray-300 ml-2",children:[r.lifecycle.onUnmount.length,"개 액션"]})]})]})]})]})]}),l.jsxs("div",{children:[l.jsx(ud,{title:"classMap (조건부 스타일)",badge:h?"활성화":void 0,isExpanded:t.classMap,onToggle:()=>i("classMap")}),t.classMap&&l.jsx("div",{className:"mt-3",children:l.jsx(qE,{value:h,onChange:d,label:"조건부 클래스 매핑",description:"상태에 따라 다른 CSS 클래스를 적용합니다. 중첩 삼항 연산자 대신 사용하세요."})})]}),l.jsxs("div",{children:[l.jsx(ud,{title:"표현식 헬퍼",isExpanded:t.expressionHelpers,onToggle:()=>i("expressionHelpers")}),t.expressionHelpers&&l.jsxs("div",{className:"mt-3 space-y-4",children:[l.jsxs("div",{className:"p-3 bg-orange-50 dark:bg-orange-900/20 rounded text-xs",children:[l.jsx("div",{className:"font-medium text-orange-700 dark:text-orange-300 mb-2",children:"$switch 표현식"}),l.jsx("p",{className:"text-orange-600 dark:text-orange-400 mb-2",children:"중첩 삼항 연산자 대신 선언적 switch-case 패턴을 사용할 수 있습니다."}),l.jsx("pre",{className:"bg-white dark:bg-gray-800 p-2 rounded font-mono overflow-x-auto text-gray-700 dark:text-gray-300",children:`{ "$switch": "{{status}}", "$cases": { "active": "text-green-500", @@ -1867,5 +1867,5 @@ details[open] > .g7dt-summary::before { // 사용 {{$computed.displayPrice}} -{{$computed.canEdit}}`})]})]})]}),l.jsxs("div",{children:[l.jsx(ud,{title:"Raw JSON",isExpanded:t.rawJson,onToggle:()=>i("rawJson")}),t.rawJson&&l.jsx("div",{className:"mt-3",children:l.jsx("pre",{className:"p-3 bg-gray-50 dark:bg-gray-800 rounded border border-gray-200 dark:border-gray-700 text-xs text-gray-600 dark:text-gray-400 overflow-auto max-h-96",children:JSON.stringify(r,null,2)})})]})]})}const GE=[{id:"props",label:"Props",icon:"⚙️",description:"기본 속성 편집"},{id:"bindings",label:"Bindings",icon:"🔗",description:"데이터 바인딩 설정"},{id:"actions",label:"Actions",icon:"⚡",description:"이벤트 핸들러 설정"},{id:"conditions",label:"Conditions",icon:"🔀",description:"조건부/반복 렌더링"},{id:"responsive",label:"Responsive",icon:"📱",description:"반응형 오버라이드"},{id:"advanced",label:"Advanced",icon:"🔧",description:"고급 설정"}];function FE({tab:r,isActive:e,onClick:t}){return l.jsxs("button",{className:`flex items-center gap-1 px-3 py-2 text-sm font-medium border-b-2 transition-colors ${e?"border-blue-500 text-blue-600 dark:text-blue-400":"border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:border-gray-300 dark:hover:border-gray-600"}`,onClick:t,title:r.description,children:[l.jsx("span",{children:r.icon}),l.jsx("span",{className:"hidden lg:inline",children:r.label})]})}function VE(){return l.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-8 text-gray-500 dark:text-gray-400",children:[l.jsx("div",{className:"text-4xl mb-4",children:"👆"}),l.jsx("h3",{className:"text-lg font-medium mb-2",children:"컴포넌트를 선택하세요"}),l.jsx("p",{className:"text-sm text-center",children:"편집할 컴포넌트를 미리보기 캔버스 또는 레이아웃 트리에서 클릭하세요."})]})}function KE({component:r}){const{getMetadata:e}=Vo(),t=e(r.name);return l.jsxs("div",{className:"px-4 py-3 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-lg",children:r.type==="basic"?"📦":r.type==="composite"?"🧩":r.type==="layout"?"📐":"🔌"}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("h3",{className:"text-sm font-semibold text-gray-900 dark:text-white truncate",children:r.name}),l.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 truncate",children:["ID: ",r.id]})]}),l.jsx("span",{className:`px-2 py-0.5 text-xs rounded ${r.type==="basic"?"bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300":r.type==="composite"?"bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300":r.type==="layout"?"bg-orange-100 dark:bg-orange-900 text-orange-700 dark:text-orange-300":"bg-purple-100 dark:bg-purple-900 text-purple-700 dark:text-purple-300"}`,children:r.type})]}),t?.description&&l.jsx("p",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400",children:t.description})]})}function Jx({className:r=""}){const[e,t]=j.useState("props"),a=Se(p=>p.layoutData),i=Se(p=>p.selectedComponentId),o=Se(p=>p.updateComponentProps),d=Se(p=>p.updateComponent),g=j.useMemo(()=>{if(!a||!i)return null;const p=y=>{for(const x of y)if(typeof x!="string"){if(x.id===i)return x;if(x.children){const S=p(x.children);if(S)return S}}return null};return p(a.components)},[a,i]),h=j.useCallback(p=>{!i||!g||(Object.keys(p).length===1&&p.props?o(i,p.props):d(i,p))},[i,g,o,d]);if(!g)return l.jsx("div",{className:`h-full bg-white dark:bg-gray-900 border-l border-gray-200 dark:border-gray-700 ${r}`,children:l.jsx(VE,{})});const f=()=>{switch(e){case"props":return l.jsx(Vx,{component:g,onChange:h});case"bindings":return l.jsx(AE,{component:g,onChange:h});case"actions":return l.jsx(RE,{component:g,onChange:h});case"conditions":return l.jsx($E,{component:g,onChange:h});case"responsive":return l.jsx(PE,{component:g,onChange:h});case"advanced":return l.jsx(qE,{component:g,onChange:h});default:return null}};return l.jsxs("div",{className:`flex flex-col h-full bg-white dark:bg-gray-900 border-l border-gray-200 dark:border-gray-700 ${r}`,children:[l.jsx(KE,{component:g}),l.jsx("div",{className:"flex border-b border-gray-200 dark:border-gray-700 overflow-x-auto",children:GE.map(p=>l.jsx(FE,{tab:p,isActive:e===p.id,onClick:()=>t(p.id)},p.id))}),l.jsx("div",{className:"flex-1 overflow-auto",children:f()})]})}const Ko=it("EditorOverlay");function WE({rect:r,componentId:e,onCopy:t,onDuplicate:a,onDelete:i,onMoveUp:o,onMoveDown:d}){const g=Math.max(0,r.top-36),h=window.innerWidth-r.right;return l.jsxs("div",{className:"fixed z-50 flex items-center gap-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg px-1 py-1",style:{top:g,right:Math.max(8,h)},onClick:f=>f.stopPropagation(),children:[l.jsx("button",{className:"p-1.5 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:o,title:"위로 이동",children:"⬆️"}),l.jsx("button",{className:"p-1.5 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:d,title:"아래로 이동",children:"⬇️"}),l.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700 mx-1"}),l.jsx("button",{className:"p-1.5 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:t,title:"복사",children:"📋"}),l.jsx("button",{className:"p-1.5 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:a,title:"복제",children:"📑"}),l.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700 mx-1"}),l.jsx("button",{className:"p-1.5 text-red-500 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 hover:bg-red-50 dark:hover:bg-red-900 rounded",onClick:i,title:"삭제",children:"🗑️"}),l.jsx("div",{className:"ml-2 px-2 py-0.5 text-xs text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-700 rounded",children:e})]})}function YE({rect:r,position:e}){const t={position:"fixed",pointerEvents:"none",zIndex:40};return e==="before"?l.jsx("div",{style:{...t,left:r.left,top:r.top-2,width:r.width,height:4},className:"bg-blue-500"}):e==="after"?l.jsx("div",{style:{...t,left:r.left,top:r.bottom-2,width:r.width,height:4},className:"bg-blue-500"}):e==="inside"?l.jsx("div",{style:{...t,left:r.left,top:r.top,width:r.width,height:r.height},className:"border-2 border-dashed border-blue-500 bg-blue-500 bg-opacity-10"}):null}function Xx({rect:r,containerRect:e,type:t,label:a}){const i=t==="selected",o=e?e.left:0,d=e?e.top:0;return l.jsxs("div",{className:`absolute pointer-events-none ${i?"border-2 border-blue-500":"border border-dashed border-green-500"}`,style:{left:r.left-o,top:r.top-d,width:r.width,height:r.height,zIndex:i?31:30},children:[i&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"absolute -left-1 -top-1 w-2 h-2 bg-blue-500 rounded-full"}),l.jsx("div",{className:"absolute -right-1 -top-1 w-2 h-2 bg-blue-500 rounded-full"}),l.jsx("div",{className:"absolute -left-1 -bottom-1 w-2 h-2 bg-blue-500 rounded-full"}),l.jsx("div",{className:"absolute -right-1 -bottom-1 w-2 h-2 bg-blue-500 rounded-full"})]}),a&&l.jsx("div",{className:`absolute -top-6 left-0 px-1.5 py-0.5 text-xs text-white rounded whitespace-nowrap ${i?"bg-blue-500":"bg-green-500"}`,children:a})]})}function fh({containerRef:r,enabled:e=!0,selectionMode:t=!0}){const a=j.useRef(null),i=Se(J=>J.layoutData),o=Se(J=>J.selectedComponentId),d=Se(J=>J.hoveredComponentId),g=Se(J=>J.selectComponent),h=Se(J=>J.setHoveredComponentId),f=Se(J=>J.deleteComponent),p=Se(J=>J.duplicateComponent),y=Se(J=>J.copyToClipboard);Se(J=>J.moveComponent);const[x,S]=j.useState([]),[v,w]=j.useState(null),[k,A]=j.useState({isDragging:!1,targetId:null,position:null,targetRect:null}),O=j.useCallback(()=>{if(!r.current||!i)return[];const J=r.current.querySelectorAll("[data-editor-id]"),be=[],le=(de,je)=>{for(const W of de)if(typeof W!="string"){if(W.id===je)return W;if(W.children){const ge=le(W.children,je);if(ge)return ge}}return null};return J.forEach(de=>{const je=de.getAttribute("data-editor-id");if(!je)return;const W=de.getBoundingClientRect(),ge=le(i.components,je);ge&&be.push({id:je,rect:W,component:ge,isSelected:je===o,isHovered:je===d})}),be},[r,i,o,d]),N=j.useCallback(()=>{S(O()),r.current&&w(r.current.getBoundingClientRect())},[O,r]);j.useEffect(()=>{if(!e)return;N();const J=()=>{requestAnimationFrame(N)};window.addEventListener("resize",J),window.addEventListener("scroll",J,!0);const be=new ResizeObserver(J);r.current&&be.observe(r.current);const le=new MutationObserver(J);return r.current&&le.observe(r.current,{childList:!0,subtree:!0,attributes:!0}),()=>{window.removeEventListener("resize",J),window.removeEventListener("scroll",J,!0),be.disconnect(),le.disconnect()}},[e,r,N]),j.useCallback(J=>{if(!t)return;const be=J.target;if(a.current?.contains(be))return;let le=null;if(be.hasAttribute("data-editor-id")?le=be:le=be.closest("[data-editor-id]"),le){const de=le.getAttribute("data-editor-id");de&&(g(de),J.preventDefault(),J.stopPropagation())}else g(null)},[t,g]),j.useCallback(J=>{const be=J.target;if(a.current?.contains(be))return;let le=null;if(be.hasAttribute("data-editor-id")?le=be:le=be.closest("[data-editor-id]"),le){const de=le.getAttribute("data-editor-id");de&&de!==d&&h(de)}else d&&h(null)},[d,h]),j.useCallback(()=>{h(null)},[h]);const D=j.useCallback(()=>{if(!o)return;const J=x.find(be=>be.id===o);J&&(y(J.component),Ko.log("Copied:",o))},[o,x,y]),$=j.useCallback(()=>{o&&(p(o),Ko.log("Duplicated:",o))},[o,p]),M=j.useCallback(()=>{o&&(f(o),Ko.log("Deleted:",o))},[o,f]),z=j.useCallback(()=>{o&&Ko.log("Move up:",o)},[o]),K=j.useCallback(()=>{o&&Ko.log("Move down:",o)},[o]),pe=j.useMemo(()=>x.find(J=>J.isSelected),[x]),we=j.useMemo(()=>x.find(J=>J.isHovered&&!J.isSelected),[x]);return e?l.jsx(l.Fragment,{children:l.jsxs("div",{ref:a,className:"absolute inset-0 pointer-events-none z-20",children:[we&&l.jsx(Xx,{rect:we.rect,containerRect:v,type:"hovered",label:we.component.name}),pe&&l.jsxs(l.Fragment,{children:[l.jsx(Xx,{rect:pe.rect,containerRect:v,type:"selected",label:pe.component.name}),l.jsx("div",{className:"pointer-events-auto",children:l.jsx(WE,{rect:pe.rect,componentId:pe.id,onCopy:D,onDuplicate:$,onDelete:M,onMoveUp:z,onMoveDown:K})})]}),k.isDragging&&k.targetRect&&k.position&&l.jsx(YE,{rect:k.targetRect,position:k.position})]})}):null}const cs=it("WysiwygEditor"),JE={leftPanel:280,rightPanel:320,bottomPanel:200},ph=200,XE=400,QE=500,ZE=400;function gd({direction:r,onResize:e}){const[t,a]=j.useState(!1),i=j.useRef(0),o=j.useCallback(g=>{g.preventDefault(),a(!0),i.current=r==="horizontal"?g.clientX:g.clientY;const h=p=>{const y=r==="horizontal"?p.clientX:p.clientY,x=y-i.current;i.current=y,e(x)},f=()=>{a(!1),document.removeEventListener("mousemove",h),document.removeEventListener("mouseup",f)};document.addEventListener("mousemove",h),document.addEventListener("mouseup",f)},[r,e]),d=r==="horizontal";return l.jsx("div",{className:`${d?"w-1 cursor-col-resize":"h-1 cursor-row-resize"} bg-gray-200 dark:bg-gray-700 hover:bg-blue-400 dark:hover:bg-blue-600 transition-colors ${t?"bg-blue-500 dark:bg-blue-500":""}`,onMouseDown:o})}function e_({onClose:r,onSaveComplete:e,readOnly:t=!1,className:a=""}){const i=Se(le=>le.layoutData),o=Se(le=>le.editMode),d=Se(le=>le.selectedComponentId),g=Se(le=>le.saveLayout),h=Se(le=>le.selectComponent),f=Se(le=>le.deleteComponent),p=Se(le=>le.duplicateComponent),{undo:y,redo:x,canUndo:S,canRedo:v}=oh(),[w,k]=j.useState(JE),[A,O]=j.useState(!0),[N,D]=j.useState(!0),[$,M]=j.useState(!0),z=j.useRef(null);j.useEffect(()=>{const le=de=>{if(de.target instanceof HTMLInputElement||de.target instanceof HTMLTextAreaElement||de.target.contentEditable==="true")return;const W=navigator.platform.toUpperCase().indexOf("MAC")>=0?de.metaKey:de.ctrlKey;if(W&&de.key==="z"&&!de.shiftKey){de.preventDefault(),S&&(y(),cs.log("Keyboard shortcut: Undo"));return}if(W&&de.key==="z"&&de.shiftKey){de.preventDefault(),v&&(x(),cs.log("Keyboard shortcut: Redo"));return}if(W&&de.key==="y"){de.preventDefault(),v&&(x(),cs.log("Keyboard shortcut: Redo (Y)"));return}if(W&&de.key==="s"){de.preventDefault(),t||(K(),cs.log("Keyboard shortcut: Save"));return}if((de.key==="Delete"||de.key==="Backspace")&&d){de.preventDefault(),t||(f(d),cs.log("Keyboard shortcut: Delete"));return}if(W&&de.key==="d"&&d){de.preventDefault(),t||(p(d),cs.log("Keyboard shortcut: Duplicate"));return}if(de.key==="Escape"){de.preventDefault(),h(null),cs.log("Keyboard shortcut: Deselect");return}if(W&&de.key==="1"){de.preventDefault(),O(ge=>!ge);return}if(W&&de.key==="2"){de.preventDefault(),D(ge=>!ge);return}if(W&&de.key==="3"){de.preventDefault(),M(ge=>!ge);return}};return window.addEventListener("keydown",le),()=>window.removeEventListener("keydown",le)},[S,v,y,x,d,h,f,p,t]);const K=j.useCallback(async()=>{try{await g("Manual save"),i&&e&&e(i),cs.log("Layout saved successfully")}catch(le){cs.error("Failed to save layout:",le)}},[g,i,e]),pe=j.useCallback(le=>{k(de=>({...de,leftPanel:Math.min(XE,Math.max(ph,de.leftPanel+le))}))},[]),we=j.useCallback(le=>{k(de=>({...de,rightPanel:Math.min(QE,Math.max(ph,de.rightPanel-le))}))},[]),J=j.useCallback(le=>{k(de=>({...de,bottomPanel:Math.min(ZE,Math.max(ph,de.bottomPanel-le))}))},[]),be=()=>{switch(o){case"visual":return l.jsxs("div",{ref:z,className:"relative flex-1 overflow-hidden",children:[l.jsx(uh,{showOverlay:!t}),!t&&l.jsx(fh,{containerRef:z})]});case"json":return l.jsx("div",{className:"flex-1 overflow-hidden bg-gray-900 p-4",children:l.jsx("pre",{className:"h-full overflow-auto text-sm text-green-400 font-mono",children:JSON.stringify(i,null,2)})});case"split":return l.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[l.jsxs("div",{ref:z,className:"relative flex-1 overflow-hidden",children:[l.jsx(uh,{showOverlay:!t}),!t&&l.jsx(fh,{containerRef:z})]}),l.jsx(gd,{direction:"horizontal",onResize:()=>{}}),l.jsx("div",{className:"flex-1 overflow-hidden bg-gray-900 p-4",children:l.jsx("pre",{className:"h-full overflow-auto text-sm text-green-400 font-mono",children:JSON.stringify(i,null,2)})})]});default:return null}};return l.jsxs("div",{className:`flex flex-col h-screen bg-gray-100 dark:bg-gray-900 ${a}`,children:[l.jsx(zx,{onClose:r,onSaveComplete:K}),l.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[A&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"flex-shrink-0 overflow-hidden bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700",style:{width:w.leftPanel},children:l.jsxs("div",{className:"h-full flex flex-col",children:[l.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-200 dark:border-gray-700",children:[l.jsx("h2",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"레이아웃 트리"}),l.jsx("button",{className:"p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300",onClick:()=>O(!1),title:"패널 닫기",children:"✕"})]}),l.jsx("div",{className:"flex-1 overflow-auto",children:l.jsx(Px,{enableDragDrop:!t})})]})}),l.jsx(gd,{direction:"horizontal",onResize:pe})]}),l.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[be(),$&&l.jsxs(l.Fragment,{children:[l.jsx(gd,{direction:"vertical",onResize:J}),l.jsx("div",{className:"flex-shrink-0 overflow-hidden bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700",style:{height:w.bottomPanel},children:l.jsxs("div",{className:"h-full flex flex-col",children:[l.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-200 dark:border-gray-700",children:[l.jsx("h2",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"데이터소스 / 상태"}),l.jsx("button",{className:"p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300",onClick:()=>M(!1),title:"패널 닫기",children:"✕"})]}),l.jsx("div",{className:"flex-1 overflow-auto p-4",children:l.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 text-center",children:"데이터소스 관리자 (Phase 3에서 구현)"})})]})})]})]}),N&&l.jsxs(l.Fragment,{children:[l.jsx(gd,{direction:"horizontal",onResize:we}),l.jsx("div",{className:"flex-shrink-0 overflow-hidden bg-white dark:bg-gray-800 border-l border-gray-200 dark:border-gray-700",style:{width:w.rightPanel},children:l.jsxs("div",{className:"h-full flex flex-col",children:[l.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-200 dark:border-gray-700",children:[l.jsx("h2",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"속성"}),l.jsx("button",{className:"p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300",onClick:()=>D(!1),title:"패널 닫기",children:"✕"})]}),l.jsx("div",{className:"flex-1 overflow-auto",children:l.jsx(Jx,{})})]})})]})]}),(!A||!N||!$)&&l.jsxs("div",{className:"fixed bottom-4 left-1/2 transform -translate-x-1/2 flex items-center gap-2 bg-white dark:bg-gray-800 rounded-lg shadow-lg px-4 py-2 border border-gray-200 dark:border-gray-700",children:[!A&&l.jsx("button",{className:"px-3 py-1 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:()=>O(!0),children:"📑 트리"}),!$&&l.jsx("button",{className:"px-3 py-1 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:()=>M(!0),children:"📊 데이터"}),!N&&l.jsx("button",{className:"px-3 py-1 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:()=>D(!0),children:"⚙️ 속성"})]}),t&&l.jsx("div",{className:"fixed top-16 right-4 bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-200 px-3 py-1 rounded-full text-sm font-medium shadow",children:"읽기 전용"})]})}function Qx({layoutData:r,templateId:e,onClose:t,onSaveComplete:a,onPublishComplete:i,initialEditMode:o="visual",readOnly:d=!1,className:g=""}){return l.jsx(Ix,{layoutData:r,templateId:e,initialEditMode:o,children:l.jsx(e_,{onClose:t,onSaveComplete:a,readOnly:d,className:g})})}const t_=Object.freeze(Object.defineProperty({__proto__:null,EditorOverlay:fh,EditorProvider:Ix,LayoutTree:Px,PreviewCanvas:uh,PropertyPanel:Jx,PropsEditor:Vx,Toolbar:zx,WysiwygEditor:Qx,addComponentToLayout:Go,deepCloneComponent:rh,default:Qx,duplicateComponentInLayout:Mx,findComponentById:jr,generateUniqueId:qo,isIdDuplicate:sh,moveComponentInLayout:od,removeComponentFromLayout:rd,selectCanRedo:cd,selectCanUndo:ld,updateComponentInLayout:id,useComponentMetadata:Vo,useEditorState:Se,useHistory:oh},Symbol.toStringTag,{value:"Module"}));ln.DataSourceManager=is,ln.LayoutLoader=Rg,ln.TemplateApp=Oo,ln.TemplateEngine=Io,ln.default=Io,ln.destroyTemplate=Bc,ln.getActionDispatcher=gx,ln.getState=Is,ln.initTemplateApp=Pg,ln.initTemplateEngine=Mo,ln.renderTemplate=$o,ln.updateTemplateData=fi,Object.defineProperties(ln,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})(this.G7Core=this.G7Core||{}); +{{$computed.canEdit}}`})]})]})]}),l.jsxs("div",{children:[l.jsx(ud,{title:"Raw JSON",isExpanded:t.rawJson,onToggle:()=>i("rawJson")}),t.rawJson&&l.jsx("div",{className:"mt-3",children:l.jsx("pre",{className:"p-3 bg-gray-50 dark:bg-gray-800 rounded border border-gray-200 dark:border-gray-700 text-xs text-gray-600 dark:text-gray-400 overflow-auto max-h-96",children:JSON.stringify(r,null,2)})})]})]})}const FE=[{id:"props",label:"Props",icon:"⚙️",description:"기본 속성 편집"},{id:"bindings",label:"Bindings",icon:"🔗",description:"데이터 바인딩 설정"},{id:"actions",label:"Actions",icon:"⚡",description:"이벤트 핸들러 설정"},{id:"conditions",label:"Conditions",icon:"🔀",description:"조건부/반복 렌더링"},{id:"responsive",label:"Responsive",icon:"📱",description:"반응형 오버라이드"},{id:"advanced",label:"Advanced",icon:"🔧",description:"고급 설정"}];function VE({tab:r,isActive:e,onClick:t}){return l.jsxs("button",{className:`flex items-center gap-1 px-3 py-2 text-sm font-medium border-b-2 transition-colors ${e?"border-blue-500 text-blue-600 dark:text-blue-400":"border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:border-gray-300 dark:hover:border-gray-600"}`,onClick:t,title:r.description,children:[l.jsx("span",{children:r.icon}),l.jsx("span",{className:"hidden lg:inline",children:r.label})]})}function KE(){return l.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-8 text-gray-500 dark:text-gray-400",children:[l.jsx("div",{className:"text-4xl mb-4",children:"👆"}),l.jsx("h3",{className:"text-lg font-medium mb-2",children:"컴포넌트를 선택하세요"}),l.jsx("p",{className:"text-sm text-center",children:"편집할 컴포넌트를 미리보기 캔버스 또는 레이아웃 트리에서 클릭하세요."})]})}function WE({component:r}){const{getMetadata:e}=Ko(),t=e(r.name);return l.jsxs("div",{className:"px-4 py-3 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-lg",children:r.type==="basic"?"📦":r.type==="composite"?"🧩":r.type==="layout"?"📐":"🔌"}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("h3",{className:"text-sm font-semibold text-gray-900 dark:text-white truncate",children:r.name}),l.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 truncate",children:["ID: ",r.id]})]}),l.jsx("span",{className:`px-2 py-0.5 text-xs rounded ${r.type==="basic"?"bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300":r.type==="composite"?"bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300":r.type==="layout"?"bg-orange-100 dark:bg-orange-900 text-orange-700 dark:text-orange-300":"bg-purple-100 dark:bg-purple-900 text-purple-700 dark:text-purple-300"}`,children:r.type})]}),t?.description&&l.jsx("p",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400",children:t.description})]})}function Xx({className:r=""}){const[e,t]=j.useState("props"),a=Se(p=>p.layoutData),i=Se(p=>p.selectedComponentId),o=Se(p=>p.updateComponentProps),d=Se(p=>p.updateComponent),g=j.useMemo(()=>{if(!a||!i)return null;const p=y=>{for(const x of y)if(typeof x!="string"){if(x.id===i)return x;if(x.children){const S=p(x.children);if(S)return S}}return null};return p(a.components)},[a,i]),h=j.useCallback(p=>{!i||!g||(Object.keys(p).length===1&&p.props?o(i,p.props):d(i,p))},[i,g,o,d]);if(!g)return l.jsx("div",{className:`h-full bg-white dark:bg-gray-900 border-l border-gray-200 dark:border-gray-700 ${r}`,children:l.jsx(KE,{})});const f=()=>{switch(e){case"props":return l.jsx(Kx,{component:g,onChange:h});case"bindings":return l.jsx(TE,{component:g,onChange:h});case"actions":return l.jsx(OE,{component:g,onChange:h});case"conditions":return l.jsx(IE,{component:g,onChange:h});case"responsive":return l.jsx(BE,{component:g,onChange:h});case"advanced":return l.jsx(GE,{component:g,onChange:h});default:return null}};return l.jsxs("div",{className:`flex flex-col h-full bg-white dark:bg-gray-900 border-l border-gray-200 dark:border-gray-700 ${r}`,children:[l.jsx(WE,{component:g}),l.jsx("div",{className:"flex border-b border-gray-200 dark:border-gray-700 overflow-x-auto",children:FE.map(p=>l.jsx(VE,{tab:p,isActive:e===p.id,onClick:()=>t(p.id)},p.id))}),l.jsx("div",{className:"flex-1 overflow-auto",children:f()})]})}const Wo=it("EditorOverlay");function YE({rect:r,componentId:e,onCopy:t,onDuplicate:a,onDelete:i,onMoveUp:o,onMoveDown:d}){const g=Math.max(0,r.top-36),h=window.innerWidth-r.right;return l.jsxs("div",{className:"fixed z-50 flex items-center gap-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg px-1 py-1",style:{top:g,right:Math.max(8,h)},onClick:f=>f.stopPropagation(),children:[l.jsx("button",{className:"p-1.5 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:o,title:"위로 이동",children:"⬆️"}),l.jsx("button",{className:"p-1.5 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:d,title:"아래로 이동",children:"⬇️"}),l.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700 mx-1"}),l.jsx("button",{className:"p-1.5 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:t,title:"복사",children:"📋"}),l.jsx("button",{className:"p-1.5 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:a,title:"복제",children:"📑"}),l.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700 mx-1"}),l.jsx("button",{className:"p-1.5 text-red-500 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 hover:bg-red-50 dark:hover:bg-red-900 rounded",onClick:i,title:"삭제",children:"🗑️"}),l.jsx("div",{className:"ml-2 px-2 py-0.5 text-xs text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-700 rounded",children:e})]})}function JE({rect:r,position:e}){const t={position:"fixed",pointerEvents:"none",zIndex:40};return e==="before"?l.jsx("div",{style:{...t,left:r.left,top:r.top-2,width:r.width,height:4},className:"bg-blue-500"}):e==="after"?l.jsx("div",{style:{...t,left:r.left,top:r.bottom-2,width:r.width,height:4},className:"bg-blue-500"}):e==="inside"?l.jsx("div",{style:{...t,left:r.left,top:r.top,width:r.width,height:r.height},className:"border-2 border-dashed border-blue-500 bg-blue-500 bg-opacity-10"}):null}function Qx({rect:r,containerRect:e,type:t,label:a}){const i=t==="selected",o=e?e.left:0,d=e?e.top:0;return l.jsxs("div",{className:`absolute pointer-events-none ${i?"border-2 border-blue-500":"border border-dashed border-green-500"}`,style:{left:r.left-o,top:r.top-d,width:r.width,height:r.height,zIndex:i?31:30},children:[i&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"absolute -left-1 -top-1 w-2 h-2 bg-blue-500 rounded-full"}),l.jsx("div",{className:"absolute -right-1 -top-1 w-2 h-2 bg-blue-500 rounded-full"}),l.jsx("div",{className:"absolute -left-1 -bottom-1 w-2 h-2 bg-blue-500 rounded-full"}),l.jsx("div",{className:"absolute -right-1 -bottom-1 w-2 h-2 bg-blue-500 rounded-full"})]}),a&&l.jsx("div",{className:`absolute -top-6 left-0 px-1.5 py-0.5 text-xs text-white rounded whitespace-nowrap ${i?"bg-blue-500":"bg-green-500"}`,children:a})]})}function fh({containerRef:r,enabled:e=!0,selectionMode:t=!0}){const a=j.useRef(null),i=Se(J=>J.layoutData),o=Se(J=>J.selectedComponentId),d=Se(J=>J.hoveredComponentId),g=Se(J=>J.selectComponent),h=Se(J=>J.setHoveredComponentId),f=Se(J=>J.deleteComponent),p=Se(J=>J.duplicateComponent),y=Se(J=>J.copyToClipboard);Se(J=>J.moveComponent);const[x,S]=j.useState([]),[v,w]=j.useState(null),[k,A]=j.useState({isDragging:!1,targetId:null,position:null,targetRect:null}),O=j.useCallback(()=>{if(!r.current||!i)return[];const J=r.current.querySelectorAll("[data-editor-id]"),ve=[],le=(de,je)=>{for(const W of de)if(typeof W!="string"){if(W.id===je)return W;if(W.children){const he=le(W.children,je);if(he)return he}}return null};return J.forEach(de=>{const je=de.getAttribute("data-editor-id");if(!je)return;const W=de.getBoundingClientRect(),he=le(i.components,je);he&&ve.push({id:je,rect:W,component:he,isSelected:je===o,isHovered:je===d})}),ve},[r,i,o,d]),N=j.useCallback(()=>{S(O()),r.current&&w(r.current.getBoundingClientRect())},[O,r]);j.useEffect(()=>{if(!e)return;N();const J=()=>{requestAnimationFrame(N)};window.addEventListener("resize",J),window.addEventListener("scroll",J,!0);const ve=new ResizeObserver(J);r.current&&ve.observe(r.current);const le=new MutationObserver(J);return r.current&&le.observe(r.current,{childList:!0,subtree:!0,attributes:!0}),()=>{window.removeEventListener("resize",J),window.removeEventListener("scroll",J,!0),ve.disconnect(),le.disconnect()}},[e,r,N]),j.useCallback(J=>{if(!t)return;const ve=J.target;if(a.current?.contains(ve))return;let le=null;if(ve.hasAttribute("data-editor-id")?le=ve:le=ve.closest("[data-editor-id]"),le){const de=le.getAttribute("data-editor-id");de&&(g(de),J.preventDefault(),J.stopPropagation())}else g(null)},[t,g]),j.useCallback(J=>{const ve=J.target;if(a.current?.contains(ve))return;let le=null;if(ve.hasAttribute("data-editor-id")?le=ve:le=ve.closest("[data-editor-id]"),le){const de=le.getAttribute("data-editor-id");de&&de!==d&&h(de)}else d&&h(null)},[d,h]),j.useCallback(()=>{h(null)},[h]);const D=j.useCallback(()=>{if(!o)return;const J=x.find(ve=>ve.id===o);J&&(y(J.component),Wo.log("Copied:",o))},[o,x,y]),$=j.useCallback(()=>{o&&(p(o),Wo.log("Duplicated:",o))},[o,p]),M=j.useCallback(()=>{o&&(f(o),Wo.log("Deleted:",o))},[o,f]),z=j.useCallback(()=>{o&&Wo.log("Move up:",o)},[o]),K=j.useCallback(()=>{o&&Wo.log("Move down:",o)},[o]),ye=j.useMemo(()=>x.find(J=>J.isSelected),[x]),we=j.useMemo(()=>x.find(J=>J.isHovered&&!J.isSelected),[x]);return e?l.jsx(l.Fragment,{children:l.jsxs("div",{ref:a,className:"absolute inset-0 pointer-events-none z-20",children:[we&&l.jsx(Qx,{rect:we.rect,containerRect:v,type:"hovered",label:we.component.name}),ye&&l.jsxs(l.Fragment,{children:[l.jsx(Qx,{rect:ye.rect,containerRect:v,type:"selected",label:ye.component.name}),l.jsx("div",{className:"pointer-events-auto",children:l.jsx(YE,{rect:ye.rect,componentId:ye.id,onCopy:D,onDuplicate:$,onDelete:M,onMoveUp:z,onMoveDown:K})})]}),k.isDragging&&k.targetRect&&k.position&&l.jsx(JE,{rect:k.targetRect,position:k.position})]})}):null}const cs=it("WysiwygEditor"),XE={leftPanel:280,rightPanel:320,bottomPanel:200},ph=200,QE=400,ZE=500,e_=400;function gd({direction:r,onResize:e}){const[t,a]=j.useState(!1),i=j.useRef(0),o=j.useCallback(g=>{g.preventDefault(),a(!0),i.current=r==="horizontal"?g.clientX:g.clientY;const h=p=>{const y=r==="horizontal"?p.clientX:p.clientY,x=y-i.current;i.current=y,e(x)},f=()=>{a(!1),document.removeEventListener("mousemove",h),document.removeEventListener("mouseup",f)};document.addEventListener("mousemove",h),document.addEventListener("mouseup",f)},[r,e]),d=r==="horizontal";return l.jsx("div",{className:`${d?"w-1 cursor-col-resize":"h-1 cursor-row-resize"} bg-gray-200 dark:bg-gray-700 hover:bg-blue-400 dark:hover:bg-blue-600 transition-colors ${t?"bg-blue-500 dark:bg-blue-500":""}`,onMouseDown:o})}function t_({onClose:r,onSaveComplete:e,readOnly:t=!1,className:a=""}){const i=Se(le=>le.layoutData),o=Se(le=>le.editMode),d=Se(le=>le.selectedComponentId),g=Se(le=>le.saveLayout),h=Se(le=>le.selectComponent),f=Se(le=>le.deleteComponent),p=Se(le=>le.duplicateComponent),{undo:y,redo:x,canUndo:S,canRedo:v}=oh(),[w,k]=j.useState(XE),[A,O]=j.useState(!0),[N,D]=j.useState(!0),[$,M]=j.useState(!0),z=j.useRef(null);j.useEffect(()=>{const le=de=>{if(de.target instanceof HTMLInputElement||de.target instanceof HTMLTextAreaElement||de.target.contentEditable==="true")return;const W=navigator.platform.toUpperCase().indexOf("MAC")>=0?de.metaKey:de.ctrlKey;if(W&&de.key==="z"&&!de.shiftKey){de.preventDefault(),S&&(y(),cs.log("Keyboard shortcut: Undo"));return}if(W&&de.key==="z"&&de.shiftKey){de.preventDefault(),v&&(x(),cs.log("Keyboard shortcut: Redo"));return}if(W&&de.key==="y"){de.preventDefault(),v&&(x(),cs.log("Keyboard shortcut: Redo (Y)"));return}if(W&&de.key==="s"){de.preventDefault(),t||(K(),cs.log("Keyboard shortcut: Save"));return}if((de.key==="Delete"||de.key==="Backspace")&&d){de.preventDefault(),t||(f(d),cs.log("Keyboard shortcut: Delete"));return}if(W&&de.key==="d"&&d){de.preventDefault(),t||(p(d),cs.log("Keyboard shortcut: Duplicate"));return}if(de.key==="Escape"){de.preventDefault(),h(null),cs.log("Keyboard shortcut: Deselect");return}if(W&&de.key==="1"){de.preventDefault(),O(he=>!he);return}if(W&&de.key==="2"){de.preventDefault(),D(he=>!he);return}if(W&&de.key==="3"){de.preventDefault(),M(he=>!he);return}};return window.addEventListener("keydown",le),()=>window.removeEventListener("keydown",le)},[S,v,y,x,d,h,f,p,t]);const K=j.useCallback(async()=>{try{await g("Manual save"),i&&e&&e(i),cs.log("Layout saved successfully")}catch(le){cs.error("Failed to save layout:",le)}},[g,i,e]),ye=j.useCallback(le=>{k(de=>({...de,leftPanel:Math.min(QE,Math.max(ph,de.leftPanel+le))}))},[]),we=j.useCallback(le=>{k(de=>({...de,rightPanel:Math.min(ZE,Math.max(ph,de.rightPanel-le))}))},[]),J=j.useCallback(le=>{k(de=>({...de,bottomPanel:Math.min(e_,Math.max(ph,de.bottomPanel-le))}))},[]),ve=()=>{switch(o){case"visual":return l.jsxs("div",{ref:z,className:"relative flex-1 overflow-hidden",children:[l.jsx(uh,{showOverlay:!t}),!t&&l.jsx(fh,{containerRef:z})]});case"json":return l.jsx("div",{className:"flex-1 overflow-hidden bg-gray-900 p-4",children:l.jsx("pre",{className:"h-full overflow-auto text-sm text-green-400 font-mono",children:JSON.stringify(i,null,2)})});case"split":return l.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[l.jsxs("div",{ref:z,className:"relative flex-1 overflow-hidden",children:[l.jsx(uh,{showOverlay:!t}),!t&&l.jsx(fh,{containerRef:z})]}),l.jsx(gd,{direction:"horizontal",onResize:()=>{}}),l.jsx("div",{className:"flex-1 overflow-hidden bg-gray-900 p-4",children:l.jsx("pre",{className:"h-full overflow-auto text-sm text-green-400 font-mono",children:JSON.stringify(i,null,2)})})]});default:return null}};return l.jsxs("div",{className:`flex flex-col h-screen bg-gray-100 dark:bg-gray-900 ${a}`,children:[l.jsx(Hx,{onClose:r,onSaveComplete:K}),l.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[A&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"flex-shrink-0 overflow-hidden bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700",style:{width:w.leftPanel},children:l.jsxs("div",{className:"h-full flex flex-col",children:[l.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-200 dark:border-gray-700",children:[l.jsx("h2",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"레이아웃 트리"}),l.jsx("button",{className:"p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300",onClick:()=>O(!1),title:"패널 닫기",children:"✕"})]}),l.jsx("div",{className:"flex-1 overflow-auto",children:l.jsx(Bx,{enableDragDrop:!t})})]})}),l.jsx(gd,{direction:"horizontal",onResize:ye})]}),l.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[ve(),$&&l.jsxs(l.Fragment,{children:[l.jsx(gd,{direction:"vertical",onResize:J}),l.jsx("div",{className:"flex-shrink-0 overflow-hidden bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700",style:{height:w.bottomPanel},children:l.jsxs("div",{className:"h-full flex flex-col",children:[l.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-200 dark:border-gray-700",children:[l.jsx("h2",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"데이터소스 / 상태"}),l.jsx("button",{className:"p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300",onClick:()=>M(!1),title:"패널 닫기",children:"✕"})]}),l.jsx("div",{className:"flex-1 overflow-auto p-4",children:l.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 text-center",children:"데이터소스 관리자 (Phase 3에서 구현)"})})]})})]})]}),N&&l.jsxs(l.Fragment,{children:[l.jsx(gd,{direction:"horizontal",onResize:we}),l.jsx("div",{className:"flex-shrink-0 overflow-hidden bg-white dark:bg-gray-800 border-l border-gray-200 dark:border-gray-700",style:{width:w.rightPanel},children:l.jsxs("div",{className:"h-full flex flex-col",children:[l.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-200 dark:border-gray-700",children:[l.jsx("h2",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"속성"}),l.jsx("button",{className:"p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300",onClick:()=>D(!1),title:"패널 닫기",children:"✕"})]}),l.jsx("div",{className:"flex-1 overflow-auto",children:l.jsx(Xx,{})})]})})]})]}),(!A||!N||!$)&&l.jsxs("div",{className:"fixed bottom-4 left-1/2 transform -translate-x-1/2 flex items-center gap-2 bg-white dark:bg-gray-800 rounded-lg shadow-lg px-4 py-2 border border-gray-200 dark:border-gray-700",children:[!A&&l.jsx("button",{className:"px-3 py-1 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:()=>O(!0),children:"📑 트리"}),!$&&l.jsx("button",{className:"px-3 py-1 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:()=>M(!0),children:"📊 데이터"}),!N&&l.jsx("button",{className:"px-3 py-1 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",onClick:()=>D(!0),children:"⚙️ 속성"})]}),t&&l.jsx("div",{className:"fixed top-16 right-4 bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-200 px-3 py-1 rounded-full text-sm font-medium shadow",children:"읽기 전용"})]})}function Zx({layoutData:r,templateId:e,onClose:t,onSaveComplete:a,onPublishComplete:i,initialEditMode:o="visual",readOnly:d=!1,className:g=""}){return l.jsx(zx,{layoutData:r,templateId:e,initialEditMode:o,children:l.jsx(t_,{onClose:t,onSaveComplete:a,readOnly:d,className:g})})}const n_=Object.freeze(Object.defineProperty({__proto__:null,EditorOverlay:fh,EditorProvider:zx,LayoutTree:Bx,PreviewCanvas:uh,PropertyPanel:Xx,PropsEditor:Kx,Toolbar:Hx,WysiwygEditor:Zx,addComponentToLayout:Fo,deepCloneComponent:rh,default:Zx,duplicateComponentInLayout:$x,findComponentById:jr,generateUniqueId:Go,isIdDuplicate:sh,moveComponentInLayout:od,removeComponentFromLayout:rd,selectCanRedo:cd,selectCanUndo:ld,updateComponentInLayout:id,useComponentMetadata:Ko,useEditorState:Se,useHistory:oh},Symbol.toStringTag,{value:"Module"}));ln.DataSourceManager=is,ln.LayoutLoader=Rg,ln.TemplateApp=Oo,ln.TemplateEngine=zo,ln.default=zo,ln.destroyTemplate=Bc,ln.getActionDispatcher=hx,ln.getState=Is,ln.initTemplateApp=Pg,ln.initTemplateEngine=$o,ln.renderTemplate=Io,ln.updateTemplateData=fi,Object.defineProperties(ln,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})(this.G7Core=this.G7Core||{}); //# sourceMappingURL=template-engine.min.js.map diff --git a/public/build/core/template-engine.min.js.map b/public/build/core/template-engine.min.js.map index c5092bcc..4a86127e 100644 --- a/public/build/core/template-engine.min.js.map +++ b/public/build/core/template-engine.min.js.map @@ -1 +1 @@ -{"version":3,"file":"template-engine.min.js","sources":["../../../node_modules/react/cjs/react.production.js","../../../node_modules/react/index.js","../../../node_modules/scheduler/cjs/scheduler.production.js","../../../node_modules/scheduler/index.js","../../../node_modules/react-dom/cjs/react-dom.production.js","../../../node_modules/react-dom/index.js","../../../node_modules/react-dom/cjs/react-dom-client.production.js","../../../node_modules/react-dom/client.js","../../../resources/js/core/utils/Logger.ts","../../../resources/js/core/template-engine/ComponentRegistry.ts","../../../resources/js/core/template-engine/TranslationEngine.ts","../../../resources/js/core/template-engine/PipeRegistry.ts","../../../resources/js/core/template-engine/rawMarkers.ts","../../../resources/js/core/template-engine/DataBindingEngine.ts","../../../resources/js/core/template-engine/ResponsiveManager.ts","../../../resources/js/core/template-engine/helpers/ConditionEvaluator.ts","../../../resources/js/core/template-engine/helpers/RenderHelpers.ts","../../../node_modules/axios/lib/helpers/bind.js","../../../node_modules/axios/lib/utils.js","../../../node_modules/axios/lib/core/AxiosError.js","../../../node_modules/axios/lib/helpers/null.js","../../../node_modules/axios/lib/helpers/toFormData.js","../../../node_modules/axios/lib/helpers/AxiosURLSearchParams.js","../../../node_modules/axios/lib/helpers/buildURL.js","../../../node_modules/axios/lib/core/InterceptorManager.js","../../../node_modules/axios/lib/defaults/transitional.js","../../../node_modules/axios/lib/platform/browser/index.js","../../../node_modules/axios/lib/platform/browser/classes/URLSearchParams.js","../../../node_modules/axios/lib/platform/browser/classes/FormData.js","../../../node_modules/axios/lib/platform/browser/classes/Blob.js","../../../node_modules/axios/lib/platform/common/utils.js","../../../node_modules/axios/lib/platform/index.js","../../../node_modules/axios/lib/helpers/toURLEncodedForm.js","../../../node_modules/axios/lib/helpers/formDataToJSON.js","../../../node_modules/axios/lib/defaults/index.js","../../../node_modules/axios/lib/helpers/parseHeaders.js","../../../node_modules/axios/lib/core/AxiosHeaders.js","../../../node_modules/axios/lib/core/transformData.js","../../../node_modules/axios/lib/cancel/isCancel.js","../../../node_modules/axios/lib/cancel/CanceledError.js","../../../node_modules/axios/lib/core/settle.js","../../../node_modules/axios/lib/helpers/parseProtocol.js","../../../node_modules/axios/lib/helpers/speedometer.js","../../../node_modules/axios/lib/helpers/throttle.js","../../../node_modules/axios/lib/helpers/progressEventReducer.js","../../../node_modules/axios/lib/helpers/isURLSameOrigin.js","../../../node_modules/axios/lib/helpers/cookies.js","../../../node_modules/axios/lib/helpers/isAbsoluteURL.js","../../../node_modules/axios/lib/helpers/combineURLs.js","../../../node_modules/axios/lib/core/buildFullPath.js","../../../node_modules/axios/lib/core/mergeConfig.js","../../../node_modules/axios/lib/helpers/resolveConfig.js","../../../node_modules/axios/lib/adapters/xhr.js","../../../node_modules/axios/lib/helpers/composeSignals.js","../../../node_modules/axios/lib/helpers/trackStream.js","../../../node_modules/axios/lib/adapters/fetch.js","../../../node_modules/axios/lib/adapters/adapters.js","../../../node_modules/axios/lib/core/dispatchRequest.js","../../../node_modules/axios/lib/env/data.js","../../../node_modules/axios/lib/helpers/validator.js","../../../node_modules/axios/lib/core/Axios.js","../../../node_modules/axios/lib/cancel/CancelToken.js","../../../node_modules/axios/lib/helpers/spread.js","../../../node_modules/axios/lib/helpers/isAxiosError.js","../../../node_modules/axios/lib/helpers/HttpStatusCode.js","../../../node_modules/axios/lib/axios.js","../../../node_modules/axios/index.js","../../../resources/js/core/api/ApiClient.ts","../../../resources/js/core/auth/AuthManager.ts","../../../resources/js/core/types/ErrorHandling.ts","../../../resources/js/core/error/ErrorHandlingResolver.ts","../../../node_modules/react/cjs/react-jsx-runtime.production.js","../../../node_modules/react/jsx-runtime.js","../../../resources/js/core/template-engine/ParentContextProvider.tsx","../../../resources/js/core/template-engine/ActionDispatcher.ts","../../../resources/js/core/template-engine/TransitionManager.ts","../../../resources/js/core/template-engine/TransitionContext.tsx","../../../resources/js/core/template-engine/ResponsiveContext.tsx","../../../resources/js/core/hooks/useControllableState.ts","../../../resources/js/core/template-engine/FormContext.tsx","../../../resources/js/core/template-engine/IsolatedStateContext.tsx","../../../node_modules/@dnd-kit/utilities/dist/utilities.esm.js","../../../node_modules/@dnd-kit/accessibility/dist/accessibility.esm.js","../../../node_modules/@dnd-kit/core/dist/core.esm.js","../../../node_modules/@dnd-kit/sortable/dist/sortable.esm.js","../../../resources/js/core/template-engine/sortable/SortableContainer.tsx","../../../resources/js/core/template-engine/sortable/SortableContext.tsx","../../../resources/js/core/template-engine/sortable/SortableItemWrapper.tsx","../../../resources/js/core/template-engine/DynamicRenderer.tsx","../../../resources/js/core/devtools/types.ts","../../../resources/js/core/devtools/G7DevToolsCore.ts","../../../resources/js/core/template-engine/LayoutLoader.ts","../../../resources/js/core/template-engine/TranslationContext.tsx","../../../resources/js/core/template-engine/SlotContext.tsx","../../../node_modules/laravel-echo/dist/echo.js","../../../node_modules/pusher-js/dist/web/pusher.js","../../../resources/js/core/websocket/WebSocketManager.ts","../../../resources/js/core/template-engine/DataSourceManager.ts","../../../resources/js/core/template-engine/ModalDataSourceWrapper.tsx","../../../resources/js/core/template-engine/TemplateEngineError.ts","../../../resources/js/core/routing/Router.ts","../../../resources/js/core/template-engine/ErrorDisplay.ts","../../../resources/js/core/template-engine/ErrorPageHandler.ts","../../../resources/js/core/modules/ModuleAssetLoader.ts","../../../resources/js/core/template-engine/SystemBannerManager.ts","../../../resources/js/core/TemplateApp.ts","../../../resources/js/core/devtools/DiagnosticEngine.ts","../../../resources/js/core/devtools/ServerConnector.ts","../../../resources/js/core/devtools/ui/styles.ts","../../../resources/js/core/devtools/ui/constants.ts","../../../resources/js/core/devtools/ui/utils.ts","../../../resources/js/core/devtools/ui/components/JsonTreeNode.tsx","../../../resources/js/core/devtools/ui/tabs/StateTab.tsx","../../../resources/js/core/devtools/ui/tabs/ActionsTab.tsx","../../../resources/js/core/devtools/ui/tabs/CacheTab.tsx","../../../resources/js/core/devtools/ui/tabs/DiagnoseTab.tsx","../../../resources/js/core/devtools/ui/tabs/PerformanceTab.tsx","../../../resources/js/core/devtools/ui/tabs/LifecycleTab.tsx","../../../resources/js/core/devtools/ui/tabs/NetworkTab.tsx","../../../resources/js/core/devtools/ui/tabs/FormTab.tsx","../../../resources/js/core/devtools/ui/tabs/ConditionalTab.tsx","../../../resources/js/core/devtools/ui/tabs/ExpressionTab.tsx","../../../resources/js/core/devtools/ui/tabs/HandlersTab.tsx","../../../resources/js/core/devtools/ui/tabs/EventsTab.tsx","../../../resources/js/core/devtools/ui/tabs/DataSourcesTab.tsx","../../../resources/js/core/devtools/ui/tabs/RendersTab.tsx","../../../resources/js/core/devtools/ui/tabs/StylesTab.tsx","../../../resources/js/core/devtools/ui/tabs/AuthTab.tsx","../../../resources/js/core/devtools/ui/tabs/LogsTab.tsx","../../../resources/js/core/devtools/ui/tabs/LayoutTab.tsx","../../../resources/js/core/devtools/ui/tabs/ChangeDetectionTab.tsx","../../../resources/js/core/devtools/ui/tabs/StaleClosureTab.tsx","../../../resources/js/core/devtools/ui/tabs/NestedContextTab.tsx","../../../resources/js/core/devtools/ui/tabs/ModalScopeTab.tsx","../../../resources/js/core/devtools/ui/tabs/NamedActionsTab.tsx","../../../resources/js/core/devtools/ui/DevToolsPanel.tsx","../../../resources/js/core/devtools/StyleTracker.ts","../../../resources/js/core/template-engine/helpers/EventHelpers.ts","../../../resources/js/core/template-engine/helpers/StyleHelpers.ts","../../../resources/js/core/template-engine/G7CoreGlobals.ts","../../../resources/js/core/template-engine.ts","../../../node_modules/zustand/esm/vanilla.mjs","../../../node_modules/zustand/esm/react.mjs","../../../node_modules/immer/dist/immer.mjs","../../../node_modules/zustand/esm/middleware/immer.mjs","../../../node_modules/zustand/esm/middleware.mjs","../../../resources/js/core/template-engine/wysiwyg/types/editor.ts","../../../resources/js/core/template-engine/wysiwyg/utils/layoutUtils.ts","../../../resources/js/core/template-engine/wysiwyg/hooks/useEditorState.ts","../../../resources/js/core/template-engine/wysiwyg/EditorContext.tsx","../../../resources/js/core/template-engine/wysiwyg/hooks/useHistory.ts","../../../resources/js/core/template-engine/wysiwyg/components/PropertyPanel/PermissionSelector.tsx","../../../resources/js/core/template-engine/wysiwyg/components/LayoutSettingsModal.tsx","../../../resources/js/core/template-engine/wysiwyg/components/Toolbar.tsx","../../../resources/js/core/template-engine/wysiwyg/components/LayoutTree.tsx","../../../resources/js/core/template-engine/wysiwyg/components/PreviewCanvas.tsx","../../../resources/js/core/template-engine/wysiwyg/hooks/useComponentMetadata.ts","../../../resources/js/core/template-engine/wysiwyg/components/PropertyPanel/PropsEditor.tsx","../../../resources/js/core/template-engine/wysiwyg/components/PropertyPanel/BindingsEditor.tsx","../../../resources/js/core/template-engine/wysiwyg/components/PropertyPanel/ActionsEditor.tsx","../../../resources/js/core/template-engine/wysiwyg/components/PropertyPanel/ConditionsEditor.tsx","../../../resources/js/core/template-engine/wysiwyg/components/PropertyPanel/ResponsiveEditor.tsx","../../../resources/js/core/template-engine/wysiwyg/components/PropertyPanel/ClassMapEditor.tsx","../../../resources/js/core/template-engine/wysiwyg/components/PropertyPanel/AdvancedEditor.tsx","../../../resources/js/core/template-engine/wysiwyg/components/PropertyPanel/index.tsx","../../../resources/js/core/template-engine/wysiwyg/components/EditorOverlay.tsx","../../../resources/js/core/template-engine/wysiwyg/WysiwygEditor.tsx"],"sourcesContent":["/**\n * @license React\n * react.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_PORTAL_TYPE = Symbol.for(\"react.portal\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\"),\n REACT_STRICT_MODE_TYPE = Symbol.for(\"react.strict_mode\"),\n REACT_PROFILER_TYPE = Symbol.for(\"react.profiler\"),\n REACT_CONSUMER_TYPE = Symbol.for(\"react.consumer\"),\n REACT_CONTEXT_TYPE = Symbol.for(\"react.context\"),\n REACT_FORWARD_REF_TYPE = Symbol.for(\"react.forward_ref\"),\n REACT_SUSPENSE_TYPE = Symbol.for(\"react.suspense\"),\n REACT_MEMO_TYPE = Symbol.for(\"react.memo\"),\n REACT_LAZY_TYPE = Symbol.for(\"react.lazy\"),\n REACT_ACTIVITY_TYPE = Symbol.for(\"react.activity\"),\n MAYBE_ITERATOR_SYMBOL = Symbol.iterator;\nfunction getIteratorFn(maybeIterable) {\n if (null === maybeIterable || \"object\" !== typeof maybeIterable) return null;\n maybeIterable =\n (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) ||\n maybeIterable[\"@@iterator\"];\n return \"function\" === typeof maybeIterable ? maybeIterable : null;\n}\nvar ReactNoopUpdateQueue = {\n isMounted: function () {\n return !1;\n },\n enqueueForceUpdate: function () {},\n enqueueReplaceState: function () {},\n enqueueSetState: function () {}\n },\n assign = Object.assign,\n emptyObject = {};\nfunction Component(props, context, updater) {\n this.props = props;\n this.context = context;\n this.refs = emptyObject;\n this.updater = updater || ReactNoopUpdateQueue;\n}\nComponent.prototype.isReactComponent = {};\nComponent.prototype.setState = function (partialState, callback) {\n if (\n \"object\" !== typeof partialState &&\n \"function\" !== typeof partialState &&\n null != partialState\n )\n throw Error(\n \"takes an object of state variables to update or a function which returns an object of state variables.\"\n );\n this.updater.enqueueSetState(this, partialState, callback, \"setState\");\n};\nComponent.prototype.forceUpdate = function (callback) {\n this.updater.enqueueForceUpdate(this, callback, \"forceUpdate\");\n};\nfunction ComponentDummy() {}\nComponentDummy.prototype = Component.prototype;\nfunction PureComponent(props, context, updater) {\n this.props = props;\n this.context = context;\n this.refs = emptyObject;\n this.updater = updater || ReactNoopUpdateQueue;\n}\nvar pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());\npureComponentPrototype.constructor = PureComponent;\nassign(pureComponentPrototype, Component.prototype);\npureComponentPrototype.isPureReactComponent = !0;\nvar isArrayImpl = Array.isArray;\nfunction noop() {}\nvar ReactSharedInternals = { H: null, A: null, T: null, S: null },\n hasOwnProperty = Object.prototype.hasOwnProperty;\nfunction ReactElement(type, key, props) {\n var refProp = props.ref;\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n ref: void 0 !== refProp ? refProp : null,\n props: props\n };\n}\nfunction cloneAndReplaceKey(oldElement, newKey) {\n return ReactElement(oldElement.type, newKey, oldElement.props);\n}\nfunction isValidElement(object) {\n return (\n \"object\" === typeof object &&\n null !== object &&\n object.$$typeof === REACT_ELEMENT_TYPE\n );\n}\nfunction escape(key) {\n var escaperLookup = { \"=\": \"=0\", \":\": \"=2\" };\n return (\n \"$\" +\n key.replace(/[=:]/g, function (match) {\n return escaperLookup[match];\n })\n );\n}\nvar userProvidedKeyEscapeRegex = /\\/+/g;\nfunction getElementKey(element, index) {\n return \"object\" === typeof element && null !== element && null != element.key\n ? escape(\"\" + element.key)\n : index.toString(36);\n}\nfunction resolveThenable(thenable) {\n switch (thenable.status) {\n case \"fulfilled\":\n return thenable.value;\n case \"rejected\":\n throw thenable.reason;\n default:\n switch (\n (\"string\" === typeof thenable.status\n ? thenable.then(noop, noop)\n : ((thenable.status = \"pending\"),\n thenable.then(\n function (fulfilledValue) {\n \"pending\" === thenable.status &&\n ((thenable.status = \"fulfilled\"),\n (thenable.value = fulfilledValue));\n },\n function (error) {\n \"pending\" === thenable.status &&\n ((thenable.status = \"rejected\"), (thenable.reason = error));\n }\n )),\n thenable.status)\n ) {\n case \"fulfilled\":\n return thenable.value;\n case \"rejected\":\n throw thenable.reason;\n }\n }\n throw thenable;\n}\nfunction mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {\n var type = typeof children;\n if (\"undefined\" === type || \"boolean\" === type) children = null;\n var invokeCallback = !1;\n if (null === children) invokeCallback = !0;\n else\n switch (type) {\n case \"bigint\":\n case \"string\":\n case \"number\":\n invokeCallback = !0;\n break;\n case \"object\":\n switch (children.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_PORTAL_TYPE:\n invokeCallback = !0;\n break;\n case REACT_LAZY_TYPE:\n return (\n (invokeCallback = children._init),\n mapIntoArray(\n invokeCallback(children._payload),\n array,\n escapedPrefix,\n nameSoFar,\n callback\n )\n );\n }\n }\n if (invokeCallback)\n return (\n (callback = callback(children)),\n (invokeCallback =\n \"\" === nameSoFar ? \".\" + getElementKey(children, 0) : nameSoFar),\n isArrayImpl(callback)\n ? ((escapedPrefix = \"\"),\n null != invokeCallback &&\n (escapedPrefix =\n invokeCallback.replace(userProvidedKeyEscapeRegex, \"$&/\") + \"/\"),\n mapIntoArray(callback, array, escapedPrefix, \"\", function (c) {\n return c;\n }))\n : null != callback &&\n (isValidElement(callback) &&\n (callback = cloneAndReplaceKey(\n callback,\n escapedPrefix +\n (null == callback.key ||\n (children && children.key === callback.key)\n ? \"\"\n : (\"\" + callback.key).replace(\n userProvidedKeyEscapeRegex,\n \"$&/\"\n ) + \"/\") +\n invokeCallback\n )),\n array.push(callback)),\n 1\n );\n invokeCallback = 0;\n var nextNamePrefix = \"\" === nameSoFar ? \".\" : nameSoFar + \":\";\n if (isArrayImpl(children))\n for (var i = 0; i < children.length; i++)\n (nameSoFar = children[i]),\n (type = nextNamePrefix + getElementKey(nameSoFar, i)),\n (invokeCallback += mapIntoArray(\n nameSoFar,\n array,\n escapedPrefix,\n type,\n callback\n ));\n else if (((i = getIteratorFn(children)), \"function\" === typeof i))\n for (\n children = i.call(children), i = 0;\n !(nameSoFar = children.next()).done;\n\n )\n (nameSoFar = nameSoFar.value),\n (type = nextNamePrefix + getElementKey(nameSoFar, i++)),\n (invokeCallback += mapIntoArray(\n nameSoFar,\n array,\n escapedPrefix,\n type,\n callback\n ));\n else if (\"object\" === type) {\n if (\"function\" === typeof children.then)\n return mapIntoArray(\n resolveThenable(children),\n array,\n escapedPrefix,\n nameSoFar,\n callback\n );\n array = String(children);\n throw Error(\n \"Objects are not valid as a React child (found: \" +\n (\"[object Object]\" === array\n ? \"object with keys {\" + Object.keys(children).join(\", \") + \"}\"\n : array) +\n \"). If you meant to render a collection of children, use an array instead.\"\n );\n }\n return invokeCallback;\n}\nfunction mapChildren(children, func, context) {\n if (null == children) return children;\n var result = [],\n count = 0;\n mapIntoArray(children, result, \"\", \"\", function (child) {\n return func.call(context, child, count++);\n });\n return result;\n}\nfunction lazyInitializer(payload) {\n if (-1 === payload._status) {\n var ctor = payload._result;\n ctor = ctor();\n ctor.then(\n function (moduleObject) {\n if (0 === payload._status || -1 === payload._status)\n (payload._status = 1), (payload._result = moduleObject);\n },\n function (error) {\n if (0 === payload._status || -1 === payload._status)\n (payload._status = 2), (payload._result = error);\n }\n );\n -1 === payload._status && ((payload._status = 0), (payload._result = ctor));\n }\n if (1 === payload._status) return payload._result.default;\n throw payload._result;\n}\nvar reportGlobalError =\n \"function\" === typeof reportError\n ? reportError\n : function (error) {\n if (\n \"object\" === typeof window &&\n \"function\" === typeof window.ErrorEvent\n ) {\n var event = new window.ErrorEvent(\"error\", {\n bubbles: !0,\n cancelable: !0,\n message:\n \"object\" === typeof error &&\n null !== error &&\n \"string\" === typeof error.message\n ? String(error.message)\n : String(error),\n error: error\n });\n if (!window.dispatchEvent(event)) return;\n } else if (\n \"object\" === typeof process &&\n \"function\" === typeof process.emit\n ) {\n process.emit(\"uncaughtException\", error);\n return;\n }\n console.error(error);\n },\n Children = {\n map: mapChildren,\n forEach: function (children, forEachFunc, forEachContext) {\n mapChildren(\n children,\n function () {\n forEachFunc.apply(this, arguments);\n },\n forEachContext\n );\n },\n count: function (children) {\n var n = 0;\n mapChildren(children, function () {\n n++;\n });\n return n;\n },\n toArray: function (children) {\n return (\n mapChildren(children, function (child) {\n return child;\n }) || []\n );\n },\n only: function (children) {\n if (!isValidElement(children))\n throw Error(\n \"React.Children.only expected to receive a single React element child.\"\n );\n return children;\n }\n };\nexports.Activity = REACT_ACTIVITY_TYPE;\nexports.Children = Children;\nexports.Component = Component;\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.Profiler = REACT_PROFILER_TYPE;\nexports.PureComponent = PureComponent;\nexports.StrictMode = REACT_STRICT_MODE_TYPE;\nexports.Suspense = REACT_SUSPENSE_TYPE;\nexports.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE =\n ReactSharedInternals;\nexports.__COMPILER_RUNTIME = {\n __proto__: null,\n c: function (size) {\n return ReactSharedInternals.H.useMemoCache(size);\n }\n};\nexports.cache = function (fn) {\n return function () {\n return fn.apply(null, arguments);\n };\n};\nexports.cacheSignal = function () {\n return null;\n};\nexports.cloneElement = function (element, config, children) {\n if (null === element || void 0 === element)\n throw Error(\n \"The argument must be a React element, but you passed \" + element + \".\"\n );\n var props = assign({}, element.props),\n key = element.key;\n if (null != config)\n for (propName in (void 0 !== config.key && (key = \"\" + config.key), config))\n !hasOwnProperty.call(config, propName) ||\n \"key\" === propName ||\n \"__self\" === propName ||\n \"__source\" === propName ||\n (\"ref\" === propName && void 0 === config.ref) ||\n (props[propName] = config[propName]);\n var propName = arguments.length - 2;\n if (1 === propName) props.children = children;\n else if (1 < propName) {\n for (var childArray = Array(propName), i = 0; i < propName; i++)\n childArray[i] = arguments[i + 2];\n props.children = childArray;\n }\n return ReactElement(element.type, key, props);\n};\nexports.createContext = function (defaultValue) {\n defaultValue = {\n $$typeof: REACT_CONTEXT_TYPE,\n _currentValue: defaultValue,\n _currentValue2: defaultValue,\n _threadCount: 0,\n Provider: null,\n Consumer: null\n };\n defaultValue.Provider = defaultValue;\n defaultValue.Consumer = {\n $$typeof: REACT_CONSUMER_TYPE,\n _context: defaultValue\n };\n return defaultValue;\n};\nexports.createElement = function (type, config, children) {\n var propName,\n props = {},\n key = null;\n if (null != config)\n for (propName in (void 0 !== config.key && (key = \"\" + config.key), config))\n hasOwnProperty.call(config, propName) &&\n \"key\" !== propName &&\n \"__self\" !== propName &&\n \"__source\" !== propName &&\n (props[propName] = config[propName]);\n var childrenLength = arguments.length - 2;\n if (1 === childrenLength) props.children = children;\n else if (1 < childrenLength) {\n for (var childArray = Array(childrenLength), i = 0; i < childrenLength; i++)\n childArray[i] = arguments[i + 2];\n props.children = childArray;\n }\n if (type && type.defaultProps)\n for (propName in ((childrenLength = type.defaultProps), childrenLength))\n void 0 === props[propName] &&\n (props[propName] = childrenLength[propName]);\n return ReactElement(type, key, props);\n};\nexports.createRef = function () {\n return { current: null };\n};\nexports.forwardRef = function (render) {\n return { $$typeof: REACT_FORWARD_REF_TYPE, render: render };\n};\nexports.isValidElement = isValidElement;\nexports.lazy = function (ctor) {\n return {\n $$typeof: REACT_LAZY_TYPE,\n _payload: { _status: -1, _result: ctor },\n _init: lazyInitializer\n };\n};\nexports.memo = function (type, compare) {\n return {\n $$typeof: REACT_MEMO_TYPE,\n type: type,\n compare: void 0 === compare ? null : compare\n };\n};\nexports.startTransition = function (scope) {\n var prevTransition = ReactSharedInternals.T,\n currentTransition = {};\n ReactSharedInternals.T = currentTransition;\n try {\n var returnValue = scope(),\n onStartTransitionFinish = ReactSharedInternals.S;\n null !== onStartTransitionFinish &&\n onStartTransitionFinish(currentTransition, returnValue);\n \"object\" === typeof returnValue &&\n null !== returnValue &&\n \"function\" === typeof returnValue.then &&\n returnValue.then(noop, reportGlobalError);\n } catch (error) {\n reportGlobalError(error);\n } finally {\n null !== prevTransition &&\n null !== currentTransition.types &&\n (prevTransition.types = currentTransition.types),\n (ReactSharedInternals.T = prevTransition);\n }\n};\nexports.unstable_useCacheRefresh = function () {\n return ReactSharedInternals.H.useCacheRefresh();\n};\nexports.use = function (usable) {\n return ReactSharedInternals.H.use(usable);\n};\nexports.useActionState = function (action, initialState, permalink) {\n return ReactSharedInternals.H.useActionState(action, initialState, permalink);\n};\nexports.useCallback = function (callback, deps) {\n return ReactSharedInternals.H.useCallback(callback, deps);\n};\nexports.useContext = function (Context) {\n return ReactSharedInternals.H.useContext(Context);\n};\nexports.useDebugValue = function () {};\nexports.useDeferredValue = function (value, initialValue) {\n return ReactSharedInternals.H.useDeferredValue(value, initialValue);\n};\nexports.useEffect = function (create, deps) {\n return ReactSharedInternals.H.useEffect(create, deps);\n};\nexports.useEffectEvent = function (callback) {\n return ReactSharedInternals.H.useEffectEvent(callback);\n};\nexports.useId = function () {\n return ReactSharedInternals.H.useId();\n};\nexports.useImperativeHandle = function (ref, create, deps) {\n return ReactSharedInternals.H.useImperativeHandle(ref, create, deps);\n};\nexports.useInsertionEffect = function (create, deps) {\n return ReactSharedInternals.H.useInsertionEffect(create, deps);\n};\nexports.useLayoutEffect = function (create, deps) {\n return ReactSharedInternals.H.useLayoutEffect(create, deps);\n};\nexports.useMemo = function (create, deps) {\n return ReactSharedInternals.H.useMemo(create, deps);\n};\nexports.useOptimistic = function (passthrough, reducer) {\n return ReactSharedInternals.H.useOptimistic(passthrough, reducer);\n};\nexports.useReducer = function (reducer, initialArg, init) {\n return ReactSharedInternals.H.useReducer(reducer, initialArg, init);\n};\nexports.useRef = function (initialValue) {\n return ReactSharedInternals.H.useRef(initialValue);\n};\nexports.useState = function (initialState) {\n return ReactSharedInternals.H.useState(initialState);\n};\nexports.useSyncExternalStore = function (\n subscribe,\n getSnapshot,\n getServerSnapshot\n) {\n return ReactSharedInternals.H.useSyncExternalStore(\n subscribe,\n getSnapshot,\n getServerSnapshot\n );\n};\nexports.useTransition = function () {\n return ReactSharedInternals.H.useTransition();\n};\nexports.version = \"19.2.0\";\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react.production.js');\n} else {\n module.exports = require('./cjs/react.development.js');\n}\n","/**\n * @license React\n * scheduler.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nfunction push(heap, node) {\n var index = heap.length;\n heap.push(node);\n a: for (; 0 < index; ) {\n var parentIndex = (index - 1) >>> 1,\n parent = heap[parentIndex];\n if (0 < compare(parent, node))\n (heap[parentIndex] = node), (heap[index] = parent), (index = parentIndex);\n else break a;\n }\n}\nfunction peek(heap) {\n return 0 === heap.length ? null : heap[0];\n}\nfunction pop(heap) {\n if (0 === heap.length) return null;\n var first = heap[0],\n last = heap.pop();\n if (last !== first) {\n heap[0] = last;\n a: for (\n var index = 0, length = heap.length, halfLength = length >>> 1;\n index < halfLength;\n\n ) {\n var leftIndex = 2 * (index + 1) - 1,\n left = heap[leftIndex],\n rightIndex = leftIndex + 1,\n right = heap[rightIndex];\n if (0 > compare(left, last))\n rightIndex < length && 0 > compare(right, left)\n ? ((heap[index] = right),\n (heap[rightIndex] = last),\n (index = rightIndex))\n : ((heap[index] = left),\n (heap[leftIndex] = last),\n (index = leftIndex));\n else if (rightIndex < length && 0 > compare(right, last))\n (heap[index] = right), (heap[rightIndex] = last), (index = rightIndex);\n else break a;\n }\n }\n return first;\n}\nfunction compare(a, b) {\n var diff = a.sortIndex - b.sortIndex;\n return 0 !== diff ? diff : a.id - b.id;\n}\nexports.unstable_now = void 0;\nif (\"object\" === typeof performance && \"function\" === typeof performance.now) {\n var localPerformance = performance;\n exports.unstable_now = function () {\n return localPerformance.now();\n };\n} else {\n var localDate = Date,\n initialTime = localDate.now();\n exports.unstable_now = function () {\n return localDate.now() - initialTime;\n };\n}\nvar taskQueue = [],\n timerQueue = [],\n taskIdCounter = 1,\n currentTask = null,\n currentPriorityLevel = 3,\n isPerformingWork = !1,\n isHostCallbackScheduled = !1,\n isHostTimeoutScheduled = !1,\n needsPaint = !1,\n localSetTimeout = \"function\" === typeof setTimeout ? setTimeout : null,\n localClearTimeout = \"function\" === typeof clearTimeout ? clearTimeout : null,\n localSetImmediate = \"undefined\" !== typeof setImmediate ? setImmediate : null;\nfunction advanceTimers(currentTime) {\n for (var timer = peek(timerQueue); null !== timer; ) {\n if (null === timer.callback) pop(timerQueue);\n else if (timer.startTime <= currentTime)\n pop(timerQueue),\n (timer.sortIndex = timer.expirationTime),\n push(taskQueue, timer);\n else break;\n timer = peek(timerQueue);\n }\n}\nfunction handleTimeout(currentTime) {\n isHostTimeoutScheduled = !1;\n advanceTimers(currentTime);\n if (!isHostCallbackScheduled)\n if (null !== peek(taskQueue))\n (isHostCallbackScheduled = !0),\n isMessageLoopRunning ||\n ((isMessageLoopRunning = !0), schedulePerformWorkUntilDeadline());\n else {\n var firstTimer = peek(timerQueue);\n null !== firstTimer &&\n requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);\n }\n}\nvar isMessageLoopRunning = !1,\n taskTimeoutID = -1,\n frameInterval = 5,\n startTime = -1;\nfunction shouldYieldToHost() {\n return needsPaint\n ? !0\n : exports.unstable_now() - startTime < frameInterval\n ? !1\n : !0;\n}\nfunction performWorkUntilDeadline() {\n needsPaint = !1;\n if (isMessageLoopRunning) {\n var currentTime = exports.unstable_now();\n startTime = currentTime;\n var hasMoreWork = !0;\n try {\n a: {\n isHostCallbackScheduled = !1;\n isHostTimeoutScheduled &&\n ((isHostTimeoutScheduled = !1),\n localClearTimeout(taskTimeoutID),\n (taskTimeoutID = -1));\n isPerformingWork = !0;\n var previousPriorityLevel = currentPriorityLevel;\n try {\n b: {\n advanceTimers(currentTime);\n for (\n currentTask = peek(taskQueue);\n null !== currentTask &&\n !(\n currentTask.expirationTime > currentTime && shouldYieldToHost()\n );\n\n ) {\n var callback = currentTask.callback;\n if (\"function\" === typeof callback) {\n currentTask.callback = null;\n currentPriorityLevel = currentTask.priorityLevel;\n var continuationCallback = callback(\n currentTask.expirationTime <= currentTime\n );\n currentTime = exports.unstable_now();\n if (\"function\" === typeof continuationCallback) {\n currentTask.callback = continuationCallback;\n advanceTimers(currentTime);\n hasMoreWork = !0;\n break b;\n }\n currentTask === peek(taskQueue) && pop(taskQueue);\n advanceTimers(currentTime);\n } else pop(taskQueue);\n currentTask = peek(taskQueue);\n }\n if (null !== currentTask) hasMoreWork = !0;\n else {\n var firstTimer = peek(timerQueue);\n null !== firstTimer &&\n requestHostTimeout(\n handleTimeout,\n firstTimer.startTime - currentTime\n );\n hasMoreWork = !1;\n }\n }\n break a;\n } finally {\n (currentTask = null),\n (currentPriorityLevel = previousPriorityLevel),\n (isPerformingWork = !1);\n }\n hasMoreWork = void 0;\n }\n } finally {\n hasMoreWork\n ? schedulePerformWorkUntilDeadline()\n : (isMessageLoopRunning = !1);\n }\n }\n}\nvar schedulePerformWorkUntilDeadline;\nif (\"function\" === typeof localSetImmediate)\n schedulePerformWorkUntilDeadline = function () {\n localSetImmediate(performWorkUntilDeadline);\n };\nelse if (\"undefined\" !== typeof MessageChannel) {\n var channel = new MessageChannel(),\n port = channel.port2;\n channel.port1.onmessage = performWorkUntilDeadline;\n schedulePerformWorkUntilDeadline = function () {\n port.postMessage(null);\n };\n} else\n schedulePerformWorkUntilDeadline = function () {\n localSetTimeout(performWorkUntilDeadline, 0);\n };\nfunction requestHostTimeout(callback, ms) {\n taskTimeoutID = localSetTimeout(function () {\n callback(exports.unstable_now());\n }, ms);\n}\nexports.unstable_IdlePriority = 5;\nexports.unstable_ImmediatePriority = 1;\nexports.unstable_LowPriority = 4;\nexports.unstable_NormalPriority = 3;\nexports.unstable_Profiling = null;\nexports.unstable_UserBlockingPriority = 2;\nexports.unstable_cancelCallback = function (task) {\n task.callback = null;\n};\nexports.unstable_forceFrameRate = function (fps) {\n 0 > fps || 125 < fps\n ? console.error(\n \"forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported\"\n )\n : (frameInterval = 0 < fps ? Math.floor(1e3 / fps) : 5);\n};\nexports.unstable_getCurrentPriorityLevel = function () {\n return currentPriorityLevel;\n};\nexports.unstable_next = function (eventHandler) {\n switch (currentPriorityLevel) {\n case 1:\n case 2:\n case 3:\n var priorityLevel = 3;\n break;\n default:\n priorityLevel = currentPriorityLevel;\n }\n var previousPriorityLevel = currentPriorityLevel;\n currentPriorityLevel = priorityLevel;\n try {\n return eventHandler();\n } finally {\n currentPriorityLevel = previousPriorityLevel;\n }\n};\nexports.unstable_requestPaint = function () {\n needsPaint = !0;\n};\nexports.unstable_runWithPriority = function (priorityLevel, eventHandler) {\n switch (priorityLevel) {\n case 1:\n case 2:\n case 3:\n case 4:\n case 5:\n break;\n default:\n priorityLevel = 3;\n }\n var previousPriorityLevel = currentPriorityLevel;\n currentPriorityLevel = priorityLevel;\n try {\n return eventHandler();\n } finally {\n currentPriorityLevel = previousPriorityLevel;\n }\n};\nexports.unstable_scheduleCallback = function (\n priorityLevel,\n callback,\n options\n) {\n var currentTime = exports.unstable_now();\n \"object\" === typeof options && null !== options\n ? ((options = options.delay),\n (options =\n \"number\" === typeof options && 0 < options\n ? currentTime + options\n : currentTime))\n : (options = currentTime);\n switch (priorityLevel) {\n case 1:\n var timeout = -1;\n break;\n case 2:\n timeout = 250;\n break;\n case 5:\n timeout = 1073741823;\n break;\n case 4:\n timeout = 1e4;\n break;\n default:\n timeout = 5e3;\n }\n timeout = options + timeout;\n priorityLevel = {\n id: taskIdCounter++,\n callback: callback,\n priorityLevel: priorityLevel,\n startTime: options,\n expirationTime: timeout,\n sortIndex: -1\n };\n options > currentTime\n ? ((priorityLevel.sortIndex = options),\n push(timerQueue, priorityLevel),\n null === peek(taskQueue) &&\n priorityLevel === peek(timerQueue) &&\n (isHostTimeoutScheduled\n ? (localClearTimeout(taskTimeoutID), (taskTimeoutID = -1))\n : (isHostTimeoutScheduled = !0),\n requestHostTimeout(handleTimeout, options - currentTime)))\n : ((priorityLevel.sortIndex = timeout),\n push(taskQueue, priorityLevel),\n isHostCallbackScheduled ||\n isPerformingWork ||\n ((isHostCallbackScheduled = !0),\n isMessageLoopRunning ||\n ((isMessageLoopRunning = !0), schedulePerformWorkUntilDeadline())));\n return priorityLevel;\n};\nexports.unstable_shouldYield = shouldYieldToHost;\nexports.unstable_wrapCallback = function (callback) {\n var parentPriorityLevel = currentPriorityLevel;\n return function () {\n var previousPriorityLevel = currentPriorityLevel;\n currentPriorityLevel = parentPriorityLevel;\n try {\n return callback.apply(this, arguments);\n } finally {\n currentPriorityLevel = previousPriorityLevel;\n }\n };\n};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n","/**\n * @license React\n * react-dom.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar React = require(\"react\");\nfunction formatProdErrorMessage(code) {\n var url = \"https://react.dev/errors/\" + code;\n if (1 < arguments.length) {\n url += \"?args[]=\" + encodeURIComponent(arguments[1]);\n for (var i = 2; i < arguments.length; i++)\n url += \"&args[]=\" + encodeURIComponent(arguments[i]);\n }\n return (\n \"Minified React error #\" +\n code +\n \"; visit \" +\n url +\n \" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.\"\n );\n}\nfunction noop() {}\nvar Internals = {\n d: {\n f: noop,\n r: function () {\n throw Error(formatProdErrorMessage(522));\n },\n D: noop,\n C: noop,\n L: noop,\n m: noop,\n X: noop,\n S: noop,\n M: noop\n },\n p: 0,\n findDOMNode: null\n },\n REACT_PORTAL_TYPE = Symbol.for(\"react.portal\");\nfunction createPortal$1(children, containerInfo, implementation) {\n var key =\n 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null;\n return {\n $$typeof: REACT_PORTAL_TYPE,\n key: null == key ? null : \"\" + key,\n children: children,\n containerInfo: containerInfo,\n implementation: implementation\n };\n}\nvar ReactSharedInternals =\n React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;\nfunction getCrossOriginStringAs(as, input) {\n if (\"font\" === as) return \"\";\n if (\"string\" === typeof input)\n return \"use-credentials\" === input ? input : \"\";\n}\nexports.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE =\n Internals;\nexports.createPortal = function (children, container) {\n var key =\n 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : null;\n if (\n !container ||\n (1 !== container.nodeType &&\n 9 !== container.nodeType &&\n 11 !== container.nodeType)\n )\n throw Error(formatProdErrorMessage(299));\n return createPortal$1(children, container, null, key);\n};\nexports.flushSync = function (fn) {\n var previousTransition = ReactSharedInternals.T,\n previousUpdatePriority = Internals.p;\n try {\n if (((ReactSharedInternals.T = null), (Internals.p = 2), fn)) return fn();\n } finally {\n (ReactSharedInternals.T = previousTransition),\n (Internals.p = previousUpdatePriority),\n Internals.d.f();\n }\n};\nexports.preconnect = function (href, options) {\n \"string\" === typeof href &&\n (options\n ? ((options = options.crossOrigin),\n (options =\n \"string\" === typeof options\n ? \"use-credentials\" === options\n ? options\n : \"\"\n : void 0))\n : (options = null),\n Internals.d.C(href, options));\n};\nexports.prefetchDNS = function (href) {\n \"string\" === typeof href && Internals.d.D(href);\n};\nexports.preinit = function (href, options) {\n if (\"string\" === typeof href && options && \"string\" === typeof options.as) {\n var as = options.as,\n crossOrigin = getCrossOriginStringAs(as, options.crossOrigin),\n integrity =\n \"string\" === typeof options.integrity ? options.integrity : void 0,\n fetchPriority =\n \"string\" === typeof options.fetchPriority\n ? options.fetchPriority\n : void 0;\n \"style\" === as\n ? Internals.d.S(\n href,\n \"string\" === typeof options.precedence ? options.precedence : void 0,\n {\n crossOrigin: crossOrigin,\n integrity: integrity,\n fetchPriority: fetchPriority\n }\n )\n : \"script\" === as &&\n Internals.d.X(href, {\n crossOrigin: crossOrigin,\n integrity: integrity,\n fetchPriority: fetchPriority,\n nonce: \"string\" === typeof options.nonce ? options.nonce : void 0\n });\n }\n};\nexports.preinitModule = function (href, options) {\n if (\"string\" === typeof href)\n if (\"object\" === typeof options && null !== options) {\n if (null == options.as || \"script\" === options.as) {\n var crossOrigin = getCrossOriginStringAs(\n options.as,\n options.crossOrigin\n );\n Internals.d.M(href, {\n crossOrigin: crossOrigin,\n integrity:\n \"string\" === typeof options.integrity ? options.integrity : void 0,\n nonce: \"string\" === typeof options.nonce ? options.nonce : void 0\n });\n }\n } else null == options && Internals.d.M(href);\n};\nexports.preload = function (href, options) {\n if (\n \"string\" === typeof href &&\n \"object\" === typeof options &&\n null !== options &&\n \"string\" === typeof options.as\n ) {\n var as = options.as,\n crossOrigin = getCrossOriginStringAs(as, options.crossOrigin);\n Internals.d.L(href, as, {\n crossOrigin: crossOrigin,\n integrity:\n \"string\" === typeof options.integrity ? options.integrity : void 0,\n nonce: \"string\" === typeof options.nonce ? options.nonce : void 0,\n type: \"string\" === typeof options.type ? options.type : void 0,\n fetchPriority:\n \"string\" === typeof options.fetchPriority\n ? options.fetchPriority\n : void 0,\n referrerPolicy:\n \"string\" === typeof options.referrerPolicy\n ? options.referrerPolicy\n : void 0,\n imageSrcSet:\n \"string\" === typeof options.imageSrcSet ? options.imageSrcSet : void 0,\n imageSizes:\n \"string\" === typeof options.imageSizes ? options.imageSizes : void 0,\n media: \"string\" === typeof options.media ? options.media : void 0\n });\n }\n};\nexports.preloadModule = function (href, options) {\n if (\"string\" === typeof href)\n if (options) {\n var crossOrigin = getCrossOriginStringAs(options.as, options.crossOrigin);\n Internals.d.m(href, {\n as:\n \"string\" === typeof options.as && \"script\" !== options.as\n ? options.as\n : void 0,\n crossOrigin: crossOrigin,\n integrity:\n \"string\" === typeof options.integrity ? options.integrity : void 0\n });\n } else Internals.d.m(href);\n};\nexports.requestFormReset = function (form) {\n Internals.d.r(form);\n};\nexports.unstable_batchedUpdates = function (fn, a) {\n return fn(a);\n};\nexports.useFormState = function (action, initialState, permalink) {\n return ReactSharedInternals.H.useFormState(action, initialState, permalink);\n};\nexports.useFormStatus = function () {\n return ReactSharedInternals.H.useHostTransitionStatus();\n};\nexports.version = \"19.2.0\";\n","'use strict';\n\nfunction checkDCE() {\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\n if (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'\n ) {\n return;\n }\n if (process.env.NODE_ENV !== 'production') {\n // This branch is unreachable because this function is only called\n // in production, but the condition is true only in development.\n // Therefore if the branch is still here, dead code elimination wasn't\n // properly applied.\n // Don't change the message. React DevTools relies on it. Also make sure\n // this message doesn't occur elsewhere in this function, or it will cause\n // a false positive.\n throw new Error('^_^');\n }\n try {\n // Verify that the code above has been dead code eliminated (DCE'd).\n __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);\n } catch (err) {\n // DevTools shouldn't crash React, no matter what.\n // We should still report in case we break this code.\n console.error(err);\n }\n}\n\nif (process.env.NODE_ENV === 'production') {\n // DCE check should happen before ReactDOM bundle executes so that\n // DevTools can report bad minification during injection.\n checkDCE();\n module.exports = require('./cjs/react-dom.production.js');\n} else {\n module.exports = require('./cjs/react-dom.development.js');\n}\n","/**\n * @license React\n * react-dom-client.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n/*\n Modernizr 3.0.0pre (Custom Build) | MIT\n*/\n\"use strict\";\nvar Scheduler = require(\"scheduler\"),\n React = require(\"react\"),\n ReactDOM = require(\"react-dom\");\nfunction formatProdErrorMessage(code) {\n var url = \"https://react.dev/errors/\" + code;\n if (1 < arguments.length) {\n url += \"?args[]=\" + encodeURIComponent(arguments[1]);\n for (var i = 2; i < arguments.length; i++)\n url += \"&args[]=\" + encodeURIComponent(arguments[i]);\n }\n return (\n \"Minified React error #\" +\n code +\n \"; visit \" +\n url +\n \" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.\"\n );\n}\nfunction isValidContainer(node) {\n return !(\n !node ||\n (1 !== node.nodeType && 9 !== node.nodeType && 11 !== node.nodeType)\n );\n}\nfunction getNearestMountedFiber(fiber) {\n var node = fiber,\n nearestMounted = fiber;\n if (fiber.alternate) for (; node.return; ) node = node.return;\n else {\n fiber = node;\n do\n (node = fiber),\n 0 !== (node.flags & 4098) && (nearestMounted = node.return),\n (fiber = node.return);\n while (fiber);\n }\n return 3 === node.tag ? nearestMounted : null;\n}\nfunction getSuspenseInstanceFromFiber(fiber) {\n if (13 === fiber.tag) {\n var suspenseState = fiber.memoizedState;\n null === suspenseState &&\n ((fiber = fiber.alternate),\n null !== fiber && (suspenseState = fiber.memoizedState));\n if (null !== suspenseState) return suspenseState.dehydrated;\n }\n return null;\n}\nfunction getActivityInstanceFromFiber(fiber) {\n if (31 === fiber.tag) {\n var activityState = fiber.memoizedState;\n null === activityState &&\n ((fiber = fiber.alternate),\n null !== fiber && (activityState = fiber.memoizedState));\n if (null !== activityState) return activityState.dehydrated;\n }\n return null;\n}\nfunction assertIsMounted(fiber) {\n if (getNearestMountedFiber(fiber) !== fiber)\n throw Error(formatProdErrorMessage(188));\n}\nfunction findCurrentFiberUsingSlowPath(fiber) {\n var alternate = fiber.alternate;\n if (!alternate) {\n alternate = getNearestMountedFiber(fiber);\n if (null === alternate) throw Error(formatProdErrorMessage(188));\n return alternate !== fiber ? null : fiber;\n }\n for (var a = fiber, b = alternate; ; ) {\n var parentA = a.return;\n if (null === parentA) break;\n var parentB = parentA.alternate;\n if (null === parentB) {\n b = parentA.return;\n if (null !== b) {\n a = b;\n continue;\n }\n break;\n }\n if (parentA.child === parentB.child) {\n for (parentB = parentA.child; parentB; ) {\n if (parentB === a) return assertIsMounted(parentA), fiber;\n if (parentB === b) return assertIsMounted(parentA), alternate;\n parentB = parentB.sibling;\n }\n throw Error(formatProdErrorMessage(188));\n }\n if (a.return !== b.return) (a = parentA), (b = parentB);\n else {\n for (var didFindChild = !1, child$0 = parentA.child; child$0; ) {\n if (child$0 === a) {\n didFindChild = !0;\n a = parentA;\n b = parentB;\n break;\n }\n if (child$0 === b) {\n didFindChild = !0;\n b = parentA;\n a = parentB;\n break;\n }\n child$0 = child$0.sibling;\n }\n if (!didFindChild) {\n for (child$0 = parentB.child; child$0; ) {\n if (child$0 === a) {\n didFindChild = !0;\n a = parentB;\n b = parentA;\n break;\n }\n if (child$0 === b) {\n didFindChild = !0;\n b = parentB;\n a = parentA;\n break;\n }\n child$0 = child$0.sibling;\n }\n if (!didFindChild) throw Error(formatProdErrorMessage(189));\n }\n }\n if (a.alternate !== b) throw Error(formatProdErrorMessage(190));\n }\n if (3 !== a.tag) throw Error(formatProdErrorMessage(188));\n return a.stateNode.current === a ? fiber : alternate;\n}\nfunction findCurrentHostFiberImpl(node) {\n var tag = node.tag;\n if (5 === tag || 26 === tag || 27 === tag || 6 === tag) return node;\n for (node = node.child; null !== node; ) {\n tag = findCurrentHostFiberImpl(node);\n if (null !== tag) return tag;\n node = node.sibling;\n }\n return null;\n}\nvar assign = Object.assign,\n REACT_LEGACY_ELEMENT_TYPE = Symbol.for(\"react.element\"),\n REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_PORTAL_TYPE = Symbol.for(\"react.portal\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\"),\n REACT_STRICT_MODE_TYPE = Symbol.for(\"react.strict_mode\"),\n REACT_PROFILER_TYPE = Symbol.for(\"react.profiler\"),\n REACT_CONSUMER_TYPE = Symbol.for(\"react.consumer\"),\n REACT_CONTEXT_TYPE = Symbol.for(\"react.context\"),\n REACT_FORWARD_REF_TYPE = Symbol.for(\"react.forward_ref\"),\n REACT_SUSPENSE_TYPE = Symbol.for(\"react.suspense\"),\n REACT_SUSPENSE_LIST_TYPE = Symbol.for(\"react.suspense_list\"),\n REACT_MEMO_TYPE = Symbol.for(\"react.memo\"),\n REACT_LAZY_TYPE = Symbol.for(\"react.lazy\");\nSymbol.for(\"react.scope\");\nvar REACT_ACTIVITY_TYPE = Symbol.for(\"react.activity\");\nSymbol.for(\"react.legacy_hidden\");\nSymbol.for(\"react.tracing_marker\");\nvar REACT_MEMO_CACHE_SENTINEL = Symbol.for(\"react.memo_cache_sentinel\");\nSymbol.for(\"react.view_transition\");\nvar MAYBE_ITERATOR_SYMBOL = Symbol.iterator;\nfunction getIteratorFn(maybeIterable) {\n if (null === maybeIterable || \"object\" !== typeof maybeIterable) return null;\n maybeIterable =\n (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) ||\n maybeIterable[\"@@iterator\"];\n return \"function\" === typeof maybeIterable ? maybeIterable : null;\n}\nvar REACT_CLIENT_REFERENCE = Symbol.for(\"react.client.reference\");\nfunction getComponentNameFromType(type) {\n if (null == type) return null;\n if (\"function\" === typeof type)\n return type.$$typeof === REACT_CLIENT_REFERENCE\n ? null\n : type.displayName || type.name || null;\n if (\"string\" === typeof type) return type;\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return \"Fragment\";\n case REACT_PROFILER_TYPE:\n return \"Profiler\";\n case REACT_STRICT_MODE_TYPE:\n return \"StrictMode\";\n case REACT_SUSPENSE_TYPE:\n return \"Suspense\";\n case REACT_SUSPENSE_LIST_TYPE:\n return \"SuspenseList\";\n case REACT_ACTIVITY_TYPE:\n return \"Activity\";\n }\n if (\"object\" === typeof type)\n switch (type.$$typeof) {\n case REACT_PORTAL_TYPE:\n return \"Portal\";\n case REACT_CONTEXT_TYPE:\n return type.displayName || \"Context\";\n case REACT_CONSUMER_TYPE:\n return (type._context.displayName || \"Context\") + \".Consumer\";\n case REACT_FORWARD_REF_TYPE:\n var innerType = type.render;\n type = type.displayName;\n type ||\n ((type = innerType.displayName || innerType.name || \"\"),\n (type = \"\" !== type ? \"ForwardRef(\" + type + \")\" : \"ForwardRef\"));\n return type;\n case REACT_MEMO_TYPE:\n return (\n (innerType = type.displayName || null),\n null !== innerType\n ? innerType\n : getComponentNameFromType(type.type) || \"Memo\"\n );\n case REACT_LAZY_TYPE:\n innerType = type._payload;\n type = type._init;\n try {\n return getComponentNameFromType(type(innerType));\n } catch (x) {}\n }\n return null;\n}\nvar isArrayImpl = Array.isArray,\n ReactSharedInternals =\n React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,\n ReactDOMSharedInternals =\n ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,\n sharedNotPendingObject = {\n pending: !1,\n data: null,\n method: null,\n action: null\n },\n valueStack = [],\n index = -1;\nfunction createCursor(defaultValue) {\n return { current: defaultValue };\n}\nfunction pop(cursor) {\n 0 > index ||\n ((cursor.current = valueStack[index]), (valueStack[index] = null), index--);\n}\nfunction push(cursor, value) {\n index++;\n valueStack[index] = cursor.current;\n cursor.current = value;\n}\nvar contextStackCursor = createCursor(null),\n contextFiberStackCursor = createCursor(null),\n rootInstanceStackCursor = createCursor(null),\n hostTransitionProviderCursor = createCursor(null);\nfunction pushHostContainer(fiber, nextRootInstance) {\n push(rootInstanceStackCursor, nextRootInstance);\n push(contextFiberStackCursor, fiber);\n push(contextStackCursor, null);\n switch (nextRootInstance.nodeType) {\n case 9:\n case 11:\n fiber = (fiber = nextRootInstance.documentElement)\n ? (fiber = fiber.namespaceURI)\n ? getOwnHostContext(fiber)\n : 0\n : 0;\n break;\n default:\n if (\n ((fiber = nextRootInstance.tagName),\n (nextRootInstance = nextRootInstance.namespaceURI))\n )\n (nextRootInstance = getOwnHostContext(nextRootInstance)),\n (fiber = getChildHostContextProd(nextRootInstance, fiber));\n else\n switch (fiber) {\n case \"svg\":\n fiber = 1;\n break;\n case \"math\":\n fiber = 2;\n break;\n default:\n fiber = 0;\n }\n }\n pop(contextStackCursor);\n push(contextStackCursor, fiber);\n}\nfunction popHostContainer() {\n pop(contextStackCursor);\n pop(contextFiberStackCursor);\n pop(rootInstanceStackCursor);\n}\nfunction pushHostContext(fiber) {\n null !== fiber.memoizedState && push(hostTransitionProviderCursor, fiber);\n var context = contextStackCursor.current;\n var JSCompiler_inline_result = getChildHostContextProd(context, fiber.type);\n context !== JSCompiler_inline_result &&\n (push(contextFiberStackCursor, fiber),\n push(contextStackCursor, JSCompiler_inline_result));\n}\nfunction popHostContext(fiber) {\n contextFiberStackCursor.current === fiber &&\n (pop(contextStackCursor), pop(contextFiberStackCursor));\n hostTransitionProviderCursor.current === fiber &&\n (pop(hostTransitionProviderCursor),\n (HostTransitionContext._currentValue = sharedNotPendingObject));\n}\nvar prefix, suffix;\nfunction describeBuiltInComponentFrame(name) {\n if (void 0 === prefix)\n try {\n throw Error();\n } catch (x) {\n var match = x.stack.trim().match(/\\n( *(at )?)/);\n prefix = (match && match[1]) || \"\";\n suffix =\n -1 < x.stack.indexOf(\"\\n at\")\n ? \" ()\"\n : -1 < x.stack.indexOf(\"@\")\n ? \"@unknown:0:0\"\n : \"\";\n }\n return \"\\n\" + prefix + name + suffix;\n}\nvar reentry = !1;\nfunction describeNativeComponentFrame(fn, construct) {\n if (!fn || reentry) return \"\";\n reentry = !0;\n var previousPrepareStackTrace = Error.prepareStackTrace;\n Error.prepareStackTrace = void 0;\n try {\n var RunInRootFrame = {\n DetermineComponentFrameRoot: function () {\n try {\n if (construct) {\n var Fake = function () {\n throw Error();\n };\n Object.defineProperty(Fake.prototype, \"props\", {\n set: function () {\n throw Error();\n }\n });\n if (\"object\" === typeof Reflect && Reflect.construct) {\n try {\n Reflect.construct(Fake, []);\n } catch (x) {\n var control = x;\n }\n Reflect.construct(fn, [], Fake);\n } else {\n try {\n Fake.call();\n } catch (x$1) {\n control = x$1;\n }\n fn.call(Fake.prototype);\n }\n } else {\n try {\n throw Error();\n } catch (x$2) {\n control = x$2;\n }\n (Fake = fn()) &&\n \"function\" === typeof Fake.catch &&\n Fake.catch(function () {});\n }\n } catch (sample) {\n if (sample && control && \"string\" === typeof sample.stack)\n return [sample.stack, control.stack];\n }\n return [null, null];\n }\n };\n RunInRootFrame.DetermineComponentFrameRoot.displayName =\n \"DetermineComponentFrameRoot\";\n var namePropDescriptor = Object.getOwnPropertyDescriptor(\n RunInRootFrame.DetermineComponentFrameRoot,\n \"name\"\n );\n namePropDescriptor &&\n namePropDescriptor.configurable &&\n Object.defineProperty(\n RunInRootFrame.DetermineComponentFrameRoot,\n \"name\",\n { value: \"DetermineComponentFrameRoot\" }\n );\n var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(),\n sampleStack = _RunInRootFrame$Deter[0],\n controlStack = _RunInRootFrame$Deter[1];\n if (sampleStack && controlStack) {\n var sampleLines = sampleStack.split(\"\\n\"),\n controlLines = controlStack.split(\"\\n\");\n for (\n namePropDescriptor = RunInRootFrame = 0;\n RunInRootFrame < sampleLines.length &&\n !sampleLines[RunInRootFrame].includes(\"DetermineComponentFrameRoot\");\n\n )\n RunInRootFrame++;\n for (\n ;\n namePropDescriptor < controlLines.length &&\n !controlLines[namePropDescriptor].includes(\n \"DetermineComponentFrameRoot\"\n );\n\n )\n namePropDescriptor++;\n if (\n RunInRootFrame === sampleLines.length ||\n namePropDescriptor === controlLines.length\n )\n for (\n RunInRootFrame = sampleLines.length - 1,\n namePropDescriptor = controlLines.length - 1;\n 1 <= RunInRootFrame &&\n 0 <= namePropDescriptor &&\n sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor];\n\n )\n namePropDescriptor--;\n for (\n ;\n 1 <= RunInRootFrame && 0 <= namePropDescriptor;\n RunInRootFrame--, namePropDescriptor--\n )\n if (sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) {\n if (1 !== RunInRootFrame || 1 !== namePropDescriptor) {\n do\n if (\n (RunInRootFrame--,\n namePropDescriptor--,\n 0 > namePropDescriptor ||\n sampleLines[RunInRootFrame] !==\n controlLines[namePropDescriptor])\n ) {\n var frame =\n \"\\n\" +\n sampleLines[RunInRootFrame].replace(\" at new \", \" at \");\n fn.displayName &&\n frame.includes(\"\") &&\n (frame = frame.replace(\"\", fn.displayName));\n return frame;\n }\n while (1 <= RunInRootFrame && 0 <= namePropDescriptor);\n }\n break;\n }\n }\n } finally {\n (reentry = !1), (Error.prepareStackTrace = previousPrepareStackTrace);\n }\n return (previousPrepareStackTrace = fn ? fn.displayName || fn.name : \"\")\n ? describeBuiltInComponentFrame(previousPrepareStackTrace)\n : \"\";\n}\nfunction describeFiber(fiber, childFiber) {\n switch (fiber.tag) {\n case 26:\n case 27:\n case 5:\n return describeBuiltInComponentFrame(fiber.type);\n case 16:\n return describeBuiltInComponentFrame(\"Lazy\");\n case 13:\n return fiber.child !== childFiber && null !== childFiber\n ? describeBuiltInComponentFrame(\"Suspense Fallback\")\n : describeBuiltInComponentFrame(\"Suspense\");\n case 19:\n return describeBuiltInComponentFrame(\"SuspenseList\");\n case 0:\n case 15:\n return describeNativeComponentFrame(fiber.type, !1);\n case 11:\n return describeNativeComponentFrame(fiber.type.render, !1);\n case 1:\n return describeNativeComponentFrame(fiber.type, !0);\n case 31:\n return describeBuiltInComponentFrame(\"Activity\");\n default:\n return \"\";\n }\n}\nfunction getStackByFiberInDevAndProd(workInProgress) {\n try {\n var info = \"\",\n previous = null;\n do\n (info += describeFiber(workInProgress, previous)),\n (previous = workInProgress),\n (workInProgress = workInProgress.return);\n while (workInProgress);\n return info;\n } catch (x) {\n return \"\\nError generating stack: \" + x.message + \"\\n\" + x.stack;\n }\n}\nvar hasOwnProperty = Object.prototype.hasOwnProperty,\n scheduleCallback$3 = Scheduler.unstable_scheduleCallback,\n cancelCallback$1 = Scheduler.unstable_cancelCallback,\n shouldYield = Scheduler.unstable_shouldYield,\n requestPaint = Scheduler.unstable_requestPaint,\n now = Scheduler.unstable_now,\n getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel,\n ImmediatePriority = Scheduler.unstable_ImmediatePriority,\n UserBlockingPriority = Scheduler.unstable_UserBlockingPriority,\n NormalPriority$1 = Scheduler.unstable_NormalPriority,\n LowPriority = Scheduler.unstable_LowPriority,\n IdlePriority = Scheduler.unstable_IdlePriority,\n log$1 = Scheduler.log,\n unstable_setDisableYieldValue = Scheduler.unstable_setDisableYieldValue,\n rendererID = null,\n injectedHook = null;\nfunction setIsStrictModeForDevtools(newIsStrictMode) {\n \"function\" === typeof log$1 && unstable_setDisableYieldValue(newIsStrictMode);\n if (injectedHook && \"function\" === typeof injectedHook.setStrictMode)\n try {\n injectedHook.setStrictMode(rendererID, newIsStrictMode);\n } catch (err) {}\n}\nvar clz32 = Math.clz32 ? Math.clz32 : clz32Fallback,\n log = Math.log,\n LN2 = Math.LN2;\nfunction clz32Fallback(x) {\n x >>>= 0;\n return 0 === x ? 32 : (31 - ((log(x) / LN2) | 0)) | 0;\n}\nvar nextTransitionUpdateLane = 256,\n nextTransitionDeferredLane = 262144,\n nextRetryLane = 4194304;\nfunction getHighestPriorityLanes(lanes) {\n var pendingSyncLanes = lanes & 42;\n if (0 !== pendingSyncLanes) return pendingSyncLanes;\n switch (lanes & -lanes) {\n case 1:\n return 1;\n case 2:\n return 2;\n case 4:\n return 4;\n case 8:\n return 8;\n case 16:\n return 16;\n case 32:\n return 32;\n case 64:\n return 64;\n case 128:\n return 128;\n case 256:\n case 512:\n case 1024:\n case 2048:\n case 4096:\n case 8192:\n case 16384:\n case 32768:\n case 65536:\n case 131072:\n return lanes & 261888;\n case 262144:\n case 524288:\n case 1048576:\n case 2097152:\n return lanes & 3932160;\n case 4194304:\n case 8388608:\n case 16777216:\n case 33554432:\n return lanes & 62914560;\n case 67108864:\n return 67108864;\n case 134217728:\n return 134217728;\n case 268435456:\n return 268435456;\n case 536870912:\n return 536870912;\n case 1073741824:\n return 0;\n default:\n return lanes;\n }\n}\nfunction getNextLanes(root, wipLanes, rootHasPendingCommit) {\n var pendingLanes = root.pendingLanes;\n if (0 === pendingLanes) return 0;\n var nextLanes = 0,\n suspendedLanes = root.suspendedLanes,\n pingedLanes = root.pingedLanes;\n root = root.warmLanes;\n var nonIdlePendingLanes = pendingLanes & 134217727;\n 0 !== nonIdlePendingLanes\n ? ((pendingLanes = nonIdlePendingLanes & ~suspendedLanes),\n 0 !== pendingLanes\n ? (nextLanes = getHighestPriorityLanes(pendingLanes))\n : ((pingedLanes &= nonIdlePendingLanes),\n 0 !== pingedLanes\n ? (nextLanes = getHighestPriorityLanes(pingedLanes))\n : rootHasPendingCommit ||\n ((rootHasPendingCommit = nonIdlePendingLanes & ~root),\n 0 !== rootHasPendingCommit &&\n (nextLanes = getHighestPriorityLanes(rootHasPendingCommit)))))\n : ((nonIdlePendingLanes = pendingLanes & ~suspendedLanes),\n 0 !== nonIdlePendingLanes\n ? (nextLanes = getHighestPriorityLanes(nonIdlePendingLanes))\n : 0 !== pingedLanes\n ? (nextLanes = getHighestPriorityLanes(pingedLanes))\n : rootHasPendingCommit ||\n ((rootHasPendingCommit = pendingLanes & ~root),\n 0 !== rootHasPendingCommit &&\n (nextLanes = getHighestPriorityLanes(rootHasPendingCommit))));\n return 0 === nextLanes\n ? 0\n : 0 !== wipLanes &&\n wipLanes !== nextLanes &&\n 0 === (wipLanes & suspendedLanes) &&\n ((suspendedLanes = nextLanes & -nextLanes),\n (rootHasPendingCommit = wipLanes & -wipLanes),\n suspendedLanes >= rootHasPendingCommit ||\n (32 === suspendedLanes && 0 !== (rootHasPendingCommit & 4194048)))\n ? wipLanes\n : nextLanes;\n}\nfunction checkIfRootIsPrerendering(root, renderLanes) {\n return (\n 0 ===\n (root.pendingLanes &\n ~(root.suspendedLanes & ~root.pingedLanes) &\n renderLanes)\n );\n}\nfunction computeExpirationTime(lane, currentTime) {\n switch (lane) {\n case 1:\n case 2:\n case 4:\n case 8:\n case 64:\n return currentTime + 250;\n case 16:\n case 32:\n case 128:\n case 256:\n case 512:\n case 1024:\n case 2048:\n case 4096:\n case 8192:\n case 16384:\n case 32768:\n case 65536:\n case 131072:\n case 262144:\n case 524288:\n case 1048576:\n case 2097152:\n return currentTime + 5e3;\n case 4194304:\n case 8388608:\n case 16777216:\n case 33554432:\n return -1;\n case 67108864:\n case 134217728:\n case 268435456:\n case 536870912:\n case 1073741824:\n return -1;\n default:\n return -1;\n }\n}\nfunction claimNextRetryLane() {\n var lane = nextRetryLane;\n nextRetryLane <<= 1;\n 0 === (nextRetryLane & 62914560) && (nextRetryLane = 4194304);\n return lane;\n}\nfunction createLaneMap(initial) {\n for (var laneMap = [], i = 0; 31 > i; i++) laneMap.push(initial);\n return laneMap;\n}\nfunction markRootUpdated$1(root, updateLane) {\n root.pendingLanes |= updateLane;\n 268435456 !== updateLane &&\n ((root.suspendedLanes = 0), (root.pingedLanes = 0), (root.warmLanes = 0));\n}\nfunction markRootFinished(\n root,\n finishedLanes,\n remainingLanes,\n spawnedLane,\n updatedLanes,\n suspendedRetryLanes\n) {\n var previouslyPendingLanes = root.pendingLanes;\n root.pendingLanes = remainingLanes;\n root.suspendedLanes = 0;\n root.pingedLanes = 0;\n root.warmLanes = 0;\n root.expiredLanes &= remainingLanes;\n root.entangledLanes &= remainingLanes;\n root.errorRecoveryDisabledLanes &= remainingLanes;\n root.shellSuspendCounter = 0;\n var entanglements = root.entanglements,\n expirationTimes = root.expirationTimes,\n hiddenUpdates = root.hiddenUpdates;\n for (\n remainingLanes = previouslyPendingLanes & ~remainingLanes;\n 0 < remainingLanes;\n\n ) {\n var index$7 = 31 - clz32(remainingLanes),\n lane = 1 << index$7;\n entanglements[index$7] = 0;\n expirationTimes[index$7] = -1;\n var hiddenUpdatesForLane = hiddenUpdates[index$7];\n if (null !== hiddenUpdatesForLane)\n for (\n hiddenUpdates[index$7] = null, index$7 = 0;\n index$7 < hiddenUpdatesForLane.length;\n index$7++\n ) {\n var update = hiddenUpdatesForLane[index$7];\n null !== update && (update.lane &= -536870913);\n }\n remainingLanes &= ~lane;\n }\n 0 !== spawnedLane && markSpawnedDeferredLane(root, spawnedLane, 0);\n 0 !== suspendedRetryLanes &&\n 0 === updatedLanes &&\n 0 !== root.tag &&\n (root.suspendedLanes |=\n suspendedRetryLanes & ~(previouslyPendingLanes & ~finishedLanes));\n}\nfunction markSpawnedDeferredLane(root, spawnedLane, entangledLanes) {\n root.pendingLanes |= spawnedLane;\n root.suspendedLanes &= ~spawnedLane;\n var spawnedLaneIndex = 31 - clz32(spawnedLane);\n root.entangledLanes |= spawnedLane;\n root.entanglements[spawnedLaneIndex] =\n root.entanglements[spawnedLaneIndex] |\n 1073741824 |\n (entangledLanes & 261930);\n}\nfunction markRootEntangled(root, entangledLanes) {\n var rootEntangledLanes = (root.entangledLanes |= entangledLanes);\n for (root = root.entanglements; rootEntangledLanes; ) {\n var index$8 = 31 - clz32(rootEntangledLanes),\n lane = 1 << index$8;\n (lane & entangledLanes) | (root[index$8] & entangledLanes) &&\n (root[index$8] |= entangledLanes);\n rootEntangledLanes &= ~lane;\n }\n}\nfunction getBumpedLaneForHydration(root, renderLanes) {\n var renderLane = renderLanes & -renderLanes;\n renderLane =\n 0 !== (renderLane & 42) ? 1 : getBumpedLaneForHydrationByLane(renderLane);\n return 0 !== (renderLane & (root.suspendedLanes | renderLanes))\n ? 0\n : renderLane;\n}\nfunction getBumpedLaneForHydrationByLane(lane) {\n switch (lane) {\n case 2:\n lane = 1;\n break;\n case 8:\n lane = 4;\n break;\n case 32:\n lane = 16;\n break;\n case 256:\n case 512:\n case 1024:\n case 2048:\n case 4096:\n case 8192:\n case 16384:\n case 32768:\n case 65536:\n case 131072:\n case 262144:\n case 524288:\n case 1048576:\n case 2097152:\n case 4194304:\n case 8388608:\n case 16777216:\n case 33554432:\n lane = 128;\n break;\n case 268435456:\n lane = 134217728;\n break;\n default:\n lane = 0;\n }\n return lane;\n}\nfunction lanesToEventPriority(lanes) {\n lanes &= -lanes;\n return 2 < lanes\n ? 8 < lanes\n ? 0 !== (lanes & 134217727)\n ? 32\n : 268435456\n : 8\n : 2;\n}\nfunction resolveUpdatePriority() {\n var updatePriority = ReactDOMSharedInternals.p;\n if (0 !== updatePriority) return updatePriority;\n updatePriority = window.event;\n return void 0 === updatePriority ? 32 : getEventPriority(updatePriority.type);\n}\nfunction runWithPriority(priority, fn) {\n var previousPriority = ReactDOMSharedInternals.p;\n try {\n return (ReactDOMSharedInternals.p = priority), fn();\n } finally {\n ReactDOMSharedInternals.p = previousPriority;\n }\n}\nvar randomKey = Math.random().toString(36).slice(2),\n internalInstanceKey = \"__reactFiber$\" + randomKey,\n internalPropsKey = \"__reactProps$\" + randomKey,\n internalContainerInstanceKey = \"__reactContainer$\" + randomKey,\n internalEventHandlersKey = \"__reactEvents$\" + randomKey,\n internalEventHandlerListenersKey = \"__reactListeners$\" + randomKey,\n internalEventHandlesSetKey = \"__reactHandles$\" + randomKey,\n internalRootNodeResourcesKey = \"__reactResources$\" + randomKey,\n internalHoistableMarker = \"__reactMarker$\" + randomKey;\nfunction detachDeletedInstance(node) {\n delete node[internalInstanceKey];\n delete node[internalPropsKey];\n delete node[internalEventHandlersKey];\n delete node[internalEventHandlerListenersKey];\n delete node[internalEventHandlesSetKey];\n}\nfunction getClosestInstanceFromNode(targetNode) {\n var targetInst = targetNode[internalInstanceKey];\n if (targetInst) return targetInst;\n for (var parentNode = targetNode.parentNode; parentNode; ) {\n if (\n (targetInst =\n parentNode[internalContainerInstanceKey] ||\n parentNode[internalInstanceKey])\n ) {\n parentNode = targetInst.alternate;\n if (\n null !== targetInst.child ||\n (null !== parentNode && null !== parentNode.child)\n )\n for (\n targetNode = getParentHydrationBoundary(targetNode);\n null !== targetNode;\n\n ) {\n if ((parentNode = targetNode[internalInstanceKey])) return parentNode;\n targetNode = getParentHydrationBoundary(targetNode);\n }\n return targetInst;\n }\n targetNode = parentNode;\n parentNode = targetNode.parentNode;\n }\n return null;\n}\nfunction getInstanceFromNode(node) {\n if (\n (node = node[internalInstanceKey] || node[internalContainerInstanceKey])\n ) {\n var tag = node.tag;\n if (\n 5 === tag ||\n 6 === tag ||\n 13 === tag ||\n 31 === tag ||\n 26 === tag ||\n 27 === tag ||\n 3 === tag\n )\n return node;\n }\n return null;\n}\nfunction getNodeFromInstance(inst) {\n var tag = inst.tag;\n if (5 === tag || 26 === tag || 27 === tag || 6 === tag) return inst.stateNode;\n throw Error(formatProdErrorMessage(33));\n}\nfunction getResourcesFromRoot(root) {\n var resources = root[internalRootNodeResourcesKey];\n resources ||\n (resources = root[internalRootNodeResourcesKey] =\n { hoistableStyles: new Map(), hoistableScripts: new Map() });\n return resources;\n}\nfunction markNodeAsHoistable(node) {\n node[internalHoistableMarker] = !0;\n}\nvar allNativeEvents = new Set(),\n registrationNameDependencies = {};\nfunction registerTwoPhaseEvent(registrationName, dependencies) {\n registerDirectEvent(registrationName, dependencies);\n registerDirectEvent(registrationName + \"Capture\", dependencies);\n}\nfunction registerDirectEvent(registrationName, dependencies) {\n registrationNameDependencies[registrationName] = dependencies;\n for (\n registrationName = 0;\n registrationName < dependencies.length;\n registrationName++\n )\n allNativeEvents.add(dependencies[registrationName]);\n}\nvar VALID_ATTRIBUTE_NAME_REGEX = RegExp(\n \"^[:A-Z_a-z\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD][:A-Z_a-z\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD\\\\-.0-9\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040]*$\"\n ),\n illegalAttributeNameCache = {},\n validatedAttributeNameCache = {};\nfunction isAttributeNameSafe(attributeName) {\n if (hasOwnProperty.call(validatedAttributeNameCache, attributeName))\n return !0;\n if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) return !1;\n if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName))\n return (validatedAttributeNameCache[attributeName] = !0);\n illegalAttributeNameCache[attributeName] = !0;\n return !1;\n}\nfunction setValueForAttribute(node, name, value) {\n if (isAttributeNameSafe(name))\n if (null === value) node.removeAttribute(name);\n else {\n switch (typeof value) {\n case \"undefined\":\n case \"function\":\n case \"symbol\":\n node.removeAttribute(name);\n return;\n case \"boolean\":\n var prefix$10 = name.toLowerCase().slice(0, 5);\n if (\"data-\" !== prefix$10 && \"aria-\" !== prefix$10) {\n node.removeAttribute(name);\n return;\n }\n }\n node.setAttribute(name, \"\" + value);\n }\n}\nfunction setValueForKnownAttribute(node, name, value) {\n if (null === value) node.removeAttribute(name);\n else {\n switch (typeof value) {\n case \"undefined\":\n case \"function\":\n case \"symbol\":\n case \"boolean\":\n node.removeAttribute(name);\n return;\n }\n node.setAttribute(name, \"\" + value);\n }\n}\nfunction setValueForNamespacedAttribute(node, namespace, name, value) {\n if (null === value) node.removeAttribute(name);\n else {\n switch (typeof value) {\n case \"undefined\":\n case \"function\":\n case \"symbol\":\n case \"boolean\":\n node.removeAttribute(name);\n return;\n }\n node.setAttributeNS(namespace, name, \"\" + value);\n }\n}\nfunction getToStringValue(value) {\n switch (typeof value) {\n case \"bigint\":\n case \"boolean\":\n case \"number\":\n case \"string\":\n case \"undefined\":\n return value;\n case \"object\":\n return value;\n default:\n return \"\";\n }\n}\nfunction isCheckable(elem) {\n var type = elem.type;\n return (\n (elem = elem.nodeName) &&\n \"input\" === elem.toLowerCase() &&\n (\"checkbox\" === type || \"radio\" === type)\n );\n}\nfunction trackValueOnNode(node, valueField, currentValue) {\n var descriptor = Object.getOwnPropertyDescriptor(\n node.constructor.prototype,\n valueField\n );\n if (\n !node.hasOwnProperty(valueField) &&\n \"undefined\" !== typeof descriptor &&\n \"function\" === typeof descriptor.get &&\n \"function\" === typeof descriptor.set\n ) {\n var get = descriptor.get,\n set = descriptor.set;\n Object.defineProperty(node, valueField, {\n configurable: !0,\n get: function () {\n return get.call(this);\n },\n set: function (value) {\n currentValue = \"\" + value;\n set.call(this, value);\n }\n });\n Object.defineProperty(node, valueField, {\n enumerable: descriptor.enumerable\n });\n return {\n getValue: function () {\n return currentValue;\n },\n setValue: function (value) {\n currentValue = \"\" + value;\n },\n stopTracking: function () {\n node._valueTracker = null;\n delete node[valueField];\n }\n };\n }\n}\nfunction track(node) {\n if (!node._valueTracker) {\n var valueField = isCheckable(node) ? \"checked\" : \"value\";\n node._valueTracker = trackValueOnNode(\n node,\n valueField,\n \"\" + node[valueField]\n );\n }\n}\nfunction updateValueIfChanged(node) {\n if (!node) return !1;\n var tracker = node._valueTracker;\n if (!tracker) return !0;\n var lastValue = tracker.getValue();\n var value = \"\";\n node &&\n (value = isCheckable(node)\n ? node.checked\n ? \"true\"\n : \"false\"\n : node.value);\n node = value;\n return node !== lastValue ? (tracker.setValue(node), !0) : !1;\n}\nfunction getActiveElement(doc) {\n doc = doc || (\"undefined\" !== typeof document ? document : void 0);\n if (\"undefined\" === typeof doc) return null;\n try {\n return doc.activeElement || doc.body;\n } catch (e) {\n return doc.body;\n }\n}\nvar escapeSelectorAttributeValueInsideDoubleQuotesRegex = /[\\n\"\\\\]/g;\nfunction escapeSelectorAttributeValueInsideDoubleQuotes(value) {\n return value.replace(\n escapeSelectorAttributeValueInsideDoubleQuotesRegex,\n function (ch) {\n return \"\\\\\" + ch.charCodeAt(0).toString(16) + \" \";\n }\n );\n}\nfunction updateInput(\n element,\n value,\n defaultValue,\n lastDefaultValue,\n checked,\n defaultChecked,\n type,\n name\n) {\n element.name = \"\";\n null != type &&\n \"function\" !== typeof type &&\n \"symbol\" !== typeof type &&\n \"boolean\" !== typeof type\n ? (element.type = type)\n : element.removeAttribute(\"type\");\n if (null != value)\n if (\"number\" === type) {\n if ((0 === value && \"\" === element.value) || element.value != value)\n element.value = \"\" + getToStringValue(value);\n } else\n element.value !== \"\" + getToStringValue(value) &&\n (element.value = \"\" + getToStringValue(value));\n else\n (\"submit\" !== type && \"reset\" !== type) || element.removeAttribute(\"value\");\n null != value\n ? setDefaultValue(element, type, getToStringValue(value))\n : null != defaultValue\n ? setDefaultValue(element, type, getToStringValue(defaultValue))\n : null != lastDefaultValue && element.removeAttribute(\"value\");\n null == checked &&\n null != defaultChecked &&\n (element.defaultChecked = !!defaultChecked);\n null != checked &&\n (element.checked =\n checked && \"function\" !== typeof checked && \"symbol\" !== typeof checked);\n null != name &&\n \"function\" !== typeof name &&\n \"symbol\" !== typeof name &&\n \"boolean\" !== typeof name\n ? (element.name = \"\" + getToStringValue(name))\n : element.removeAttribute(\"name\");\n}\nfunction initInput(\n element,\n value,\n defaultValue,\n checked,\n defaultChecked,\n type,\n name,\n isHydrating\n) {\n null != type &&\n \"function\" !== typeof type &&\n \"symbol\" !== typeof type &&\n \"boolean\" !== typeof type &&\n (element.type = type);\n if (null != value || null != defaultValue) {\n if (\n !(\n (\"submit\" !== type && \"reset\" !== type) ||\n (void 0 !== value && null !== value)\n )\n ) {\n track(element);\n return;\n }\n defaultValue =\n null != defaultValue ? \"\" + getToStringValue(defaultValue) : \"\";\n value = null != value ? \"\" + getToStringValue(value) : defaultValue;\n isHydrating || value === element.value || (element.value = value);\n element.defaultValue = value;\n }\n checked = null != checked ? checked : defaultChecked;\n checked =\n \"function\" !== typeof checked && \"symbol\" !== typeof checked && !!checked;\n element.checked = isHydrating ? element.checked : !!checked;\n element.defaultChecked = !!checked;\n null != name &&\n \"function\" !== typeof name &&\n \"symbol\" !== typeof name &&\n \"boolean\" !== typeof name &&\n (element.name = name);\n track(element);\n}\nfunction setDefaultValue(node, type, value) {\n (\"number\" === type && getActiveElement(node.ownerDocument) === node) ||\n node.defaultValue === \"\" + value ||\n (node.defaultValue = \"\" + value);\n}\nfunction updateOptions(node, multiple, propValue, setDefaultSelected) {\n node = node.options;\n if (multiple) {\n multiple = {};\n for (var i = 0; i < propValue.length; i++)\n multiple[\"$\" + propValue[i]] = !0;\n for (propValue = 0; propValue < node.length; propValue++)\n (i = multiple.hasOwnProperty(\"$\" + node[propValue].value)),\n node[propValue].selected !== i && (node[propValue].selected = i),\n i && setDefaultSelected && (node[propValue].defaultSelected = !0);\n } else {\n propValue = \"\" + getToStringValue(propValue);\n multiple = null;\n for (i = 0; i < node.length; i++) {\n if (node[i].value === propValue) {\n node[i].selected = !0;\n setDefaultSelected && (node[i].defaultSelected = !0);\n return;\n }\n null !== multiple || node[i].disabled || (multiple = node[i]);\n }\n null !== multiple && (multiple.selected = !0);\n }\n}\nfunction updateTextarea(element, value, defaultValue) {\n if (\n null != value &&\n ((value = \"\" + getToStringValue(value)),\n value !== element.value && (element.value = value),\n null == defaultValue)\n ) {\n element.defaultValue !== value && (element.defaultValue = value);\n return;\n }\n element.defaultValue =\n null != defaultValue ? \"\" + getToStringValue(defaultValue) : \"\";\n}\nfunction initTextarea(element, value, defaultValue, children) {\n if (null == value) {\n if (null != children) {\n if (null != defaultValue) throw Error(formatProdErrorMessage(92));\n if (isArrayImpl(children)) {\n if (1 < children.length) throw Error(formatProdErrorMessage(93));\n children = children[0];\n }\n defaultValue = children;\n }\n null == defaultValue && (defaultValue = \"\");\n value = defaultValue;\n }\n defaultValue = getToStringValue(value);\n element.defaultValue = defaultValue;\n children = element.textContent;\n children === defaultValue &&\n \"\" !== children &&\n null !== children &&\n (element.value = children);\n track(element);\n}\nfunction setTextContent(node, text) {\n if (text) {\n var firstChild = node.firstChild;\n if (\n firstChild &&\n firstChild === node.lastChild &&\n 3 === firstChild.nodeType\n ) {\n firstChild.nodeValue = text;\n return;\n }\n }\n node.textContent = text;\n}\nvar unitlessNumbers = new Set(\n \"animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp\".split(\n \" \"\n )\n);\nfunction setValueForStyle(style, styleName, value) {\n var isCustomProperty = 0 === styleName.indexOf(\"--\");\n null == value || \"boolean\" === typeof value || \"\" === value\n ? isCustomProperty\n ? style.setProperty(styleName, \"\")\n : \"float\" === styleName\n ? (style.cssFloat = \"\")\n : (style[styleName] = \"\")\n : isCustomProperty\n ? style.setProperty(styleName, value)\n : \"number\" !== typeof value ||\n 0 === value ||\n unitlessNumbers.has(styleName)\n ? \"float\" === styleName\n ? (style.cssFloat = value)\n : (style[styleName] = (\"\" + value).trim())\n : (style[styleName] = value + \"px\");\n}\nfunction setValueForStyles(node, styles, prevStyles) {\n if (null != styles && \"object\" !== typeof styles)\n throw Error(formatProdErrorMessage(62));\n node = node.style;\n if (null != prevStyles) {\n for (var styleName in prevStyles)\n !prevStyles.hasOwnProperty(styleName) ||\n (null != styles && styles.hasOwnProperty(styleName)) ||\n (0 === styleName.indexOf(\"--\")\n ? node.setProperty(styleName, \"\")\n : \"float\" === styleName\n ? (node.cssFloat = \"\")\n : (node[styleName] = \"\"));\n for (var styleName$16 in styles)\n (styleName = styles[styleName$16]),\n styles.hasOwnProperty(styleName$16) &&\n prevStyles[styleName$16] !== styleName &&\n setValueForStyle(node, styleName$16, styleName);\n } else\n for (var styleName$17 in styles)\n styles.hasOwnProperty(styleName$17) &&\n setValueForStyle(node, styleName$17, styles[styleName$17]);\n}\nfunction isCustomElement(tagName) {\n if (-1 === tagName.indexOf(\"-\")) return !1;\n switch (tagName) {\n case \"annotation-xml\":\n case \"color-profile\":\n case \"font-face\":\n case \"font-face-src\":\n case \"font-face-uri\":\n case \"font-face-format\":\n case \"font-face-name\":\n case \"missing-glyph\":\n return !1;\n default:\n return !0;\n }\n}\nvar aliases = new Map([\n [\"acceptCharset\", \"accept-charset\"],\n [\"htmlFor\", \"for\"],\n [\"httpEquiv\", \"http-equiv\"],\n [\"crossOrigin\", \"crossorigin\"],\n [\"accentHeight\", \"accent-height\"],\n [\"alignmentBaseline\", \"alignment-baseline\"],\n [\"arabicForm\", \"arabic-form\"],\n [\"baselineShift\", \"baseline-shift\"],\n [\"capHeight\", \"cap-height\"],\n [\"clipPath\", \"clip-path\"],\n [\"clipRule\", \"clip-rule\"],\n [\"colorInterpolation\", \"color-interpolation\"],\n [\"colorInterpolationFilters\", \"color-interpolation-filters\"],\n [\"colorProfile\", \"color-profile\"],\n [\"colorRendering\", \"color-rendering\"],\n [\"dominantBaseline\", \"dominant-baseline\"],\n [\"enableBackground\", \"enable-background\"],\n [\"fillOpacity\", \"fill-opacity\"],\n [\"fillRule\", \"fill-rule\"],\n [\"floodColor\", \"flood-color\"],\n [\"floodOpacity\", \"flood-opacity\"],\n [\"fontFamily\", \"font-family\"],\n [\"fontSize\", \"font-size\"],\n [\"fontSizeAdjust\", \"font-size-adjust\"],\n [\"fontStretch\", \"font-stretch\"],\n [\"fontStyle\", \"font-style\"],\n [\"fontVariant\", \"font-variant\"],\n [\"fontWeight\", \"font-weight\"],\n [\"glyphName\", \"glyph-name\"],\n [\"glyphOrientationHorizontal\", \"glyph-orientation-horizontal\"],\n [\"glyphOrientationVertical\", \"glyph-orientation-vertical\"],\n [\"horizAdvX\", \"horiz-adv-x\"],\n [\"horizOriginX\", \"horiz-origin-x\"],\n [\"imageRendering\", \"image-rendering\"],\n [\"letterSpacing\", \"letter-spacing\"],\n [\"lightingColor\", \"lighting-color\"],\n [\"markerEnd\", \"marker-end\"],\n [\"markerMid\", \"marker-mid\"],\n [\"markerStart\", \"marker-start\"],\n [\"overlinePosition\", \"overline-position\"],\n [\"overlineThickness\", \"overline-thickness\"],\n [\"paintOrder\", \"paint-order\"],\n [\"panose-1\", \"panose-1\"],\n [\"pointerEvents\", \"pointer-events\"],\n [\"renderingIntent\", \"rendering-intent\"],\n [\"shapeRendering\", \"shape-rendering\"],\n [\"stopColor\", \"stop-color\"],\n [\"stopOpacity\", \"stop-opacity\"],\n [\"strikethroughPosition\", \"strikethrough-position\"],\n [\"strikethroughThickness\", \"strikethrough-thickness\"],\n [\"strokeDasharray\", \"stroke-dasharray\"],\n [\"strokeDashoffset\", \"stroke-dashoffset\"],\n [\"strokeLinecap\", \"stroke-linecap\"],\n [\"strokeLinejoin\", \"stroke-linejoin\"],\n [\"strokeMiterlimit\", \"stroke-miterlimit\"],\n [\"strokeOpacity\", \"stroke-opacity\"],\n [\"strokeWidth\", \"stroke-width\"],\n [\"textAnchor\", \"text-anchor\"],\n [\"textDecoration\", \"text-decoration\"],\n [\"textRendering\", \"text-rendering\"],\n [\"transformOrigin\", \"transform-origin\"],\n [\"underlinePosition\", \"underline-position\"],\n [\"underlineThickness\", \"underline-thickness\"],\n [\"unicodeBidi\", \"unicode-bidi\"],\n [\"unicodeRange\", \"unicode-range\"],\n [\"unitsPerEm\", \"units-per-em\"],\n [\"vAlphabetic\", \"v-alphabetic\"],\n [\"vHanging\", \"v-hanging\"],\n [\"vIdeographic\", \"v-ideographic\"],\n [\"vMathematical\", \"v-mathematical\"],\n [\"vectorEffect\", \"vector-effect\"],\n [\"vertAdvY\", \"vert-adv-y\"],\n [\"vertOriginX\", \"vert-origin-x\"],\n [\"vertOriginY\", \"vert-origin-y\"],\n [\"wordSpacing\", \"word-spacing\"],\n [\"writingMode\", \"writing-mode\"],\n [\"xmlnsXlink\", \"xmlns:xlink\"],\n [\"xHeight\", \"x-height\"]\n ]),\n isJavaScriptProtocol =\n /^[\\u0000-\\u001F ]*j[\\r\\n\\t]*a[\\r\\n\\t]*v[\\r\\n\\t]*a[\\r\\n\\t]*s[\\r\\n\\t]*c[\\r\\n\\t]*r[\\r\\n\\t]*i[\\r\\n\\t]*p[\\r\\n\\t]*t[\\r\\n\\t]*:/i;\nfunction sanitizeURL(url) {\n return isJavaScriptProtocol.test(\"\" + url)\n ? \"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')\"\n : url;\n}\nfunction noop$1() {}\nvar currentReplayingEvent = null;\nfunction getEventTarget(nativeEvent) {\n nativeEvent = nativeEvent.target || nativeEvent.srcElement || window;\n nativeEvent.correspondingUseElement &&\n (nativeEvent = nativeEvent.correspondingUseElement);\n return 3 === nativeEvent.nodeType ? nativeEvent.parentNode : nativeEvent;\n}\nvar restoreTarget = null,\n restoreQueue = null;\nfunction restoreStateOfTarget(target) {\n var internalInstance = getInstanceFromNode(target);\n if (internalInstance && (target = internalInstance.stateNode)) {\n var props = target[internalPropsKey] || null;\n a: switch (((target = internalInstance.stateNode), internalInstance.type)) {\n case \"input\":\n updateInput(\n target,\n props.value,\n props.defaultValue,\n props.defaultValue,\n props.checked,\n props.defaultChecked,\n props.type,\n props.name\n );\n internalInstance = props.name;\n if (\"radio\" === props.type && null != internalInstance) {\n for (props = target; props.parentNode; ) props = props.parentNode;\n props = props.querySelectorAll(\n 'input[name=\"' +\n escapeSelectorAttributeValueInsideDoubleQuotes(\n \"\" + internalInstance\n ) +\n '\"][type=\"radio\"]'\n );\n for (\n internalInstance = 0;\n internalInstance < props.length;\n internalInstance++\n ) {\n var otherNode = props[internalInstance];\n if (otherNode !== target && otherNode.form === target.form) {\n var otherProps = otherNode[internalPropsKey] || null;\n if (!otherProps) throw Error(formatProdErrorMessage(90));\n updateInput(\n otherNode,\n otherProps.value,\n otherProps.defaultValue,\n otherProps.defaultValue,\n otherProps.checked,\n otherProps.defaultChecked,\n otherProps.type,\n otherProps.name\n );\n }\n }\n for (\n internalInstance = 0;\n internalInstance < props.length;\n internalInstance++\n )\n (otherNode = props[internalInstance]),\n otherNode.form === target.form && updateValueIfChanged(otherNode);\n }\n break a;\n case \"textarea\":\n updateTextarea(target, props.value, props.defaultValue);\n break a;\n case \"select\":\n (internalInstance = props.value),\n null != internalInstance &&\n updateOptions(target, !!props.multiple, internalInstance, !1);\n }\n }\n}\nvar isInsideEventHandler = !1;\nfunction batchedUpdates$1(fn, a, b) {\n if (isInsideEventHandler) return fn(a, b);\n isInsideEventHandler = !0;\n try {\n var JSCompiler_inline_result = fn(a);\n return JSCompiler_inline_result;\n } finally {\n if (\n ((isInsideEventHandler = !1),\n null !== restoreTarget || null !== restoreQueue)\n )\n if (\n (flushSyncWork$1(),\n restoreTarget &&\n ((a = restoreTarget),\n (fn = restoreQueue),\n (restoreQueue = restoreTarget = null),\n restoreStateOfTarget(a),\n fn))\n )\n for (a = 0; a < fn.length; a++) restoreStateOfTarget(fn[a]);\n }\n}\nfunction getListener(inst, registrationName) {\n var stateNode = inst.stateNode;\n if (null === stateNode) return null;\n var props = stateNode[internalPropsKey] || null;\n if (null === props) return null;\n stateNode = props[registrationName];\n a: switch (registrationName) {\n case \"onClick\":\n case \"onClickCapture\":\n case \"onDoubleClick\":\n case \"onDoubleClickCapture\":\n case \"onMouseDown\":\n case \"onMouseDownCapture\":\n case \"onMouseMove\":\n case \"onMouseMoveCapture\":\n case \"onMouseUp\":\n case \"onMouseUpCapture\":\n case \"onMouseEnter\":\n (props = !props.disabled) ||\n ((inst = inst.type),\n (props = !(\n \"button\" === inst ||\n \"input\" === inst ||\n \"select\" === inst ||\n \"textarea\" === inst\n )));\n inst = !props;\n break a;\n default:\n inst = !1;\n }\n if (inst) return null;\n if (stateNode && \"function\" !== typeof stateNode)\n throw Error(\n formatProdErrorMessage(231, registrationName, typeof stateNode)\n );\n return stateNode;\n}\nvar canUseDOM = !(\n \"undefined\" === typeof window ||\n \"undefined\" === typeof window.document ||\n \"undefined\" === typeof window.document.createElement\n ),\n passiveBrowserEventsSupported = !1;\nif (canUseDOM)\n try {\n var options = {};\n Object.defineProperty(options, \"passive\", {\n get: function () {\n passiveBrowserEventsSupported = !0;\n }\n });\n window.addEventListener(\"test\", options, options);\n window.removeEventListener(\"test\", options, options);\n } catch (e) {\n passiveBrowserEventsSupported = !1;\n }\nvar root = null,\n startText = null,\n fallbackText = null;\nfunction getData() {\n if (fallbackText) return fallbackText;\n var start,\n startValue = startText,\n startLength = startValue.length,\n end,\n endValue = \"value\" in root ? root.value : root.textContent,\n endLength = endValue.length;\n for (\n start = 0;\n start < startLength && startValue[start] === endValue[start];\n start++\n );\n var minEnd = startLength - start;\n for (\n end = 1;\n end <= minEnd &&\n startValue[startLength - end] === endValue[endLength - end];\n end++\n );\n return (fallbackText = endValue.slice(start, 1 < end ? 1 - end : void 0));\n}\nfunction getEventCharCode(nativeEvent) {\n var keyCode = nativeEvent.keyCode;\n \"charCode\" in nativeEvent\n ? ((nativeEvent = nativeEvent.charCode),\n 0 === nativeEvent && 13 === keyCode && (nativeEvent = 13))\n : (nativeEvent = keyCode);\n 10 === nativeEvent && (nativeEvent = 13);\n return 32 <= nativeEvent || 13 === nativeEvent ? nativeEvent : 0;\n}\nfunction functionThatReturnsTrue() {\n return !0;\n}\nfunction functionThatReturnsFalse() {\n return !1;\n}\nfunction createSyntheticEvent(Interface) {\n function SyntheticBaseEvent(\n reactName,\n reactEventType,\n targetInst,\n nativeEvent,\n nativeEventTarget\n ) {\n this._reactName = reactName;\n this._targetInst = targetInst;\n this.type = reactEventType;\n this.nativeEvent = nativeEvent;\n this.target = nativeEventTarget;\n this.currentTarget = null;\n for (var propName in Interface)\n Interface.hasOwnProperty(propName) &&\n ((reactName = Interface[propName]),\n (this[propName] = reactName\n ? reactName(nativeEvent)\n : nativeEvent[propName]));\n this.isDefaultPrevented = (\n null != nativeEvent.defaultPrevented\n ? nativeEvent.defaultPrevented\n : !1 === nativeEvent.returnValue\n )\n ? functionThatReturnsTrue\n : functionThatReturnsFalse;\n this.isPropagationStopped = functionThatReturnsFalse;\n return this;\n }\n assign(SyntheticBaseEvent.prototype, {\n preventDefault: function () {\n this.defaultPrevented = !0;\n var event = this.nativeEvent;\n event &&\n (event.preventDefault\n ? event.preventDefault()\n : \"unknown\" !== typeof event.returnValue && (event.returnValue = !1),\n (this.isDefaultPrevented = functionThatReturnsTrue));\n },\n stopPropagation: function () {\n var event = this.nativeEvent;\n event &&\n (event.stopPropagation\n ? event.stopPropagation()\n : \"unknown\" !== typeof event.cancelBubble &&\n (event.cancelBubble = !0),\n (this.isPropagationStopped = functionThatReturnsTrue));\n },\n persist: function () {},\n isPersistent: functionThatReturnsTrue\n });\n return SyntheticBaseEvent;\n}\nvar EventInterface = {\n eventPhase: 0,\n bubbles: 0,\n cancelable: 0,\n timeStamp: function (event) {\n return event.timeStamp || Date.now();\n },\n defaultPrevented: 0,\n isTrusted: 0\n },\n SyntheticEvent = createSyntheticEvent(EventInterface),\n UIEventInterface = assign({}, EventInterface, { view: 0, detail: 0 }),\n SyntheticUIEvent = createSyntheticEvent(UIEventInterface),\n lastMovementX,\n lastMovementY,\n lastMouseEvent,\n MouseEventInterface = assign({}, UIEventInterface, {\n screenX: 0,\n screenY: 0,\n clientX: 0,\n clientY: 0,\n pageX: 0,\n pageY: 0,\n ctrlKey: 0,\n shiftKey: 0,\n altKey: 0,\n metaKey: 0,\n getModifierState: getEventModifierState,\n button: 0,\n buttons: 0,\n relatedTarget: function (event) {\n return void 0 === event.relatedTarget\n ? event.fromElement === event.srcElement\n ? event.toElement\n : event.fromElement\n : event.relatedTarget;\n },\n movementX: function (event) {\n if (\"movementX\" in event) return event.movementX;\n event !== lastMouseEvent &&\n (lastMouseEvent && \"mousemove\" === event.type\n ? ((lastMovementX = event.screenX - lastMouseEvent.screenX),\n (lastMovementY = event.screenY - lastMouseEvent.screenY))\n : (lastMovementY = lastMovementX = 0),\n (lastMouseEvent = event));\n return lastMovementX;\n },\n movementY: function (event) {\n return \"movementY\" in event ? event.movementY : lastMovementY;\n }\n }),\n SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface),\n DragEventInterface = assign({}, MouseEventInterface, { dataTransfer: 0 }),\n SyntheticDragEvent = createSyntheticEvent(DragEventInterface),\n FocusEventInterface = assign({}, UIEventInterface, { relatedTarget: 0 }),\n SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface),\n AnimationEventInterface = assign({}, EventInterface, {\n animationName: 0,\n elapsedTime: 0,\n pseudoElement: 0\n }),\n SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface),\n ClipboardEventInterface = assign({}, EventInterface, {\n clipboardData: function (event) {\n return \"clipboardData\" in event\n ? event.clipboardData\n : window.clipboardData;\n }\n }),\n SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface),\n CompositionEventInterface = assign({}, EventInterface, { data: 0 }),\n SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface),\n normalizeKey = {\n Esc: \"Escape\",\n Spacebar: \" \",\n Left: \"ArrowLeft\",\n Up: \"ArrowUp\",\n Right: \"ArrowRight\",\n Down: \"ArrowDown\",\n Del: \"Delete\",\n Win: \"OS\",\n Menu: \"ContextMenu\",\n Apps: \"ContextMenu\",\n Scroll: \"ScrollLock\",\n MozPrintableKey: \"Unidentified\"\n },\n translateToKey = {\n 8: \"Backspace\",\n 9: \"Tab\",\n 12: \"Clear\",\n 13: \"Enter\",\n 16: \"Shift\",\n 17: \"Control\",\n 18: \"Alt\",\n 19: \"Pause\",\n 20: \"CapsLock\",\n 27: \"Escape\",\n 32: \" \",\n 33: \"PageUp\",\n 34: \"PageDown\",\n 35: \"End\",\n 36: \"Home\",\n 37: \"ArrowLeft\",\n 38: \"ArrowUp\",\n 39: \"ArrowRight\",\n 40: \"ArrowDown\",\n 45: \"Insert\",\n 46: \"Delete\",\n 112: \"F1\",\n 113: \"F2\",\n 114: \"F3\",\n 115: \"F4\",\n 116: \"F5\",\n 117: \"F6\",\n 118: \"F7\",\n 119: \"F8\",\n 120: \"F9\",\n 121: \"F10\",\n 122: \"F11\",\n 123: \"F12\",\n 144: \"NumLock\",\n 145: \"ScrollLock\",\n 224: \"Meta\"\n },\n modifierKeyToProp = {\n Alt: \"altKey\",\n Control: \"ctrlKey\",\n Meta: \"metaKey\",\n Shift: \"shiftKey\"\n };\nfunction modifierStateGetter(keyArg) {\n var nativeEvent = this.nativeEvent;\n return nativeEvent.getModifierState\n ? nativeEvent.getModifierState(keyArg)\n : (keyArg = modifierKeyToProp[keyArg])\n ? !!nativeEvent[keyArg]\n : !1;\n}\nfunction getEventModifierState() {\n return modifierStateGetter;\n}\nvar KeyboardEventInterface = assign({}, UIEventInterface, {\n key: function (nativeEvent) {\n if (nativeEvent.key) {\n var key = normalizeKey[nativeEvent.key] || nativeEvent.key;\n if (\"Unidentified\" !== key) return key;\n }\n return \"keypress\" === nativeEvent.type\n ? ((nativeEvent = getEventCharCode(nativeEvent)),\n 13 === nativeEvent ? \"Enter\" : String.fromCharCode(nativeEvent))\n : \"keydown\" === nativeEvent.type || \"keyup\" === nativeEvent.type\n ? translateToKey[nativeEvent.keyCode] || \"Unidentified\"\n : \"\";\n },\n code: 0,\n location: 0,\n ctrlKey: 0,\n shiftKey: 0,\n altKey: 0,\n metaKey: 0,\n repeat: 0,\n locale: 0,\n getModifierState: getEventModifierState,\n charCode: function (event) {\n return \"keypress\" === event.type ? getEventCharCode(event) : 0;\n },\n keyCode: function (event) {\n return \"keydown\" === event.type || \"keyup\" === event.type\n ? event.keyCode\n : 0;\n },\n which: function (event) {\n return \"keypress\" === event.type\n ? getEventCharCode(event)\n : \"keydown\" === event.type || \"keyup\" === event.type\n ? event.keyCode\n : 0;\n }\n }),\n SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface),\n PointerEventInterface = assign({}, MouseEventInterface, {\n pointerId: 0,\n width: 0,\n height: 0,\n pressure: 0,\n tangentialPressure: 0,\n tiltX: 0,\n tiltY: 0,\n twist: 0,\n pointerType: 0,\n isPrimary: 0\n }),\n SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface),\n TouchEventInterface = assign({}, UIEventInterface, {\n touches: 0,\n targetTouches: 0,\n changedTouches: 0,\n altKey: 0,\n metaKey: 0,\n ctrlKey: 0,\n shiftKey: 0,\n getModifierState: getEventModifierState\n }),\n SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface),\n TransitionEventInterface = assign({}, EventInterface, {\n propertyName: 0,\n elapsedTime: 0,\n pseudoElement: 0\n }),\n SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface),\n WheelEventInterface = assign({}, MouseEventInterface, {\n deltaX: function (event) {\n return \"deltaX\" in event\n ? event.deltaX\n : \"wheelDeltaX\" in event\n ? -event.wheelDeltaX\n : 0;\n },\n deltaY: function (event) {\n return \"deltaY\" in event\n ? event.deltaY\n : \"wheelDeltaY\" in event\n ? -event.wheelDeltaY\n : \"wheelDelta\" in event\n ? -event.wheelDelta\n : 0;\n },\n deltaZ: 0,\n deltaMode: 0\n }),\n SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface),\n ToggleEventInterface = assign({}, EventInterface, {\n newState: 0,\n oldState: 0\n }),\n SyntheticToggleEvent = createSyntheticEvent(ToggleEventInterface),\n END_KEYCODES = [9, 13, 27, 32],\n canUseCompositionEvent = canUseDOM && \"CompositionEvent\" in window,\n documentMode = null;\ncanUseDOM &&\n \"documentMode\" in document &&\n (documentMode = document.documentMode);\nvar canUseTextInputEvent = canUseDOM && \"TextEvent\" in window && !documentMode,\n useFallbackCompositionData =\n canUseDOM &&\n (!canUseCompositionEvent ||\n (documentMode && 8 < documentMode && 11 >= documentMode)),\n SPACEBAR_CHAR = String.fromCharCode(32),\n hasSpaceKeypress = !1;\nfunction isFallbackCompositionEnd(domEventName, nativeEvent) {\n switch (domEventName) {\n case \"keyup\":\n return -1 !== END_KEYCODES.indexOf(nativeEvent.keyCode);\n case \"keydown\":\n return 229 !== nativeEvent.keyCode;\n case \"keypress\":\n case \"mousedown\":\n case \"focusout\":\n return !0;\n default:\n return !1;\n }\n}\nfunction getDataFromCustomEvent(nativeEvent) {\n nativeEvent = nativeEvent.detail;\n return \"object\" === typeof nativeEvent && \"data\" in nativeEvent\n ? nativeEvent.data\n : null;\n}\nvar isComposing = !1;\nfunction getNativeBeforeInputChars(domEventName, nativeEvent) {\n switch (domEventName) {\n case \"compositionend\":\n return getDataFromCustomEvent(nativeEvent);\n case \"keypress\":\n if (32 !== nativeEvent.which) return null;\n hasSpaceKeypress = !0;\n return SPACEBAR_CHAR;\n case \"textInput\":\n return (\n (domEventName = nativeEvent.data),\n domEventName === SPACEBAR_CHAR && hasSpaceKeypress ? null : domEventName\n );\n default:\n return null;\n }\n}\nfunction getFallbackBeforeInputChars(domEventName, nativeEvent) {\n if (isComposing)\n return \"compositionend\" === domEventName ||\n (!canUseCompositionEvent &&\n isFallbackCompositionEnd(domEventName, nativeEvent))\n ? ((domEventName = getData()),\n (fallbackText = startText = root = null),\n (isComposing = !1),\n domEventName)\n : null;\n switch (domEventName) {\n case \"paste\":\n return null;\n case \"keypress\":\n if (\n !(nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) ||\n (nativeEvent.ctrlKey && nativeEvent.altKey)\n ) {\n if (nativeEvent.char && 1 < nativeEvent.char.length)\n return nativeEvent.char;\n if (nativeEvent.which) return String.fromCharCode(nativeEvent.which);\n }\n return null;\n case \"compositionend\":\n return useFallbackCompositionData && \"ko\" !== nativeEvent.locale\n ? null\n : nativeEvent.data;\n default:\n return null;\n }\n}\nvar supportedInputTypes = {\n color: !0,\n date: !0,\n datetime: !0,\n \"datetime-local\": !0,\n email: !0,\n month: !0,\n number: !0,\n password: !0,\n range: !0,\n search: !0,\n tel: !0,\n text: !0,\n time: !0,\n url: !0,\n week: !0\n};\nfunction isTextInputElement(elem) {\n var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();\n return \"input\" === nodeName\n ? !!supportedInputTypes[elem.type]\n : \"textarea\" === nodeName\n ? !0\n : !1;\n}\nfunction createAndAccumulateChangeEvent(\n dispatchQueue,\n inst,\n nativeEvent,\n target\n) {\n restoreTarget\n ? restoreQueue\n ? restoreQueue.push(target)\n : (restoreQueue = [target])\n : (restoreTarget = target);\n inst = accumulateTwoPhaseListeners(inst, \"onChange\");\n 0 < inst.length &&\n ((nativeEvent = new SyntheticEvent(\n \"onChange\",\n \"change\",\n null,\n nativeEvent,\n target\n )),\n dispatchQueue.push({ event: nativeEvent, listeners: inst }));\n}\nvar activeElement$1 = null,\n activeElementInst$1 = null;\nfunction runEventInBatch(dispatchQueue) {\n processDispatchQueue(dispatchQueue, 0);\n}\nfunction getInstIfValueChanged(targetInst) {\n var targetNode = getNodeFromInstance(targetInst);\n if (updateValueIfChanged(targetNode)) return targetInst;\n}\nfunction getTargetInstForChangeEvent(domEventName, targetInst) {\n if (\"change\" === domEventName) return targetInst;\n}\nvar isInputEventSupported = !1;\nif (canUseDOM) {\n var JSCompiler_inline_result$jscomp$286;\n if (canUseDOM) {\n var isSupported$jscomp$inline_427 = \"oninput\" in document;\n if (!isSupported$jscomp$inline_427) {\n var element$jscomp$inline_428 = document.createElement(\"div\");\n element$jscomp$inline_428.setAttribute(\"oninput\", \"return;\");\n isSupported$jscomp$inline_427 =\n \"function\" === typeof element$jscomp$inline_428.oninput;\n }\n JSCompiler_inline_result$jscomp$286 = isSupported$jscomp$inline_427;\n } else JSCompiler_inline_result$jscomp$286 = !1;\n isInputEventSupported =\n JSCompiler_inline_result$jscomp$286 &&\n (!document.documentMode || 9 < document.documentMode);\n}\nfunction stopWatchingForValueChange() {\n activeElement$1 &&\n (activeElement$1.detachEvent(\"onpropertychange\", handlePropertyChange),\n (activeElementInst$1 = activeElement$1 = null));\n}\nfunction handlePropertyChange(nativeEvent) {\n if (\n \"value\" === nativeEvent.propertyName &&\n getInstIfValueChanged(activeElementInst$1)\n ) {\n var dispatchQueue = [];\n createAndAccumulateChangeEvent(\n dispatchQueue,\n activeElementInst$1,\n nativeEvent,\n getEventTarget(nativeEvent)\n );\n batchedUpdates$1(runEventInBatch, dispatchQueue);\n }\n}\nfunction handleEventsForInputEventPolyfill(domEventName, target, targetInst) {\n \"focusin\" === domEventName\n ? (stopWatchingForValueChange(),\n (activeElement$1 = target),\n (activeElementInst$1 = targetInst),\n activeElement$1.attachEvent(\"onpropertychange\", handlePropertyChange))\n : \"focusout\" === domEventName && stopWatchingForValueChange();\n}\nfunction getTargetInstForInputEventPolyfill(domEventName) {\n if (\n \"selectionchange\" === domEventName ||\n \"keyup\" === domEventName ||\n \"keydown\" === domEventName\n )\n return getInstIfValueChanged(activeElementInst$1);\n}\nfunction getTargetInstForClickEvent(domEventName, targetInst) {\n if (\"click\" === domEventName) return getInstIfValueChanged(targetInst);\n}\nfunction getTargetInstForInputOrChangeEvent(domEventName, targetInst) {\n if (\"input\" === domEventName || \"change\" === domEventName)\n return getInstIfValueChanged(targetInst);\n}\nfunction is(x, y) {\n return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);\n}\nvar objectIs = \"function\" === typeof Object.is ? Object.is : is;\nfunction shallowEqual(objA, objB) {\n if (objectIs(objA, objB)) return !0;\n if (\n \"object\" !== typeof objA ||\n null === objA ||\n \"object\" !== typeof objB ||\n null === objB\n )\n return !1;\n var keysA = Object.keys(objA),\n keysB = Object.keys(objB);\n if (keysA.length !== keysB.length) return !1;\n for (keysB = 0; keysB < keysA.length; keysB++) {\n var currentKey = keysA[keysB];\n if (\n !hasOwnProperty.call(objB, currentKey) ||\n !objectIs(objA[currentKey], objB[currentKey])\n )\n return !1;\n }\n return !0;\n}\nfunction getLeafNode(node) {\n for (; node && node.firstChild; ) node = node.firstChild;\n return node;\n}\nfunction getNodeForCharacterOffset(root, offset) {\n var node = getLeafNode(root);\n root = 0;\n for (var nodeEnd; node; ) {\n if (3 === node.nodeType) {\n nodeEnd = root + node.textContent.length;\n if (root <= offset && nodeEnd >= offset)\n return { node: node, offset: offset - root };\n root = nodeEnd;\n }\n a: {\n for (; node; ) {\n if (node.nextSibling) {\n node = node.nextSibling;\n break a;\n }\n node = node.parentNode;\n }\n node = void 0;\n }\n node = getLeafNode(node);\n }\n}\nfunction containsNode(outerNode, innerNode) {\n return outerNode && innerNode\n ? outerNode === innerNode\n ? !0\n : outerNode && 3 === outerNode.nodeType\n ? !1\n : innerNode && 3 === innerNode.nodeType\n ? containsNode(outerNode, innerNode.parentNode)\n : \"contains\" in outerNode\n ? outerNode.contains(innerNode)\n : outerNode.compareDocumentPosition\n ? !!(outerNode.compareDocumentPosition(innerNode) & 16)\n : !1\n : !1;\n}\nfunction getActiveElementDeep(containerInfo) {\n containerInfo =\n null != containerInfo &&\n null != containerInfo.ownerDocument &&\n null != containerInfo.ownerDocument.defaultView\n ? containerInfo.ownerDocument.defaultView\n : window;\n for (\n var element = getActiveElement(containerInfo.document);\n element instanceof containerInfo.HTMLIFrameElement;\n\n ) {\n try {\n var JSCompiler_inline_result =\n \"string\" === typeof element.contentWindow.location.href;\n } catch (err) {\n JSCompiler_inline_result = !1;\n }\n if (JSCompiler_inline_result) containerInfo = element.contentWindow;\n else break;\n element = getActiveElement(containerInfo.document);\n }\n return element;\n}\nfunction hasSelectionCapabilities(elem) {\n var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();\n return (\n nodeName &&\n ((\"input\" === nodeName &&\n (\"text\" === elem.type ||\n \"search\" === elem.type ||\n \"tel\" === elem.type ||\n \"url\" === elem.type ||\n \"password\" === elem.type)) ||\n \"textarea\" === nodeName ||\n \"true\" === elem.contentEditable)\n );\n}\nvar skipSelectionChangeEvent =\n canUseDOM && \"documentMode\" in document && 11 >= document.documentMode,\n activeElement = null,\n activeElementInst = null,\n lastSelection = null,\n mouseDown = !1;\nfunction constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) {\n var doc =\n nativeEventTarget.window === nativeEventTarget\n ? nativeEventTarget.document\n : 9 === nativeEventTarget.nodeType\n ? nativeEventTarget\n : nativeEventTarget.ownerDocument;\n mouseDown ||\n null == activeElement ||\n activeElement !== getActiveElement(doc) ||\n ((doc = activeElement),\n \"selectionStart\" in doc && hasSelectionCapabilities(doc)\n ? (doc = { start: doc.selectionStart, end: doc.selectionEnd })\n : ((doc = (\n (doc.ownerDocument && doc.ownerDocument.defaultView) ||\n window\n ).getSelection()),\n (doc = {\n anchorNode: doc.anchorNode,\n anchorOffset: doc.anchorOffset,\n focusNode: doc.focusNode,\n focusOffset: doc.focusOffset\n })),\n (lastSelection && shallowEqual(lastSelection, doc)) ||\n ((lastSelection = doc),\n (doc = accumulateTwoPhaseListeners(activeElementInst, \"onSelect\")),\n 0 < doc.length &&\n ((nativeEvent = new SyntheticEvent(\n \"onSelect\",\n \"select\",\n null,\n nativeEvent,\n nativeEventTarget\n )),\n dispatchQueue.push({ event: nativeEvent, listeners: doc }),\n (nativeEvent.target = activeElement))));\n}\nfunction makePrefixMap(styleProp, eventName) {\n var prefixes = {};\n prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();\n prefixes[\"Webkit\" + styleProp] = \"webkit\" + eventName;\n prefixes[\"Moz\" + styleProp] = \"moz\" + eventName;\n return prefixes;\n}\nvar vendorPrefixes = {\n animationend: makePrefixMap(\"Animation\", \"AnimationEnd\"),\n animationiteration: makePrefixMap(\"Animation\", \"AnimationIteration\"),\n animationstart: makePrefixMap(\"Animation\", \"AnimationStart\"),\n transitionrun: makePrefixMap(\"Transition\", \"TransitionRun\"),\n transitionstart: makePrefixMap(\"Transition\", \"TransitionStart\"),\n transitioncancel: makePrefixMap(\"Transition\", \"TransitionCancel\"),\n transitionend: makePrefixMap(\"Transition\", \"TransitionEnd\")\n },\n prefixedEventNames = {},\n style = {};\ncanUseDOM &&\n ((style = document.createElement(\"div\").style),\n \"AnimationEvent\" in window ||\n (delete vendorPrefixes.animationend.animation,\n delete vendorPrefixes.animationiteration.animation,\n delete vendorPrefixes.animationstart.animation),\n \"TransitionEvent\" in window ||\n delete vendorPrefixes.transitionend.transition);\nfunction getVendorPrefixedEventName(eventName) {\n if (prefixedEventNames[eventName]) return prefixedEventNames[eventName];\n if (!vendorPrefixes[eventName]) return eventName;\n var prefixMap = vendorPrefixes[eventName],\n styleProp;\n for (styleProp in prefixMap)\n if (prefixMap.hasOwnProperty(styleProp) && styleProp in style)\n return (prefixedEventNames[eventName] = prefixMap[styleProp]);\n return eventName;\n}\nvar ANIMATION_END = getVendorPrefixedEventName(\"animationend\"),\n ANIMATION_ITERATION = getVendorPrefixedEventName(\"animationiteration\"),\n ANIMATION_START = getVendorPrefixedEventName(\"animationstart\"),\n TRANSITION_RUN = getVendorPrefixedEventName(\"transitionrun\"),\n TRANSITION_START = getVendorPrefixedEventName(\"transitionstart\"),\n TRANSITION_CANCEL = getVendorPrefixedEventName(\"transitioncancel\"),\n TRANSITION_END = getVendorPrefixedEventName(\"transitionend\"),\n topLevelEventsToReactNames = new Map(),\n simpleEventPluginEvents =\n \"abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel\".split(\n \" \"\n );\nsimpleEventPluginEvents.push(\"scrollEnd\");\nfunction registerSimpleEvent(domEventName, reactName) {\n topLevelEventsToReactNames.set(domEventName, reactName);\n registerTwoPhaseEvent(reactName, [domEventName]);\n}\nvar reportGlobalError =\n \"function\" === typeof reportError\n ? reportError\n : function (error) {\n if (\n \"object\" === typeof window &&\n \"function\" === typeof window.ErrorEvent\n ) {\n var event = new window.ErrorEvent(\"error\", {\n bubbles: !0,\n cancelable: !0,\n message:\n \"object\" === typeof error &&\n null !== error &&\n \"string\" === typeof error.message\n ? String(error.message)\n : String(error),\n error: error\n });\n if (!window.dispatchEvent(event)) return;\n } else if (\n \"object\" === typeof process &&\n \"function\" === typeof process.emit\n ) {\n process.emit(\"uncaughtException\", error);\n return;\n }\n console.error(error);\n },\n concurrentQueues = [],\n concurrentQueuesIndex = 0,\n concurrentlyUpdatedLanes = 0;\nfunction finishQueueingConcurrentUpdates() {\n for (\n var endIndex = concurrentQueuesIndex,\n i = (concurrentlyUpdatedLanes = concurrentQueuesIndex = 0);\n i < endIndex;\n\n ) {\n var fiber = concurrentQueues[i];\n concurrentQueues[i++] = null;\n var queue = concurrentQueues[i];\n concurrentQueues[i++] = null;\n var update = concurrentQueues[i];\n concurrentQueues[i++] = null;\n var lane = concurrentQueues[i];\n concurrentQueues[i++] = null;\n if (null !== queue && null !== update) {\n var pending = queue.pending;\n null === pending\n ? (update.next = update)\n : ((update.next = pending.next), (pending.next = update));\n queue.pending = update;\n }\n 0 !== lane && markUpdateLaneFromFiberToRoot(fiber, update, lane);\n }\n}\nfunction enqueueUpdate$1(fiber, queue, update, lane) {\n concurrentQueues[concurrentQueuesIndex++] = fiber;\n concurrentQueues[concurrentQueuesIndex++] = queue;\n concurrentQueues[concurrentQueuesIndex++] = update;\n concurrentQueues[concurrentQueuesIndex++] = lane;\n concurrentlyUpdatedLanes |= lane;\n fiber.lanes |= lane;\n fiber = fiber.alternate;\n null !== fiber && (fiber.lanes |= lane);\n}\nfunction enqueueConcurrentHookUpdate(fiber, queue, update, lane) {\n enqueueUpdate$1(fiber, queue, update, lane);\n return getRootForUpdatedFiber(fiber);\n}\nfunction enqueueConcurrentRenderForLane(fiber, lane) {\n enqueueUpdate$1(fiber, null, null, lane);\n return getRootForUpdatedFiber(fiber);\n}\nfunction markUpdateLaneFromFiberToRoot(sourceFiber, update, lane) {\n sourceFiber.lanes |= lane;\n var alternate = sourceFiber.alternate;\n null !== alternate && (alternate.lanes |= lane);\n for (var isHidden = !1, parent = sourceFiber.return; null !== parent; )\n (parent.childLanes |= lane),\n (alternate = parent.alternate),\n null !== alternate && (alternate.childLanes |= lane),\n 22 === parent.tag &&\n ((sourceFiber = parent.stateNode),\n null === sourceFiber || sourceFiber._visibility & 1 || (isHidden = !0)),\n (sourceFiber = parent),\n (parent = parent.return);\n return 3 === sourceFiber.tag\n ? ((parent = sourceFiber.stateNode),\n isHidden &&\n null !== update &&\n ((isHidden = 31 - clz32(lane)),\n (sourceFiber = parent.hiddenUpdates),\n (alternate = sourceFiber[isHidden]),\n null === alternate\n ? (sourceFiber[isHidden] = [update])\n : alternate.push(update),\n (update.lane = lane | 536870912)),\n parent)\n : null;\n}\nfunction getRootForUpdatedFiber(sourceFiber) {\n if (50 < nestedUpdateCount)\n throw (\n ((nestedUpdateCount = 0),\n (rootWithNestedUpdates = null),\n Error(formatProdErrorMessage(185)))\n );\n for (var parent = sourceFiber.return; null !== parent; )\n (sourceFiber = parent), (parent = sourceFiber.return);\n return 3 === sourceFiber.tag ? sourceFiber.stateNode : null;\n}\nvar emptyContextObject = {};\nfunction FiberNode(tag, pendingProps, key, mode) {\n this.tag = tag;\n this.key = key;\n this.sibling =\n this.child =\n this.return =\n this.stateNode =\n this.type =\n this.elementType =\n null;\n this.index = 0;\n this.refCleanup = this.ref = null;\n this.pendingProps = pendingProps;\n this.dependencies =\n this.memoizedState =\n this.updateQueue =\n this.memoizedProps =\n null;\n this.mode = mode;\n this.subtreeFlags = this.flags = 0;\n this.deletions = null;\n this.childLanes = this.lanes = 0;\n this.alternate = null;\n}\nfunction createFiberImplClass(tag, pendingProps, key, mode) {\n return new FiberNode(tag, pendingProps, key, mode);\n}\nfunction shouldConstruct(Component) {\n Component = Component.prototype;\n return !(!Component || !Component.isReactComponent);\n}\nfunction createWorkInProgress(current, pendingProps) {\n var workInProgress = current.alternate;\n null === workInProgress\n ? ((workInProgress = createFiberImplClass(\n current.tag,\n pendingProps,\n current.key,\n current.mode\n )),\n (workInProgress.elementType = current.elementType),\n (workInProgress.type = current.type),\n (workInProgress.stateNode = current.stateNode),\n (workInProgress.alternate = current),\n (current.alternate = workInProgress))\n : ((workInProgress.pendingProps = pendingProps),\n (workInProgress.type = current.type),\n (workInProgress.flags = 0),\n (workInProgress.subtreeFlags = 0),\n (workInProgress.deletions = null));\n workInProgress.flags = current.flags & 65011712;\n workInProgress.childLanes = current.childLanes;\n workInProgress.lanes = current.lanes;\n workInProgress.child = current.child;\n workInProgress.memoizedProps = current.memoizedProps;\n workInProgress.memoizedState = current.memoizedState;\n workInProgress.updateQueue = current.updateQueue;\n pendingProps = current.dependencies;\n workInProgress.dependencies =\n null === pendingProps\n ? null\n : { lanes: pendingProps.lanes, firstContext: pendingProps.firstContext };\n workInProgress.sibling = current.sibling;\n workInProgress.index = current.index;\n workInProgress.ref = current.ref;\n workInProgress.refCleanup = current.refCleanup;\n return workInProgress;\n}\nfunction resetWorkInProgress(workInProgress, renderLanes) {\n workInProgress.flags &= 65011714;\n var current = workInProgress.alternate;\n null === current\n ? ((workInProgress.childLanes = 0),\n (workInProgress.lanes = renderLanes),\n (workInProgress.child = null),\n (workInProgress.subtreeFlags = 0),\n (workInProgress.memoizedProps = null),\n (workInProgress.memoizedState = null),\n (workInProgress.updateQueue = null),\n (workInProgress.dependencies = null),\n (workInProgress.stateNode = null))\n : ((workInProgress.childLanes = current.childLanes),\n (workInProgress.lanes = current.lanes),\n (workInProgress.child = current.child),\n (workInProgress.subtreeFlags = 0),\n (workInProgress.deletions = null),\n (workInProgress.memoizedProps = current.memoizedProps),\n (workInProgress.memoizedState = current.memoizedState),\n (workInProgress.updateQueue = current.updateQueue),\n (workInProgress.type = current.type),\n (renderLanes = current.dependencies),\n (workInProgress.dependencies =\n null === renderLanes\n ? null\n : {\n lanes: renderLanes.lanes,\n firstContext: renderLanes.firstContext\n }));\n return workInProgress;\n}\nfunction createFiberFromTypeAndProps(\n type,\n key,\n pendingProps,\n owner,\n mode,\n lanes\n) {\n var fiberTag = 0;\n owner = type;\n if (\"function\" === typeof type) shouldConstruct(type) && (fiberTag = 1);\n else if (\"string\" === typeof type)\n fiberTag = isHostHoistableType(\n type,\n pendingProps,\n contextStackCursor.current\n )\n ? 26\n : \"html\" === type || \"head\" === type || \"body\" === type\n ? 27\n : 5;\n else\n a: switch (type) {\n case REACT_ACTIVITY_TYPE:\n return (\n (type = createFiberImplClass(31, pendingProps, key, mode)),\n (type.elementType = REACT_ACTIVITY_TYPE),\n (type.lanes = lanes),\n type\n );\n case REACT_FRAGMENT_TYPE:\n return createFiberFromFragment(pendingProps.children, mode, lanes, key);\n case REACT_STRICT_MODE_TYPE:\n fiberTag = 8;\n mode |= 24;\n break;\n case REACT_PROFILER_TYPE:\n return (\n (type = createFiberImplClass(12, pendingProps, key, mode | 2)),\n (type.elementType = REACT_PROFILER_TYPE),\n (type.lanes = lanes),\n type\n );\n case REACT_SUSPENSE_TYPE:\n return (\n (type = createFiberImplClass(13, pendingProps, key, mode)),\n (type.elementType = REACT_SUSPENSE_TYPE),\n (type.lanes = lanes),\n type\n );\n case REACT_SUSPENSE_LIST_TYPE:\n return (\n (type = createFiberImplClass(19, pendingProps, key, mode)),\n (type.elementType = REACT_SUSPENSE_LIST_TYPE),\n (type.lanes = lanes),\n type\n );\n default:\n if (\"object\" === typeof type && null !== type)\n switch (type.$$typeof) {\n case REACT_CONTEXT_TYPE:\n fiberTag = 10;\n break a;\n case REACT_CONSUMER_TYPE:\n fiberTag = 9;\n break a;\n case REACT_FORWARD_REF_TYPE:\n fiberTag = 11;\n break a;\n case REACT_MEMO_TYPE:\n fiberTag = 14;\n break a;\n case REACT_LAZY_TYPE:\n fiberTag = 16;\n owner = null;\n break a;\n }\n fiberTag = 29;\n pendingProps = Error(\n formatProdErrorMessage(130, null === type ? \"null\" : typeof type, \"\")\n );\n owner = null;\n }\n key = createFiberImplClass(fiberTag, pendingProps, key, mode);\n key.elementType = type;\n key.type = owner;\n key.lanes = lanes;\n return key;\n}\nfunction createFiberFromFragment(elements, mode, lanes, key) {\n elements = createFiberImplClass(7, elements, key, mode);\n elements.lanes = lanes;\n return elements;\n}\nfunction createFiberFromText(content, mode, lanes) {\n content = createFiberImplClass(6, content, null, mode);\n content.lanes = lanes;\n return content;\n}\nfunction createFiberFromDehydratedFragment(dehydratedNode) {\n var fiber = createFiberImplClass(18, null, null, 0);\n fiber.stateNode = dehydratedNode;\n return fiber;\n}\nfunction createFiberFromPortal(portal, mode, lanes) {\n mode = createFiberImplClass(\n 4,\n null !== portal.children ? portal.children : [],\n portal.key,\n mode\n );\n mode.lanes = lanes;\n mode.stateNode = {\n containerInfo: portal.containerInfo,\n pendingChildren: null,\n implementation: portal.implementation\n };\n return mode;\n}\nvar CapturedStacks = new WeakMap();\nfunction createCapturedValueAtFiber(value, source) {\n if (\"object\" === typeof value && null !== value) {\n var existing = CapturedStacks.get(value);\n if (void 0 !== existing) return existing;\n source = {\n value: value,\n source: source,\n stack: getStackByFiberInDevAndProd(source)\n };\n CapturedStacks.set(value, source);\n return source;\n }\n return {\n value: value,\n source: source,\n stack: getStackByFiberInDevAndProd(source)\n };\n}\nvar forkStack = [],\n forkStackIndex = 0,\n treeForkProvider = null,\n treeForkCount = 0,\n idStack = [],\n idStackIndex = 0,\n treeContextProvider = null,\n treeContextId = 1,\n treeContextOverflow = \"\";\nfunction pushTreeFork(workInProgress, totalChildren) {\n forkStack[forkStackIndex++] = treeForkCount;\n forkStack[forkStackIndex++] = treeForkProvider;\n treeForkProvider = workInProgress;\n treeForkCount = totalChildren;\n}\nfunction pushTreeId(workInProgress, totalChildren, index) {\n idStack[idStackIndex++] = treeContextId;\n idStack[idStackIndex++] = treeContextOverflow;\n idStack[idStackIndex++] = treeContextProvider;\n treeContextProvider = workInProgress;\n var baseIdWithLeadingBit = treeContextId;\n workInProgress = treeContextOverflow;\n var baseLength = 32 - clz32(baseIdWithLeadingBit) - 1;\n baseIdWithLeadingBit &= ~(1 << baseLength);\n index += 1;\n var length = 32 - clz32(totalChildren) + baseLength;\n if (30 < length) {\n var numberOfOverflowBits = baseLength - (baseLength % 5);\n length = (\n baseIdWithLeadingBit &\n ((1 << numberOfOverflowBits) - 1)\n ).toString(32);\n baseIdWithLeadingBit >>= numberOfOverflowBits;\n baseLength -= numberOfOverflowBits;\n treeContextId =\n (1 << (32 - clz32(totalChildren) + baseLength)) |\n (index << baseLength) |\n baseIdWithLeadingBit;\n treeContextOverflow = length + workInProgress;\n } else\n (treeContextId =\n (1 << length) | (index << baseLength) | baseIdWithLeadingBit),\n (treeContextOverflow = workInProgress);\n}\nfunction pushMaterializedTreeId(workInProgress) {\n null !== workInProgress.return &&\n (pushTreeFork(workInProgress, 1), pushTreeId(workInProgress, 1, 0));\n}\nfunction popTreeContext(workInProgress) {\n for (; workInProgress === treeForkProvider; )\n (treeForkProvider = forkStack[--forkStackIndex]),\n (forkStack[forkStackIndex] = null),\n (treeForkCount = forkStack[--forkStackIndex]),\n (forkStack[forkStackIndex] = null);\n for (; workInProgress === treeContextProvider; )\n (treeContextProvider = idStack[--idStackIndex]),\n (idStack[idStackIndex] = null),\n (treeContextOverflow = idStack[--idStackIndex]),\n (idStack[idStackIndex] = null),\n (treeContextId = idStack[--idStackIndex]),\n (idStack[idStackIndex] = null);\n}\nfunction restoreSuspendedTreeContext(workInProgress, suspendedContext) {\n idStack[idStackIndex++] = treeContextId;\n idStack[idStackIndex++] = treeContextOverflow;\n idStack[idStackIndex++] = treeContextProvider;\n treeContextId = suspendedContext.id;\n treeContextOverflow = suspendedContext.overflow;\n treeContextProvider = workInProgress;\n}\nvar hydrationParentFiber = null,\n nextHydratableInstance = null,\n isHydrating = !1,\n hydrationErrors = null,\n rootOrSingletonContext = !1,\n HydrationMismatchException = Error(formatProdErrorMessage(519));\nfunction throwOnHydrationMismatch(fiber) {\n var error = Error(\n formatProdErrorMessage(\n 418,\n 1 < arguments.length && void 0 !== arguments[1] && arguments[1]\n ? \"text\"\n : \"HTML\",\n \"\"\n )\n );\n queueHydrationError(createCapturedValueAtFiber(error, fiber));\n throw HydrationMismatchException;\n}\nfunction prepareToHydrateHostInstance(fiber) {\n var instance = fiber.stateNode,\n type = fiber.type,\n props = fiber.memoizedProps;\n instance[internalInstanceKey] = fiber;\n instance[internalPropsKey] = props;\n switch (type) {\n case \"dialog\":\n listenToNonDelegatedEvent(\"cancel\", instance);\n listenToNonDelegatedEvent(\"close\", instance);\n break;\n case \"iframe\":\n case \"object\":\n case \"embed\":\n listenToNonDelegatedEvent(\"load\", instance);\n break;\n case \"video\":\n case \"audio\":\n for (type = 0; type < mediaEventTypes.length; type++)\n listenToNonDelegatedEvent(mediaEventTypes[type], instance);\n break;\n case \"source\":\n listenToNonDelegatedEvent(\"error\", instance);\n break;\n case \"img\":\n case \"image\":\n case \"link\":\n listenToNonDelegatedEvent(\"error\", instance);\n listenToNonDelegatedEvent(\"load\", instance);\n break;\n case \"details\":\n listenToNonDelegatedEvent(\"toggle\", instance);\n break;\n case \"input\":\n listenToNonDelegatedEvent(\"invalid\", instance);\n initInput(\n instance,\n props.value,\n props.defaultValue,\n props.checked,\n props.defaultChecked,\n props.type,\n props.name,\n !0\n );\n break;\n case \"select\":\n listenToNonDelegatedEvent(\"invalid\", instance);\n break;\n case \"textarea\":\n listenToNonDelegatedEvent(\"invalid\", instance),\n initTextarea(instance, props.value, props.defaultValue, props.children);\n }\n type = props.children;\n (\"string\" !== typeof type &&\n \"number\" !== typeof type &&\n \"bigint\" !== typeof type) ||\n instance.textContent === \"\" + type ||\n !0 === props.suppressHydrationWarning ||\n checkForUnmatchedText(instance.textContent, type)\n ? (null != props.popover &&\n (listenToNonDelegatedEvent(\"beforetoggle\", instance),\n listenToNonDelegatedEvent(\"toggle\", instance)),\n null != props.onScroll && listenToNonDelegatedEvent(\"scroll\", instance),\n null != props.onScrollEnd &&\n listenToNonDelegatedEvent(\"scrollend\", instance),\n null != props.onClick && (instance.onclick = noop$1),\n (instance = !0))\n : (instance = !1);\n instance || throwOnHydrationMismatch(fiber, !0);\n}\nfunction popToNextHostParent(fiber) {\n for (hydrationParentFiber = fiber.return; hydrationParentFiber; )\n switch (hydrationParentFiber.tag) {\n case 5:\n case 31:\n case 13:\n rootOrSingletonContext = !1;\n return;\n case 27:\n case 3:\n rootOrSingletonContext = !0;\n return;\n default:\n hydrationParentFiber = hydrationParentFiber.return;\n }\n}\nfunction popHydrationState(fiber) {\n if (fiber !== hydrationParentFiber) return !1;\n if (!isHydrating) return popToNextHostParent(fiber), (isHydrating = !0), !1;\n var tag = fiber.tag,\n JSCompiler_temp;\n if ((JSCompiler_temp = 3 !== tag && 27 !== tag)) {\n if ((JSCompiler_temp = 5 === tag))\n (JSCompiler_temp = fiber.type),\n (JSCompiler_temp =\n !(\"form\" !== JSCompiler_temp && \"button\" !== JSCompiler_temp) ||\n shouldSetTextContent(fiber.type, fiber.memoizedProps));\n JSCompiler_temp = !JSCompiler_temp;\n }\n JSCompiler_temp && nextHydratableInstance && throwOnHydrationMismatch(fiber);\n popToNextHostParent(fiber);\n if (13 === tag) {\n fiber = fiber.memoizedState;\n fiber = null !== fiber ? fiber.dehydrated : null;\n if (!fiber) throw Error(formatProdErrorMessage(317));\n nextHydratableInstance =\n getNextHydratableInstanceAfterHydrationBoundary(fiber);\n } else if (31 === tag) {\n fiber = fiber.memoizedState;\n fiber = null !== fiber ? fiber.dehydrated : null;\n if (!fiber) throw Error(formatProdErrorMessage(317));\n nextHydratableInstance =\n getNextHydratableInstanceAfterHydrationBoundary(fiber);\n } else\n 27 === tag\n ? ((tag = nextHydratableInstance),\n isSingletonScope(fiber.type)\n ? ((fiber = previousHydratableOnEnteringScopedSingleton),\n (previousHydratableOnEnteringScopedSingleton = null),\n (nextHydratableInstance = fiber))\n : (nextHydratableInstance = tag))\n : (nextHydratableInstance = hydrationParentFiber\n ? getNextHydratable(fiber.stateNode.nextSibling)\n : null);\n return !0;\n}\nfunction resetHydrationState() {\n nextHydratableInstance = hydrationParentFiber = null;\n isHydrating = !1;\n}\nfunction upgradeHydrationErrorsToRecoverable() {\n var queuedErrors = hydrationErrors;\n null !== queuedErrors &&\n (null === workInProgressRootRecoverableErrors\n ? (workInProgressRootRecoverableErrors = queuedErrors)\n : workInProgressRootRecoverableErrors.push.apply(\n workInProgressRootRecoverableErrors,\n queuedErrors\n ),\n (hydrationErrors = null));\n return queuedErrors;\n}\nfunction queueHydrationError(error) {\n null === hydrationErrors\n ? (hydrationErrors = [error])\n : hydrationErrors.push(error);\n}\nvar valueCursor = createCursor(null),\n currentlyRenderingFiber$1 = null,\n lastContextDependency = null;\nfunction pushProvider(providerFiber, context, nextValue) {\n push(valueCursor, context._currentValue);\n context._currentValue = nextValue;\n}\nfunction popProvider(context) {\n context._currentValue = valueCursor.current;\n pop(valueCursor);\n}\nfunction scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) {\n for (; null !== parent; ) {\n var alternate = parent.alternate;\n (parent.childLanes & renderLanes) !== renderLanes\n ? ((parent.childLanes |= renderLanes),\n null !== alternate && (alternate.childLanes |= renderLanes))\n : null !== alternate &&\n (alternate.childLanes & renderLanes) !== renderLanes &&\n (alternate.childLanes |= renderLanes);\n if (parent === propagationRoot) break;\n parent = parent.return;\n }\n}\nfunction propagateContextChanges(\n workInProgress,\n contexts,\n renderLanes,\n forcePropagateEntireTree\n) {\n var fiber = workInProgress.child;\n null !== fiber && (fiber.return = workInProgress);\n for (; null !== fiber; ) {\n var list = fiber.dependencies;\n if (null !== list) {\n var nextFiber = fiber.child;\n list = list.firstContext;\n a: for (; null !== list; ) {\n var dependency = list;\n list = fiber;\n for (var i = 0; i < contexts.length; i++)\n if (dependency.context === contexts[i]) {\n list.lanes |= renderLanes;\n dependency = list.alternate;\n null !== dependency && (dependency.lanes |= renderLanes);\n scheduleContextWorkOnParentPath(\n list.return,\n renderLanes,\n workInProgress\n );\n forcePropagateEntireTree || (nextFiber = null);\n break a;\n }\n list = dependency.next;\n }\n } else if (18 === fiber.tag) {\n nextFiber = fiber.return;\n if (null === nextFiber) throw Error(formatProdErrorMessage(341));\n nextFiber.lanes |= renderLanes;\n list = nextFiber.alternate;\n null !== list && (list.lanes |= renderLanes);\n scheduleContextWorkOnParentPath(nextFiber, renderLanes, workInProgress);\n nextFiber = null;\n } else nextFiber = fiber.child;\n if (null !== nextFiber) nextFiber.return = fiber;\n else\n for (nextFiber = fiber; null !== nextFiber; ) {\n if (nextFiber === workInProgress) {\n nextFiber = null;\n break;\n }\n fiber = nextFiber.sibling;\n if (null !== fiber) {\n fiber.return = nextFiber.return;\n nextFiber = fiber;\n break;\n }\n nextFiber = nextFiber.return;\n }\n fiber = nextFiber;\n }\n}\nfunction propagateParentContextChanges(\n current,\n workInProgress,\n renderLanes,\n forcePropagateEntireTree\n) {\n current = null;\n for (\n var parent = workInProgress, isInsidePropagationBailout = !1;\n null !== parent;\n\n ) {\n if (!isInsidePropagationBailout)\n if (0 !== (parent.flags & 524288)) isInsidePropagationBailout = !0;\n else if (0 !== (parent.flags & 262144)) break;\n if (10 === parent.tag) {\n var currentParent = parent.alternate;\n if (null === currentParent) throw Error(formatProdErrorMessage(387));\n currentParent = currentParent.memoizedProps;\n if (null !== currentParent) {\n var context = parent.type;\n objectIs(parent.pendingProps.value, currentParent.value) ||\n (null !== current ? current.push(context) : (current = [context]));\n }\n } else if (parent === hostTransitionProviderCursor.current) {\n currentParent = parent.alternate;\n if (null === currentParent) throw Error(formatProdErrorMessage(387));\n currentParent.memoizedState.memoizedState !==\n parent.memoizedState.memoizedState &&\n (null !== current\n ? current.push(HostTransitionContext)\n : (current = [HostTransitionContext]));\n }\n parent = parent.return;\n }\n null !== current &&\n propagateContextChanges(\n workInProgress,\n current,\n renderLanes,\n forcePropagateEntireTree\n );\n workInProgress.flags |= 262144;\n}\nfunction checkIfContextChanged(currentDependencies) {\n for (\n currentDependencies = currentDependencies.firstContext;\n null !== currentDependencies;\n\n ) {\n if (\n !objectIs(\n currentDependencies.context._currentValue,\n currentDependencies.memoizedValue\n )\n )\n return !0;\n currentDependencies = currentDependencies.next;\n }\n return !1;\n}\nfunction prepareToReadContext(workInProgress) {\n currentlyRenderingFiber$1 = workInProgress;\n lastContextDependency = null;\n workInProgress = workInProgress.dependencies;\n null !== workInProgress && (workInProgress.firstContext = null);\n}\nfunction readContext(context) {\n return readContextForConsumer(currentlyRenderingFiber$1, context);\n}\nfunction readContextDuringReconciliation(consumer, context) {\n null === currentlyRenderingFiber$1 && prepareToReadContext(consumer);\n return readContextForConsumer(consumer, context);\n}\nfunction readContextForConsumer(consumer, context) {\n var value = context._currentValue;\n context = { context: context, memoizedValue: value, next: null };\n if (null === lastContextDependency) {\n if (null === consumer) throw Error(formatProdErrorMessage(308));\n lastContextDependency = context;\n consumer.dependencies = { lanes: 0, firstContext: context };\n consumer.flags |= 524288;\n } else lastContextDependency = lastContextDependency.next = context;\n return value;\n}\nvar AbortControllerLocal =\n \"undefined\" !== typeof AbortController\n ? AbortController\n : function () {\n var listeners = [],\n signal = (this.signal = {\n aborted: !1,\n addEventListener: function (type, listener) {\n listeners.push(listener);\n }\n });\n this.abort = function () {\n signal.aborted = !0;\n listeners.forEach(function (listener) {\n return listener();\n });\n };\n },\n scheduleCallback$2 = Scheduler.unstable_scheduleCallback,\n NormalPriority = Scheduler.unstable_NormalPriority,\n CacheContext = {\n $$typeof: REACT_CONTEXT_TYPE,\n Consumer: null,\n Provider: null,\n _currentValue: null,\n _currentValue2: null,\n _threadCount: 0\n };\nfunction createCache() {\n return {\n controller: new AbortControllerLocal(),\n data: new Map(),\n refCount: 0\n };\n}\nfunction releaseCache(cache) {\n cache.refCount--;\n 0 === cache.refCount &&\n scheduleCallback$2(NormalPriority, function () {\n cache.controller.abort();\n });\n}\nvar currentEntangledListeners = null,\n currentEntangledPendingCount = 0,\n currentEntangledLane = 0,\n currentEntangledActionThenable = null;\nfunction entangleAsyncAction(transition, thenable) {\n if (null === currentEntangledListeners) {\n var entangledListeners = (currentEntangledListeners = []);\n currentEntangledPendingCount = 0;\n currentEntangledLane = requestTransitionLane();\n currentEntangledActionThenable = {\n status: \"pending\",\n value: void 0,\n then: function (resolve) {\n entangledListeners.push(resolve);\n }\n };\n }\n currentEntangledPendingCount++;\n thenable.then(pingEngtangledActionScope, pingEngtangledActionScope);\n return thenable;\n}\nfunction pingEngtangledActionScope() {\n if (\n 0 === --currentEntangledPendingCount &&\n null !== currentEntangledListeners\n ) {\n null !== currentEntangledActionThenable &&\n (currentEntangledActionThenable.status = \"fulfilled\");\n var listeners = currentEntangledListeners;\n currentEntangledListeners = null;\n currentEntangledLane = 0;\n currentEntangledActionThenable = null;\n for (var i = 0; i < listeners.length; i++) (0, listeners[i])();\n }\n}\nfunction chainThenableValue(thenable, result) {\n var listeners = [],\n thenableWithOverride = {\n status: \"pending\",\n value: null,\n reason: null,\n then: function (resolve) {\n listeners.push(resolve);\n }\n };\n thenable.then(\n function () {\n thenableWithOverride.status = \"fulfilled\";\n thenableWithOverride.value = result;\n for (var i = 0; i < listeners.length; i++) (0, listeners[i])(result);\n },\n function (error) {\n thenableWithOverride.status = \"rejected\";\n thenableWithOverride.reason = error;\n for (error = 0; error < listeners.length; error++)\n (0, listeners[error])(void 0);\n }\n );\n return thenableWithOverride;\n}\nvar prevOnStartTransitionFinish = ReactSharedInternals.S;\nReactSharedInternals.S = function (transition, returnValue) {\n globalMostRecentTransitionTime = now();\n \"object\" === typeof returnValue &&\n null !== returnValue &&\n \"function\" === typeof returnValue.then &&\n entangleAsyncAction(transition, returnValue);\n null !== prevOnStartTransitionFinish &&\n prevOnStartTransitionFinish(transition, returnValue);\n};\nvar resumedCache = createCursor(null);\nfunction peekCacheFromPool() {\n var cacheResumedFromPreviousRender = resumedCache.current;\n return null !== cacheResumedFromPreviousRender\n ? cacheResumedFromPreviousRender\n : workInProgressRoot.pooledCache;\n}\nfunction pushTransition(offscreenWorkInProgress, prevCachePool) {\n null === prevCachePool\n ? push(resumedCache, resumedCache.current)\n : push(resumedCache, prevCachePool.pool);\n}\nfunction getSuspendedCache() {\n var cacheFromPool = peekCacheFromPool();\n return null === cacheFromPool\n ? null\n : { parent: CacheContext._currentValue, pool: cacheFromPool };\n}\nvar SuspenseException = Error(formatProdErrorMessage(460)),\n SuspenseyCommitException = Error(formatProdErrorMessage(474)),\n SuspenseActionException = Error(formatProdErrorMessage(542)),\n noopSuspenseyCommitThenable = { then: function () {} };\nfunction isThenableResolved(thenable) {\n thenable = thenable.status;\n return \"fulfilled\" === thenable || \"rejected\" === thenable;\n}\nfunction trackUsedThenable(thenableState, thenable, index) {\n index = thenableState[index];\n void 0 === index\n ? thenableState.push(thenable)\n : index !== thenable && (thenable.then(noop$1, noop$1), (thenable = index));\n switch (thenable.status) {\n case \"fulfilled\":\n return thenable.value;\n case \"rejected\":\n throw (\n ((thenableState = thenable.reason),\n checkIfUseWrappedInAsyncCatch(thenableState),\n thenableState)\n );\n default:\n if (\"string\" === typeof thenable.status) thenable.then(noop$1, noop$1);\n else {\n thenableState = workInProgressRoot;\n if (null !== thenableState && 100 < thenableState.shellSuspendCounter)\n throw Error(formatProdErrorMessage(482));\n thenableState = thenable;\n thenableState.status = \"pending\";\n thenableState.then(\n function (fulfilledValue) {\n if (\"pending\" === thenable.status) {\n var fulfilledThenable = thenable;\n fulfilledThenable.status = \"fulfilled\";\n fulfilledThenable.value = fulfilledValue;\n }\n },\n function (error) {\n if (\"pending\" === thenable.status) {\n var rejectedThenable = thenable;\n rejectedThenable.status = \"rejected\";\n rejectedThenable.reason = error;\n }\n }\n );\n }\n switch (thenable.status) {\n case \"fulfilled\":\n return thenable.value;\n case \"rejected\":\n throw (\n ((thenableState = thenable.reason),\n checkIfUseWrappedInAsyncCatch(thenableState),\n thenableState)\n );\n }\n suspendedThenable = thenable;\n throw SuspenseException;\n }\n}\nfunction resolveLazy(lazyType) {\n try {\n var init = lazyType._init;\n return init(lazyType._payload);\n } catch (x) {\n if (null !== x && \"object\" === typeof x && \"function\" === typeof x.then)\n throw ((suspendedThenable = x), SuspenseException);\n throw x;\n }\n}\nvar suspendedThenable = null;\nfunction getSuspendedThenable() {\n if (null === suspendedThenable) throw Error(formatProdErrorMessage(459));\n var thenable = suspendedThenable;\n suspendedThenable = null;\n return thenable;\n}\nfunction checkIfUseWrappedInAsyncCatch(rejectedReason) {\n if (\n rejectedReason === SuspenseException ||\n rejectedReason === SuspenseActionException\n )\n throw Error(formatProdErrorMessage(483));\n}\nvar thenableState$1 = null,\n thenableIndexCounter$1 = 0;\nfunction unwrapThenable(thenable) {\n var index = thenableIndexCounter$1;\n thenableIndexCounter$1 += 1;\n null === thenableState$1 && (thenableState$1 = []);\n return trackUsedThenable(thenableState$1, thenable, index);\n}\nfunction coerceRef(workInProgress, element) {\n element = element.props.ref;\n workInProgress.ref = void 0 !== element ? element : null;\n}\nfunction throwOnInvalidObjectTypeImpl(returnFiber, newChild) {\n if (newChild.$$typeof === REACT_LEGACY_ELEMENT_TYPE)\n throw Error(formatProdErrorMessage(525));\n returnFiber = Object.prototype.toString.call(newChild);\n throw Error(\n formatProdErrorMessage(\n 31,\n \"[object Object]\" === returnFiber\n ? \"object with keys {\" + Object.keys(newChild).join(\", \") + \"}\"\n : returnFiber\n )\n );\n}\nfunction createChildReconciler(shouldTrackSideEffects) {\n function deleteChild(returnFiber, childToDelete) {\n if (shouldTrackSideEffects) {\n var deletions = returnFiber.deletions;\n null === deletions\n ? ((returnFiber.deletions = [childToDelete]), (returnFiber.flags |= 16))\n : deletions.push(childToDelete);\n }\n }\n function deleteRemainingChildren(returnFiber, currentFirstChild) {\n if (!shouldTrackSideEffects) return null;\n for (; null !== currentFirstChild; )\n deleteChild(returnFiber, currentFirstChild),\n (currentFirstChild = currentFirstChild.sibling);\n return null;\n }\n function mapRemainingChildren(currentFirstChild) {\n for (var existingChildren = new Map(); null !== currentFirstChild; )\n null !== currentFirstChild.key\n ? existingChildren.set(currentFirstChild.key, currentFirstChild)\n : existingChildren.set(currentFirstChild.index, currentFirstChild),\n (currentFirstChild = currentFirstChild.sibling);\n return existingChildren;\n }\n function useFiber(fiber, pendingProps) {\n fiber = createWorkInProgress(fiber, pendingProps);\n fiber.index = 0;\n fiber.sibling = null;\n return fiber;\n }\n function placeChild(newFiber, lastPlacedIndex, newIndex) {\n newFiber.index = newIndex;\n if (!shouldTrackSideEffects)\n return (newFiber.flags |= 1048576), lastPlacedIndex;\n newIndex = newFiber.alternate;\n if (null !== newIndex)\n return (\n (newIndex = newIndex.index),\n newIndex < lastPlacedIndex\n ? ((newFiber.flags |= 67108866), lastPlacedIndex)\n : newIndex\n );\n newFiber.flags |= 67108866;\n return lastPlacedIndex;\n }\n function placeSingleChild(newFiber) {\n shouldTrackSideEffects &&\n null === newFiber.alternate &&\n (newFiber.flags |= 67108866);\n return newFiber;\n }\n function updateTextNode(returnFiber, current, textContent, lanes) {\n if (null === current || 6 !== current.tag)\n return (\n (current = createFiberFromText(textContent, returnFiber.mode, lanes)),\n (current.return = returnFiber),\n current\n );\n current = useFiber(current, textContent);\n current.return = returnFiber;\n return current;\n }\n function updateElement(returnFiber, current, element, lanes) {\n var elementType = element.type;\n if (elementType === REACT_FRAGMENT_TYPE)\n return updateFragment(\n returnFiber,\n current,\n element.props.children,\n lanes,\n element.key\n );\n if (\n null !== current &&\n (current.elementType === elementType ||\n (\"object\" === typeof elementType &&\n null !== elementType &&\n elementType.$$typeof === REACT_LAZY_TYPE &&\n resolveLazy(elementType) === current.type))\n )\n return (\n (current = useFiber(current, element.props)),\n coerceRef(current, element),\n (current.return = returnFiber),\n current\n );\n current = createFiberFromTypeAndProps(\n element.type,\n element.key,\n element.props,\n null,\n returnFiber.mode,\n lanes\n );\n coerceRef(current, element);\n current.return = returnFiber;\n return current;\n }\n function updatePortal(returnFiber, current, portal, lanes) {\n if (\n null === current ||\n 4 !== current.tag ||\n current.stateNode.containerInfo !== portal.containerInfo ||\n current.stateNode.implementation !== portal.implementation\n )\n return (\n (current = createFiberFromPortal(portal, returnFiber.mode, lanes)),\n (current.return = returnFiber),\n current\n );\n current = useFiber(current, portal.children || []);\n current.return = returnFiber;\n return current;\n }\n function updateFragment(returnFiber, current, fragment, lanes, key) {\n if (null === current || 7 !== current.tag)\n return (\n (current = createFiberFromFragment(\n fragment,\n returnFiber.mode,\n lanes,\n key\n )),\n (current.return = returnFiber),\n current\n );\n current = useFiber(current, fragment);\n current.return = returnFiber;\n return current;\n }\n function createChild(returnFiber, newChild, lanes) {\n if (\n (\"string\" === typeof newChild && \"\" !== newChild) ||\n \"number\" === typeof newChild ||\n \"bigint\" === typeof newChild\n )\n return (\n (newChild = createFiberFromText(\n \"\" + newChild,\n returnFiber.mode,\n lanes\n )),\n (newChild.return = returnFiber),\n newChild\n );\n if (\"object\" === typeof newChild && null !== newChild) {\n switch (newChild.$$typeof) {\n case REACT_ELEMENT_TYPE:\n return (\n (lanes = createFiberFromTypeAndProps(\n newChild.type,\n newChild.key,\n newChild.props,\n null,\n returnFiber.mode,\n lanes\n )),\n coerceRef(lanes, newChild),\n (lanes.return = returnFiber),\n lanes\n );\n case REACT_PORTAL_TYPE:\n return (\n (newChild = createFiberFromPortal(\n newChild,\n returnFiber.mode,\n lanes\n )),\n (newChild.return = returnFiber),\n newChild\n );\n case REACT_LAZY_TYPE:\n return (\n (newChild = resolveLazy(newChild)),\n createChild(returnFiber, newChild, lanes)\n );\n }\n if (isArrayImpl(newChild) || getIteratorFn(newChild))\n return (\n (newChild = createFiberFromFragment(\n newChild,\n returnFiber.mode,\n lanes,\n null\n )),\n (newChild.return = returnFiber),\n newChild\n );\n if (\"function\" === typeof newChild.then)\n return createChild(returnFiber, unwrapThenable(newChild), lanes);\n if (newChild.$$typeof === REACT_CONTEXT_TYPE)\n return createChild(\n returnFiber,\n readContextDuringReconciliation(returnFiber, newChild),\n lanes\n );\n throwOnInvalidObjectTypeImpl(returnFiber, newChild);\n }\n return null;\n }\n function updateSlot(returnFiber, oldFiber, newChild, lanes) {\n var key = null !== oldFiber ? oldFiber.key : null;\n if (\n (\"string\" === typeof newChild && \"\" !== newChild) ||\n \"number\" === typeof newChild ||\n \"bigint\" === typeof newChild\n )\n return null !== key\n ? null\n : updateTextNode(returnFiber, oldFiber, \"\" + newChild, lanes);\n if (\"object\" === typeof newChild && null !== newChild) {\n switch (newChild.$$typeof) {\n case REACT_ELEMENT_TYPE:\n return newChild.key === key\n ? updateElement(returnFiber, oldFiber, newChild, lanes)\n : null;\n case REACT_PORTAL_TYPE:\n return newChild.key === key\n ? updatePortal(returnFiber, oldFiber, newChild, lanes)\n : null;\n case REACT_LAZY_TYPE:\n return (\n (newChild = resolveLazy(newChild)),\n updateSlot(returnFiber, oldFiber, newChild, lanes)\n );\n }\n if (isArrayImpl(newChild) || getIteratorFn(newChild))\n return null !== key\n ? null\n : updateFragment(returnFiber, oldFiber, newChild, lanes, null);\n if (\"function\" === typeof newChild.then)\n return updateSlot(\n returnFiber,\n oldFiber,\n unwrapThenable(newChild),\n lanes\n );\n if (newChild.$$typeof === REACT_CONTEXT_TYPE)\n return updateSlot(\n returnFiber,\n oldFiber,\n readContextDuringReconciliation(returnFiber, newChild),\n lanes\n );\n throwOnInvalidObjectTypeImpl(returnFiber, newChild);\n }\n return null;\n }\n function updateFromMap(\n existingChildren,\n returnFiber,\n newIdx,\n newChild,\n lanes\n ) {\n if (\n (\"string\" === typeof newChild && \"\" !== newChild) ||\n \"number\" === typeof newChild ||\n \"bigint\" === typeof newChild\n )\n return (\n (existingChildren = existingChildren.get(newIdx) || null),\n updateTextNode(returnFiber, existingChildren, \"\" + newChild, lanes)\n );\n if (\"object\" === typeof newChild && null !== newChild) {\n switch (newChild.$$typeof) {\n case REACT_ELEMENT_TYPE:\n return (\n (existingChildren =\n existingChildren.get(\n null === newChild.key ? newIdx : newChild.key\n ) || null),\n updateElement(returnFiber, existingChildren, newChild, lanes)\n );\n case REACT_PORTAL_TYPE:\n return (\n (existingChildren =\n existingChildren.get(\n null === newChild.key ? newIdx : newChild.key\n ) || null),\n updatePortal(returnFiber, existingChildren, newChild, lanes)\n );\n case REACT_LAZY_TYPE:\n return (\n (newChild = resolveLazy(newChild)),\n updateFromMap(\n existingChildren,\n returnFiber,\n newIdx,\n newChild,\n lanes\n )\n );\n }\n if (isArrayImpl(newChild) || getIteratorFn(newChild))\n return (\n (existingChildren = existingChildren.get(newIdx) || null),\n updateFragment(returnFiber, existingChildren, newChild, lanes, null)\n );\n if (\"function\" === typeof newChild.then)\n return updateFromMap(\n existingChildren,\n returnFiber,\n newIdx,\n unwrapThenable(newChild),\n lanes\n );\n if (newChild.$$typeof === REACT_CONTEXT_TYPE)\n return updateFromMap(\n existingChildren,\n returnFiber,\n newIdx,\n readContextDuringReconciliation(returnFiber, newChild),\n lanes\n );\n throwOnInvalidObjectTypeImpl(returnFiber, newChild);\n }\n return null;\n }\n function reconcileChildrenArray(\n returnFiber,\n currentFirstChild,\n newChildren,\n lanes\n ) {\n for (\n var resultingFirstChild = null,\n previousNewFiber = null,\n oldFiber = currentFirstChild,\n newIdx = (currentFirstChild = 0),\n nextOldFiber = null;\n null !== oldFiber && newIdx < newChildren.length;\n newIdx++\n ) {\n oldFiber.index > newIdx\n ? ((nextOldFiber = oldFiber), (oldFiber = null))\n : (nextOldFiber = oldFiber.sibling);\n var newFiber = updateSlot(\n returnFiber,\n oldFiber,\n newChildren[newIdx],\n lanes\n );\n if (null === newFiber) {\n null === oldFiber && (oldFiber = nextOldFiber);\n break;\n }\n shouldTrackSideEffects &&\n oldFiber &&\n null === newFiber.alternate &&\n deleteChild(returnFiber, oldFiber);\n currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);\n null === previousNewFiber\n ? (resultingFirstChild = newFiber)\n : (previousNewFiber.sibling = newFiber);\n previousNewFiber = newFiber;\n oldFiber = nextOldFiber;\n }\n if (newIdx === newChildren.length)\n return (\n deleteRemainingChildren(returnFiber, oldFiber),\n isHydrating && pushTreeFork(returnFiber, newIdx),\n resultingFirstChild\n );\n if (null === oldFiber) {\n for (; newIdx < newChildren.length; newIdx++)\n (oldFiber = createChild(returnFiber, newChildren[newIdx], lanes)),\n null !== oldFiber &&\n ((currentFirstChild = placeChild(\n oldFiber,\n currentFirstChild,\n newIdx\n )),\n null === previousNewFiber\n ? (resultingFirstChild = oldFiber)\n : (previousNewFiber.sibling = oldFiber),\n (previousNewFiber = oldFiber));\n isHydrating && pushTreeFork(returnFiber, newIdx);\n return resultingFirstChild;\n }\n for (\n oldFiber = mapRemainingChildren(oldFiber);\n newIdx < newChildren.length;\n newIdx++\n )\n (nextOldFiber = updateFromMap(\n oldFiber,\n returnFiber,\n newIdx,\n newChildren[newIdx],\n lanes\n )),\n null !== nextOldFiber &&\n (shouldTrackSideEffects &&\n null !== nextOldFiber.alternate &&\n oldFiber.delete(\n null === nextOldFiber.key ? newIdx : nextOldFiber.key\n ),\n (currentFirstChild = placeChild(\n nextOldFiber,\n currentFirstChild,\n newIdx\n )),\n null === previousNewFiber\n ? (resultingFirstChild = nextOldFiber)\n : (previousNewFiber.sibling = nextOldFiber),\n (previousNewFiber = nextOldFiber));\n shouldTrackSideEffects &&\n oldFiber.forEach(function (child) {\n return deleteChild(returnFiber, child);\n });\n isHydrating && pushTreeFork(returnFiber, newIdx);\n return resultingFirstChild;\n }\n function reconcileChildrenIterator(\n returnFiber,\n currentFirstChild,\n newChildren,\n lanes\n ) {\n if (null == newChildren) throw Error(formatProdErrorMessage(151));\n for (\n var resultingFirstChild = null,\n previousNewFiber = null,\n oldFiber = currentFirstChild,\n newIdx = (currentFirstChild = 0),\n nextOldFiber = null,\n step = newChildren.next();\n null !== oldFiber && !step.done;\n newIdx++, step = newChildren.next()\n ) {\n oldFiber.index > newIdx\n ? ((nextOldFiber = oldFiber), (oldFiber = null))\n : (nextOldFiber = oldFiber.sibling);\n var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);\n if (null === newFiber) {\n null === oldFiber && (oldFiber = nextOldFiber);\n break;\n }\n shouldTrackSideEffects &&\n oldFiber &&\n null === newFiber.alternate &&\n deleteChild(returnFiber, oldFiber);\n currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);\n null === previousNewFiber\n ? (resultingFirstChild = newFiber)\n : (previousNewFiber.sibling = newFiber);\n previousNewFiber = newFiber;\n oldFiber = nextOldFiber;\n }\n if (step.done)\n return (\n deleteRemainingChildren(returnFiber, oldFiber),\n isHydrating && pushTreeFork(returnFiber, newIdx),\n resultingFirstChild\n );\n if (null === oldFiber) {\n for (; !step.done; newIdx++, step = newChildren.next())\n (step = createChild(returnFiber, step.value, lanes)),\n null !== step &&\n ((currentFirstChild = placeChild(step, currentFirstChild, newIdx)),\n null === previousNewFiber\n ? (resultingFirstChild = step)\n : (previousNewFiber.sibling = step),\n (previousNewFiber = step));\n isHydrating && pushTreeFork(returnFiber, newIdx);\n return resultingFirstChild;\n }\n for (\n oldFiber = mapRemainingChildren(oldFiber);\n !step.done;\n newIdx++, step = newChildren.next()\n )\n (step = updateFromMap(oldFiber, returnFiber, newIdx, step.value, lanes)),\n null !== step &&\n (shouldTrackSideEffects &&\n null !== step.alternate &&\n oldFiber.delete(null === step.key ? newIdx : step.key),\n (currentFirstChild = placeChild(step, currentFirstChild, newIdx)),\n null === previousNewFiber\n ? (resultingFirstChild = step)\n : (previousNewFiber.sibling = step),\n (previousNewFiber = step));\n shouldTrackSideEffects &&\n oldFiber.forEach(function (child) {\n return deleteChild(returnFiber, child);\n });\n isHydrating && pushTreeFork(returnFiber, newIdx);\n return resultingFirstChild;\n }\n function reconcileChildFibersImpl(\n returnFiber,\n currentFirstChild,\n newChild,\n lanes\n ) {\n \"object\" === typeof newChild &&\n null !== newChild &&\n newChild.type === REACT_FRAGMENT_TYPE &&\n null === newChild.key &&\n (newChild = newChild.props.children);\n if (\"object\" === typeof newChild && null !== newChild) {\n switch (newChild.$$typeof) {\n case REACT_ELEMENT_TYPE:\n a: {\n for (var key = newChild.key; null !== currentFirstChild; ) {\n if (currentFirstChild.key === key) {\n key = newChild.type;\n if (key === REACT_FRAGMENT_TYPE) {\n if (7 === currentFirstChild.tag) {\n deleteRemainingChildren(\n returnFiber,\n currentFirstChild.sibling\n );\n lanes = useFiber(\n currentFirstChild,\n newChild.props.children\n );\n lanes.return = returnFiber;\n returnFiber = lanes;\n break a;\n }\n } else if (\n currentFirstChild.elementType === key ||\n (\"object\" === typeof key &&\n null !== key &&\n key.$$typeof === REACT_LAZY_TYPE &&\n resolveLazy(key) === currentFirstChild.type)\n ) {\n deleteRemainingChildren(\n returnFiber,\n currentFirstChild.sibling\n );\n lanes = useFiber(currentFirstChild, newChild.props);\n coerceRef(lanes, newChild);\n lanes.return = returnFiber;\n returnFiber = lanes;\n break a;\n }\n deleteRemainingChildren(returnFiber, currentFirstChild);\n break;\n } else deleteChild(returnFiber, currentFirstChild);\n currentFirstChild = currentFirstChild.sibling;\n }\n newChild.type === REACT_FRAGMENT_TYPE\n ? ((lanes = createFiberFromFragment(\n newChild.props.children,\n returnFiber.mode,\n lanes,\n newChild.key\n )),\n (lanes.return = returnFiber),\n (returnFiber = lanes))\n : ((lanes = createFiberFromTypeAndProps(\n newChild.type,\n newChild.key,\n newChild.props,\n null,\n returnFiber.mode,\n lanes\n )),\n coerceRef(lanes, newChild),\n (lanes.return = returnFiber),\n (returnFiber = lanes));\n }\n return placeSingleChild(returnFiber);\n case REACT_PORTAL_TYPE:\n a: {\n for (key = newChild.key; null !== currentFirstChild; ) {\n if (currentFirstChild.key === key)\n if (\n 4 === currentFirstChild.tag &&\n currentFirstChild.stateNode.containerInfo ===\n newChild.containerInfo &&\n currentFirstChild.stateNode.implementation ===\n newChild.implementation\n ) {\n deleteRemainingChildren(\n returnFiber,\n currentFirstChild.sibling\n );\n lanes = useFiber(currentFirstChild, newChild.children || []);\n lanes.return = returnFiber;\n returnFiber = lanes;\n break a;\n } else {\n deleteRemainingChildren(returnFiber, currentFirstChild);\n break;\n }\n else deleteChild(returnFiber, currentFirstChild);\n currentFirstChild = currentFirstChild.sibling;\n }\n lanes = createFiberFromPortal(newChild, returnFiber.mode, lanes);\n lanes.return = returnFiber;\n returnFiber = lanes;\n }\n return placeSingleChild(returnFiber);\n case REACT_LAZY_TYPE:\n return (\n (newChild = resolveLazy(newChild)),\n reconcileChildFibersImpl(\n returnFiber,\n currentFirstChild,\n newChild,\n lanes\n )\n );\n }\n if (isArrayImpl(newChild))\n return reconcileChildrenArray(\n returnFiber,\n currentFirstChild,\n newChild,\n lanes\n );\n if (getIteratorFn(newChild)) {\n key = getIteratorFn(newChild);\n if (\"function\" !== typeof key) throw Error(formatProdErrorMessage(150));\n newChild = key.call(newChild);\n return reconcileChildrenIterator(\n returnFiber,\n currentFirstChild,\n newChild,\n lanes\n );\n }\n if (\"function\" === typeof newChild.then)\n return reconcileChildFibersImpl(\n returnFiber,\n currentFirstChild,\n unwrapThenable(newChild),\n lanes\n );\n if (newChild.$$typeof === REACT_CONTEXT_TYPE)\n return reconcileChildFibersImpl(\n returnFiber,\n currentFirstChild,\n readContextDuringReconciliation(returnFiber, newChild),\n lanes\n );\n throwOnInvalidObjectTypeImpl(returnFiber, newChild);\n }\n return (\"string\" === typeof newChild && \"\" !== newChild) ||\n \"number\" === typeof newChild ||\n \"bigint\" === typeof newChild\n ? ((newChild = \"\" + newChild),\n null !== currentFirstChild && 6 === currentFirstChild.tag\n ? (deleteRemainingChildren(returnFiber, currentFirstChild.sibling),\n (lanes = useFiber(currentFirstChild, newChild)),\n (lanes.return = returnFiber),\n (returnFiber = lanes))\n : (deleteRemainingChildren(returnFiber, currentFirstChild),\n (lanes = createFiberFromText(newChild, returnFiber.mode, lanes)),\n (lanes.return = returnFiber),\n (returnFiber = lanes)),\n placeSingleChild(returnFiber))\n : deleteRemainingChildren(returnFiber, currentFirstChild);\n }\n return function (returnFiber, currentFirstChild, newChild, lanes) {\n try {\n thenableIndexCounter$1 = 0;\n var firstChildFiber = reconcileChildFibersImpl(\n returnFiber,\n currentFirstChild,\n newChild,\n lanes\n );\n thenableState$1 = null;\n return firstChildFiber;\n } catch (x) {\n if (x === SuspenseException || x === SuspenseActionException) throw x;\n var fiber = createFiberImplClass(29, x, null, returnFiber.mode);\n fiber.lanes = lanes;\n fiber.return = returnFiber;\n return fiber;\n } finally {\n }\n };\n}\nvar reconcileChildFibers = createChildReconciler(!0),\n mountChildFibers = createChildReconciler(!1),\n hasForceUpdate = !1;\nfunction initializeUpdateQueue(fiber) {\n fiber.updateQueue = {\n baseState: fiber.memoizedState,\n firstBaseUpdate: null,\n lastBaseUpdate: null,\n shared: { pending: null, lanes: 0, hiddenCallbacks: null },\n callbacks: null\n };\n}\nfunction cloneUpdateQueue(current, workInProgress) {\n current = current.updateQueue;\n workInProgress.updateQueue === current &&\n (workInProgress.updateQueue = {\n baseState: current.baseState,\n firstBaseUpdate: current.firstBaseUpdate,\n lastBaseUpdate: current.lastBaseUpdate,\n shared: current.shared,\n callbacks: null\n });\n}\nfunction createUpdate(lane) {\n return { lane: lane, tag: 0, payload: null, callback: null, next: null };\n}\nfunction enqueueUpdate(fiber, update, lane) {\n var updateQueue = fiber.updateQueue;\n if (null === updateQueue) return null;\n updateQueue = updateQueue.shared;\n if (0 !== (executionContext & 2)) {\n var pending = updateQueue.pending;\n null === pending\n ? (update.next = update)\n : ((update.next = pending.next), (pending.next = update));\n updateQueue.pending = update;\n update = getRootForUpdatedFiber(fiber);\n markUpdateLaneFromFiberToRoot(fiber, null, lane);\n return update;\n }\n enqueueUpdate$1(fiber, updateQueue, update, lane);\n return getRootForUpdatedFiber(fiber);\n}\nfunction entangleTransitions(root, fiber, lane) {\n fiber = fiber.updateQueue;\n if (null !== fiber && ((fiber = fiber.shared), 0 !== (lane & 4194048))) {\n var queueLanes = fiber.lanes;\n queueLanes &= root.pendingLanes;\n lane |= queueLanes;\n fiber.lanes = lane;\n markRootEntangled(root, lane);\n }\n}\nfunction enqueueCapturedUpdate(workInProgress, capturedUpdate) {\n var queue = workInProgress.updateQueue,\n current = workInProgress.alternate;\n if (\n null !== current &&\n ((current = current.updateQueue), queue === current)\n ) {\n var newFirst = null,\n newLast = null;\n queue = queue.firstBaseUpdate;\n if (null !== queue) {\n do {\n var clone = {\n lane: queue.lane,\n tag: queue.tag,\n payload: queue.payload,\n callback: null,\n next: null\n };\n null === newLast\n ? (newFirst = newLast = clone)\n : (newLast = newLast.next = clone);\n queue = queue.next;\n } while (null !== queue);\n null === newLast\n ? (newFirst = newLast = capturedUpdate)\n : (newLast = newLast.next = capturedUpdate);\n } else newFirst = newLast = capturedUpdate;\n queue = {\n baseState: current.baseState,\n firstBaseUpdate: newFirst,\n lastBaseUpdate: newLast,\n shared: current.shared,\n callbacks: current.callbacks\n };\n workInProgress.updateQueue = queue;\n return;\n }\n workInProgress = queue.lastBaseUpdate;\n null === workInProgress\n ? (queue.firstBaseUpdate = capturedUpdate)\n : (workInProgress.next = capturedUpdate);\n queue.lastBaseUpdate = capturedUpdate;\n}\nvar didReadFromEntangledAsyncAction = !1;\nfunction suspendIfUpdateReadFromEntangledAsyncAction() {\n if (didReadFromEntangledAsyncAction) {\n var entangledActionThenable = currentEntangledActionThenable;\n if (null !== entangledActionThenable) throw entangledActionThenable;\n }\n}\nfunction processUpdateQueue(\n workInProgress$jscomp$0,\n props,\n instance$jscomp$0,\n renderLanes\n) {\n didReadFromEntangledAsyncAction = !1;\n var queue = workInProgress$jscomp$0.updateQueue;\n hasForceUpdate = !1;\n var firstBaseUpdate = queue.firstBaseUpdate,\n lastBaseUpdate = queue.lastBaseUpdate,\n pendingQueue = queue.shared.pending;\n if (null !== pendingQueue) {\n queue.shared.pending = null;\n var lastPendingUpdate = pendingQueue,\n firstPendingUpdate = lastPendingUpdate.next;\n lastPendingUpdate.next = null;\n null === lastBaseUpdate\n ? (firstBaseUpdate = firstPendingUpdate)\n : (lastBaseUpdate.next = firstPendingUpdate);\n lastBaseUpdate = lastPendingUpdate;\n var current = workInProgress$jscomp$0.alternate;\n null !== current &&\n ((current = current.updateQueue),\n (pendingQueue = current.lastBaseUpdate),\n pendingQueue !== lastBaseUpdate &&\n (null === pendingQueue\n ? (current.firstBaseUpdate = firstPendingUpdate)\n : (pendingQueue.next = firstPendingUpdate),\n (current.lastBaseUpdate = lastPendingUpdate)));\n }\n if (null !== firstBaseUpdate) {\n var newState = queue.baseState;\n lastBaseUpdate = 0;\n current = firstPendingUpdate = lastPendingUpdate = null;\n pendingQueue = firstBaseUpdate;\n do {\n var updateLane = pendingQueue.lane & -536870913,\n isHiddenUpdate = updateLane !== pendingQueue.lane;\n if (\n isHiddenUpdate\n ? (workInProgressRootRenderLanes & updateLane) === updateLane\n : (renderLanes & updateLane) === updateLane\n ) {\n 0 !== updateLane &&\n updateLane === currentEntangledLane &&\n (didReadFromEntangledAsyncAction = !0);\n null !== current &&\n (current = current.next =\n {\n lane: 0,\n tag: pendingQueue.tag,\n payload: pendingQueue.payload,\n callback: null,\n next: null\n });\n a: {\n var workInProgress = workInProgress$jscomp$0,\n update = pendingQueue;\n updateLane = props;\n var instance = instance$jscomp$0;\n switch (update.tag) {\n case 1:\n workInProgress = update.payload;\n if (\"function\" === typeof workInProgress) {\n newState = workInProgress.call(instance, newState, updateLane);\n break a;\n }\n newState = workInProgress;\n break a;\n case 3:\n workInProgress.flags = (workInProgress.flags & -65537) | 128;\n case 0:\n workInProgress = update.payload;\n updateLane =\n \"function\" === typeof workInProgress\n ? workInProgress.call(instance, newState, updateLane)\n : workInProgress;\n if (null === updateLane || void 0 === updateLane) break a;\n newState = assign({}, newState, updateLane);\n break a;\n case 2:\n hasForceUpdate = !0;\n }\n }\n updateLane = pendingQueue.callback;\n null !== updateLane &&\n ((workInProgress$jscomp$0.flags |= 64),\n isHiddenUpdate && (workInProgress$jscomp$0.flags |= 8192),\n (isHiddenUpdate = queue.callbacks),\n null === isHiddenUpdate\n ? (queue.callbacks = [updateLane])\n : isHiddenUpdate.push(updateLane));\n } else\n (isHiddenUpdate = {\n lane: updateLane,\n tag: pendingQueue.tag,\n payload: pendingQueue.payload,\n callback: pendingQueue.callback,\n next: null\n }),\n null === current\n ? ((firstPendingUpdate = current = isHiddenUpdate),\n (lastPendingUpdate = newState))\n : (current = current.next = isHiddenUpdate),\n (lastBaseUpdate |= updateLane);\n pendingQueue = pendingQueue.next;\n if (null === pendingQueue)\n if (((pendingQueue = queue.shared.pending), null === pendingQueue))\n break;\n else\n (isHiddenUpdate = pendingQueue),\n (pendingQueue = isHiddenUpdate.next),\n (isHiddenUpdate.next = null),\n (queue.lastBaseUpdate = isHiddenUpdate),\n (queue.shared.pending = null);\n } while (1);\n null === current && (lastPendingUpdate = newState);\n queue.baseState = lastPendingUpdate;\n queue.firstBaseUpdate = firstPendingUpdate;\n queue.lastBaseUpdate = current;\n null === firstBaseUpdate && (queue.shared.lanes = 0);\n workInProgressRootSkippedLanes |= lastBaseUpdate;\n workInProgress$jscomp$0.lanes = lastBaseUpdate;\n workInProgress$jscomp$0.memoizedState = newState;\n }\n}\nfunction callCallback(callback, context) {\n if (\"function\" !== typeof callback)\n throw Error(formatProdErrorMessage(191, callback));\n callback.call(context);\n}\nfunction commitCallbacks(updateQueue, context) {\n var callbacks = updateQueue.callbacks;\n if (null !== callbacks)\n for (\n updateQueue.callbacks = null, updateQueue = 0;\n updateQueue < callbacks.length;\n updateQueue++\n )\n callCallback(callbacks[updateQueue], context);\n}\nvar currentTreeHiddenStackCursor = createCursor(null),\n prevEntangledRenderLanesCursor = createCursor(0);\nfunction pushHiddenContext(fiber, context) {\n fiber = entangledRenderLanes;\n push(prevEntangledRenderLanesCursor, fiber);\n push(currentTreeHiddenStackCursor, context);\n entangledRenderLanes = fiber | context.baseLanes;\n}\nfunction reuseHiddenContextOnStack() {\n push(prevEntangledRenderLanesCursor, entangledRenderLanes);\n push(currentTreeHiddenStackCursor, currentTreeHiddenStackCursor.current);\n}\nfunction popHiddenContext() {\n entangledRenderLanes = prevEntangledRenderLanesCursor.current;\n pop(currentTreeHiddenStackCursor);\n pop(prevEntangledRenderLanesCursor);\n}\nvar suspenseHandlerStackCursor = createCursor(null),\n shellBoundary = null;\nfunction pushPrimaryTreeSuspenseHandler(handler) {\n var current = handler.alternate;\n push(suspenseStackCursor, suspenseStackCursor.current & 1);\n push(suspenseHandlerStackCursor, handler);\n null === shellBoundary &&\n (null === current || null !== currentTreeHiddenStackCursor.current\n ? (shellBoundary = handler)\n : null !== current.memoizedState && (shellBoundary = handler));\n}\nfunction pushDehydratedActivitySuspenseHandler(fiber) {\n push(suspenseStackCursor, suspenseStackCursor.current);\n push(suspenseHandlerStackCursor, fiber);\n null === shellBoundary && (shellBoundary = fiber);\n}\nfunction pushOffscreenSuspenseHandler(fiber) {\n 22 === fiber.tag\n ? (push(suspenseStackCursor, suspenseStackCursor.current),\n push(suspenseHandlerStackCursor, fiber),\n null === shellBoundary && (shellBoundary = fiber))\n : reuseSuspenseHandlerOnStack(fiber);\n}\nfunction reuseSuspenseHandlerOnStack() {\n push(suspenseStackCursor, suspenseStackCursor.current);\n push(suspenseHandlerStackCursor, suspenseHandlerStackCursor.current);\n}\nfunction popSuspenseHandler(fiber) {\n pop(suspenseHandlerStackCursor);\n shellBoundary === fiber && (shellBoundary = null);\n pop(suspenseStackCursor);\n}\nvar suspenseStackCursor = createCursor(0);\nfunction findFirstSuspended(row) {\n for (var node = row; null !== node; ) {\n if (13 === node.tag) {\n var state = node.memoizedState;\n if (\n null !== state &&\n ((state = state.dehydrated),\n null === state ||\n isSuspenseInstancePending(state) ||\n isSuspenseInstanceFallback(state))\n )\n return node;\n } else if (\n 19 === node.tag &&\n (\"forwards\" === node.memoizedProps.revealOrder ||\n \"backwards\" === node.memoizedProps.revealOrder ||\n \"unstable_legacy-backwards\" === node.memoizedProps.revealOrder ||\n \"together\" === node.memoizedProps.revealOrder)\n ) {\n if (0 !== (node.flags & 128)) return node;\n } else if (null !== node.child) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n if (node === row) break;\n for (; null === node.sibling; ) {\n if (null === node.return || node.return === row) return null;\n node = node.return;\n }\n node.sibling.return = node.return;\n node = node.sibling;\n }\n return null;\n}\nvar renderLanes = 0,\n currentlyRenderingFiber = null,\n currentHook = null,\n workInProgressHook = null,\n didScheduleRenderPhaseUpdate = !1,\n didScheduleRenderPhaseUpdateDuringThisPass = !1,\n shouldDoubleInvokeUserFnsInHooksDEV = !1,\n localIdCounter = 0,\n thenableIndexCounter = 0,\n thenableState = null,\n globalClientIdCounter = 0;\nfunction throwInvalidHookError() {\n throw Error(formatProdErrorMessage(321));\n}\nfunction areHookInputsEqual(nextDeps, prevDeps) {\n if (null === prevDeps) return !1;\n for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++)\n if (!objectIs(nextDeps[i], prevDeps[i])) return !1;\n return !0;\n}\nfunction renderWithHooks(\n current,\n workInProgress,\n Component,\n props,\n secondArg,\n nextRenderLanes\n) {\n renderLanes = nextRenderLanes;\n currentlyRenderingFiber = workInProgress;\n workInProgress.memoizedState = null;\n workInProgress.updateQueue = null;\n workInProgress.lanes = 0;\n ReactSharedInternals.H =\n null === current || null === current.memoizedState\n ? HooksDispatcherOnMount\n : HooksDispatcherOnUpdate;\n shouldDoubleInvokeUserFnsInHooksDEV = !1;\n nextRenderLanes = Component(props, secondArg);\n shouldDoubleInvokeUserFnsInHooksDEV = !1;\n didScheduleRenderPhaseUpdateDuringThisPass &&\n (nextRenderLanes = renderWithHooksAgain(\n workInProgress,\n Component,\n props,\n secondArg\n ));\n finishRenderingHooks(current);\n return nextRenderLanes;\n}\nfunction finishRenderingHooks(current) {\n ReactSharedInternals.H = ContextOnlyDispatcher;\n var didRenderTooFewHooks = null !== currentHook && null !== currentHook.next;\n renderLanes = 0;\n workInProgressHook = currentHook = currentlyRenderingFiber = null;\n didScheduleRenderPhaseUpdate = !1;\n thenableIndexCounter = 0;\n thenableState = null;\n if (didRenderTooFewHooks) throw Error(formatProdErrorMessage(300));\n null === current ||\n didReceiveUpdate ||\n ((current = current.dependencies),\n null !== current &&\n checkIfContextChanged(current) &&\n (didReceiveUpdate = !0));\n}\nfunction renderWithHooksAgain(workInProgress, Component, props, secondArg) {\n currentlyRenderingFiber = workInProgress;\n var numberOfReRenders = 0;\n do {\n didScheduleRenderPhaseUpdateDuringThisPass && (thenableState = null);\n thenableIndexCounter = 0;\n didScheduleRenderPhaseUpdateDuringThisPass = !1;\n if (25 <= numberOfReRenders) throw Error(formatProdErrorMessage(301));\n numberOfReRenders += 1;\n workInProgressHook = currentHook = null;\n if (null != workInProgress.updateQueue) {\n var children = workInProgress.updateQueue;\n children.lastEffect = null;\n children.events = null;\n children.stores = null;\n null != children.memoCache && (children.memoCache.index = 0);\n }\n ReactSharedInternals.H = HooksDispatcherOnRerender;\n children = Component(props, secondArg);\n } while (didScheduleRenderPhaseUpdateDuringThisPass);\n return children;\n}\nfunction TransitionAwareHostComponent() {\n var dispatcher = ReactSharedInternals.H,\n maybeThenable = dispatcher.useState()[0];\n maybeThenable =\n \"function\" === typeof maybeThenable.then\n ? useThenable(maybeThenable)\n : maybeThenable;\n dispatcher = dispatcher.useState()[0];\n (null !== currentHook ? currentHook.memoizedState : null) !== dispatcher &&\n (currentlyRenderingFiber.flags |= 1024);\n return maybeThenable;\n}\nfunction checkDidRenderIdHook() {\n var didRenderIdHook = 0 !== localIdCounter;\n localIdCounter = 0;\n return didRenderIdHook;\n}\nfunction bailoutHooks(current, workInProgress, lanes) {\n workInProgress.updateQueue = current.updateQueue;\n workInProgress.flags &= -2053;\n current.lanes &= ~lanes;\n}\nfunction resetHooksOnUnwind(workInProgress) {\n if (didScheduleRenderPhaseUpdate) {\n for (\n workInProgress = workInProgress.memoizedState;\n null !== workInProgress;\n\n ) {\n var queue = workInProgress.queue;\n null !== queue && (queue.pending = null);\n workInProgress = workInProgress.next;\n }\n didScheduleRenderPhaseUpdate = !1;\n }\n renderLanes = 0;\n workInProgressHook = currentHook = currentlyRenderingFiber = null;\n didScheduleRenderPhaseUpdateDuringThisPass = !1;\n thenableIndexCounter = localIdCounter = 0;\n thenableState = null;\n}\nfunction mountWorkInProgressHook() {\n var hook = {\n memoizedState: null,\n baseState: null,\n baseQueue: null,\n queue: null,\n next: null\n };\n null === workInProgressHook\n ? (currentlyRenderingFiber.memoizedState = workInProgressHook = hook)\n : (workInProgressHook = workInProgressHook.next = hook);\n return workInProgressHook;\n}\nfunction updateWorkInProgressHook() {\n if (null === currentHook) {\n var nextCurrentHook = currentlyRenderingFiber.alternate;\n nextCurrentHook =\n null !== nextCurrentHook ? nextCurrentHook.memoizedState : null;\n } else nextCurrentHook = currentHook.next;\n var nextWorkInProgressHook =\n null === workInProgressHook\n ? currentlyRenderingFiber.memoizedState\n : workInProgressHook.next;\n if (null !== nextWorkInProgressHook)\n (workInProgressHook = nextWorkInProgressHook),\n (currentHook = nextCurrentHook);\n else {\n if (null === nextCurrentHook) {\n if (null === currentlyRenderingFiber.alternate)\n throw Error(formatProdErrorMessage(467));\n throw Error(formatProdErrorMessage(310));\n }\n currentHook = nextCurrentHook;\n nextCurrentHook = {\n memoizedState: currentHook.memoizedState,\n baseState: currentHook.baseState,\n baseQueue: currentHook.baseQueue,\n queue: currentHook.queue,\n next: null\n };\n null === workInProgressHook\n ? (currentlyRenderingFiber.memoizedState = workInProgressHook =\n nextCurrentHook)\n : (workInProgressHook = workInProgressHook.next = nextCurrentHook);\n }\n return workInProgressHook;\n}\nfunction createFunctionComponentUpdateQueue() {\n return { lastEffect: null, events: null, stores: null, memoCache: null };\n}\nfunction useThenable(thenable) {\n var index = thenableIndexCounter;\n thenableIndexCounter += 1;\n null === thenableState && (thenableState = []);\n thenable = trackUsedThenable(thenableState, thenable, index);\n index = currentlyRenderingFiber;\n null ===\n (null === workInProgressHook\n ? index.memoizedState\n : workInProgressHook.next) &&\n ((index = index.alternate),\n (ReactSharedInternals.H =\n null === index || null === index.memoizedState\n ? HooksDispatcherOnMount\n : HooksDispatcherOnUpdate));\n return thenable;\n}\nfunction use(usable) {\n if (null !== usable && \"object\" === typeof usable) {\n if (\"function\" === typeof usable.then) return useThenable(usable);\n if (usable.$$typeof === REACT_CONTEXT_TYPE) return readContext(usable);\n }\n throw Error(formatProdErrorMessage(438, String(usable)));\n}\nfunction useMemoCache(size) {\n var memoCache = null,\n updateQueue = currentlyRenderingFiber.updateQueue;\n null !== updateQueue && (memoCache = updateQueue.memoCache);\n if (null == memoCache) {\n var current = currentlyRenderingFiber.alternate;\n null !== current &&\n ((current = current.updateQueue),\n null !== current &&\n ((current = current.memoCache),\n null != current &&\n (memoCache = {\n data: current.data.map(function (array) {\n return array.slice();\n }),\n index: 0\n })));\n }\n null == memoCache && (memoCache = { data: [], index: 0 });\n null === updateQueue &&\n ((updateQueue = createFunctionComponentUpdateQueue()),\n (currentlyRenderingFiber.updateQueue = updateQueue));\n updateQueue.memoCache = memoCache;\n updateQueue = memoCache.data[memoCache.index];\n if (void 0 === updateQueue)\n for (\n updateQueue = memoCache.data[memoCache.index] = Array(size), current = 0;\n current < size;\n current++\n )\n updateQueue[current] = REACT_MEMO_CACHE_SENTINEL;\n memoCache.index++;\n return updateQueue;\n}\nfunction basicStateReducer(state, action) {\n return \"function\" === typeof action ? action(state) : action;\n}\nfunction updateReducer(reducer) {\n var hook = updateWorkInProgressHook();\n return updateReducerImpl(hook, currentHook, reducer);\n}\nfunction updateReducerImpl(hook, current, reducer) {\n var queue = hook.queue;\n if (null === queue) throw Error(formatProdErrorMessage(311));\n queue.lastRenderedReducer = reducer;\n var baseQueue = hook.baseQueue,\n pendingQueue = queue.pending;\n if (null !== pendingQueue) {\n if (null !== baseQueue) {\n var baseFirst = baseQueue.next;\n baseQueue.next = pendingQueue.next;\n pendingQueue.next = baseFirst;\n }\n current.baseQueue = baseQueue = pendingQueue;\n queue.pending = null;\n }\n pendingQueue = hook.baseState;\n if (null === baseQueue) hook.memoizedState = pendingQueue;\n else {\n current = baseQueue.next;\n var newBaseQueueFirst = (baseFirst = null),\n newBaseQueueLast = null,\n update = current,\n didReadFromEntangledAsyncAction$60 = !1;\n do {\n var updateLane = update.lane & -536870913;\n if (\n updateLane !== update.lane\n ? (workInProgressRootRenderLanes & updateLane) === updateLane\n : (renderLanes & updateLane) === updateLane\n ) {\n var revertLane = update.revertLane;\n if (0 === revertLane)\n null !== newBaseQueueLast &&\n (newBaseQueueLast = newBaseQueueLast.next =\n {\n lane: 0,\n revertLane: 0,\n gesture: null,\n action: update.action,\n hasEagerState: update.hasEagerState,\n eagerState: update.eagerState,\n next: null\n }),\n updateLane === currentEntangledLane &&\n (didReadFromEntangledAsyncAction$60 = !0);\n else if ((renderLanes & revertLane) === revertLane) {\n update = update.next;\n revertLane === currentEntangledLane &&\n (didReadFromEntangledAsyncAction$60 = !0);\n continue;\n } else\n (updateLane = {\n lane: 0,\n revertLane: update.revertLane,\n gesture: null,\n action: update.action,\n hasEagerState: update.hasEagerState,\n eagerState: update.eagerState,\n next: null\n }),\n null === newBaseQueueLast\n ? ((newBaseQueueFirst = newBaseQueueLast = updateLane),\n (baseFirst = pendingQueue))\n : (newBaseQueueLast = newBaseQueueLast.next = updateLane),\n (currentlyRenderingFiber.lanes |= revertLane),\n (workInProgressRootSkippedLanes |= revertLane);\n updateLane = update.action;\n shouldDoubleInvokeUserFnsInHooksDEV &&\n reducer(pendingQueue, updateLane);\n pendingQueue = update.hasEagerState\n ? update.eagerState\n : reducer(pendingQueue, updateLane);\n } else\n (revertLane = {\n lane: updateLane,\n revertLane: update.revertLane,\n gesture: update.gesture,\n action: update.action,\n hasEagerState: update.hasEagerState,\n eagerState: update.eagerState,\n next: null\n }),\n null === newBaseQueueLast\n ? ((newBaseQueueFirst = newBaseQueueLast = revertLane),\n (baseFirst = pendingQueue))\n : (newBaseQueueLast = newBaseQueueLast.next = revertLane),\n (currentlyRenderingFiber.lanes |= updateLane),\n (workInProgressRootSkippedLanes |= updateLane);\n update = update.next;\n } while (null !== update && update !== current);\n null === newBaseQueueLast\n ? (baseFirst = pendingQueue)\n : (newBaseQueueLast.next = newBaseQueueFirst);\n if (\n !objectIs(pendingQueue, hook.memoizedState) &&\n ((didReceiveUpdate = !0),\n didReadFromEntangledAsyncAction$60 &&\n ((reducer = currentEntangledActionThenable), null !== reducer))\n )\n throw reducer;\n hook.memoizedState = pendingQueue;\n hook.baseState = baseFirst;\n hook.baseQueue = newBaseQueueLast;\n queue.lastRenderedState = pendingQueue;\n }\n null === baseQueue && (queue.lanes = 0);\n return [hook.memoizedState, queue.dispatch];\n}\nfunction rerenderReducer(reducer) {\n var hook = updateWorkInProgressHook(),\n queue = hook.queue;\n if (null === queue) throw Error(formatProdErrorMessage(311));\n queue.lastRenderedReducer = reducer;\n var dispatch = queue.dispatch,\n lastRenderPhaseUpdate = queue.pending,\n newState = hook.memoizedState;\n if (null !== lastRenderPhaseUpdate) {\n queue.pending = null;\n var update = (lastRenderPhaseUpdate = lastRenderPhaseUpdate.next);\n do (newState = reducer(newState, update.action)), (update = update.next);\n while (update !== lastRenderPhaseUpdate);\n objectIs(newState, hook.memoizedState) || (didReceiveUpdate = !0);\n hook.memoizedState = newState;\n null === hook.baseQueue && (hook.baseState = newState);\n queue.lastRenderedState = newState;\n }\n return [newState, dispatch];\n}\nfunction updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {\n var fiber = currentlyRenderingFiber,\n hook = updateWorkInProgressHook(),\n isHydrating$jscomp$0 = isHydrating;\n if (isHydrating$jscomp$0) {\n if (void 0 === getServerSnapshot) throw Error(formatProdErrorMessage(407));\n getServerSnapshot = getServerSnapshot();\n } else getServerSnapshot = getSnapshot();\n var snapshotChanged = !objectIs(\n (currentHook || hook).memoizedState,\n getServerSnapshot\n );\n snapshotChanged &&\n ((hook.memoizedState = getServerSnapshot), (didReceiveUpdate = !0));\n hook = hook.queue;\n updateEffect(subscribeToStore.bind(null, fiber, hook, subscribe), [\n subscribe\n ]);\n if (\n hook.getSnapshot !== getSnapshot ||\n snapshotChanged ||\n (null !== workInProgressHook && workInProgressHook.memoizedState.tag & 1)\n ) {\n fiber.flags |= 2048;\n pushSimpleEffect(\n 9,\n { destroy: void 0 },\n updateStoreInstance.bind(\n null,\n fiber,\n hook,\n getServerSnapshot,\n getSnapshot\n ),\n null\n );\n if (null === workInProgressRoot) throw Error(formatProdErrorMessage(349));\n isHydrating$jscomp$0 ||\n 0 !== (renderLanes & 127) ||\n pushStoreConsistencyCheck(fiber, getSnapshot, getServerSnapshot);\n }\n return getServerSnapshot;\n}\nfunction pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) {\n fiber.flags |= 16384;\n fiber = { getSnapshot: getSnapshot, value: renderedSnapshot };\n getSnapshot = currentlyRenderingFiber.updateQueue;\n null === getSnapshot\n ? ((getSnapshot = createFunctionComponentUpdateQueue()),\n (currentlyRenderingFiber.updateQueue = getSnapshot),\n (getSnapshot.stores = [fiber]))\n : ((renderedSnapshot = getSnapshot.stores),\n null === renderedSnapshot\n ? (getSnapshot.stores = [fiber])\n : renderedSnapshot.push(fiber));\n}\nfunction updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) {\n inst.value = nextSnapshot;\n inst.getSnapshot = getSnapshot;\n checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);\n}\nfunction subscribeToStore(fiber, inst, subscribe) {\n return subscribe(function () {\n checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);\n });\n}\nfunction checkIfSnapshotChanged(inst) {\n var latestGetSnapshot = inst.getSnapshot;\n inst = inst.value;\n try {\n var nextValue = latestGetSnapshot();\n return !objectIs(inst, nextValue);\n } catch (error) {\n return !0;\n }\n}\nfunction forceStoreRerender(fiber) {\n var root = enqueueConcurrentRenderForLane(fiber, 2);\n null !== root && scheduleUpdateOnFiber(root, fiber, 2);\n}\nfunction mountStateImpl(initialState) {\n var hook = mountWorkInProgressHook();\n if (\"function\" === typeof initialState) {\n var initialStateInitializer = initialState;\n initialState = initialStateInitializer();\n if (shouldDoubleInvokeUserFnsInHooksDEV) {\n setIsStrictModeForDevtools(!0);\n try {\n initialStateInitializer();\n } finally {\n setIsStrictModeForDevtools(!1);\n }\n }\n }\n hook.memoizedState = hook.baseState = initialState;\n hook.queue = {\n pending: null,\n lanes: 0,\n dispatch: null,\n lastRenderedReducer: basicStateReducer,\n lastRenderedState: initialState\n };\n return hook;\n}\nfunction updateOptimisticImpl(hook, current, passthrough, reducer) {\n hook.baseState = passthrough;\n return updateReducerImpl(\n hook,\n currentHook,\n \"function\" === typeof reducer ? reducer : basicStateReducer\n );\n}\nfunction dispatchActionState(\n fiber,\n actionQueue,\n setPendingState,\n setState,\n payload\n) {\n if (isRenderPhaseUpdate(fiber)) throw Error(formatProdErrorMessage(485));\n fiber = actionQueue.action;\n if (null !== fiber) {\n var actionNode = {\n payload: payload,\n action: fiber,\n next: null,\n isTransition: !0,\n status: \"pending\",\n value: null,\n reason: null,\n listeners: [],\n then: function (listener) {\n actionNode.listeners.push(listener);\n }\n };\n null !== ReactSharedInternals.T\n ? setPendingState(!0)\n : (actionNode.isTransition = !1);\n setState(actionNode);\n setPendingState = actionQueue.pending;\n null === setPendingState\n ? ((actionNode.next = actionQueue.pending = actionNode),\n runActionStateAction(actionQueue, actionNode))\n : ((actionNode.next = setPendingState.next),\n (actionQueue.pending = setPendingState.next = actionNode));\n }\n}\nfunction runActionStateAction(actionQueue, node) {\n var action = node.action,\n payload = node.payload,\n prevState = actionQueue.state;\n if (node.isTransition) {\n var prevTransition = ReactSharedInternals.T,\n currentTransition = {};\n ReactSharedInternals.T = currentTransition;\n try {\n var returnValue = action(prevState, payload),\n onStartTransitionFinish = ReactSharedInternals.S;\n null !== onStartTransitionFinish &&\n onStartTransitionFinish(currentTransition, returnValue);\n handleActionReturnValue(actionQueue, node, returnValue);\n } catch (error) {\n onActionError(actionQueue, node, error);\n } finally {\n null !== prevTransition &&\n null !== currentTransition.types &&\n (prevTransition.types = currentTransition.types),\n (ReactSharedInternals.T = prevTransition);\n }\n } else\n try {\n (prevTransition = action(prevState, payload)),\n handleActionReturnValue(actionQueue, node, prevTransition);\n } catch (error$66) {\n onActionError(actionQueue, node, error$66);\n }\n}\nfunction handleActionReturnValue(actionQueue, node, returnValue) {\n null !== returnValue &&\n \"object\" === typeof returnValue &&\n \"function\" === typeof returnValue.then\n ? returnValue.then(\n function (nextState) {\n onActionSuccess(actionQueue, node, nextState);\n },\n function (error) {\n return onActionError(actionQueue, node, error);\n }\n )\n : onActionSuccess(actionQueue, node, returnValue);\n}\nfunction onActionSuccess(actionQueue, actionNode, nextState) {\n actionNode.status = \"fulfilled\";\n actionNode.value = nextState;\n notifyActionListeners(actionNode);\n actionQueue.state = nextState;\n actionNode = actionQueue.pending;\n null !== actionNode &&\n ((nextState = actionNode.next),\n nextState === actionNode\n ? (actionQueue.pending = null)\n : ((nextState = nextState.next),\n (actionNode.next = nextState),\n runActionStateAction(actionQueue, nextState)));\n}\nfunction onActionError(actionQueue, actionNode, error) {\n var last = actionQueue.pending;\n actionQueue.pending = null;\n if (null !== last) {\n last = last.next;\n do\n (actionNode.status = \"rejected\"),\n (actionNode.reason = error),\n notifyActionListeners(actionNode),\n (actionNode = actionNode.next);\n while (actionNode !== last);\n }\n actionQueue.action = null;\n}\nfunction notifyActionListeners(actionNode) {\n actionNode = actionNode.listeners;\n for (var i = 0; i < actionNode.length; i++) (0, actionNode[i])();\n}\nfunction actionStateReducer(oldState, newState) {\n return newState;\n}\nfunction mountActionState(action, initialStateProp) {\n if (isHydrating) {\n var ssrFormState = workInProgressRoot.formState;\n if (null !== ssrFormState) {\n a: {\n var JSCompiler_inline_result = currentlyRenderingFiber;\n if (isHydrating) {\n if (nextHydratableInstance) {\n b: {\n var JSCompiler_inline_result$jscomp$0 = nextHydratableInstance;\n for (\n var inRootOrSingleton = rootOrSingletonContext;\n 8 !== JSCompiler_inline_result$jscomp$0.nodeType;\n\n ) {\n if (!inRootOrSingleton) {\n JSCompiler_inline_result$jscomp$0 = null;\n break b;\n }\n JSCompiler_inline_result$jscomp$0 = getNextHydratable(\n JSCompiler_inline_result$jscomp$0.nextSibling\n );\n if (null === JSCompiler_inline_result$jscomp$0) {\n JSCompiler_inline_result$jscomp$0 = null;\n break b;\n }\n }\n inRootOrSingleton = JSCompiler_inline_result$jscomp$0.data;\n JSCompiler_inline_result$jscomp$0 =\n \"F!\" === inRootOrSingleton || \"F\" === inRootOrSingleton\n ? JSCompiler_inline_result$jscomp$0\n : null;\n }\n if (JSCompiler_inline_result$jscomp$0) {\n nextHydratableInstance = getNextHydratable(\n JSCompiler_inline_result$jscomp$0.nextSibling\n );\n JSCompiler_inline_result =\n \"F!\" === JSCompiler_inline_result$jscomp$0.data;\n break a;\n }\n }\n throwOnHydrationMismatch(JSCompiler_inline_result);\n }\n JSCompiler_inline_result = !1;\n }\n JSCompiler_inline_result && (initialStateProp = ssrFormState[0]);\n }\n }\n ssrFormState = mountWorkInProgressHook();\n ssrFormState.memoizedState = ssrFormState.baseState = initialStateProp;\n JSCompiler_inline_result = {\n pending: null,\n lanes: 0,\n dispatch: null,\n lastRenderedReducer: actionStateReducer,\n lastRenderedState: initialStateProp\n };\n ssrFormState.queue = JSCompiler_inline_result;\n ssrFormState = dispatchSetState.bind(\n null,\n currentlyRenderingFiber,\n JSCompiler_inline_result\n );\n JSCompiler_inline_result.dispatch = ssrFormState;\n JSCompiler_inline_result = mountStateImpl(!1);\n inRootOrSingleton = dispatchOptimisticSetState.bind(\n null,\n currentlyRenderingFiber,\n !1,\n JSCompiler_inline_result.queue\n );\n JSCompiler_inline_result = mountWorkInProgressHook();\n JSCompiler_inline_result$jscomp$0 = {\n state: initialStateProp,\n dispatch: null,\n action: action,\n pending: null\n };\n JSCompiler_inline_result.queue = JSCompiler_inline_result$jscomp$0;\n ssrFormState = dispatchActionState.bind(\n null,\n currentlyRenderingFiber,\n JSCompiler_inline_result$jscomp$0,\n inRootOrSingleton,\n ssrFormState\n );\n JSCompiler_inline_result$jscomp$0.dispatch = ssrFormState;\n JSCompiler_inline_result.memoizedState = action;\n return [initialStateProp, ssrFormState, !1];\n}\nfunction updateActionState(action) {\n var stateHook = updateWorkInProgressHook();\n return updateActionStateImpl(stateHook, currentHook, action);\n}\nfunction updateActionStateImpl(stateHook, currentStateHook, action) {\n currentStateHook = updateReducerImpl(\n stateHook,\n currentStateHook,\n actionStateReducer\n )[0];\n stateHook = updateReducer(basicStateReducer)[0];\n if (\n \"object\" === typeof currentStateHook &&\n null !== currentStateHook &&\n \"function\" === typeof currentStateHook.then\n )\n try {\n var state = useThenable(currentStateHook);\n } catch (x) {\n if (x === SuspenseException) throw SuspenseActionException;\n throw x;\n }\n else state = currentStateHook;\n currentStateHook = updateWorkInProgressHook();\n var actionQueue = currentStateHook.queue,\n dispatch = actionQueue.dispatch;\n action !== currentStateHook.memoizedState &&\n ((currentlyRenderingFiber.flags |= 2048),\n pushSimpleEffect(\n 9,\n { destroy: void 0 },\n actionStateActionEffect.bind(null, actionQueue, action),\n null\n ));\n return [state, dispatch, stateHook];\n}\nfunction actionStateActionEffect(actionQueue, action) {\n actionQueue.action = action;\n}\nfunction rerenderActionState(action) {\n var stateHook = updateWorkInProgressHook(),\n currentStateHook = currentHook;\n if (null !== currentStateHook)\n return updateActionStateImpl(stateHook, currentStateHook, action);\n updateWorkInProgressHook();\n stateHook = stateHook.memoizedState;\n currentStateHook = updateWorkInProgressHook();\n var dispatch = currentStateHook.queue.dispatch;\n currentStateHook.memoizedState = action;\n return [stateHook, dispatch, !1];\n}\nfunction pushSimpleEffect(tag, inst, create, deps) {\n tag = { tag: tag, create: create, deps: deps, inst: inst, next: null };\n inst = currentlyRenderingFiber.updateQueue;\n null === inst &&\n ((inst = createFunctionComponentUpdateQueue()),\n (currentlyRenderingFiber.updateQueue = inst));\n create = inst.lastEffect;\n null === create\n ? (inst.lastEffect = tag.next = tag)\n : ((deps = create.next),\n (create.next = tag),\n (tag.next = deps),\n (inst.lastEffect = tag));\n return tag;\n}\nfunction updateRef() {\n return updateWorkInProgressHook().memoizedState;\n}\nfunction mountEffectImpl(fiberFlags, hookFlags, create, deps) {\n var hook = mountWorkInProgressHook();\n currentlyRenderingFiber.flags |= fiberFlags;\n hook.memoizedState = pushSimpleEffect(\n 1 | hookFlags,\n { destroy: void 0 },\n create,\n void 0 === deps ? null : deps\n );\n}\nfunction updateEffectImpl(fiberFlags, hookFlags, create, deps) {\n var hook = updateWorkInProgressHook();\n deps = void 0 === deps ? null : deps;\n var inst = hook.memoizedState.inst;\n null !== currentHook &&\n null !== deps &&\n areHookInputsEqual(deps, currentHook.memoizedState.deps)\n ? (hook.memoizedState = pushSimpleEffect(hookFlags, inst, create, deps))\n : ((currentlyRenderingFiber.flags |= fiberFlags),\n (hook.memoizedState = pushSimpleEffect(\n 1 | hookFlags,\n inst,\n create,\n deps\n )));\n}\nfunction mountEffect(create, deps) {\n mountEffectImpl(8390656, 8, create, deps);\n}\nfunction updateEffect(create, deps) {\n updateEffectImpl(2048, 8, create, deps);\n}\nfunction useEffectEventImpl(payload) {\n currentlyRenderingFiber.flags |= 4;\n var componentUpdateQueue = currentlyRenderingFiber.updateQueue;\n if (null === componentUpdateQueue)\n (componentUpdateQueue = createFunctionComponentUpdateQueue()),\n (currentlyRenderingFiber.updateQueue = componentUpdateQueue),\n (componentUpdateQueue.events = [payload]);\n else {\n var events = componentUpdateQueue.events;\n null === events\n ? (componentUpdateQueue.events = [payload])\n : events.push(payload);\n }\n}\nfunction updateEvent(callback) {\n var ref = updateWorkInProgressHook().memoizedState;\n useEffectEventImpl({ ref: ref, nextImpl: callback });\n return function () {\n if (0 !== (executionContext & 2)) throw Error(formatProdErrorMessage(440));\n return ref.impl.apply(void 0, arguments);\n };\n}\nfunction updateInsertionEffect(create, deps) {\n return updateEffectImpl(4, 2, create, deps);\n}\nfunction updateLayoutEffect(create, deps) {\n return updateEffectImpl(4, 4, create, deps);\n}\nfunction imperativeHandleEffect(create, ref) {\n if (\"function\" === typeof ref) {\n create = create();\n var refCleanup = ref(create);\n return function () {\n \"function\" === typeof refCleanup ? refCleanup() : ref(null);\n };\n }\n if (null !== ref && void 0 !== ref)\n return (\n (create = create()),\n (ref.current = create),\n function () {\n ref.current = null;\n }\n );\n}\nfunction updateImperativeHandle(ref, create, deps) {\n deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null;\n updateEffectImpl(4, 4, imperativeHandleEffect.bind(null, create, ref), deps);\n}\nfunction mountDebugValue() {}\nfunction updateCallback(callback, deps) {\n var hook = updateWorkInProgressHook();\n deps = void 0 === deps ? null : deps;\n var prevState = hook.memoizedState;\n if (null !== deps && areHookInputsEqual(deps, prevState[1]))\n return prevState[0];\n hook.memoizedState = [callback, deps];\n return callback;\n}\nfunction updateMemo(nextCreate, deps) {\n var hook = updateWorkInProgressHook();\n deps = void 0 === deps ? null : deps;\n var prevState = hook.memoizedState;\n if (null !== deps && areHookInputsEqual(deps, prevState[1]))\n return prevState[0];\n prevState = nextCreate();\n if (shouldDoubleInvokeUserFnsInHooksDEV) {\n setIsStrictModeForDevtools(!0);\n try {\n nextCreate();\n } finally {\n setIsStrictModeForDevtools(!1);\n }\n }\n hook.memoizedState = [prevState, deps];\n return prevState;\n}\nfunction mountDeferredValueImpl(hook, value, initialValue) {\n if (\n void 0 === initialValue ||\n (0 !== (renderLanes & 1073741824) &&\n 0 === (workInProgressRootRenderLanes & 261930))\n )\n return (hook.memoizedState = value);\n hook.memoizedState = initialValue;\n hook = requestDeferredLane();\n currentlyRenderingFiber.lanes |= hook;\n workInProgressRootSkippedLanes |= hook;\n return initialValue;\n}\nfunction updateDeferredValueImpl(hook, prevValue, value, initialValue) {\n if (objectIs(value, prevValue)) return value;\n if (null !== currentTreeHiddenStackCursor.current)\n return (\n (hook = mountDeferredValueImpl(hook, value, initialValue)),\n objectIs(hook, prevValue) || (didReceiveUpdate = !0),\n hook\n );\n if (\n 0 === (renderLanes & 42) ||\n (0 !== (renderLanes & 1073741824) &&\n 0 === (workInProgressRootRenderLanes & 261930))\n )\n return (didReceiveUpdate = !0), (hook.memoizedState = value);\n hook = requestDeferredLane();\n currentlyRenderingFiber.lanes |= hook;\n workInProgressRootSkippedLanes |= hook;\n return prevValue;\n}\nfunction startTransition(fiber, queue, pendingState, finishedState, callback) {\n var previousPriority = ReactDOMSharedInternals.p;\n ReactDOMSharedInternals.p =\n 0 !== previousPriority && 8 > previousPriority ? previousPriority : 8;\n var prevTransition = ReactSharedInternals.T,\n currentTransition = {};\n ReactSharedInternals.T = currentTransition;\n dispatchOptimisticSetState(fiber, !1, queue, pendingState);\n try {\n var returnValue = callback(),\n onStartTransitionFinish = ReactSharedInternals.S;\n null !== onStartTransitionFinish &&\n onStartTransitionFinish(currentTransition, returnValue);\n if (\n null !== returnValue &&\n \"object\" === typeof returnValue &&\n \"function\" === typeof returnValue.then\n ) {\n var thenableForFinishedState = chainThenableValue(\n returnValue,\n finishedState\n );\n dispatchSetStateInternal(\n fiber,\n queue,\n thenableForFinishedState,\n requestUpdateLane(fiber)\n );\n } else\n dispatchSetStateInternal(\n fiber,\n queue,\n finishedState,\n requestUpdateLane(fiber)\n );\n } catch (error) {\n dispatchSetStateInternal(\n fiber,\n queue,\n { then: function () {}, status: \"rejected\", reason: error },\n requestUpdateLane()\n );\n } finally {\n (ReactDOMSharedInternals.p = previousPriority),\n null !== prevTransition &&\n null !== currentTransition.types &&\n (prevTransition.types = currentTransition.types),\n (ReactSharedInternals.T = prevTransition);\n }\n}\nfunction noop() {}\nfunction startHostTransition(formFiber, pendingState, action, formData) {\n if (5 !== formFiber.tag) throw Error(formatProdErrorMessage(476));\n var queue = ensureFormComponentIsStateful(formFiber).queue;\n startTransition(\n formFiber,\n queue,\n pendingState,\n sharedNotPendingObject,\n null === action\n ? noop\n : function () {\n requestFormReset$1(formFiber);\n return action(formData);\n }\n );\n}\nfunction ensureFormComponentIsStateful(formFiber) {\n var existingStateHook = formFiber.memoizedState;\n if (null !== existingStateHook) return existingStateHook;\n existingStateHook = {\n memoizedState: sharedNotPendingObject,\n baseState: sharedNotPendingObject,\n baseQueue: null,\n queue: {\n pending: null,\n lanes: 0,\n dispatch: null,\n lastRenderedReducer: basicStateReducer,\n lastRenderedState: sharedNotPendingObject\n },\n next: null\n };\n var initialResetState = {};\n existingStateHook.next = {\n memoizedState: initialResetState,\n baseState: initialResetState,\n baseQueue: null,\n queue: {\n pending: null,\n lanes: 0,\n dispatch: null,\n lastRenderedReducer: basicStateReducer,\n lastRenderedState: initialResetState\n },\n next: null\n };\n formFiber.memoizedState = existingStateHook;\n formFiber = formFiber.alternate;\n null !== formFiber && (formFiber.memoizedState = existingStateHook);\n return existingStateHook;\n}\nfunction requestFormReset$1(formFiber) {\n var stateHook = ensureFormComponentIsStateful(formFiber);\n null === stateHook.next && (stateHook = formFiber.alternate.memoizedState);\n dispatchSetStateInternal(\n formFiber,\n stateHook.next.queue,\n {},\n requestUpdateLane()\n );\n}\nfunction useHostTransitionStatus() {\n return readContext(HostTransitionContext);\n}\nfunction updateId() {\n return updateWorkInProgressHook().memoizedState;\n}\nfunction updateRefresh() {\n return updateWorkInProgressHook().memoizedState;\n}\nfunction refreshCache(fiber) {\n for (var provider = fiber.return; null !== provider; ) {\n switch (provider.tag) {\n case 24:\n case 3:\n var lane = requestUpdateLane();\n fiber = createUpdate(lane);\n var root$69 = enqueueUpdate(provider, fiber, lane);\n null !== root$69 &&\n (scheduleUpdateOnFiber(root$69, provider, lane),\n entangleTransitions(root$69, provider, lane));\n provider = { cache: createCache() };\n fiber.payload = provider;\n return;\n }\n provider = provider.return;\n }\n}\nfunction dispatchReducerAction(fiber, queue, action) {\n var lane = requestUpdateLane();\n action = {\n lane: lane,\n revertLane: 0,\n gesture: null,\n action: action,\n hasEagerState: !1,\n eagerState: null,\n next: null\n };\n isRenderPhaseUpdate(fiber)\n ? enqueueRenderPhaseUpdate(queue, action)\n : ((action = enqueueConcurrentHookUpdate(fiber, queue, action, lane)),\n null !== action &&\n (scheduleUpdateOnFiber(action, fiber, lane),\n entangleTransitionUpdate(action, queue, lane)));\n}\nfunction dispatchSetState(fiber, queue, action) {\n var lane = requestUpdateLane();\n dispatchSetStateInternal(fiber, queue, action, lane);\n}\nfunction dispatchSetStateInternal(fiber, queue, action, lane) {\n var update = {\n lane: lane,\n revertLane: 0,\n gesture: null,\n action: action,\n hasEagerState: !1,\n eagerState: null,\n next: null\n };\n if (isRenderPhaseUpdate(fiber)) enqueueRenderPhaseUpdate(queue, update);\n else {\n var alternate = fiber.alternate;\n if (\n 0 === fiber.lanes &&\n (null === alternate || 0 === alternate.lanes) &&\n ((alternate = queue.lastRenderedReducer), null !== alternate)\n )\n try {\n var currentState = queue.lastRenderedState,\n eagerState = alternate(currentState, action);\n update.hasEagerState = !0;\n update.eagerState = eagerState;\n if (objectIs(eagerState, currentState))\n return (\n enqueueUpdate$1(fiber, queue, update, 0),\n null === workInProgressRoot && finishQueueingConcurrentUpdates(),\n !1\n );\n } catch (error) {\n } finally {\n }\n action = enqueueConcurrentHookUpdate(fiber, queue, update, lane);\n if (null !== action)\n return (\n scheduleUpdateOnFiber(action, fiber, lane),\n entangleTransitionUpdate(action, queue, lane),\n !0\n );\n }\n return !1;\n}\nfunction dispatchOptimisticSetState(fiber, throwIfDuringRender, queue, action) {\n action = {\n lane: 2,\n revertLane: requestTransitionLane(),\n gesture: null,\n action: action,\n hasEagerState: !1,\n eagerState: null,\n next: null\n };\n if (isRenderPhaseUpdate(fiber)) {\n if (throwIfDuringRender) throw Error(formatProdErrorMessage(479));\n } else\n (throwIfDuringRender = enqueueConcurrentHookUpdate(\n fiber,\n queue,\n action,\n 2\n )),\n null !== throwIfDuringRender &&\n scheduleUpdateOnFiber(throwIfDuringRender, fiber, 2);\n}\nfunction isRenderPhaseUpdate(fiber) {\n var alternate = fiber.alternate;\n return (\n fiber === currentlyRenderingFiber ||\n (null !== alternate && alternate === currentlyRenderingFiber)\n );\n}\nfunction enqueueRenderPhaseUpdate(queue, update) {\n didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate =\n !0;\n var pending = queue.pending;\n null === pending\n ? (update.next = update)\n : ((update.next = pending.next), (pending.next = update));\n queue.pending = update;\n}\nfunction entangleTransitionUpdate(root, queue, lane) {\n if (0 !== (lane & 4194048)) {\n var queueLanes = queue.lanes;\n queueLanes &= root.pendingLanes;\n lane |= queueLanes;\n queue.lanes = lane;\n markRootEntangled(root, lane);\n }\n}\nvar ContextOnlyDispatcher = {\n readContext: readContext,\n use: use,\n useCallback: throwInvalidHookError,\n useContext: throwInvalidHookError,\n useEffect: throwInvalidHookError,\n useImperativeHandle: throwInvalidHookError,\n useLayoutEffect: throwInvalidHookError,\n useInsertionEffect: throwInvalidHookError,\n useMemo: throwInvalidHookError,\n useReducer: throwInvalidHookError,\n useRef: throwInvalidHookError,\n useState: throwInvalidHookError,\n useDebugValue: throwInvalidHookError,\n useDeferredValue: throwInvalidHookError,\n useTransition: throwInvalidHookError,\n useSyncExternalStore: throwInvalidHookError,\n useId: throwInvalidHookError,\n useHostTransitionStatus: throwInvalidHookError,\n useFormState: throwInvalidHookError,\n useActionState: throwInvalidHookError,\n useOptimistic: throwInvalidHookError,\n useMemoCache: throwInvalidHookError,\n useCacheRefresh: throwInvalidHookError\n};\nContextOnlyDispatcher.useEffectEvent = throwInvalidHookError;\nvar HooksDispatcherOnMount = {\n readContext: readContext,\n use: use,\n useCallback: function (callback, deps) {\n mountWorkInProgressHook().memoizedState = [\n callback,\n void 0 === deps ? null : deps\n ];\n return callback;\n },\n useContext: readContext,\n useEffect: mountEffect,\n useImperativeHandle: function (ref, create, deps) {\n deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null;\n mountEffectImpl(\n 4194308,\n 4,\n imperativeHandleEffect.bind(null, create, ref),\n deps\n );\n },\n useLayoutEffect: function (create, deps) {\n return mountEffectImpl(4194308, 4, create, deps);\n },\n useInsertionEffect: function (create, deps) {\n mountEffectImpl(4, 2, create, deps);\n },\n useMemo: function (nextCreate, deps) {\n var hook = mountWorkInProgressHook();\n deps = void 0 === deps ? null : deps;\n var nextValue = nextCreate();\n if (shouldDoubleInvokeUserFnsInHooksDEV) {\n setIsStrictModeForDevtools(!0);\n try {\n nextCreate();\n } finally {\n setIsStrictModeForDevtools(!1);\n }\n }\n hook.memoizedState = [nextValue, deps];\n return nextValue;\n },\n useReducer: function (reducer, initialArg, init) {\n var hook = mountWorkInProgressHook();\n if (void 0 !== init) {\n var initialState = init(initialArg);\n if (shouldDoubleInvokeUserFnsInHooksDEV) {\n setIsStrictModeForDevtools(!0);\n try {\n init(initialArg);\n } finally {\n setIsStrictModeForDevtools(!1);\n }\n }\n } else initialState = initialArg;\n hook.memoizedState = hook.baseState = initialState;\n reducer = {\n pending: null,\n lanes: 0,\n dispatch: null,\n lastRenderedReducer: reducer,\n lastRenderedState: initialState\n };\n hook.queue = reducer;\n reducer = reducer.dispatch = dispatchReducerAction.bind(\n null,\n currentlyRenderingFiber,\n reducer\n );\n return [hook.memoizedState, reducer];\n },\n useRef: function (initialValue) {\n var hook = mountWorkInProgressHook();\n initialValue = { current: initialValue };\n return (hook.memoizedState = initialValue);\n },\n useState: function (initialState) {\n initialState = mountStateImpl(initialState);\n var queue = initialState.queue,\n dispatch = dispatchSetState.bind(null, currentlyRenderingFiber, queue);\n queue.dispatch = dispatch;\n return [initialState.memoizedState, dispatch];\n },\n useDebugValue: mountDebugValue,\n useDeferredValue: function (value, initialValue) {\n var hook = mountWorkInProgressHook();\n return mountDeferredValueImpl(hook, value, initialValue);\n },\n useTransition: function () {\n var stateHook = mountStateImpl(!1);\n stateHook = startTransition.bind(\n null,\n currentlyRenderingFiber,\n stateHook.queue,\n !0,\n !1\n );\n mountWorkInProgressHook().memoizedState = stateHook;\n return [!1, stateHook];\n },\n useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {\n var fiber = currentlyRenderingFiber,\n hook = mountWorkInProgressHook();\n if (isHydrating) {\n if (void 0 === getServerSnapshot)\n throw Error(formatProdErrorMessage(407));\n getServerSnapshot = getServerSnapshot();\n } else {\n getServerSnapshot = getSnapshot();\n if (null === workInProgressRoot)\n throw Error(formatProdErrorMessage(349));\n 0 !== (workInProgressRootRenderLanes & 127) ||\n pushStoreConsistencyCheck(fiber, getSnapshot, getServerSnapshot);\n }\n hook.memoizedState = getServerSnapshot;\n var inst = { value: getServerSnapshot, getSnapshot: getSnapshot };\n hook.queue = inst;\n mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [\n subscribe\n ]);\n fiber.flags |= 2048;\n pushSimpleEffect(\n 9,\n { destroy: void 0 },\n updateStoreInstance.bind(\n null,\n fiber,\n inst,\n getServerSnapshot,\n getSnapshot\n ),\n null\n );\n return getServerSnapshot;\n },\n useId: function () {\n var hook = mountWorkInProgressHook(),\n identifierPrefix = workInProgressRoot.identifierPrefix;\n if (isHydrating) {\n var JSCompiler_inline_result = treeContextOverflow;\n var idWithLeadingBit = treeContextId;\n JSCompiler_inline_result =\n (\n idWithLeadingBit & ~(1 << (32 - clz32(idWithLeadingBit) - 1))\n ).toString(32) + JSCompiler_inline_result;\n identifierPrefix =\n \"_\" + identifierPrefix + \"R_\" + JSCompiler_inline_result;\n JSCompiler_inline_result = localIdCounter++;\n 0 < JSCompiler_inline_result &&\n (identifierPrefix += \"H\" + JSCompiler_inline_result.toString(32));\n identifierPrefix += \"_\";\n } else\n (JSCompiler_inline_result = globalClientIdCounter++),\n (identifierPrefix =\n \"_\" +\n identifierPrefix +\n \"r_\" +\n JSCompiler_inline_result.toString(32) +\n \"_\");\n return (hook.memoizedState = identifierPrefix);\n },\n useHostTransitionStatus: useHostTransitionStatus,\n useFormState: mountActionState,\n useActionState: mountActionState,\n useOptimistic: function (passthrough) {\n var hook = mountWorkInProgressHook();\n hook.memoizedState = hook.baseState = passthrough;\n var queue = {\n pending: null,\n lanes: 0,\n dispatch: null,\n lastRenderedReducer: null,\n lastRenderedState: null\n };\n hook.queue = queue;\n hook = dispatchOptimisticSetState.bind(\n null,\n currentlyRenderingFiber,\n !0,\n queue\n );\n queue.dispatch = hook;\n return [passthrough, hook];\n },\n useMemoCache: useMemoCache,\n useCacheRefresh: function () {\n return (mountWorkInProgressHook().memoizedState = refreshCache.bind(\n null,\n currentlyRenderingFiber\n ));\n },\n useEffectEvent: function (callback) {\n var hook = mountWorkInProgressHook(),\n ref = { impl: callback };\n hook.memoizedState = ref;\n return function () {\n if (0 !== (executionContext & 2))\n throw Error(formatProdErrorMessage(440));\n return ref.impl.apply(void 0, arguments);\n };\n }\n },\n HooksDispatcherOnUpdate = {\n readContext: readContext,\n use: use,\n useCallback: updateCallback,\n useContext: readContext,\n useEffect: updateEffect,\n useImperativeHandle: updateImperativeHandle,\n useInsertionEffect: updateInsertionEffect,\n useLayoutEffect: updateLayoutEffect,\n useMemo: updateMemo,\n useReducer: updateReducer,\n useRef: updateRef,\n useState: function () {\n return updateReducer(basicStateReducer);\n },\n useDebugValue: mountDebugValue,\n useDeferredValue: function (value, initialValue) {\n var hook = updateWorkInProgressHook();\n return updateDeferredValueImpl(\n hook,\n currentHook.memoizedState,\n value,\n initialValue\n );\n },\n useTransition: function () {\n var booleanOrThenable = updateReducer(basicStateReducer)[0],\n start = updateWorkInProgressHook().memoizedState;\n return [\n \"boolean\" === typeof booleanOrThenable\n ? booleanOrThenable\n : useThenable(booleanOrThenable),\n start\n ];\n },\n useSyncExternalStore: updateSyncExternalStore,\n useId: updateId,\n useHostTransitionStatus: useHostTransitionStatus,\n useFormState: updateActionState,\n useActionState: updateActionState,\n useOptimistic: function (passthrough, reducer) {\n var hook = updateWorkInProgressHook();\n return updateOptimisticImpl(hook, currentHook, passthrough, reducer);\n },\n useMemoCache: useMemoCache,\n useCacheRefresh: updateRefresh\n };\nHooksDispatcherOnUpdate.useEffectEvent = updateEvent;\nvar HooksDispatcherOnRerender = {\n readContext: readContext,\n use: use,\n useCallback: updateCallback,\n useContext: readContext,\n useEffect: updateEffect,\n useImperativeHandle: updateImperativeHandle,\n useInsertionEffect: updateInsertionEffect,\n useLayoutEffect: updateLayoutEffect,\n useMemo: updateMemo,\n useReducer: rerenderReducer,\n useRef: updateRef,\n useState: function () {\n return rerenderReducer(basicStateReducer);\n },\n useDebugValue: mountDebugValue,\n useDeferredValue: function (value, initialValue) {\n var hook = updateWorkInProgressHook();\n return null === currentHook\n ? mountDeferredValueImpl(hook, value, initialValue)\n : updateDeferredValueImpl(\n hook,\n currentHook.memoizedState,\n value,\n initialValue\n );\n },\n useTransition: function () {\n var booleanOrThenable = rerenderReducer(basicStateReducer)[0],\n start = updateWorkInProgressHook().memoizedState;\n return [\n \"boolean\" === typeof booleanOrThenable\n ? booleanOrThenable\n : useThenable(booleanOrThenable),\n start\n ];\n },\n useSyncExternalStore: updateSyncExternalStore,\n useId: updateId,\n useHostTransitionStatus: useHostTransitionStatus,\n useFormState: rerenderActionState,\n useActionState: rerenderActionState,\n useOptimistic: function (passthrough, reducer) {\n var hook = updateWorkInProgressHook();\n if (null !== currentHook)\n return updateOptimisticImpl(hook, currentHook, passthrough, reducer);\n hook.baseState = passthrough;\n return [passthrough, hook.queue.dispatch];\n },\n useMemoCache: useMemoCache,\n useCacheRefresh: updateRefresh\n};\nHooksDispatcherOnRerender.useEffectEvent = updateEvent;\nfunction applyDerivedStateFromProps(\n workInProgress,\n ctor,\n getDerivedStateFromProps,\n nextProps\n) {\n ctor = workInProgress.memoizedState;\n getDerivedStateFromProps = getDerivedStateFromProps(nextProps, ctor);\n getDerivedStateFromProps =\n null === getDerivedStateFromProps || void 0 === getDerivedStateFromProps\n ? ctor\n : assign({}, ctor, getDerivedStateFromProps);\n workInProgress.memoizedState = getDerivedStateFromProps;\n 0 === workInProgress.lanes &&\n (workInProgress.updateQueue.baseState = getDerivedStateFromProps);\n}\nvar classComponentUpdater = {\n enqueueSetState: function (inst, payload, callback) {\n inst = inst._reactInternals;\n var lane = requestUpdateLane(),\n update = createUpdate(lane);\n update.payload = payload;\n void 0 !== callback && null !== callback && (update.callback = callback);\n payload = enqueueUpdate(inst, update, lane);\n null !== payload &&\n (scheduleUpdateOnFiber(payload, inst, lane),\n entangleTransitions(payload, inst, lane));\n },\n enqueueReplaceState: function (inst, payload, callback) {\n inst = inst._reactInternals;\n var lane = requestUpdateLane(),\n update = createUpdate(lane);\n update.tag = 1;\n update.payload = payload;\n void 0 !== callback && null !== callback && (update.callback = callback);\n payload = enqueueUpdate(inst, update, lane);\n null !== payload &&\n (scheduleUpdateOnFiber(payload, inst, lane),\n entangleTransitions(payload, inst, lane));\n },\n enqueueForceUpdate: function (inst, callback) {\n inst = inst._reactInternals;\n var lane = requestUpdateLane(),\n update = createUpdate(lane);\n update.tag = 2;\n void 0 !== callback && null !== callback && (update.callback = callback);\n callback = enqueueUpdate(inst, update, lane);\n null !== callback &&\n (scheduleUpdateOnFiber(callback, inst, lane),\n entangleTransitions(callback, inst, lane));\n }\n};\nfunction checkShouldComponentUpdate(\n workInProgress,\n ctor,\n oldProps,\n newProps,\n oldState,\n newState,\n nextContext\n) {\n workInProgress = workInProgress.stateNode;\n return \"function\" === typeof workInProgress.shouldComponentUpdate\n ? workInProgress.shouldComponentUpdate(newProps, newState, nextContext)\n : ctor.prototype && ctor.prototype.isPureReactComponent\n ? !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState)\n : !0;\n}\nfunction callComponentWillReceiveProps(\n workInProgress,\n instance,\n newProps,\n nextContext\n) {\n workInProgress = instance.state;\n \"function\" === typeof instance.componentWillReceiveProps &&\n instance.componentWillReceiveProps(newProps, nextContext);\n \"function\" === typeof instance.UNSAFE_componentWillReceiveProps &&\n instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);\n instance.state !== workInProgress &&\n classComponentUpdater.enqueueReplaceState(instance, instance.state, null);\n}\nfunction resolveClassComponentProps(Component, baseProps) {\n var newProps = baseProps;\n if (\"ref\" in baseProps) {\n newProps = {};\n for (var propName in baseProps)\n \"ref\" !== propName && (newProps[propName] = baseProps[propName]);\n }\n if ((Component = Component.defaultProps)) {\n newProps === baseProps && (newProps = assign({}, newProps));\n for (var propName$73 in Component)\n void 0 === newProps[propName$73] &&\n (newProps[propName$73] = Component[propName$73]);\n }\n return newProps;\n}\nfunction defaultOnUncaughtError(error) {\n reportGlobalError(error);\n}\nfunction defaultOnCaughtError(error) {\n console.error(error);\n}\nfunction defaultOnRecoverableError(error) {\n reportGlobalError(error);\n}\nfunction logUncaughtError(root, errorInfo) {\n try {\n var onUncaughtError = root.onUncaughtError;\n onUncaughtError(errorInfo.value, { componentStack: errorInfo.stack });\n } catch (e$74) {\n setTimeout(function () {\n throw e$74;\n });\n }\n}\nfunction logCaughtError(root, boundary, errorInfo) {\n try {\n var onCaughtError = root.onCaughtError;\n onCaughtError(errorInfo.value, {\n componentStack: errorInfo.stack,\n errorBoundary: 1 === boundary.tag ? boundary.stateNode : null\n });\n } catch (e$75) {\n setTimeout(function () {\n throw e$75;\n });\n }\n}\nfunction createRootErrorUpdate(root, errorInfo, lane) {\n lane = createUpdate(lane);\n lane.tag = 3;\n lane.payload = { element: null };\n lane.callback = function () {\n logUncaughtError(root, errorInfo);\n };\n return lane;\n}\nfunction createClassErrorUpdate(lane) {\n lane = createUpdate(lane);\n lane.tag = 3;\n return lane;\n}\nfunction initializeClassErrorUpdate(update, root, fiber, errorInfo) {\n var getDerivedStateFromError = fiber.type.getDerivedStateFromError;\n if (\"function\" === typeof getDerivedStateFromError) {\n var error = errorInfo.value;\n update.payload = function () {\n return getDerivedStateFromError(error);\n };\n update.callback = function () {\n logCaughtError(root, fiber, errorInfo);\n };\n }\n var inst = fiber.stateNode;\n null !== inst &&\n \"function\" === typeof inst.componentDidCatch &&\n (update.callback = function () {\n logCaughtError(root, fiber, errorInfo);\n \"function\" !== typeof getDerivedStateFromError &&\n (null === legacyErrorBoundariesThatAlreadyFailed\n ? (legacyErrorBoundariesThatAlreadyFailed = new Set([this]))\n : legacyErrorBoundariesThatAlreadyFailed.add(this));\n var stack = errorInfo.stack;\n this.componentDidCatch(errorInfo.value, {\n componentStack: null !== stack ? stack : \"\"\n });\n });\n}\nfunction throwException(\n root,\n returnFiber,\n sourceFiber,\n value,\n rootRenderLanes\n) {\n sourceFiber.flags |= 32768;\n if (\n null !== value &&\n \"object\" === typeof value &&\n \"function\" === typeof value.then\n ) {\n returnFiber = sourceFiber.alternate;\n null !== returnFiber &&\n propagateParentContextChanges(\n returnFiber,\n sourceFiber,\n rootRenderLanes,\n !0\n );\n sourceFiber = suspenseHandlerStackCursor.current;\n if (null !== sourceFiber) {\n switch (sourceFiber.tag) {\n case 31:\n case 13:\n return (\n null === shellBoundary\n ? renderDidSuspendDelayIfPossible()\n : null === sourceFiber.alternate &&\n 0 === workInProgressRootExitStatus &&\n (workInProgressRootExitStatus = 3),\n (sourceFiber.flags &= -257),\n (sourceFiber.flags |= 65536),\n (sourceFiber.lanes = rootRenderLanes),\n value === noopSuspenseyCommitThenable\n ? (sourceFiber.flags |= 16384)\n : ((returnFiber = sourceFiber.updateQueue),\n null === returnFiber\n ? (sourceFiber.updateQueue = new Set([value]))\n : returnFiber.add(value),\n attachPingListener(root, value, rootRenderLanes)),\n !1\n );\n case 22:\n return (\n (sourceFiber.flags |= 65536),\n value === noopSuspenseyCommitThenable\n ? (sourceFiber.flags |= 16384)\n : ((returnFiber = sourceFiber.updateQueue),\n null === returnFiber\n ? ((returnFiber = {\n transitions: null,\n markerInstances: null,\n retryQueue: new Set([value])\n }),\n (sourceFiber.updateQueue = returnFiber))\n : ((sourceFiber = returnFiber.retryQueue),\n null === sourceFiber\n ? (returnFiber.retryQueue = new Set([value]))\n : sourceFiber.add(value)),\n attachPingListener(root, value, rootRenderLanes)),\n !1\n );\n }\n throw Error(formatProdErrorMessage(435, sourceFiber.tag));\n }\n attachPingListener(root, value, rootRenderLanes);\n renderDidSuspendDelayIfPossible();\n return !1;\n }\n if (isHydrating)\n return (\n (returnFiber = suspenseHandlerStackCursor.current),\n null !== returnFiber\n ? (0 === (returnFiber.flags & 65536) && (returnFiber.flags |= 256),\n (returnFiber.flags |= 65536),\n (returnFiber.lanes = rootRenderLanes),\n value !== HydrationMismatchException &&\n ((root = Error(formatProdErrorMessage(422), { cause: value })),\n queueHydrationError(createCapturedValueAtFiber(root, sourceFiber))))\n : (value !== HydrationMismatchException &&\n ((returnFiber = Error(formatProdErrorMessage(423), {\n cause: value\n })),\n queueHydrationError(\n createCapturedValueAtFiber(returnFiber, sourceFiber)\n )),\n (root = root.current.alternate),\n (root.flags |= 65536),\n (rootRenderLanes &= -rootRenderLanes),\n (root.lanes |= rootRenderLanes),\n (value = createCapturedValueAtFiber(value, sourceFiber)),\n (rootRenderLanes = createRootErrorUpdate(\n root.stateNode,\n value,\n rootRenderLanes\n )),\n enqueueCapturedUpdate(root, rootRenderLanes),\n 4 !== workInProgressRootExitStatus &&\n (workInProgressRootExitStatus = 2)),\n !1\n );\n var wrapperError = Error(formatProdErrorMessage(520), { cause: value });\n wrapperError = createCapturedValueAtFiber(wrapperError, sourceFiber);\n null === workInProgressRootConcurrentErrors\n ? (workInProgressRootConcurrentErrors = [wrapperError])\n : workInProgressRootConcurrentErrors.push(wrapperError);\n 4 !== workInProgressRootExitStatus && (workInProgressRootExitStatus = 2);\n if (null === returnFiber) return !0;\n value = createCapturedValueAtFiber(value, sourceFiber);\n sourceFiber = returnFiber;\n do {\n switch (sourceFiber.tag) {\n case 3:\n return (\n (sourceFiber.flags |= 65536),\n (root = rootRenderLanes & -rootRenderLanes),\n (sourceFiber.lanes |= root),\n (root = createRootErrorUpdate(sourceFiber.stateNode, value, root)),\n enqueueCapturedUpdate(sourceFiber, root),\n !1\n );\n case 1:\n if (\n ((returnFiber = sourceFiber.type),\n (wrapperError = sourceFiber.stateNode),\n 0 === (sourceFiber.flags & 128) &&\n (\"function\" === typeof returnFiber.getDerivedStateFromError ||\n (null !== wrapperError &&\n \"function\" === typeof wrapperError.componentDidCatch &&\n (null === legacyErrorBoundariesThatAlreadyFailed ||\n !legacyErrorBoundariesThatAlreadyFailed.has(wrapperError)))))\n )\n return (\n (sourceFiber.flags |= 65536),\n (rootRenderLanes &= -rootRenderLanes),\n (sourceFiber.lanes |= rootRenderLanes),\n (rootRenderLanes = createClassErrorUpdate(rootRenderLanes)),\n initializeClassErrorUpdate(\n rootRenderLanes,\n root,\n sourceFiber,\n value\n ),\n enqueueCapturedUpdate(sourceFiber, rootRenderLanes),\n !1\n );\n }\n sourceFiber = sourceFiber.return;\n } while (null !== sourceFiber);\n return !1;\n}\nvar SelectiveHydrationException = Error(formatProdErrorMessage(461)),\n didReceiveUpdate = !1;\nfunction reconcileChildren(current, workInProgress, nextChildren, renderLanes) {\n workInProgress.child =\n null === current\n ? mountChildFibers(workInProgress, null, nextChildren, renderLanes)\n : reconcileChildFibers(\n workInProgress,\n current.child,\n nextChildren,\n renderLanes\n );\n}\nfunction updateForwardRef(\n current,\n workInProgress,\n Component,\n nextProps,\n renderLanes\n) {\n Component = Component.render;\n var ref = workInProgress.ref;\n if (\"ref\" in nextProps) {\n var propsWithoutRef = {};\n for (var key in nextProps)\n \"ref\" !== key && (propsWithoutRef[key] = nextProps[key]);\n } else propsWithoutRef = nextProps;\n prepareToReadContext(workInProgress);\n nextProps = renderWithHooks(\n current,\n workInProgress,\n Component,\n propsWithoutRef,\n ref,\n renderLanes\n );\n key = checkDidRenderIdHook();\n if (null !== current && !didReceiveUpdate)\n return (\n bailoutHooks(current, workInProgress, renderLanes),\n bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes)\n );\n isHydrating && key && pushMaterializedTreeId(workInProgress);\n workInProgress.flags |= 1;\n reconcileChildren(current, workInProgress, nextProps, renderLanes);\n return workInProgress.child;\n}\nfunction updateMemoComponent(\n current,\n workInProgress,\n Component,\n nextProps,\n renderLanes\n) {\n if (null === current) {\n var type = Component.type;\n if (\n \"function\" === typeof type &&\n !shouldConstruct(type) &&\n void 0 === type.defaultProps &&\n null === Component.compare\n )\n return (\n (workInProgress.tag = 15),\n (workInProgress.type = type),\n updateSimpleMemoComponent(\n current,\n workInProgress,\n type,\n nextProps,\n renderLanes\n )\n );\n current = createFiberFromTypeAndProps(\n Component.type,\n null,\n nextProps,\n workInProgress,\n workInProgress.mode,\n renderLanes\n );\n current.ref = workInProgress.ref;\n current.return = workInProgress;\n return (workInProgress.child = current);\n }\n type = current.child;\n if (!checkScheduledUpdateOrContext(current, renderLanes)) {\n var prevProps = type.memoizedProps;\n Component = Component.compare;\n Component = null !== Component ? Component : shallowEqual;\n if (Component(prevProps, nextProps) && current.ref === workInProgress.ref)\n return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);\n }\n workInProgress.flags |= 1;\n current = createWorkInProgress(type, nextProps);\n current.ref = workInProgress.ref;\n current.return = workInProgress;\n return (workInProgress.child = current);\n}\nfunction updateSimpleMemoComponent(\n current,\n workInProgress,\n Component,\n nextProps,\n renderLanes\n) {\n if (null !== current) {\n var prevProps = current.memoizedProps;\n if (\n shallowEqual(prevProps, nextProps) &&\n current.ref === workInProgress.ref\n )\n if (\n ((didReceiveUpdate = !1),\n (workInProgress.pendingProps = nextProps = prevProps),\n checkScheduledUpdateOrContext(current, renderLanes))\n )\n 0 !== (current.flags & 131072) && (didReceiveUpdate = !0);\n else\n return (\n (workInProgress.lanes = current.lanes),\n bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes)\n );\n }\n return updateFunctionComponent(\n current,\n workInProgress,\n Component,\n nextProps,\n renderLanes\n );\n}\nfunction updateOffscreenComponent(\n current,\n workInProgress,\n renderLanes,\n nextProps\n) {\n var nextChildren = nextProps.children,\n prevState = null !== current ? current.memoizedState : null;\n null === current &&\n null === workInProgress.stateNode &&\n (workInProgress.stateNode = {\n _visibility: 1,\n _pendingMarkers: null,\n _retryCache: null,\n _transitions: null\n });\n if (\"hidden\" === nextProps.mode) {\n if (0 !== (workInProgress.flags & 128)) {\n prevState =\n null !== prevState ? prevState.baseLanes | renderLanes : renderLanes;\n if (null !== current) {\n nextProps = workInProgress.child = current.child;\n for (nextChildren = 0; null !== nextProps; )\n (nextChildren =\n nextChildren | nextProps.lanes | nextProps.childLanes),\n (nextProps = nextProps.sibling);\n nextProps = nextChildren & ~prevState;\n } else (nextProps = 0), (workInProgress.child = null);\n return deferHiddenOffscreenComponent(\n current,\n workInProgress,\n prevState,\n renderLanes,\n nextProps\n );\n }\n if (0 !== (renderLanes & 536870912))\n (workInProgress.memoizedState = { baseLanes: 0, cachePool: null }),\n null !== current &&\n pushTransition(\n workInProgress,\n null !== prevState ? prevState.cachePool : null\n ),\n null !== prevState\n ? pushHiddenContext(workInProgress, prevState)\n : reuseHiddenContextOnStack(),\n pushOffscreenSuspenseHandler(workInProgress);\n else\n return (\n (nextProps = workInProgress.lanes = 536870912),\n deferHiddenOffscreenComponent(\n current,\n workInProgress,\n null !== prevState ? prevState.baseLanes | renderLanes : renderLanes,\n renderLanes,\n nextProps\n )\n );\n } else\n null !== prevState\n ? (pushTransition(workInProgress, prevState.cachePool),\n pushHiddenContext(workInProgress, prevState),\n reuseSuspenseHandlerOnStack(workInProgress),\n (workInProgress.memoizedState = null))\n : (null !== current && pushTransition(workInProgress, null),\n reuseHiddenContextOnStack(),\n reuseSuspenseHandlerOnStack(workInProgress));\n reconcileChildren(current, workInProgress, nextChildren, renderLanes);\n return workInProgress.child;\n}\nfunction bailoutOffscreenComponent(current, workInProgress) {\n (null !== current && 22 === current.tag) ||\n null !== workInProgress.stateNode ||\n (workInProgress.stateNode = {\n _visibility: 1,\n _pendingMarkers: null,\n _retryCache: null,\n _transitions: null\n });\n return workInProgress.sibling;\n}\nfunction deferHiddenOffscreenComponent(\n current,\n workInProgress,\n nextBaseLanes,\n renderLanes,\n remainingChildLanes\n) {\n var JSCompiler_inline_result = peekCacheFromPool();\n JSCompiler_inline_result =\n null === JSCompiler_inline_result\n ? null\n : { parent: CacheContext._currentValue, pool: JSCompiler_inline_result };\n workInProgress.memoizedState = {\n baseLanes: nextBaseLanes,\n cachePool: JSCompiler_inline_result\n };\n null !== current && pushTransition(workInProgress, null);\n reuseHiddenContextOnStack();\n pushOffscreenSuspenseHandler(workInProgress);\n null !== current &&\n propagateParentContextChanges(current, workInProgress, renderLanes, !0);\n workInProgress.childLanes = remainingChildLanes;\n return null;\n}\nfunction mountActivityChildren(workInProgress, nextProps) {\n nextProps = mountWorkInProgressOffscreenFiber(\n { mode: nextProps.mode, children: nextProps.children },\n workInProgress.mode\n );\n nextProps.ref = workInProgress.ref;\n workInProgress.child = nextProps;\n nextProps.return = workInProgress;\n return nextProps;\n}\nfunction retryActivityComponentWithoutHydrating(\n current,\n workInProgress,\n renderLanes\n) {\n reconcileChildFibers(workInProgress, current.child, null, renderLanes);\n current = mountActivityChildren(workInProgress, workInProgress.pendingProps);\n current.flags |= 2;\n popSuspenseHandler(workInProgress);\n workInProgress.memoizedState = null;\n return current;\n}\nfunction updateActivityComponent(current, workInProgress, renderLanes) {\n var nextProps = workInProgress.pendingProps,\n didSuspend = 0 !== (workInProgress.flags & 128);\n workInProgress.flags &= -129;\n if (null === current) {\n if (isHydrating) {\n if (\"hidden\" === nextProps.mode)\n return (\n (current = mountActivityChildren(workInProgress, nextProps)),\n (workInProgress.lanes = 536870912),\n bailoutOffscreenComponent(null, current)\n );\n pushDehydratedActivitySuspenseHandler(workInProgress);\n (current = nextHydratableInstance)\n ? ((current = canHydrateHydrationBoundary(\n current,\n rootOrSingletonContext\n )),\n (current = null !== current && \"&\" === current.data ? current : null),\n null !== current &&\n ((workInProgress.memoizedState = {\n dehydrated: current,\n treeContext:\n null !== treeContextProvider\n ? { id: treeContextId, overflow: treeContextOverflow }\n : null,\n retryLane: 536870912,\n hydrationErrors: null\n }),\n (renderLanes = createFiberFromDehydratedFragment(current)),\n (renderLanes.return = workInProgress),\n (workInProgress.child = renderLanes),\n (hydrationParentFiber = workInProgress),\n (nextHydratableInstance = null)))\n : (current = null);\n if (null === current) throw throwOnHydrationMismatch(workInProgress);\n workInProgress.lanes = 536870912;\n return null;\n }\n return mountActivityChildren(workInProgress, nextProps);\n }\n var prevState = current.memoizedState;\n if (null !== prevState) {\n var dehydrated = prevState.dehydrated;\n pushDehydratedActivitySuspenseHandler(workInProgress);\n if (didSuspend)\n if (workInProgress.flags & 256)\n (workInProgress.flags &= -257),\n (workInProgress = retryActivityComponentWithoutHydrating(\n current,\n workInProgress,\n renderLanes\n ));\n else if (null !== workInProgress.memoizedState)\n (workInProgress.child = current.child),\n (workInProgress.flags |= 128),\n (workInProgress = null);\n else throw Error(formatProdErrorMessage(558));\n else if (\n (didReceiveUpdate ||\n propagateParentContextChanges(current, workInProgress, renderLanes, !1),\n (didSuspend = 0 !== (renderLanes & current.childLanes)),\n didReceiveUpdate || didSuspend)\n ) {\n nextProps = workInProgressRoot;\n if (\n null !== nextProps &&\n ((dehydrated = getBumpedLaneForHydration(nextProps, renderLanes)),\n 0 !== dehydrated && dehydrated !== prevState.retryLane)\n )\n throw (\n ((prevState.retryLane = dehydrated),\n enqueueConcurrentRenderForLane(current, dehydrated),\n scheduleUpdateOnFiber(nextProps, current, dehydrated),\n SelectiveHydrationException)\n );\n renderDidSuspendDelayIfPossible();\n workInProgress = retryActivityComponentWithoutHydrating(\n current,\n workInProgress,\n renderLanes\n );\n } else\n (current = prevState.treeContext),\n (nextHydratableInstance = getNextHydratable(dehydrated.nextSibling)),\n (hydrationParentFiber = workInProgress),\n (isHydrating = !0),\n (hydrationErrors = null),\n (rootOrSingletonContext = !1),\n null !== current &&\n restoreSuspendedTreeContext(workInProgress, current),\n (workInProgress = mountActivityChildren(workInProgress, nextProps)),\n (workInProgress.flags |= 4096);\n return workInProgress;\n }\n current = createWorkInProgress(current.child, {\n mode: nextProps.mode,\n children: nextProps.children\n });\n current.ref = workInProgress.ref;\n workInProgress.child = current;\n current.return = workInProgress;\n return current;\n}\nfunction markRef(current, workInProgress) {\n var ref = workInProgress.ref;\n if (null === ref)\n null !== current &&\n null !== current.ref &&\n (workInProgress.flags |= 4194816);\n else {\n if (\"function\" !== typeof ref && \"object\" !== typeof ref)\n throw Error(formatProdErrorMessage(284));\n if (null === current || current.ref !== ref)\n workInProgress.flags |= 4194816;\n }\n}\nfunction updateFunctionComponent(\n current,\n workInProgress,\n Component,\n nextProps,\n renderLanes\n) {\n prepareToReadContext(workInProgress);\n Component = renderWithHooks(\n current,\n workInProgress,\n Component,\n nextProps,\n void 0,\n renderLanes\n );\n nextProps = checkDidRenderIdHook();\n if (null !== current && !didReceiveUpdate)\n return (\n bailoutHooks(current, workInProgress, renderLanes),\n bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes)\n );\n isHydrating && nextProps && pushMaterializedTreeId(workInProgress);\n workInProgress.flags |= 1;\n reconcileChildren(current, workInProgress, Component, renderLanes);\n return workInProgress.child;\n}\nfunction replayFunctionComponent(\n current,\n workInProgress,\n nextProps,\n Component,\n secondArg,\n renderLanes\n) {\n prepareToReadContext(workInProgress);\n workInProgress.updateQueue = null;\n nextProps = renderWithHooksAgain(\n workInProgress,\n Component,\n nextProps,\n secondArg\n );\n finishRenderingHooks(current);\n Component = checkDidRenderIdHook();\n if (null !== current && !didReceiveUpdate)\n return (\n bailoutHooks(current, workInProgress, renderLanes),\n bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes)\n );\n isHydrating && Component && pushMaterializedTreeId(workInProgress);\n workInProgress.flags |= 1;\n reconcileChildren(current, workInProgress, nextProps, renderLanes);\n return workInProgress.child;\n}\nfunction updateClassComponent(\n current,\n workInProgress,\n Component,\n nextProps,\n renderLanes\n) {\n prepareToReadContext(workInProgress);\n if (null === workInProgress.stateNode) {\n var context = emptyContextObject,\n contextType = Component.contextType;\n \"object\" === typeof contextType &&\n null !== contextType &&\n (context = readContext(contextType));\n context = new Component(nextProps, context);\n workInProgress.memoizedState =\n null !== context.state && void 0 !== context.state ? context.state : null;\n context.updater = classComponentUpdater;\n workInProgress.stateNode = context;\n context._reactInternals = workInProgress;\n context = workInProgress.stateNode;\n context.props = nextProps;\n context.state = workInProgress.memoizedState;\n context.refs = {};\n initializeUpdateQueue(workInProgress);\n contextType = Component.contextType;\n context.context =\n \"object\" === typeof contextType && null !== contextType\n ? readContext(contextType)\n : emptyContextObject;\n context.state = workInProgress.memoizedState;\n contextType = Component.getDerivedStateFromProps;\n \"function\" === typeof contextType &&\n (applyDerivedStateFromProps(\n workInProgress,\n Component,\n contextType,\n nextProps\n ),\n (context.state = workInProgress.memoizedState));\n \"function\" === typeof Component.getDerivedStateFromProps ||\n \"function\" === typeof context.getSnapshotBeforeUpdate ||\n (\"function\" !== typeof context.UNSAFE_componentWillMount &&\n \"function\" !== typeof context.componentWillMount) ||\n ((contextType = context.state),\n \"function\" === typeof context.componentWillMount &&\n context.componentWillMount(),\n \"function\" === typeof context.UNSAFE_componentWillMount &&\n context.UNSAFE_componentWillMount(),\n contextType !== context.state &&\n classComponentUpdater.enqueueReplaceState(context, context.state, null),\n processUpdateQueue(workInProgress, nextProps, context, renderLanes),\n suspendIfUpdateReadFromEntangledAsyncAction(),\n (context.state = workInProgress.memoizedState));\n \"function\" === typeof context.componentDidMount &&\n (workInProgress.flags |= 4194308);\n nextProps = !0;\n } else if (null === current) {\n context = workInProgress.stateNode;\n var unresolvedOldProps = workInProgress.memoizedProps,\n oldProps = resolveClassComponentProps(Component, unresolvedOldProps);\n context.props = oldProps;\n var oldContext = context.context,\n contextType$jscomp$0 = Component.contextType;\n contextType = emptyContextObject;\n \"object\" === typeof contextType$jscomp$0 &&\n null !== contextType$jscomp$0 &&\n (contextType = readContext(contextType$jscomp$0));\n var getDerivedStateFromProps = Component.getDerivedStateFromProps;\n contextType$jscomp$0 =\n \"function\" === typeof getDerivedStateFromProps ||\n \"function\" === typeof context.getSnapshotBeforeUpdate;\n unresolvedOldProps = workInProgress.pendingProps !== unresolvedOldProps;\n contextType$jscomp$0 ||\n (\"function\" !== typeof context.UNSAFE_componentWillReceiveProps &&\n \"function\" !== typeof context.componentWillReceiveProps) ||\n ((unresolvedOldProps || oldContext !== contextType) &&\n callComponentWillReceiveProps(\n workInProgress,\n context,\n nextProps,\n contextType\n ));\n hasForceUpdate = !1;\n var oldState = workInProgress.memoizedState;\n context.state = oldState;\n processUpdateQueue(workInProgress, nextProps, context, renderLanes);\n suspendIfUpdateReadFromEntangledAsyncAction();\n oldContext = workInProgress.memoizedState;\n unresolvedOldProps || oldState !== oldContext || hasForceUpdate\n ? (\"function\" === typeof getDerivedStateFromProps &&\n (applyDerivedStateFromProps(\n workInProgress,\n Component,\n getDerivedStateFromProps,\n nextProps\n ),\n (oldContext = workInProgress.memoizedState)),\n (oldProps =\n hasForceUpdate ||\n checkShouldComponentUpdate(\n workInProgress,\n Component,\n oldProps,\n nextProps,\n oldState,\n oldContext,\n contextType\n ))\n ? (contextType$jscomp$0 ||\n (\"function\" !== typeof context.UNSAFE_componentWillMount &&\n \"function\" !== typeof context.componentWillMount) ||\n (\"function\" === typeof context.componentWillMount &&\n context.componentWillMount(),\n \"function\" === typeof context.UNSAFE_componentWillMount &&\n context.UNSAFE_componentWillMount()),\n \"function\" === typeof context.componentDidMount &&\n (workInProgress.flags |= 4194308))\n : (\"function\" === typeof context.componentDidMount &&\n (workInProgress.flags |= 4194308),\n (workInProgress.memoizedProps = nextProps),\n (workInProgress.memoizedState = oldContext)),\n (context.props = nextProps),\n (context.state = oldContext),\n (context.context = contextType),\n (nextProps = oldProps))\n : (\"function\" === typeof context.componentDidMount &&\n (workInProgress.flags |= 4194308),\n (nextProps = !1));\n } else {\n context = workInProgress.stateNode;\n cloneUpdateQueue(current, workInProgress);\n contextType = workInProgress.memoizedProps;\n contextType$jscomp$0 = resolveClassComponentProps(Component, contextType);\n context.props = contextType$jscomp$0;\n getDerivedStateFromProps = workInProgress.pendingProps;\n oldState = context.context;\n oldContext = Component.contextType;\n oldProps = emptyContextObject;\n \"object\" === typeof oldContext &&\n null !== oldContext &&\n (oldProps = readContext(oldContext));\n unresolvedOldProps = Component.getDerivedStateFromProps;\n (oldContext =\n \"function\" === typeof unresolvedOldProps ||\n \"function\" === typeof context.getSnapshotBeforeUpdate) ||\n (\"function\" !== typeof context.UNSAFE_componentWillReceiveProps &&\n \"function\" !== typeof context.componentWillReceiveProps) ||\n ((contextType !== getDerivedStateFromProps || oldState !== oldProps) &&\n callComponentWillReceiveProps(\n workInProgress,\n context,\n nextProps,\n oldProps\n ));\n hasForceUpdate = !1;\n oldState = workInProgress.memoizedState;\n context.state = oldState;\n processUpdateQueue(workInProgress, nextProps, context, renderLanes);\n suspendIfUpdateReadFromEntangledAsyncAction();\n var newState = workInProgress.memoizedState;\n contextType !== getDerivedStateFromProps ||\n oldState !== newState ||\n hasForceUpdate ||\n (null !== current &&\n null !== current.dependencies &&\n checkIfContextChanged(current.dependencies))\n ? (\"function\" === typeof unresolvedOldProps &&\n (applyDerivedStateFromProps(\n workInProgress,\n Component,\n unresolvedOldProps,\n nextProps\n ),\n (newState = workInProgress.memoizedState)),\n (contextType$jscomp$0 =\n hasForceUpdate ||\n checkShouldComponentUpdate(\n workInProgress,\n Component,\n contextType$jscomp$0,\n nextProps,\n oldState,\n newState,\n oldProps\n ) ||\n (null !== current &&\n null !== current.dependencies &&\n checkIfContextChanged(current.dependencies)))\n ? (oldContext ||\n (\"function\" !== typeof context.UNSAFE_componentWillUpdate &&\n \"function\" !== typeof context.componentWillUpdate) ||\n (\"function\" === typeof context.componentWillUpdate &&\n context.componentWillUpdate(nextProps, newState, oldProps),\n \"function\" === typeof context.UNSAFE_componentWillUpdate &&\n context.UNSAFE_componentWillUpdate(\n nextProps,\n newState,\n oldProps\n )),\n \"function\" === typeof context.componentDidUpdate &&\n (workInProgress.flags |= 4),\n \"function\" === typeof context.getSnapshotBeforeUpdate &&\n (workInProgress.flags |= 1024))\n : (\"function\" !== typeof context.componentDidUpdate ||\n (contextType === current.memoizedProps &&\n oldState === current.memoizedState) ||\n (workInProgress.flags |= 4),\n \"function\" !== typeof context.getSnapshotBeforeUpdate ||\n (contextType === current.memoizedProps &&\n oldState === current.memoizedState) ||\n (workInProgress.flags |= 1024),\n (workInProgress.memoizedProps = nextProps),\n (workInProgress.memoizedState = newState)),\n (context.props = nextProps),\n (context.state = newState),\n (context.context = oldProps),\n (nextProps = contextType$jscomp$0))\n : (\"function\" !== typeof context.componentDidUpdate ||\n (contextType === current.memoizedProps &&\n oldState === current.memoizedState) ||\n (workInProgress.flags |= 4),\n \"function\" !== typeof context.getSnapshotBeforeUpdate ||\n (contextType === current.memoizedProps &&\n oldState === current.memoizedState) ||\n (workInProgress.flags |= 1024),\n (nextProps = !1));\n }\n context = nextProps;\n markRef(current, workInProgress);\n nextProps = 0 !== (workInProgress.flags & 128);\n context || nextProps\n ? ((context = workInProgress.stateNode),\n (Component =\n nextProps && \"function\" !== typeof Component.getDerivedStateFromError\n ? null\n : context.render()),\n (workInProgress.flags |= 1),\n null !== current && nextProps\n ? ((workInProgress.child = reconcileChildFibers(\n workInProgress,\n current.child,\n null,\n renderLanes\n )),\n (workInProgress.child = reconcileChildFibers(\n workInProgress,\n null,\n Component,\n renderLanes\n )))\n : reconcileChildren(current, workInProgress, Component, renderLanes),\n (workInProgress.memoizedState = context.state),\n (current = workInProgress.child))\n : (current = bailoutOnAlreadyFinishedWork(\n current,\n workInProgress,\n renderLanes\n ));\n return current;\n}\nfunction mountHostRootWithoutHydrating(\n current,\n workInProgress,\n nextChildren,\n renderLanes\n) {\n resetHydrationState();\n workInProgress.flags |= 256;\n reconcileChildren(current, workInProgress, nextChildren, renderLanes);\n return workInProgress.child;\n}\nvar SUSPENDED_MARKER = {\n dehydrated: null,\n treeContext: null,\n retryLane: 0,\n hydrationErrors: null\n};\nfunction mountSuspenseOffscreenState(renderLanes) {\n return { baseLanes: renderLanes, cachePool: getSuspendedCache() };\n}\nfunction getRemainingWorkInPrimaryTree(\n current,\n primaryTreeDidDefer,\n renderLanes\n) {\n current = null !== current ? current.childLanes & ~renderLanes : 0;\n primaryTreeDidDefer && (current |= workInProgressDeferredLane);\n return current;\n}\nfunction updateSuspenseComponent(current, workInProgress, renderLanes) {\n var nextProps = workInProgress.pendingProps,\n showFallback = !1,\n didSuspend = 0 !== (workInProgress.flags & 128),\n JSCompiler_temp;\n (JSCompiler_temp = didSuspend) ||\n (JSCompiler_temp =\n null !== current && null === current.memoizedState\n ? !1\n : 0 !== (suspenseStackCursor.current & 2));\n JSCompiler_temp && ((showFallback = !0), (workInProgress.flags &= -129));\n JSCompiler_temp = 0 !== (workInProgress.flags & 32);\n workInProgress.flags &= -33;\n if (null === current) {\n if (isHydrating) {\n showFallback\n ? pushPrimaryTreeSuspenseHandler(workInProgress)\n : reuseSuspenseHandlerOnStack(workInProgress);\n (current = nextHydratableInstance)\n ? ((current = canHydrateHydrationBoundary(\n current,\n rootOrSingletonContext\n )),\n (current = null !== current && \"&\" !== current.data ? current : null),\n null !== current &&\n ((workInProgress.memoizedState = {\n dehydrated: current,\n treeContext:\n null !== treeContextProvider\n ? { id: treeContextId, overflow: treeContextOverflow }\n : null,\n retryLane: 536870912,\n hydrationErrors: null\n }),\n (renderLanes = createFiberFromDehydratedFragment(current)),\n (renderLanes.return = workInProgress),\n (workInProgress.child = renderLanes),\n (hydrationParentFiber = workInProgress),\n (nextHydratableInstance = null)))\n : (current = null);\n if (null === current) throw throwOnHydrationMismatch(workInProgress);\n isSuspenseInstanceFallback(current)\n ? (workInProgress.lanes = 32)\n : (workInProgress.lanes = 536870912);\n return null;\n }\n var nextPrimaryChildren = nextProps.children;\n nextProps = nextProps.fallback;\n if (showFallback)\n return (\n reuseSuspenseHandlerOnStack(workInProgress),\n (showFallback = workInProgress.mode),\n (nextPrimaryChildren = mountWorkInProgressOffscreenFiber(\n { mode: \"hidden\", children: nextPrimaryChildren },\n showFallback\n )),\n (nextProps = createFiberFromFragment(\n nextProps,\n showFallback,\n renderLanes,\n null\n )),\n (nextPrimaryChildren.return = workInProgress),\n (nextProps.return = workInProgress),\n (nextPrimaryChildren.sibling = nextProps),\n (workInProgress.child = nextPrimaryChildren),\n (nextProps = workInProgress.child),\n (nextProps.memoizedState = mountSuspenseOffscreenState(renderLanes)),\n (nextProps.childLanes = getRemainingWorkInPrimaryTree(\n current,\n JSCompiler_temp,\n renderLanes\n )),\n (workInProgress.memoizedState = SUSPENDED_MARKER),\n bailoutOffscreenComponent(null, nextProps)\n );\n pushPrimaryTreeSuspenseHandler(workInProgress);\n return mountSuspensePrimaryChildren(workInProgress, nextPrimaryChildren);\n }\n var prevState = current.memoizedState;\n if (\n null !== prevState &&\n ((nextPrimaryChildren = prevState.dehydrated), null !== nextPrimaryChildren)\n ) {\n if (didSuspend)\n workInProgress.flags & 256\n ? (pushPrimaryTreeSuspenseHandler(workInProgress),\n (workInProgress.flags &= -257),\n (workInProgress = retrySuspenseComponentWithoutHydrating(\n current,\n workInProgress,\n renderLanes\n )))\n : null !== workInProgress.memoizedState\n ? (reuseSuspenseHandlerOnStack(workInProgress),\n (workInProgress.child = current.child),\n (workInProgress.flags |= 128),\n (workInProgress = null))\n : (reuseSuspenseHandlerOnStack(workInProgress),\n (nextPrimaryChildren = nextProps.fallback),\n (showFallback = workInProgress.mode),\n (nextProps = mountWorkInProgressOffscreenFiber(\n { mode: \"visible\", children: nextProps.children },\n showFallback\n )),\n (nextPrimaryChildren = createFiberFromFragment(\n nextPrimaryChildren,\n showFallback,\n renderLanes,\n null\n )),\n (nextPrimaryChildren.flags |= 2),\n (nextProps.return = workInProgress),\n (nextPrimaryChildren.return = workInProgress),\n (nextProps.sibling = nextPrimaryChildren),\n (workInProgress.child = nextProps),\n reconcileChildFibers(\n workInProgress,\n current.child,\n null,\n renderLanes\n ),\n (nextProps = workInProgress.child),\n (nextProps.memoizedState =\n mountSuspenseOffscreenState(renderLanes)),\n (nextProps.childLanes = getRemainingWorkInPrimaryTree(\n current,\n JSCompiler_temp,\n renderLanes\n )),\n (workInProgress.memoizedState = SUSPENDED_MARKER),\n (workInProgress = bailoutOffscreenComponent(null, nextProps)));\n else if (\n (pushPrimaryTreeSuspenseHandler(workInProgress),\n isSuspenseInstanceFallback(nextPrimaryChildren))\n ) {\n JSCompiler_temp =\n nextPrimaryChildren.nextSibling &&\n nextPrimaryChildren.nextSibling.dataset;\n if (JSCompiler_temp) var digest = JSCompiler_temp.dgst;\n JSCompiler_temp = digest;\n nextProps = Error(formatProdErrorMessage(419));\n nextProps.stack = \"\";\n nextProps.digest = JSCompiler_temp;\n queueHydrationError({ value: nextProps, source: null, stack: null });\n workInProgress = retrySuspenseComponentWithoutHydrating(\n current,\n workInProgress,\n renderLanes\n );\n } else if (\n (didReceiveUpdate ||\n propagateParentContextChanges(current, workInProgress, renderLanes, !1),\n (JSCompiler_temp = 0 !== (renderLanes & current.childLanes)),\n didReceiveUpdate || JSCompiler_temp)\n ) {\n JSCompiler_temp = workInProgressRoot;\n if (\n null !== JSCompiler_temp &&\n ((nextProps = getBumpedLaneForHydration(JSCompiler_temp, renderLanes)),\n 0 !== nextProps && nextProps !== prevState.retryLane)\n )\n throw (\n ((prevState.retryLane = nextProps),\n enqueueConcurrentRenderForLane(current, nextProps),\n scheduleUpdateOnFiber(JSCompiler_temp, current, nextProps),\n SelectiveHydrationException)\n );\n isSuspenseInstancePending(nextPrimaryChildren) ||\n renderDidSuspendDelayIfPossible();\n workInProgress = retrySuspenseComponentWithoutHydrating(\n current,\n workInProgress,\n renderLanes\n );\n } else\n isSuspenseInstancePending(nextPrimaryChildren)\n ? ((workInProgress.flags |= 192),\n (workInProgress.child = current.child),\n (workInProgress = null))\n : ((current = prevState.treeContext),\n (nextHydratableInstance = getNextHydratable(\n nextPrimaryChildren.nextSibling\n )),\n (hydrationParentFiber = workInProgress),\n (isHydrating = !0),\n (hydrationErrors = null),\n (rootOrSingletonContext = !1),\n null !== current &&\n restoreSuspendedTreeContext(workInProgress, current),\n (workInProgress = mountSuspensePrimaryChildren(\n workInProgress,\n nextProps.children\n )),\n (workInProgress.flags |= 4096));\n return workInProgress;\n }\n if (showFallback)\n return (\n reuseSuspenseHandlerOnStack(workInProgress),\n (nextPrimaryChildren = nextProps.fallback),\n (showFallback = workInProgress.mode),\n (prevState = current.child),\n (digest = prevState.sibling),\n (nextProps = createWorkInProgress(prevState, {\n mode: \"hidden\",\n children: nextProps.children\n })),\n (nextProps.subtreeFlags = prevState.subtreeFlags & 65011712),\n null !== digest\n ? (nextPrimaryChildren = createWorkInProgress(\n digest,\n nextPrimaryChildren\n ))\n : ((nextPrimaryChildren = createFiberFromFragment(\n nextPrimaryChildren,\n showFallback,\n renderLanes,\n null\n )),\n (nextPrimaryChildren.flags |= 2)),\n (nextPrimaryChildren.return = workInProgress),\n (nextProps.return = workInProgress),\n (nextProps.sibling = nextPrimaryChildren),\n (workInProgress.child = nextProps),\n bailoutOffscreenComponent(null, nextProps),\n (nextProps = workInProgress.child),\n (nextPrimaryChildren = current.child.memoizedState),\n null === nextPrimaryChildren\n ? (nextPrimaryChildren = mountSuspenseOffscreenState(renderLanes))\n : ((showFallback = nextPrimaryChildren.cachePool),\n null !== showFallback\n ? ((prevState = CacheContext._currentValue),\n (showFallback =\n showFallback.parent !== prevState\n ? { parent: prevState, pool: prevState }\n : showFallback))\n : (showFallback = getSuspendedCache()),\n (nextPrimaryChildren = {\n baseLanes: nextPrimaryChildren.baseLanes | renderLanes,\n cachePool: showFallback\n })),\n (nextProps.memoizedState = nextPrimaryChildren),\n (nextProps.childLanes = getRemainingWorkInPrimaryTree(\n current,\n JSCompiler_temp,\n renderLanes\n )),\n (workInProgress.memoizedState = SUSPENDED_MARKER),\n bailoutOffscreenComponent(current.child, nextProps)\n );\n pushPrimaryTreeSuspenseHandler(workInProgress);\n renderLanes = current.child;\n current = renderLanes.sibling;\n renderLanes = createWorkInProgress(renderLanes, {\n mode: \"visible\",\n children: nextProps.children\n });\n renderLanes.return = workInProgress;\n renderLanes.sibling = null;\n null !== current &&\n ((JSCompiler_temp = workInProgress.deletions),\n null === JSCompiler_temp\n ? ((workInProgress.deletions = [current]), (workInProgress.flags |= 16))\n : JSCompiler_temp.push(current));\n workInProgress.child = renderLanes;\n workInProgress.memoizedState = null;\n return renderLanes;\n}\nfunction mountSuspensePrimaryChildren(workInProgress, primaryChildren) {\n primaryChildren = mountWorkInProgressOffscreenFiber(\n { mode: \"visible\", children: primaryChildren },\n workInProgress.mode\n );\n primaryChildren.return = workInProgress;\n return (workInProgress.child = primaryChildren);\n}\nfunction mountWorkInProgressOffscreenFiber(offscreenProps, mode) {\n offscreenProps = createFiberImplClass(22, offscreenProps, null, mode);\n offscreenProps.lanes = 0;\n return offscreenProps;\n}\nfunction retrySuspenseComponentWithoutHydrating(\n current,\n workInProgress,\n renderLanes\n) {\n reconcileChildFibers(workInProgress, current.child, null, renderLanes);\n current = mountSuspensePrimaryChildren(\n workInProgress,\n workInProgress.pendingProps.children\n );\n current.flags |= 2;\n workInProgress.memoizedState = null;\n return current;\n}\nfunction scheduleSuspenseWorkOnFiber(fiber, renderLanes, propagationRoot) {\n fiber.lanes |= renderLanes;\n var alternate = fiber.alternate;\n null !== alternate && (alternate.lanes |= renderLanes);\n scheduleContextWorkOnParentPath(fiber.return, renderLanes, propagationRoot);\n}\nfunction initSuspenseListRenderState(\n workInProgress,\n isBackwards,\n tail,\n lastContentRow,\n tailMode,\n treeForkCount\n) {\n var renderState = workInProgress.memoizedState;\n null === renderState\n ? (workInProgress.memoizedState = {\n isBackwards: isBackwards,\n rendering: null,\n renderingStartTime: 0,\n last: lastContentRow,\n tail: tail,\n tailMode: tailMode,\n treeForkCount: treeForkCount\n })\n : ((renderState.isBackwards = isBackwards),\n (renderState.rendering = null),\n (renderState.renderingStartTime = 0),\n (renderState.last = lastContentRow),\n (renderState.tail = tail),\n (renderState.tailMode = tailMode),\n (renderState.treeForkCount = treeForkCount));\n}\nfunction updateSuspenseListComponent(current, workInProgress, renderLanes) {\n var nextProps = workInProgress.pendingProps,\n revealOrder = nextProps.revealOrder,\n tailMode = nextProps.tail;\n nextProps = nextProps.children;\n var suspenseContext = suspenseStackCursor.current,\n shouldForceFallback = 0 !== (suspenseContext & 2);\n shouldForceFallback\n ? ((suspenseContext = (suspenseContext & 1) | 2),\n (workInProgress.flags |= 128))\n : (suspenseContext &= 1);\n push(suspenseStackCursor, suspenseContext);\n reconcileChildren(current, workInProgress, nextProps, renderLanes);\n nextProps = isHydrating ? treeForkCount : 0;\n if (!shouldForceFallback && null !== current && 0 !== (current.flags & 128))\n a: for (current = workInProgress.child; null !== current; ) {\n if (13 === current.tag)\n null !== current.memoizedState &&\n scheduleSuspenseWorkOnFiber(current, renderLanes, workInProgress);\n else if (19 === current.tag)\n scheduleSuspenseWorkOnFiber(current, renderLanes, workInProgress);\n else if (null !== current.child) {\n current.child.return = current;\n current = current.child;\n continue;\n }\n if (current === workInProgress) break a;\n for (; null === current.sibling; ) {\n if (null === current.return || current.return === workInProgress)\n break a;\n current = current.return;\n }\n current.sibling.return = current.return;\n current = current.sibling;\n }\n switch (revealOrder) {\n case \"forwards\":\n renderLanes = workInProgress.child;\n for (revealOrder = null; null !== renderLanes; )\n (current = renderLanes.alternate),\n null !== current &&\n null === findFirstSuspended(current) &&\n (revealOrder = renderLanes),\n (renderLanes = renderLanes.sibling);\n renderLanes = revealOrder;\n null === renderLanes\n ? ((revealOrder = workInProgress.child), (workInProgress.child = null))\n : ((revealOrder = renderLanes.sibling), (renderLanes.sibling = null));\n initSuspenseListRenderState(\n workInProgress,\n !1,\n revealOrder,\n renderLanes,\n tailMode,\n nextProps\n );\n break;\n case \"backwards\":\n case \"unstable_legacy-backwards\":\n renderLanes = null;\n revealOrder = workInProgress.child;\n for (workInProgress.child = null; null !== revealOrder; ) {\n current = revealOrder.alternate;\n if (null !== current && null === findFirstSuspended(current)) {\n workInProgress.child = revealOrder;\n break;\n }\n current = revealOrder.sibling;\n revealOrder.sibling = renderLanes;\n renderLanes = revealOrder;\n revealOrder = current;\n }\n initSuspenseListRenderState(\n workInProgress,\n !0,\n renderLanes,\n null,\n tailMode,\n nextProps\n );\n break;\n case \"together\":\n initSuspenseListRenderState(\n workInProgress,\n !1,\n null,\n null,\n void 0,\n nextProps\n );\n break;\n default:\n workInProgress.memoizedState = null;\n }\n return workInProgress.child;\n}\nfunction bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) {\n null !== current && (workInProgress.dependencies = current.dependencies);\n workInProgressRootSkippedLanes |= workInProgress.lanes;\n if (0 === (renderLanes & workInProgress.childLanes))\n if (null !== current) {\n if (\n (propagateParentContextChanges(\n current,\n workInProgress,\n renderLanes,\n !1\n ),\n 0 === (renderLanes & workInProgress.childLanes))\n )\n return null;\n } else return null;\n if (null !== current && workInProgress.child !== current.child)\n throw Error(formatProdErrorMessage(153));\n if (null !== workInProgress.child) {\n current = workInProgress.child;\n renderLanes = createWorkInProgress(current, current.pendingProps);\n workInProgress.child = renderLanes;\n for (renderLanes.return = workInProgress; null !== current.sibling; )\n (current = current.sibling),\n (renderLanes = renderLanes.sibling =\n createWorkInProgress(current, current.pendingProps)),\n (renderLanes.return = workInProgress);\n renderLanes.sibling = null;\n }\n return workInProgress.child;\n}\nfunction checkScheduledUpdateOrContext(current, renderLanes) {\n if (0 !== (current.lanes & renderLanes)) return !0;\n current = current.dependencies;\n return null !== current && checkIfContextChanged(current) ? !0 : !1;\n}\nfunction attemptEarlyBailoutIfNoScheduledUpdate(\n current,\n workInProgress,\n renderLanes\n) {\n switch (workInProgress.tag) {\n case 3:\n pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);\n pushProvider(workInProgress, CacheContext, current.memoizedState.cache);\n resetHydrationState();\n break;\n case 27:\n case 5:\n pushHostContext(workInProgress);\n break;\n case 4:\n pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);\n break;\n case 10:\n pushProvider(\n workInProgress,\n workInProgress.type,\n workInProgress.memoizedProps.value\n );\n break;\n case 31:\n if (null !== workInProgress.memoizedState)\n return (\n (workInProgress.flags |= 128),\n pushDehydratedActivitySuspenseHandler(workInProgress),\n null\n );\n break;\n case 13:\n var state$102 = workInProgress.memoizedState;\n if (null !== state$102) {\n if (null !== state$102.dehydrated)\n return (\n pushPrimaryTreeSuspenseHandler(workInProgress),\n (workInProgress.flags |= 128),\n null\n );\n if (0 !== (renderLanes & workInProgress.child.childLanes))\n return updateSuspenseComponent(current, workInProgress, renderLanes);\n pushPrimaryTreeSuspenseHandler(workInProgress);\n current = bailoutOnAlreadyFinishedWork(\n current,\n workInProgress,\n renderLanes\n );\n return null !== current ? current.sibling : null;\n }\n pushPrimaryTreeSuspenseHandler(workInProgress);\n break;\n case 19:\n var didSuspendBefore = 0 !== (current.flags & 128);\n state$102 = 0 !== (renderLanes & workInProgress.childLanes);\n state$102 ||\n (propagateParentContextChanges(\n current,\n workInProgress,\n renderLanes,\n !1\n ),\n (state$102 = 0 !== (renderLanes & workInProgress.childLanes)));\n if (didSuspendBefore) {\n if (state$102)\n return updateSuspenseListComponent(\n current,\n workInProgress,\n renderLanes\n );\n workInProgress.flags |= 128;\n }\n didSuspendBefore = workInProgress.memoizedState;\n null !== didSuspendBefore &&\n ((didSuspendBefore.rendering = null),\n (didSuspendBefore.tail = null),\n (didSuspendBefore.lastEffect = null));\n push(suspenseStackCursor, suspenseStackCursor.current);\n if (state$102) break;\n else return null;\n case 22:\n return (\n (workInProgress.lanes = 0),\n updateOffscreenComponent(\n current,\n workInProgress,\n renderLanes,\n workInProgress.pendingProps\n )\n );\n case 24:\n pushProvider(workInProgress, CacheContext, current.memoizedState.cache);\n }\n return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);\n}\nfunction beginWork(current, workInProgress, renderLanes) {\n if (null !== current)\n if (current.memoizedProps !== workInProgress.pendingProps)\n didReceiveUpdate = !0;\n else {\n if (\n !checkScheduledUpdateOrContext(current, renderLanes) &&\n 0 === (workInProgress.flags & 128)\n )\n return (\n (didReceiveUpdate = !1),\n attemptEarlyBailoutIfNoScheduledUpdate(\n current,\n workInProgress,\n renderLanes\n )\n );\n didReceiveUpdate = 0 !== (current.flags & 131072) ? !0 : !1;\n }\n else\n (didReceiveUpdate = !1),\n isHydrating &&\n 0 !== (workInProgress.flags & 1048576) &&\n pushTreeId(workInProgress, treeForkCount, workInProgress.index);\n workInProgress.lanes = 0;\n switch (workInProgress.tag) {\n case 16:\n a: {\n var props = workInProgress.pendingProps;\n current = resolveLazy(workInProgress.elementType);\n workInProgress.type = current;\n if (\"function\" === typeof current)\n shouldConstruct(current)\n ? ((props = resolveClassComponentProps(current, props)),\n (workInProgress.tag = 1),\n (workInProgress = updateClassComponent(\n null,\n workInProgress,\n current,\n props,\n renderLanes\n )))\n : ((workInProgress.tag = 0),\n (workInProgress = updateFunctionComponent(\n null,\n workInProgress,\n current,\n props,\n renderLanes\n )));\n else {\n if (void 0 !== current && null !== current) {\n var $$typeof = current.$$typeof;\n if ($$typeof === REACT_FORWARD_REF_TYPE) {\n workInProgress.tag = 11;\n workInProgress = updateForwardRef(\n null,\n workInProgress,\n current,\n props,\n renderLanes\n );\n break a;\n } else if ($$typeof === REACT_MEMO_TYPE) {\n workInProgress.tag = 14;\n workInProgress = updateMemoComponent(\n null,\n workInProgress,\n current,\n props,\n renderLanes\n );\n break a;\n }\n }\n workInProgress = getComponentNameFromType(current) || current;\n throw Error(formatProdErrorMessage(306, workInProgress, \"\"));\n }\n }\n return workInProgress;\n case 0:\n return updateFunctionComponent(\n current,\n workInProgress,\n workInProgress.type,\n workInProgress.pendingProps,\n renderLanes\n );\n case 1:\n return (\n (props = workInProgress.type),\n ($$typeof = resolveClassComponentProps(\n props,\n workInProgress.pendingProps\n )),\n updateClassComponent(\n current,\n workInProgress,\n props,\n $$typeof,\n renderLanes\n )\n );\n case 3:\n a: {\n pushHostContainer(\n workInProgress,\n workInProgress.stateNode.containerInfo\n );\n if (null === current) throw Error(formatProdErrorMessage(387));\n props = workInProgress.pendingProps;\n var prevState = workInProgress.memoizedState;\n $$typeof = prevState.element;\n cloneUpdateQueue(current, workInProgress);\n processUpdateQueue(workInProgress, props, null, renderLanes);\n var nextState = workInProgress.memoizedState;\n props = nextState.cache;\n pushProvider(workInProgress, CacheContext, props);\n props !== prevState.cache &&\n propagateContextChanges(\n workInProgress,\n [CacheContext],\n renderLanes,\n !0\n );\n suspendIfUpdateReadFromEntangledAsyncAction();\n props = nextState.element;\n if (prevState.isDehydrated)\n if (\n ((prevState = {\n element: props,\n isDehydrated: !1,\n cache: nextState.cache\n }),\n (workInProgress.updateQueue.baseState = prevState),\n (workInProgress.memoizedState = prevState),\n workInProgress.flags & 256)\n ) {\n workInProgress = mountHostRootWithoutHydrating(\n current,\n workInProgress,\n props,\n renderLanes\n );\n break a;\n } else if (props !== $$typeof) {\n $$typeof = createCapturedValueAtFiber(\n Error(formatProdErrorMessage(424)),\n workInProgress\n );\n queueHydrationError($$typeof);\n workInProgress = mountHostRootWithoutHydrating(\n current,\n workInProgress,\n props,\n renderLanes\n );\n break a;\n } else {\n current = workInProgress.stateNode.containerInfo;\n switch (current.nodeType) {\n case 9:\n current = current.body;\n break;\n default:\n current =\n \"HTML\" === current.nodeName\n ? current.ownerDocument.body\n : current;\n }\n nextHydratableInstance = getNextHydratable(current.firstChild);\n hydrationParentFiber = workInProgress;\n isHydrating = !0;\n hydrationErrors = null;\n rootOrSingletonContext = !0;\n renderLanes = mountChildFibers(\n workInProgress,\n null,\n props,\n renderLanes\n );\n for (workInProgress.child = renderLanes; renderLanes; )\n (renderLanes.flags = (renderLanes.flags & -3) | 4096),\n (renderLanes = renderLanes.sibling);\n }\n else {\n resetHydrationState();\n if (props === $$typeof) {\n workInProgress = bailoutOnAlreadyFinishedWork(\n current,\n workInProgress,\n renderLanes\n );\n break a;\n }\n reconcileChildren(current, workInProgress, props, renderLanes);\n }\n workInProgress = workInProgress.child;\n }\n return workInProgress;\n case 26:\n return (\n markRef(current, workInProgress),\n null === current\n ? (renderLanes = getResource(\n workInProgress.type,\n null,\n workInProgress.pendingProps,\n null\n ))\n ? (workInProgress.memoizedState = renderLanes)\n : isHydrating ||\n ((renderLanes = workInProgress.type),\n (current = workInProgress.pendingProps),\n (props = getOwnerDocumentFromRootContainer(\n rootInstanceStackCursor.current\n ).createElement(renderLanes)),\n (props[internalInstanceKey] = workInProgress),\n (props[internalPropsKey] = current),\n setInitialProperties(props, renderLanes, current),\n markNodeAsHoistable(props),\n (workInProgress.stateNode = props))\n : (workInProgress.memoizedState = getResource(\n workInProgress.type,\n current.memoizedProps,\n workInProgress.pendingProps,\n current.memoizedState\n )),\n null\n );\n case 27:\n return (\n pushHostContext(workInProgress),\n null === current &&\n isHydrating &&\n ((props = workInProgress.stateNode =\n resolveSingletonInstance(\n workInProgress.type,\n workInProgress.pendingProps,\n rootInstanceStackCursor.current\n )),\n (hydrationParentFiber = workInProgress),\n (rootOrSingletonContext = !0),\n ($$typeof = nextHydratableInstance),\n isSingletonScope(workInProgress.type)\n ? ((previousHydratableOnEnteringScopedSingleton = $$typeof),\n (nextHydratableInstance = getNextHydratable(props.firstChild)))\n : (nextHydratableInstance = $$typeof)),\n reconcileChildren(\n current,\n workInProgress,\n workInProgress.pendingProps.children,\n renderLanes\n ),\n markRef(current, workInProgress),\n null === current && (workInProgress.flags |= 4194304),\n workInProgress.child\n );\n case 5:\n if (null === current && isHydrating) {\n if (($$typeof = props = nextHydratableInstance))\n (props = canHydrateInstance(\n props,\n workInProgress.type,\n workInProgress.pendingProps,\n rootOrSingletonContext\n )),\n null !== props\n ? ((workInProgress.stateNode = props),\n (hydrationParentFiber = workInProgress),\n (nextHydratableInstance = getNextHydratable(props.firstChild)),\n (rootOrSingletonContext = !1),\n ($$typeof = !0))\n : ($$typeof = !1);\n $$typeof || throwOnHydrationMismatch(workInProgress);\n }\n pushHostContext(workInProgress);\n $$typeof = workInProgress.type;\n prevState = workInProgress.pendingProps;\n nextState = null !== current ? current.memoizedProps : null;\n props = prevState.children;\n shouldSetTextContent($$typeof, prevState)\n ? (props = null)\n : null !== nextState &&\n shouldSetTextContent($$typeof, nextState) &&\n (workInProgress.flags |= 32);\n null !== workInProgress.memoizedState &&\n (($$typeof = renderWithHooks(\n current,\n workInProgress,\n TransitionAwareHostComponent,\n null,\n null,\n renderLanes\n )),\n (HostTransitionContext._currentValue = $$typeof));\n markRef(current, workInProgress);\n reconcileChildren(current, workInProgress, props, renderLanes);\n return workInProgress.child;\n case 6:\n if (null === current && isHydrating) {\n if ((current = renderLanes = nextHydratableInstance))\n (renderLanes = canHydrateTextInstance(\n renderLanes,\n workInProgress.pendingProps,\n rootOrSingletonContext\n )),\n null !== renderLanes\n ? ((workInProgress.stateNode = renderLanes),\n (hydrationParentFiber = workInProgress),\n (nextHydratableInstance = null),\n (current = !0))\n : (current = !1);\n current || throwOnHydrationMismatch(workInProgress);\n }\n return null;\n case 13:\n return updateSuspenseComponent(current, workInProgress, renderLanes);\n case 4:\n return (\n pushHostContainer(\n workInProgress,\n workInProgress.stateNode.containerInfo\n ),\n (props = workInProgress.pendingProps),\n null === current\n ? (workInProgress.child = reconcileChildFibers(\n workInProgress,\n null,\n props,\n renderLanes\n ))\n : reconcileChildren(current, workInProgress, props, renderLanes),\n workInProgress.child\n );\n case 11:\n return updateForwardRef(\n current,\n workInProgress,\n workInProgress.type,\n workInProgress.pendingProps,\n renderLanes\n );\n case 7:\n return (\n reconcileChildren(\n current,\n workInProgress,\n workInProgress.pendingProps,\n renderLanes\n ),\n workInProgress.child\n );\n case 8:\n return (\n reconcileChildren(\n current,\n workInProgress,\n workInProgress.pendingProps.children,\n renderLanes\n ),\n workInProgress.child\n );\n case 12:\n return (\n reconcileChildren(\n current,\n workInProgress,\n workInProgress.pendingProps.children,\n renderLanes\n ),\n workInProgress.child\n );\n case 10:\n return (\n (props = workInProgress.pendingProps),\n pushProvider(workInProgress, workInProgress.type, props.value),\n reconcileChildren(current, workInProgress, props.children, renderLanes),\n workInProgress.child\n );\n case 9:\n return (\n ($$typeof = workInProgress.type._context),\n (props = workInProgress.pendingProps.children),\n prepareToReadContext(workInProgress),\n ($$typeof = readContext($$typeof)),\n (props = props($$typeof)),\n (workInProgress.flags |= 1),\n reconcileChildren(current, workInProgress, props, renderLanes),\n workInProgress.child\n );\n case 14:\n return updateMemoComponent(\n current,\n workInProgress,\n workInProgress.type,\n workInProgress.pendingProps,\n renderLanes\n );\n case 15:\n return updateSimpleMemoComponent(\n current,\n workInProgress,\n workInProgress.type,\n workInProgress.pendingProps,\n renderLanes\n );\n case 19:\n return updateSuspenseListComponent(current, workInProgress, renderLanes);\n case 31:\n return updateActivityComponent(current, workInProgress, renderLanes);\n case 22:\n return updateOffscreenComponent(\n current,\n workInProgress,\n renderLanes,\n workInProgress.pendingProps\n );\n case 24:\n return (\n prepareToReadContext(workInProgress),\n (props = readContext(CacheContext)),\n null === current\n ? (($$typeof = peekCacheFromPool()),\n null === $$typeof &&\n (($$typeof = workInProgressRoot),\n (prevState = createCache()),\n ($$typeof.pooledCache = prevState),\n prevState.refCount++,\n null !== prevState && ($$typeof.pooledCacheLanes |= renderLanes),\n ($$typeof = prevState)),\n (workInProgress.memoizedState = { parent: props, cache: $$typeof }),\n initializeUpdateQueue(workInProgress),\n pushProvider(workInProgress, CacheContext, $$typeof))\n : (0 !== (current.lanes & renderLanes) &&\n (cloneUpdateQueue(current, workInProgress),\n processUpdateQueue(workInProgress, null, null, renderLanes),\n suspendIfUpdateReadFromEntangledAsyncAction()),\n ($$typeof = current.memoizedState),\n (prevState = workInProgress.memoizedState),\n $$typeof.parent !== props\n ? (($$typeof = { parent: props, cache: props }),\n (workInProgress.memoizedState = $$typeof),\n 0 === workInProgress.lanes &&\n (workInProgress.memoizedState =\n workInProgress.updateQueue.baseState =\n $$typeof),\n pushProvider(workInProgress, CacheContext, props))\n : ((props = prevState.cache),\n pushProvider(workInProgress, CacheContext, props),\n props !== $$typeof.cache &&\n propagateContextChanges(\n workInProgress,\n [CacheContext],\n renderLanes,\n !0\n ))),\n reconcileChildren(\n current,\n workInProgress,\n workInProgress.pendingProps.children,\n renderLanes\n ),\n workInProgress.child\n );\n case 29:\n throw workInProgress.pendingProps;\n }\n throw Error(formatProdErrorMessage(156, workInProgress.tag));\n}\nfunction markUpdate(workInProgress) {\n workInProgress.flags |= 4;\n}\nfunction preloadInstanceAndSuspendIfNeeded(\n workInProgress,\n type,\n oldProps,\n newProps,\n renderLanes\n) {\n if ((type = 0 !== (workInProgress.mode & 32))) type = !1;\n if (type) {\n if (\n ((workInProgress.flags |= 16777216),\n (renderLanes & 335544128) === renderLanes)\n )\n if (workInProgress.stateNode.complete) workInProgress.flags |= 8192;\n else if (shouldRemainOnPreviousScreen()) workInProgress.flags |= 8192;\n else\n throw (\n ((suspendedThenable = noopSuspenseyCommitThenable),\n SuspenseyCommitException)\n );\n } else workInProgress.flags &= -16777217;\n}\nfunction preloadResourceAndSuspendIfNeeded(workInProgress, resource) {\n if (\"stylesheet\" !== resource.type || 0 !== (resource.state.loading & 4))\n workInProgress.flags &= -16777217;\n else if (((workInProgress.flags |= 16777216), !preloadResource(resource)))\n if (shouldRemainOnPreviousScreen()) workInProgress.flags |= 8192;\n else\n throw (\n ((suspendedThenable = noopSuspenseyCommitThenable),\n SuspenseyCommitException)\n );\n}\nfunction scheduleRetryEffect(workInProgress, retryQueue) {\n null !== retryQueue && (workInProgress.flags |= 4);\n workInProgress.flags & 16384 &&\n ((retryQueue =\n 22 !== workInProgress.tag ? claimNextRetryLane() : 536870912),\n (workInProgress.lanes |= retryQueue),\n (workInProgressSuspendedRetryLanes |= retryQueue));\n}\nfunction cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {\n if (!isHydrating)\n switch (renderState.tailMode) {\n case \"hidden\":\n hasRenderedATailFallback = renderState.tail;\n for (var lastTailNode = null; null !== hasRenderedATailFallback; )\n null !== hasRenderedATailFallback.alternate &&\n (lastTailNode = hasRenderedATailFallback),\n (hasRenderedATailFallback = hasRenderedATailFallback.sibling);\n null === lastTailNode\n ? (renderState.tail = null)\n : (lastTailNode.sibling = null);\n break;\n case \"collapsed\":\n lastTailNode = renderState.tail;\n for (var lastTailNode$106 = null; null !== lastTailNode; )\n null !== lastTailNode.alternate && (lastTailNode$106 = lastTailNode),\n (lastTailNode = lastTailNode.sibling);\n null === lastTailNode$106\n ? hasRenderedATailFallback || null === renderState.tail\n ? (renderState.tail = null)\n : (renderState.tail.sibling = null)\n : (lastTailNode$106.sibling = null);\n }\n}\nfunction bubbleProperties(completedWork) {\n var didBailout =\n null !== completedWork.alternate &&\n completedWork.alternate.child === completedWork.child,\n newChildLanes = 0,\n subtreeFlags = 0;\n if (didBailout)\n for (var child$107 = completedWork.child; null !== child$107; )\n (newChildLanes |= child$107.lanes | child$107.childLanes),\n (subtreeFlags |= child$107.subtreeFlags & 65011712),\n (subtreeFlags |= child$107.flags & 65011712),\n (child$107.return = completedWork),\n (child$107 = child$107.sibling);\n else\n for (child$107 = completedWork.child; null !== child$107; )\n (newChildLanes |= child$107.lanes | child$107.childLanes),\n (subtreeFlags |= child$107.subtreeFlags),\n (subtreeFlags |= child$107.flags),\n (child$107.return = completedWork),\n (child$107 = child$107.sibling);\n completedWork.subtreeFlags |= subtreeFlags;\n completedWork.childLanes = newChildLanes;\n return didBailout;\n}\nfunction completeWork(current, workInProgress, renderLanes) {\n var newProps = workInProgress.pendingProps;\n popTreeContext(workInProgress);\n switch (workInProgress.tag) {\n case 16:\n case 15:\n case 0:\n case 11:\n case 7:\n case 8:\n case 12:\n case 9:\n case 14:\n return bubbleProperties(workInProgress), null;\n case 1:\n return bubbleProperties(workInProgress), null;\n case 3:\n renderLanes = workInProgress.stateNode;\n newProps = null;\n null !== current && (newProps = current.memoizedState.cache);\n workInProgress.memoizedState.cache !== newProps &&\n (workInProgress.flags |= 2048);\n popProvider(CacheContext);\n popHostContainer();\n renderLanes.pendingContext &&\n ((renderLanes.context = renderLanes.pendingContext),\n (renderLanes.pendingContext = null));\n if (null === current || null === current.child)\n popHydrationState(workInProgress)\n ? markUpdate(workInProgress)\n : null === current ||\n (current.memoizedState.isDehydrated &&\n 0 === (workInProgress.flags & 256)) ||\n ((workInProgress.flags |= 1024),\n upgradeHydrationErrorsToRecoverable());\n bubbleProperties(workInProgress);\n return null;\n case 26:\n var type = workInProgress.type,\n nextResource = workInProgress.memoizedState;\n null === current\n ? (markUpdate(workInProgress),\n null !== nextResource\n ? (bubbleProperties(workInProgress),\n preloadResourceAndSuspendIfNeeded(workInProgress, nextResource))\n : (bubbleProperties(workInProgress),\n preloadInstanceAndSuspendIfNeeded(\n workInProgress,\n type,\n null,\n newProps,\n renderLanes\n )))\n : nextResource\n ? nextResource !== current.memoizedState\n ? (markUpdate(workInProgress),\n bubbleProperties(workInProgress),\n preloadResourceAndSuspendIfNeeded(workInProgress, nextResource))\n : (bubbleProperties(workInProgress),\n (workInProgress.flags &= -16777217))\n : ((current = current.memoizedProps),\n current !== newProps && markUpdate(workInProgress),\n bubbleProperties(workInProgress),\n preloadInstanceAndSuspendIfNeeded(\n workInProgress,\n type,\n current,\n newProps,\n renderLanes\n ));\n return null;\n case 27:\n popHostContext(workInProgress);\n renderLanes = rootInstanceStackCursor.current;\n type = workInProgress.type;\n if (null !== current && null != workInProgress.stateNode)\n current.memoizedProps !== newProps && markUpdate(workInProgress);\n else {\n if (!newProps) {\n if (null === workInProgress.stateNode)\n throw Error(formatProdErrorMessage(166));\n bubbleProperties(workInProgress);\n return null;\n }\n current = contextStackCursor.current;\n popHydrationState(workInProgress)\n ? prepareToHydrateHostInstance(workInProgress, current)\n : ((current = resolveSingletonInstance(type, newProps, renderLanes)),\n (workInProgress.stateNode = current),\n markUpdate(workInProgress));\n }\n bubbleProperties(workInProgress);\n return null;\n case 5:\n popHostContext(workInProgress);\n type = workInProgress.type;\n if (null !== current && null != workInProgress.stateNode)\n current.memoizedProps !== newProps && markUpdate(workInProgress);\n else {\n if (!newProps) {\n if (null === workInProgress.stateNode)\n throw Error(formatProdErrorMessage(166));\n bubbleProperties(workInProgress);\n return null;\n }\n nextResource = contextStackCursor.current;\n if (popHydrationState(workInProgress))\n prepareToHydrateHostInstance(workInProgress, nextResource);\n else {\n var ownerDocument = getOwnerDocumentFromRootContainer(\n rootInstanceStackCursor.current\n );\n switch (nextResource) {\n case 1:\n nextResource = ownerDocument.createElementNS(\n \"http://www.w3.org/2000/svg\",\n type\n );\n break;\n case 2:\n nextResource = ownerDocument.createElementNS(\n \"http://www.w3.org/1998/Math/MathML\",\n type\n );\n break;\n default:\n switch (type) {\n case \"svg\":\n nextResource = ownerDocument.createElementNS(\n \"http://www.w3.org/2000/svg\",\n type\n );\n break;\n case \"math\":\n nextResource = ownerDocument.createElementNS(\n \"http://www.w3.org/1998/Math/MathML\",\n type\n );\n break;\n case \"script\":\n nextResource = ownerDocument.createElement(\"div\");\n nextResource.innerHTML = \"